How to restructure/redesign an ever growing adapter class? [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 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.

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.

When is it okay to switch statements in an OO language supporting polymorphism? [duplicate]

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.
I recently learned that switch statements are bad in OOP, perticularly from "Clean Code"(p37-39) by Robert Martin.
But consider this scene: I'm writing a game server, receiving messages from clients, which contain an integer that indicates player's action, such as move, attack, pick item... etc, there will be more than 30 different actions. When I'm writing code to handle these messages, no metter what solutions I think about, it will have to use switch somewhere. What pattern should I use if not switch statement?
A switch is like any other control structure. There are places where it's the best/cleanest solution, and many more places where it's completely inappropriate. It's just abused way more than other control structures.
In OO design, it's generally considered preferable in a situation like yours to use different message types/classes that inherit from a common message class, then use overloaded methods to "automatically" differentiate between the different types.
In a case like yours, you could use an enumeration that maps to your action codes, then attach an attribute to each enumerated value that will let you use generics or type-building to build different Action sub-class objects so that the overloading method will work.
But that's a real pain.
Evaluate whether there's a design option such as the enumeration that is feasible in your solution. If not, just use the switch.
'Bad' switch statements are often those switching on object type (or something that could be an object type in another design). In other words hardcoding something that might be better handled by polymorphism. Other kinds of switch statements might well be OK
You will need a switch statement, but only one. When you receive the message, call a Factory object to return an object of the appropriate Message subclass (Move, Attack, etc), then call a message->doit() method to do the work.
That means if you add more message types, only the factory object has to change.
The Strategy pattern comes to mind.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
In this case, the "family of algorithms" are your different actions.
As for switch statements - in "Clean Code", Robert Martin says that he tries to limit himself to one switch statement per type. Not eliminate them altogether.
The reason is that switch statements do not adhere to OCP.
I'd put the messages in an array and then match the item to the solution key to display the message.
From the design patterns perspective you can use the Command Pattern for your given scenario. (See http://en.wikipedia.org/wiki/Command_pattern).
If you find yourself repeatedly using switch statements in the OOP paradigm, this is an indication that your classes may not be well design. Suppose you have a proper design of super and sub classes and a fair amount of Polymorphism. The logic behind switch statements should be handled by the sub classes.
For more information on how you are removed these switch statements and introduce the proper sub-classes, I recommend you read the first chapter of Refactoring by Martin Fowler. Or you can find similiar slides here http://www1.informatik.uni-wuerzburg.de/database/courses/pi2_ss03_dir/RefactoringExampleSlides.pdf. (Slide 44)
IMO switch statements are not bad, but should be avoided if possible. One solution would be to use a Map where the keys are the commands, and the values Command objects with an execute() method. Or a List if your commands are numeric and have no gaps.
However, usually, you would use switch statements when implementing design patterns; one example would be to use a Chain of responsibility pattern to handle the commands given any command "id" or "value". (The Strategy pattern was also mentionned.) However, in your case, you might also look into the Command pattern.
Basically, in OOP, you'll try to use other solutions than relying on switch blocks, which use a procedural programming paradigm. However, when and how to use either is somewhat your decision. I personally often use switch blocks when using the Factory pattern etc.
A definition of code organisation is :
a package is a group of classes with coherant API (ex: Collection API in many frameworks)
a class is a set of coherent functionalities (ex: a Math class...
a method is a functionality; it should do one thing and one thing only. (ex: adding an item in a list may require to enlarge that said list, in which case the add method will rely on other methods to do that and will not perform that operation itself, because it's not it's contract.)
Therefore, if your switch statement perform different kinds of operations, you are "violating" that definition; whereas using a design pattern does not as each operation is defined in it's own class (it's own set of functionalities).
I don't buy it. These OOP zealots seem to have machines that have infinite RAM and amazing performance. Obviously with inifinite RAM you don't have to worry about RAM fragmentation and the performance impacts that has when you continuously create and destroy small helper classes. To paraphrase a quote for the 'Beautiful Code' book - "Every problem in Computer Science can be solved with another level of abstraction"
Use a switch if you need it. Compilers are pretty good at generating code for them.
Use commands. Wrap the action in an object and let polymorphism do the switch for you. In C++ (shared_ptr is simply a pointer, or a reference in Java terms. It allows for dynamic dispatch):
void GameServer::perform_action(shared_ptr<Action> op) {
op->execute();
}
Clients pick an action to perform, and once they do they send that action itself to the server so the server doesn't need to do any parsing:
void BlueClient::play() {
shared_ptr<Action> a;
if( should_move() ) a = new Move(this, NORTHWEST);
else if( should_attack() ) a = new Attack(this, EAST);
else a = Wait(this);
server.perform_action(a);
}

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.

Can't seem to understand SOLID principles and design patterns [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'm trying to get into OOP lately, and I'm having trouble with SOLID principles and design patterns. I see why people use them, and I really want to use them too, but I can't wrap my head around developing my classes to the specifications. I would really appreciate anything that would help my understanding of such.
I've taken a class in college that spent two weeks around design patters, and read the Gang of Four book to no avail. Understanding what each pattern served for and how to use them to fit my problems was very hard for me, a developer that didn't have much experience in OO programming.
The book that really made it click for me was Head First Design Patterns. It starts by showing a problem, different approaches the developers considered, and then how they ended up using a design pattern in order to fix it. It uses a very simple language and keeps the book very engaging.
Design patterns end up being a way to describe a solution, but you don't have to adapt your classes to the solution. Think of them more as a guide that suggest a good solution to a wide array of problems.
Let's talk about SOLID:
Single responsibility. A class should have only one responsibility. That means that for example, a Person class should only worry about the domain problem regarding the person itself, and not for example, its persistence in the database. For that, you may want to use a PersonDAO for example. A Person class may want to keep its responsibilities the shortest it can. If a class is using too many external dependencies (that is, other classes), that's a symptom that the class is having too many responsibilities. This problem often comes when developers try to model the real world using objects and take it too far. Loosely coupled applications often are not very easy to navigate and do not exactly model how the real world works.
Open Closed. Classes should be extendible, but not modifiable. That means that adding a new field to a class is fine, but changing existing things are not. Other components on the program may depend on said field.
Liskov substitution. A class that expects an object of type animal should work if a subclass dog and a subclass cat are passed. That means that Animal should NOT have a method called bark for example, since subclasses of type cat won't be able to bark. Classes that use the Animal class, also shouldn't depend on methods that belong to a class Dog. Don't do things like "If this animal is a dog, then (casts animal to dog) bark. If animal is a cat then (casts animal to cat) meow".
Interface segregation principle. Keep your interfaces the smallest you can. A teacher that also is a student should implement both the IStudent and ITeacher interfaces, instead of a single big interface called IStudentAndTeacher.
Dependency inversion principle. Objects should not instantiate their dependencies, but they should be passed to them. For example, a Car that has an Engine object inside should not do engine = new DieselEngine(), but rather said engine should be passed to it on the constructor. This way the car class will not be coupled to the DieselEngine class.

Switch statements are bad? [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.
I recently learned that switch statements are bad in OOP, perticularly from "Clean Code"(p37-39) by Robert Martin.
But consider this scene: I'm writing a game server, receiving messages from clients, which contain an integer that indicates player's action, such as move, attack, pick item... etc, there will be more than 30 different actions. When I'm writing code to handle these messages, no metter what solutions I think about, it will have to use switch somewhere. What pattern should I use if not switch statement?
A switch is like any other control structure. There are places where it's the best/cleanest solution, and many more places where it's completely inappropriate. It's just abused way more than other control structures.
In OO design, it's generally considered preferable in a situation like yours to use different message types/classes that inherit from a common message class, then use overloaded methods to "automatically" differentiate between the different types.
In a case like yours, you could use an enumeration that maps to your action codes, then attach an attribute to each enumerated value that will let you use generics or type-building to build different Action sub-class objects so that the overloading method will work.
But that's a real pain.
Evaluate whether there's a design option such as the enumeration that is feasible in your solution. If not, just use the switch.
'Bad' switch statements are often those switching on object type (or something that could be an object type in another design). In other words hardcoding something that might be better handled by polymorphism. Other kinds of switch statements might well be OK
You will need a switch statement, but only one. When you receive the message, call a Factory object to return an object of the appropriate Message subclass (Move, Attack, etc), then call a message->doit() method to do the work.
That means if you add more message types, only the factory object has to change.
The Strategy pattern comes to mind.
The strategy pattern is intended to provide a means to define a family of algorithms, encapsulate each one as an object, and make them interchangeable. The strategy pattern lets the algorithms vary independently from clients that use them.
In this case, the "family of algorithms" are your different actions.
As for switch statements - in "Clean Code", Robert Martin says that he tries to limit himself to one switch statement per type. Not eliminate them altogether.
The reason is that switch statements do not adhere to OCP.
I'd put the messages in an array and then match the item to the solution key to display the message.
From the design patterns perspective you can use the Command Pattern for your given scenario. (See http://en.wikipedia.org/wiki/Command_pattern).
If you find yourself repeatedly using switch statements in the OOP paradigm, this is an indication that your classes may not be well design. Suppose you have a proper design of super and sub classes and a fair amount of Polymorphism. The logic behind switch statements should be handled by the sub classes.
For more information on how you are removed these switch statements and introduce the proper sub-classes, I recommend you read the first chapter of Refactoring by Martin Fowler. Or you can find similiar slides here http://www1.informatik.uni-wuerzburg.de/database/courses/pi2_ss03_dir/RefactoringExampleSlides.pdf. (Slide 44)
IMO switch statements are not bad, but should be avoided if possible. One solution would be to use a Map where the keys are the commands, and the values Command objects with an execute() method. Or a List if your commands are numeric and have no gaps.
However, usually, you would use switch statements when implementing design patterns; one example would be to use a Chain of responsibility pattern to handle the commands given any command "id" or "value". (The Strategy pattern was also mentionned.) However, in your case, you might also look into the Command pattern.
Basically, in OOP, you'll try to use other solutions than relying on switch blocks, which use a procedural programming paradigm. However, when and how to use either is somewhat your decision. I personally often use switch blocks when using the Factory pattern etc.
A definition of code organisation is :
a package is a group of classes with coherant API (ex: Collection API in many frameworks)
a class is a set of coherent functionalities (ex: a Math class...
a method is a functionality; it should do one thing and one thing only. (ex: adding an item in a list may require to enlarge that said list, in which case the add method will rely on other methods to do that and will not perform that operation itself, because it's not it's contract.)
Therefore, if your switch statement perform different kinds of operations, you are "violating" that definition; whereas using a design pattern does not as each operation is defined in it's own class (it's own set of functionalities).
I don't buy it. These OOP zealots seem to have machines that have infinite RAM and amazing performance. Obviously with inifinite RAM you don't have to worry about RAM fragmentation and the performance impacts that has when you continuously create and destroy small helper classes. To paraphrase a quote for the 'Beautiful Code' book - "Every problem in Computer Science can be solved with another level of abstraction"
Use a switch if you need it. Compilers are pretty good at generating code for them.
Use commands. Wrap the action in an object and let polymorphism do the switch for you. In C++ (shared_ptr is simply a pointer, or a reference in Java terms. It allows for dynamic dispatch):
void GameServer::perform_action(shared_ptr<Action> op) {
op->execute();
}
Clients pick an action to perform, and once they do they send that action itself to the server so the server doesn't need to do any parsing:
void BlueClient::play() {
shared_ptr<Action> a;
if( should_move() ) a = new Move(this, NORTHWEST);
else if( should_attack() ) a = new Attack(this, EAST);
else a = Wait(this);
server.perform_action(a);
}