Nested Class - Good Design? - oop

I have a problem where I have a main class which solves a numerical problem. For simplicity, assume that it solves Ax=b. Now, I want the user the ability to choose the method to solve it. There are thousands of options and each option has thousands of options within it.
My idea was to design it as follows: create a main class and then create subclasses for each method and subsubclasses for the details of each methods (which might interact via inheritance).
For instance, I envisage the user to do something like-
Model.method='CG' Model.preconditioning=off and then Model.Solve and in the Model class, there is a CG subclass which runs. Within CG there are methods CG_Precond and CG_NoPrecond which run depending on the preconditioning being on or off. (Assume that the methods are wildly different). So, in essence, the user is running Model.CG.CG_NoPrecond.
Is this good design? Should nested classes be avoided?
One important note is that other than the Model class, all of the subclasses contain only methods and no data of their own (other than what is returned).
I spent some time reading some really beautiful answers on SO and my problem ( I believe) aligns with the requirements of the accepted answer of Why/when should you use nested classes in .net? Or shouldn't you?.

First, you should create a class Solver and use the Strategy Pattern to create subclasses which represent the different methods to solve the problem.
The options and suboptions are a harder thing to do right. If i got you right, then CG_Precond and CG_NoPrecond should be subclasses of a CG (which is also a subclass of Solver) as they seem to share some inner logic.
If the options are like predefined values for the different methods where each method requires other values and type of values, then becomes more difficult. There i would like you to present some more examples of options, suboptions and so on.

Related

Tips on how to balance Polymorphism/Inheritance/TypeData architecture with Prototype/Flyweight pattern in a complex card game?

I am trying to develop a card game with Kotlin, but I feel like the complex architecture decisions I feel I have to make are stalling my process.
I would like to create a solid and flexible foundation for potentially dozens of different cards with different effects, of different types (e.g. spell, vehicle, weapon...).
Intuitively I feel like giving each different Card its own subclass would be ridiculous for several reasons, such as the loss of flexibility (can't (without crazy hacks) create new kinds of cards dynamically) and escalating complexity.
On the other hand, there will be different categories of cards (types) which generally have more in common with each other than cards - so it feels like I should definitely subclass Card because otherwise I would end up with Type enums (SPELL, WEAPON, VEHICLE...) and ugly switch-statements replacing what's usually dealt with by inheritance and polymorphism.
I initially had problems conceiving how to access specific behaviors of subclasses who live in collections of superclasses, but I now understand how I can solve this using the visitor pattern - all fine so far.
My problem now is this architectural approach seems to conflict with other things I have planned and which I consider necessary or at least very worthwhile to have:
Hybrid of Prototype-Flyweight-Pattern:
I have created a 'cyclopedia' of prototype cards that can be copied. Cards consist of a shared static part and a unique dynamic part:
Naturally, I would like to create subinstances of the identifying components in the following manner:
Doing this doesn't seem to be possible in a satisfying way no matter how I approach it. There are many solutions but all seem like weak compromises to me:
Doing it the way I described it means subclasses have to save
multiple references to their components; a baseclass and one subclass
one for each. It also leads to an ugly situation where type
attributes are spread over several component-classes all dependent on
each other.
Using interfaces instead of inheritance leads to loads of code duplication.
Subclassing only the components but not card itself hides type information in the innards of cards and also demands ugly reflection
for accessing subclass traits.
Implementing a data-equivalent of type-information instead of subclassing to circumvent the limiting rules of Kotlin inheritance
hierarchies seems to be hacky and removes IDE support.
I am sure there are even more approaches I have considered over the course of the last two weeks, but these are all I can remember right now.
I know that you probably would require more complete information on what I am planning to do to give me concrete answers, but since it's too complex and I don't know all about where this is going either, I am satisfied with rough ideas in the sense of 'consider this' or 'whatever you are doing, stay away from this' or general advice about how to deal with such a 'design crysis' where things seem so complex you don't know how to start.
Of course I am ready to elaborate or detail parts of my description if it becomes necessary.
Just thinking here.
What about creating a BaseCard class with Card low-level common parts, then a class for each category that inherits from BaseCard, named like Category, where you store each category common parts, and then classes CardofSomeType inheriting from its respective Category. So in a CardofSomeType you inherit anything relevant from either class, and you just add new Card(s)ofSomeType(s) to extend your set.
About what data is instance specific or shared in the class, that's orthogonal to this and an implementation detail of each class.

How to separate your code from specific customer code?

I have the following design problem:
I have many lines of object oriented source code (C++) and our customers want specific changes to our code to fit their needs. Here a very simplified example:
void somefunction() {
// do something
}
The function after I inserted the customer wishes:
void somefunction() {
// do something
setFlag(5000);
}
This looks not so bad, but we have many customers which want to set their own flag values on many different locations in the code. The code is getting more and more messy. How can I separate these customer code from my source code? Is there any design pattern?
One strategy to deal with this is to pull the specifics "up" from this class to the "top", where it can be setup or configured properly.
What I mean is:
Get the concrete settings out of the class. Generalize, make it a parameter in the constructor, or make different subclasses or classes, etc.
Make all the other objects that depend on this depend on the interface only, so they don't know about these settings or options.
On the "top", in the main() method, or some builders or factories where everything is plugged together, there you can plug in the exact parameters or implementations you need for the specific customer.
I'm afraid there is no (correct) way around refactoring these classes to pull all of these specifics into one place.
There are workarounds, like getting configuration values at all of these places, or just creating different branches for the different versions, but these do not really scale, and will cause maintenance problems in my experience.
This is a pretty general question, so the answer will be quite general. You want your software to be open for extensions, but closed for modifications. There are many ways to achieve this with different degrees of openness, from simple ones like parameters to architecture-level frameworks and patterns. Many of the design patterns, e.g. Template method, Strategy deal with these kinds of issues. Essentially, you provide hooks or placeholders in your code were you can plug-in custom behavior.
In modern C++, some of these patterns, or their implementation with explicit classes, are a bit dated and can be replaced with lambda functions instead. There are also numeruous examples in standard libraries, e.g the use of allocators in STL containers. The allocator let's you, as a customer of the STL, change the way memory is allocated and deallocated.
To limit the uncontrolled writing of code, you should consider to expose to your customer a strong base class(in the form of interface or abstract class) with some(or all) methods closed to modification.
Then, every customer will extend the base class behaviour implementing or subclassing it. Briefly, in my thought, to every customer corresponds a subclass CustomerA, CustomerB, etc.. in this way you'll divide the code written by every customer.
In my opinion, the base class methods open to modification should be a very limited set or, better, none. The added behaviour should stay only in the added methods in the derived class, if possible; in this way, you'll avoid the uncontrolled modification of methods that mustn't be modified.

Extending a class hierarchy

Recently, I've found a puzzling (to me) problem: Let's say I have a hierarchy of classes C1...C_n. Assume that at least some classes have more than one (direct) child class, but none have more than one parent (i.e. no multiple inheritance). I would like to change the hierarchy's behaviour. My first impulse would be to create subclasses D1...Dn and override methods as necessary, but there is one problem: when calling a newly overridden method, an actual Di may need to be passed as a formal D1 (or some level in between); this can be solved by subclassing C1 -> D1 -> D2 .... But when calling an unchanged method, any actual Di will need to be passed as a formal Ci, so we would have to derive each Di directly from Ci. Is there any elegant or generally accepted way to solve this riddle? If so, is there any way without resorting to multiple inheritance?
If there is no general way to achieve this, can the author of the original C hierarchy follow certain rules to provide this possibility?
For those who prefer a more practical approach, the original hierarchy implements SOAP in Ada. I am working on XML-RPC. From an abstract point of view, SOAP is a superset to XML-RPC, but the actual XML "on the wire" is quite different. In principle, one can perform most of the work by throwing away some of the data types (e.g. XML-RPC has one integer and one floating point type whereas SOAP has several of each), and replacing the routines that convert the remaining types to and from XML.
However, due to the aforementioned inheritance problems, I ended up copying almost the entire SOAP hierarchy. The only code I've been able to re-use properly turned out to be the HTTP part (as it is not concerned only with text payloads, not with SOAP objects).
[Edit: Removed a simplifying assumption that would allow for a simple solution not applicable to the more general problem]
The solution, because you assume single inheritance, and direct subclass relationships, is to just create D(1) as a subclass of C(n), in which case all Ds will also be in every C class.
In practice, the solution is not to create deep class hierarchies for no reason. If you're really into small classes, then use a system which accommodates multiple inheritance in some form.

How do I refactor a class with lots of operations which all require its internal data?

My Problem
I have a class with just a few fields but which represents a relatively complicated data structure. This class is central in my program and over time I found myself adding more and more functionality into it, making things a mess. Since (almost) all of its methods rely on its internal fields, I could not think of a way to move some of the methods elsewhere, even though most methods are independent of each other. How can I refactor this class to make it simpler and reduce the number of methods which are directly implemented in it?
More Information
The class in question represents a sort of automaton. It supports a ton of operations such as retrieving information about it, performing various binary operations between it and other automata, querying for specific information stored inside it, saving it to file, etc. Almost all of these operations depend on the precise implementation of the class - in my specific case I maintain an edge-set-based implementation, but other implementations were also used in the past and might be used again in the future.
Except for a narrow set of basic helper methods which are commonly used, most methods are independent of each other.
The language I am using is Java, but I'm hoping for general answers which could be applied to any statically-typed, object-oriented language.
What I've Tried
I tried refactoring it somehow to multiple types, but each of its operations require access to most of its fields, and I'm hesitant about migrating these operations elsewhere because I can't think of a way to do that without exposing the class's implementation.
I'm also not sure where I should migrate the operations to, assuming they are indeed independent of the implementation. An external utility class? An abstract base type? Will appreciate any input about this.
Perhaps you could remodel the data that your class holds, so that instead of holding the data directly, it holds objects that hold the data? Then you could move the methods that manipulate that data into the new classes, leaving the original class as a sort of container / dispatcher class.

Abstract design / patterns question

I had a bunch of objects which were responsible for their own construction (get properties from network message, then build). By construction I mean setting frame sizes, colours, that sort of thing, not literal object construction.
The code got really bloated and messy when I started adding conditions to control the building algorithm, so I decided to separate the algorithm to into a "Builder" class, which essentially gets the properties of the object, works out what needs to be done and then applies the changes to the object.
The advantage to having the builder algorithm separate is that I can wrap/decorate it, or override it completely. The object itself doesn't need to worry about how it is built, it just creates a builder and 'decorates' the builder with extra the functionality that it needs to get the job done.
I am quite happy with this approach except for one thing... Because my Builder does not inherit from the object itself (object is large and I want run-time customisation), I have to expose a lot of internal properties of the object.
It's like employing a builder to rebuild your house. He isn't a house himself but he needs access to the internal details, he can't do anything by looking through the windows. I don't want to open my house up to everyone, just the builder.
I know objects are supposed to look after themselves, and in an ideal world my object (house) would build itself, but I am refactoring the build portion of this object only, and I need a way to apply building algorithms dynamically, and I hate opening up my objects with getters and setters just for the sake of the Builder.
I should mention I'm working in Obj-C++ so lack friend classes or internal classes. If the explanation was too abstract I'd be happy to clarify with something a little more concrete. Mostly just looking for ideas or advice about what to do in this kind of situation.
Cheers folks,
Sam
EDIT: is it a good approach to declare a
interface House(StuffTheBuilderNeedsAccessTo)
category inside Builder.h ? That way I suppose I could declare the properties the builder needs and put synthesizers inside House.mm. Nobody would have access to the properties unless they included the Builder header....
That's all I can think of!
I would suggest using Factory pattern to build the object.
You can search for "Factory" on SO and you'll a get a no. of questions related to it.
Also see the Builder pattern.
You might want to consider using a delegate. Add a delegate method (and a protocol for the supported methods) to your class. The objects of the Builder class can be used as delegates.
The delegate can implement methods like calculateFrameSize (which returns a frame size) etc. The returned value of the delegate can be stored as an ivar. This way the implementation details of your class remain hidden. You are just outsourcing part the logic.
There is in fact a design pattern called, suitable enough, Builder which does tries to solve the problem with creating different configurations for a certain class. Check that out. Maybe it can give you some ideas?
But the underlying problem is still there; the builder needs to have access to the properties of the object it is building.
I don't know Obj-C++, so I don't know if this is possible, but this sounds like a problem for Categories. Expose only the necessary methods to your house in the declaration of the house itself, create a category that contains all the private methods you want to keep hidden.
What about the other way around, using multiple inheritance, so your class is also a Builder? That would mean that the bulk of the algorithms could be in the base class, and be extended to fit the neads of you specific House. It is not very beautiful, but it should let you abstract most of the functionality.