FP modelling - Mutability issue [closed] - oop

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am about to start a simulation/modelling project.
Let's say I have a component of type A, characterised by a set of data (a parameter like temperature or pressure,a PDE and some boundary conditions,etc.) and a component of type B, characterised by a different set of data(different or same parameter, different PDE and boundary conditions). Let's also assume that the functions/methods that are going to be applied on each component are the same (a Galerkin method for example).
If I were to use an FP approach, each component would be broken down to data parts and the functions that would act upon the data in order to get the solution for the PDE. This approach seems simpler to me assuming that the parameters are constant. What if the parameters are not constant(for example, temperature increases suddenly and therefore cannot be immutable)?
What would be the best approach to tackle the problem of the mutability of parameters?
I come from a C++/Fortran background, plus I'm not a professional programmer, so correct me on anything that I've got wrong.

Just because something can change doesn't mean it can't be modelled with immutable data.
In OOish style, lets say you have something like the following:
a = some_obj.calculationA(some, arguments);
b = some_obj.calculationB(more, args);
return combine(a, b)
Obviously calculationA and calculationB depend on some_obj, and you're even manually threading some_obj through as inputs to both calculations. You're just not used to seeing that that's what you're doing because you think in terms of invoking a method on an object.
Translating halfway to Haskell in the most obvious way possible gives you something like:
let a = calculationA some_obj some arguments
b = calculationB some_obj more args
in combine a b
It's really not that much trouble to manually pass some_obj as an extra parameter to all the functions, since that's what you're doing in OO style anyway.
The big thing that's missing is that in OO style calculationA and calculationB might change some_obj, which might be used after this context returns as well. That's pretty obvious to address in functional style too:
let (a, next_obj) = calculationA some_obj some arguments
(b, last_obj) = calculationB next_obj more args
in (combine a b, last_obj)
The way I'm used to thinking of things, this is "really" what's going on in the OOP version anyway, from a theoretical point of view. Every mutable object accessible to a given piece of imperative code is "really" an extra input and an extra output, passed secretly and implicitly. If you think the functional style makes your programs too complicated because there are dozens of extra inputs and outputs all over the place, ask yourself if the program is really any less complicated when all that data flow is still there but obscured?
But this is where higher abstractions (such as monads, but they're not the only one) come to the rescue. It's best not to think of monads as somehow magically giving you mutable state. Instead, think of them as encapsulating patterns, so you don't have to manually write code like the above. When you use the State monad to get "stateful programming", all this threading of states through the inputs and outputs of functions is still going on, but it's done in a strictly regimented way, and functions where this is going on are labelled by the monadic type, so you know it's happening.

Related

Is Scala mixin really better than multiple C++ inheritance? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 9 years ago.
People say C++ inheritance is evil, so Java 'fixed' this problem with interface.
But Scala introduced traits, they're... interface with partial implementation? Doesn't this brought multiple inheritance back?
Does it mean Scala guys think multiple inheritance is good? Or They have some critical differences I haven't noticed?
The worst part of multiple inheritance is diamond inheritance, where a subclass has two or more paths to the same parent somewhere up the chain. This creates ambiguity if implementations differ along the two paths (i.e. are overridden from the original implementation). In C++ the solution is particularly ugly: you embed both incompatible parent classes and have to specify when you call which implementation you want. This is confusing, creates extra work at every call site (or, more likely, forces you to override explicitly and state the one you want; this manual work is tedious and introduces a chance for error), and can lead to objects being larger than they ought to be.
Scala solves some but not all of the problems by limiting multiple inheritance to traits. Because traits have no constructors, the final class can linearize the inheritance tree, which is to say that even though two parents on a path back to a common super-parent nominally are both parents, one is the "correct" one, namely the one listed last. This scheme would leave broken half-initialized classes around if you could have (completely generic) constructors, but as it is, you don't have to embed the class twice, and at the use site you can ignore how much inheritance if any has happened. It does not, however, make it that much easier to reason about what will happen when you layer many traits on top of each other, and if you inherit from both B and C, you can't choose to take some of B's implementations and the some of C's.
So it's better in that it addresses some of the most serious criticisms of the C++ model. Whether it is better enough is a matter of taste; plenty of people even like the taste of C++'s multiple inheritance well enough to use it.

My poor design and abundance of getters [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am facing a rather annoying software design problem which has been troubling me for quite some time now. The problem is the initialization of an object and that a lot of getters are used to achieve that. I bumped into an article of Allen Holub [1] about why a lot of getters and setters usually indicate poor design. I listed several other articles below which also discuss this design issue.
Now concerning my problem. I am currently working on a fluid simulation. I have a Simulation class which contains the functions and variables relevant for simulating a fluid. At first, this class had only one public function called timeStep() which executes a time step of the simulation. Now, I want to simulate several well-known flows, one could see them as scenario's. This usually boils down to correctly initializing the simulation. For example, I have the Taylor-Green vortex flow. The simulation does not need to know that it is simulating a particular flow, it only has to execute the simulation algorithm, so I created a separate class TaylorGreenVortex. The class TaylorGreenVortex has to initialize the Simulation in such a way that it corresponds to the Taylor-Green vortex flow. Now here comes the trouble: the initialization equations of the Taylor-Green vortex flow require many variables that are also needed by Simulation and therefore are present in that class. So, the result is that I added a lot of getters to the Simulation class to obtain these variables. This is however also undesired, because all these getters makes the Simulation class very exposed and also generates high coupling between Simulation and TaylorGreenVortex. In addition, it is also annoying that the initializer (TaylorGreenVortex) first constructs a Simulation object, so it can get the relevant variables, and then later resets other variables of the Simulation object so that it will simulate a Taylor-Green vortex flow.
I have thought about several solutions, but all of these solutions do not really solve the problem, but merely shift the problem to a different class or make the design even worse. For example, if I follow the 'information expert' pattern, then I should remove the TaylorGreenVortex class and move all its functionality to the Simulation class. This however makes the Simulation class bulky when the simulation has to support many different flows. I could also introduce some sort of Data class which has the variables required by both TaylorGreenVortex and Simulation, but then I have to add a lot of getters to this Data class so that Simulation and TaylorGreenVortex get the variables from Data. What are your suggestions for a clean solution? If you know of a particular design pattern related to the problem, could you please explain somewhat concretely how it can be applied in the above situation? Thanks in advance.
http://www.javaworld.com/javaworld/jw-09-2003/jw-0905-toolbox.html
http://martinfowler.com/bliki/GetterEradicator.html
http://pragprog.com/articles/tell-dont-ask
To give a better advise I guess I should see the code, but from the description it sounds like you need a builder. However the TaylorGreenVortex class that you describe seems like it is doing the builder job, so maybe it is not what you are looking for, which puzzles me a bit. IMHO having a class that takes care of the simulations and different builder classes that know how to configure that simulation to represent different scenarios is a good design. I would start by having a constructor in the Simulation class that takes all the parameters a simulation needs and then let each specific builder pass the constructor arguments according to the specific simulation needs. If the parameters are too many then you may consider that there is something that you are not modeling and the Simulation class is having more than one responsibility (see SRP). In that case you may want to refactor the Simulation class, but again, it is hard to tell without looking at the code :(. Could you post some snippets?
HTH
I don't know much about the subject matter, or your design, so I can't comment totally on what you're trying to achieve (more snippets please) but it sounds like you're attempting to hold state (Simulation) in one location and what to do with that state (TaylorGreenVortexFlow) in the other, and are having problems decoupling them when the two need to interact.
Have you fully discarded the idea of inheritance from a common Simulation object? Overriding the timeStep() function to reflect what happens during a Taylor-Green Vortex Flow? This may be your only sensible option if you're using Java due to a lack of proper pass-by-reference.

How to restructure/redesign an ever growing adapter class? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I am working on a game/simulation application that uses multiple mathematical solvers. There is an already existing adapter class for each of them. These adapter classes provide all rendering and functional information for the application.
Broadly speaking, we keep an adapter object to represent an instance and call methods to achieve:
Generate rendering data.
modify object state. There are just too many function to do it.
read data model information for various purposes.
Now the problem is that these classes keep growing over a period of time and carry too much information and responsibility.
My question is how can I redesign/restructure these classes to make better sense. Is there any design pattern I should be looking at?
Edit: As requested, here is the broad list of things any adapter class will be doing.
Sync with the current data stored in mathematical solver.
Sync with the data model of our application. For things like
undo/redo.
Modify object state: Change in shape. This is most important and have
various, more than 50, functions to achieve it. All are self
contained single service call with parameters. I am trying to insert
interfaces and factory here but function signatures are not
compatible.
Get data model information of mathematical solver. Like getChildern
etc.
Change visibility and other graphic property.
The principle to use would be Information Expert from GRASP:
[…] Using the principle of Information Expert, a general approach to assigning responsibilities is to look at a given responsibility, determine the information needed to fulfill it, and then determine where that information is stored. Information Expert will lead to placing the responsibility on the class with the most information required to fulfill it. […]
Though never explicitly mentioned, applying this principle will likely lead you to using the patterns given by Martin Fowler in the chapter Moving Features Between Objects in his Refactoring book:
[…] Often classes become bloated with too many responsibilities. In this case I use Extract Class to separate some of these responsibilities. If a class becomes too irresponsible, I use Inline Class to merge it into another class. If another class is being used, it often is helpful to hide this fact with Hide Delegate. Sometimes hiding the delegate class results in constantly changing the owner’s interface, in which case you need to use Remove Middle Man […]
In general, break down your classes so that each only has one reason to change, per the Single Responsibility Principle. Leave your "adapters" in place as a Facade over the classes you'll extract; it will make the refactor smoother.
Since you describe a list of responsibilities that are common to all your adapters, you probably have a lot of code that is almost the same between the adapters. As you go through this exercise, try extracting the same responsibility from several adapters, and watch for ways to eliminate duplication.
It would be tempting to start with extracting a class for "Modify Object state". Since you have more than 50 (!) functions fulfilling that responsibility, you should probably break that down into several classes, if you can. As this is likely the biggest cause of bloat in your adapter class, just doing it may solve the problem, though it will be important to break it down or you'll just move the God class, instead of simplifying it.
However, this will be a lot of work and it will likely be complex enough that you won't easily see opportunities for reuse of the extracted classes between adapters. On the other hand, extracting small responsbilities won't get you a lot of benefit. I would pick something in the middle to start.

Bad practice to use 5 different method parameters? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I have two buttons that each can perform two different implementations (whether selected or not), so that's 4 possible implementations in total. After coding it all out, I noticed I had 20+ lines of code for each implementation and only 1 or 2 variables were different in each. I decided I want to clean this up and have each implementation call separate, smaller methods and pass the inconsistent variables as parameters.
I figure this is a better practice b/c I'm reusing code. However, in one of my methods I have to pass 5 different arguments implement the method with correct conditions.
Is having this many parameters in a method a bad practice?
Having many parameters is not necessary a bad thing.
There are patterns that create a class to group all the parameters into one object that may seem cleaner to you. Another alternative is to use a dictionary for with all the parameters as the single configuration parameter. Some of Apples classes does this (for example title font configuration in the navigation bar).
I personally would say that code repetition is worse than many methods calling each other and having multiple parameters.
If it allow you to remove many duplicate lines, I don't see any problem to do it this way.
If it's to remove 1 or 2 lines then it might not worth the effort.
In fact you can pass as many arguments as needed. There might be other ways to do what you what to achieve but without the code your 5 arguments seems valid at first glance.
There is no specific number of parameters that is generally "bad practice". A method should have as many parameters as it needs. That said, there are cases where having a large number of parameters may indicate that a better design might be possible. For example, there are cases where you may realize an object should be tracking some value in a member variable instead of having the value passed into its methods every time.
I think it's okay to use 5 params because some objective-c default method are also having 4 params like
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(updateConvMenu:)
notificationName:#"NSConvertersChanged"
object:converterArray];
What we can do to make it more clear is giving a better format to your code
disclaimer: I know zilch about objective c
It is difficult to say without seeing the code in question, and it completely depends on what you are doing. To say that having a method with five parameters is bad practice right off the bat is a bit presumptive, although it is certainly good practice to keep the number of method parameters as small as possible.
The fact that this method sounds like an internal 'helper' method (and not a publicly exposed component of an API) gives you more lee-way then you might otherwise have, but typically you do not want to be in a situation where a method is doing different things based on some arcane combination of parameters.
When I run into methods with uncomfortably long signatures that cannot be restructured without creating redundant code, I typically do one of the following:
wrap the offensive method with several more concise methods. You might create, as an example, a method for each of your 'implementations', with a good name indicating its purpose that accepts only the arguments needed for that purpose. It would then delegate to the internal, smellier method. The smelly method would only ever be used in your 'implementation specific' wrappers instead of being scattered throughout your code. Using the well named wrappers in its stead, developers will understand your intent without having to decipher the meaning of the parameters.
Create a Class that encapsulates the data needed by the method. If what the method does depends on the state of some system or subsystem, then encapsulate that state! I do this often with 'XXContext' type classes. Now your method can inspect and analyze this contextual data and take the appropriate actions. This is good for refactoring as well. If the method in the future needs more information to accomplish its tasks or implement new functionality, you can add this data to the argument object, instead of having to change every bit of code that uses the method. Only code that needs to make use of the changes will have to supply the the appropriate values to the contextual data.
This is one of those subjective questions that's really hard to answer definitively.
I don't mind a number of parameters in an Objective C method as it can make the API that's being called more clear (and the parameters can be nice & type safe, too).
If you can distill those many functions down to a smaller number of functions (or a "base" function which is called from all the other functions), that's probably also makes for cleaner code that's easier to follow and read. Plus if you make an update to that "base" function, the functionality change will be picked up by all the ways you call your action (that's can also be a good or bad thing, of course).

Is downcasting (i.e. casting to derived type) ALWAYS wrong? [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
What is your perspective on downcasting? Is it ALWAYS wrong, or are there cases where it is acceptable, or even preferable or desired?
Is there some good measure/guideline we can give that tells us when downcasting is "evil", and when it's "ok"/"good"?
(I know a similar question exists, but that question spins out from a concrete case. I'd like to have it answered from a general design perspective.)
No, it's definitely not always wrong.
For example, suppose in C# you have an event handler - that gets given a sender parameter, representing the originator of the event. Now you might hook up that event handler to several buttons, but you know they're always buttons. It's reasonable to cast sender to Button within that code.
That's just one example - there are plenty of others. Sometimes it's just a way around a slightly awkward API, other times it comes out of not being able to express the type within the normal type system cleanly. For example, you might have a Dictionary<Type, object> appropriate encapsulated, with generic methods to add and retrieve values - where the value of an entry is of the type of the key. A cast is entirely natural here - you can see that it will always work, and it's giving more type safety to the rest of the system.
It's never an ideal solution and should be avoided wherever possible - unless the alternative would be worse. Sometimes, it cannot be avoided, e.g. pre-Generics Java's Standard API library had lots of classes (most prominently the collections) that required downcasting to be useful. And sometimes, changing the design to avoid the downcast would complicate it significantly, so that the downcast is the better solution.
An example for "legal" downcasting is Java pre 5.0 where you had to downcast container elements to their concrete type when accessing them. It was unavoidable in that context. This also shows the other side of the question though: if you need to downcast a lot in a given situation, it starts to be evil, so it is better to find another solution without downcasting. That resulted in the introduction of generics in Java 5.
John Vlissides analyzes this issue (aka "Type Laundering") a lot in his excellent book Pattern Hatching (practically a sequel to Design Patterns).