Creating classes to represent different permutations of a type - c++

Suppose I have a class structure like (simplifying the actual classes I have):
class Graph
{
};
class DerivedGraph : public Graph
{
};
class DerivedGraph2 : public Graph
{
};
I want to expand this structure to account for different variations of the same graph. Ideally I would like to be able to do something like:
class Graph
{
};
// Removed
//class DerivedGraph : public Graph
//{
//};
// Removed
//class DerivedGraph2 : public Graph
//{
//};
class DerivedGraph3 : public Graph // really just a mode of DerivedGraph
{
};
class DerivedGraph4 : public Graph // really just a second mode of DerivedGraph
{
};
class DerivedGraph5 : public Graph // really just a mode of DerivedGraph2
{
};
class DerivedGraph6 : public Graph // really just a second mode of DerivedGraph2
{
};
But you can quickly see the problem here -- I am having to create too many classes here. Also, the base class is extremely complex and large (the bottom line is that it just plain sucks) ... so I don't want to make too many structural changes. I want the flexibility of defining things at the level of just the graph itself but at the same time have the flexibility of defining things for a particular mode of one graph type. I would like to be able to use virtual functions such as DoesGraphSupportNormalizedData() or something like that (this is just a simple example). Each class would then override this method.
Another idea I had was to create a separate class structure for the modes themselves (the Graph class would create an instance of it), like:
class BaseMode
{
};
class Mode1 : public BaseMode
{
};
class Mode2 : public BaseMode
{
};
Now the problem is that these mode classes need access to several pieces of data from the Graph class ... and I really don't want to pass all of that information. The mode class would then become just as useless and wouldn't be flexible at all. I just can't think of a clean way to deal with this. The best I could come up with is to have the mode classes do what it can without having to pass all kinds of crap to it but now the interface is just goofy and awkward. Any ideas?

You can either user and interface or use inherited classes from what I can gather from your description.
If you use a base-class and inherit off of it just have the things you don't want derived classes to have just give them the private access modifier and then protected or public for the others (depending on the situation of course). That way your derived classes only take what information they need. You could also have a instance variable that needs to be set in each of lower classes to define things about each derived class. Access modifiers are your friends.
If you use an interface just include everything each graph will need and then when building the individual classes just customize them from there to include the specialties.
If it were up to me, personally, I would go with inheritance over an interface but that's just me.

I ran in this kind of a problem before (and still now and then...)
In this case, you may be taking it the wrong way, what you're looking into is device a specialized function depending on the type of graph and mode. Inheritance is nice, but it has its limits as you mentioned. Especially because the user may want to switch the type of graph, but keep is existing graph object. Inheritance is not helpful in that case.
One way to do something like this is to create functions that get called depending on the current type and mode. Say you have to draw lines and the mode can be set to LINE or DOTS. You could have two functions that draw a line and are specific to a mode or another:
void Graph::draw_line_line(line l)
{
// draw a line
}
void Graph::draw_line_dots(line l)
{
// draw a dots along the line
}
Now you can define a type which represents that type of render functions and a variable member for it:
typedef void (Graph::*draw_line_func)(line l);
draw_line_func m_draw_line;
With that in hands, you can program your set_mode() function, something like this:
void Graph::set_mode(mode_t mode)
{
m_mode = mode; // save for get_mode() to work
switch(mode)
{
case LINE:
m_draw_line = &Draw::draw_line_line;
break;
case DOTS:
m_draw_line = &Draw::draw_line_dots;
break;
...
}
}
Now when you want to render the line, you do call this specialized function and you do not need to know whether it is a LINE or a DOTS...
void Graph::draw_line(line l)
{
this->*m_draw_line(l);
}
This way you create an indirection and make it a lot cleaner in the existing large functions that have large switch or many if() statements without breaking up the existing "powerful" class in many pieces that may become hard to use (because if it's that big it's probably already in use...)

Related

c++ particle system inheritance

i'm creating particle system and i want to have possibility to choose what kind of object will be showing on the screen (like simply pixels, or circle shapes). I have one class in which all parameters are stored (ParticleSettings), but without those entities that stores points, or circle shapes, etc. I thought that i may create pure virtual class (ParticlesInterface) as a base class, and its derived classes like ParticlesVertex, or ParticlesCircles for storing those drawable objects. It is something like that:
class ParticlesInterface
{
protected:
std::vector<ParticleSettings> m_particleAttributes;
public:
ParticlesInterface(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
const std::vector<ParticleSettings>& getParticleAttributes() { return m_particleAttributes; }
...
}
and :
class ParticlesVertex : public ParticlesInterface
{
private:
std::vector<sf::Vertex> m_particleVertex;
public:
ParticlesVertex(long int amount = 100, sf::Vector2f position = { 0.0,0.0 });
std::vector<sf::Vertex>& getParticleVertex() { return m_particleVertex; }
...
}
So... I know that i do not have access to getParticleVertex() method by using polimorphism. And I really want to have that access. I want to ask if there is any better solution for that. I have really bad times with decide how to connect all that together. I mean i was thinking also about using template classes but i need it to be dynamic binding not static. I thought that this idea of polimorphism will be okay, but i'm really need to have access to that method in that option. Can you please help me how it should be done? I want to know what is the best approach here, and also if there is any good answer to that problem i have if i decide to make that this way that i show you above.
From the sounds of it, the ParticlesInterface abstract class doesn't just have a virtual getParticleVertex because that doesn't make sense in general, only for the specific type ParticlesVertex, or maybe a group of related types.
The recommended approach here is: Any time you need code that does different things depending on the actual concrete type, make those "different things" a virtual function in the interface.
So starting from:
void GraphicsDriver::drawUpdate(ParticlesInterface &particles) {
if (auto* vparticles = dynamic_cast<ParticlesVertex*>(&particles)) {
for (sf::Vertex v : vparticles->getParticleVertex()) {
draw_one_vertex(v, getCanvas());
}
} else if (auto* cparticles = dynamic_cast<ParticlesCircle*>(&particles)) {
for (CircleWidget& c : cparticles->getParticleCircles()) {
draw_one_circle(c, getCanvas());
}
}
// else ... ?
}
(CircleWidget is made up. I'm not familiar with sf, but that's not the point here.)
Since getParticleVertex doesn't make sense for every kind of ParticleInterface, any code that would use it from the interface will necessarily have some sort of if-like check, and a dynamic_cast to get the actual data. The drawUpdate above also isn't extensible if more types are ever needed. Even if there's a generic else which "should" handle everything else, the fact one type needed something custom hints that some other future type or a change to an existing type might want its own custom behavior at that point too. Instead, change from a thing code does with the interface to a thing the interface can be asked to do:
class ParticlesInterface {
// ...
public:
virtual void drawUpdate(CanvasWidget& canvas) = 0;
// ...
};
class ParticlesVertex {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
class ParticlesCircle {
// ...
void drawUpdate(CanvasWidget& canvas) override;
// ...
};
Now the particles classes are more "alive" - they actively do things, rather than just being acted on.
For another example, say you find ParticlesCircle, but not ParticlesVertex, needs to make some member data updates whenever the coordinates are changed. You could add a virtual void coordChangeCB() {} to ParticlesInterface and call it after each motion model tick or whenever. With the {} empty definition in the interface class, any class like ParticlesVertex that doesn't care about that callback doesn't need to override it.
Do try to keep the interface's virtual functions simple in intent, following the Single Responsibility Principle. If you can't write in a sentence or two what the purpose or expected behavior of the function is in general, it might be too complicated, and maybe it could more easily be thought of in smaller steps. Or if you find the virtual overrides in multiple classes have similar patterns, maybe some smaller pieces within those implementations could be meaningful virtual functions; and the larger function might or might not stay virtual, depending on whether what remains can be considered really universal for the interface.
(Programming best practices are advice, backed by good reasons, but not absolute laws: I'm not going to say "NEVER use dynamic_cast". Sometimes for various reasons it can make sense to break the rules.)

Treating a subclass differently / avoiding code-duplication

I'm wondering how to avoid code-duplication in a scenario as given below.
(There's this question:
How do I check if an object's type is a particular subclass in C++?
The answer there is that it's not possible and even with dynamic casts member access wouldn't be possible, I guess.)
So I'm wondering how you avoid having almost the same code in different methods, where just one method would have a few additional operations.
class Basic {
...
}
class Advanced : public Basic {
...
}
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
if (*basic is actually of class Advanced)
// do one or a few specific things with members of Advanced
// more processing just using Basic
if (*basic is actually of class Advanced)
// do one or a few specific things with members of Advanced
// more processing just using Basic
}
Also from a design perspective AnotherClass::lengthy_method wouldn't want to be defined in Basic or Advanced since it's not really belonging to either of them. It's just operating on their kind.
I'm curious what the language experts know and I hope there's a nice solution, maybe at least through some functionality from C++11.
dynamic_cast can be used here, as long as the Advanced members you want to access are declared as public, or AnotherClass is declared as a friend of Advanced:
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
Advanced *adv = dynamic_cast<Advanced*>(basic);
if (adv != NULL) {
// use adv as needed...
}
// more processing just using Basic
if (adv != NULL) {
// use adv as needed...
}
// more processing just using Basic
}
Another option is to use polymorphism instead of RTTI. Expose some additional virtual methods in Basic that do nothing, and then have Advanced override them:
class Basic {
...
virtual void doSomething1() {}
virtual void doSomething2() {}
}
class Advanced : public Basic {
...
virtual void doSomething1();
virtual void doSomething2();
}
void Advanced::doSomething1() {
...
}
void Advanced::doSomething2() {
...
}
AnotherClass::lengthy_method(Basic *basic) {
// do a lot of processing, access members of basic
// do one or a few specific things with members of Advanced
basic->doSomething1();
// more processing just using Basic
// do one or a few specific things with members of Advanced
basic->doSomething2();
// more processing just using Basic
}

c++ composition (has-a) issue

One important and essential rule I have learnt as a C++ programmer is the preference of Composition over Inheritance (http://en.wikipedia.org/wiki/Composition_over_inheritance).
I totally agree with this rule which mostly makes things much more simple than It would be if we used Inheritance.
I have a problem which should be solved using Composition but I'm really struggling to do so.
Suppose you have a Vendor Machine, and you have two types of products:
Discrete product - like a snack.
Fluid product - like a drink.
These two types of products will need to be represented in a class called VendorCell which contains the cell content.
These two products share some identical attributes(dm) as Price, Quantity and so on...BUT also contain some different attributes.
Therefore using Composition here might lead for the following result:
class VendorCell {
private : // default access modifier
int price;
int quantity;
// int firstProductAttributeOnly
// char secondProductAttributeOnly
};
As you can see the commented lines show that for a single VendorCell depending on the product it containing, only one of these two commented lines will be significant and useable (the other one is only relevant for the other type - fluid for example).
Therefore I might have a VendorCell with a snack inside and its secondProductAttributeOnly is not needed.
Is composition (for the VendorCell) is the right solution? is It seems proper to you guys that someone will determine the VendorCell type via a constructor and one DM (the DM dedicated for the other type) will not be used at all (mark it as -1 for example) ?>
Thanks you all!
Your general rule of favoring composition over inheritance is right. The problem here is that you want a container of polymorphic objects, not a giant aggregate class that can hold all possible products. However, because of the slicing problem, you can't hold polymorphic objects directly, but you need to hold them by (preferably smart) pointer. You can hold them directly by (smart) pointer such as
class AbstractProduct { /* price, quauntity interface */ };
class AbstractSnack: public AbstractProduct { /* extended interface */ };
class AbstractDrink: public AbstractProduct { /* extended interface */ };
typedef std::unique_ptr<AbstractProduct> VendorCell;
typedef std::vector< VendorCell > VendorMachine;
You simply define your snacks/drinks by deriving from AbstractSnack/AbstractDrink
class SnickersBar: public AbstractSnack { /* your implementation */ };
class CocaColaBottle: public AbstractDrink { /* your implementation */ };
and then you can insert or extract products like this:
// fill the machine
VendorMachine my_machine;
my_machine.emplace_back(new SnickersBar());
my_machine.emplace_back(new CocaColaBottle());
my_snack = my_machine[0]; // get a Snickers bar
my_drink = my_machine[1]; // get a Coca Cola bottle;
There are also other solutions such as Boost.Any that uses a wrapper class that internally holds a pointer to a polymorphic object. You could also refactor this code by replacing the typedef with a separate class VendorMachine that holds a std::vector< VendorCell >, so that you can get a nicer interface (with money exchange functionality e.g.)
You inherit in order to be re-used.
You compose in order to re-use.
If you have different attributes then you probably want to inherit, otherwise compose.
Some variation:
class ProductVariety {
public:
virtual void display(Screen& screen) = 0;
};
An implementation:
class Liquid : public ProductVariety {
public:
virtual void display(Screen& screen) {
//...
}
}
Composing variation:
class Product
{
int price;
int quantity;
unique_ptr<ProductVariety> variety;
}

how to refactor gui and business logic in C++

I would like to refactor some GUI app, written in C++ and some GUI framework.
There are some dialog classes:
Class MyDialogX : public LibraryBaseDialog { };
Class MyDialogY : public LibraryBaseDialog { };
X, Y – some name, there are several such similar classes
This classes are used for gui stuff and also for some business logic – this violates SRP principle.
I would like to separate those two responsibilities and I’ve decided to create another class that will handle the business logic.
Now we have something like this:
Class MyDialogX : public LibraryBaseDialog
{
BusinesLogic *pLogic; // used to handle logic, called as a response to gui
// change, there is only one such object for all MyDialogX(Y) objects
// ... some other code...
// this method could be moved to constructor as well, only for
// short example here...
void setLogic(BusinesLogic *p) { pLogic = p; }
}
Is this a good way to do such refactoring?
Maybe there are some better options?
Assumptions:
I do not want to make “businessLogic” object as a singleton.
I cannot change LibraryBaseDialog class.
This refactoring should be quite small, so I do not want to redesign whole system J
I could even go further and create some other class:
Class LogicHolder // basic features related
{
BusinesLogic *pLogic;
}
And now MyDialogX will inherit also from this class:
Class MyDialogX : public LibraryBaseDialog, public LogocHolder
{ }
That way it will be easier to manage pLogic among several similar Dialog classes.

supplying dependency through base class

I have a list of Parts and some of them need a pointer to an Engine, lets call them EngineParts. What I want is to find these EngineParts using RTTI and then give them the Engine.
The problem is how to design the EnginePart. I have two options here, described below, and I don't know which one to choose.
Option 1 is faster because it does not have a virtual function.
Option 2 is easier if I want to Clone() the object because without data it does not need a Clone() function.
Any thoughts? Maybe there is a third option?
Option 1:
class Part;
class EnginePart : public Part {
protected: Engine *engine
public: void SetEngine(Engine *e) {engine = e}
};
class Clutch : public EnginePart {
// code that uses this->engine
}
Option 2:
class Part;
class EnginePart : public Part {
public: virtual void SetEngine(Engine *e)=0;
};
class Clutch : public EnginePart {
private: Engine *engine;
public: void SetEngine(Engine *e) { engine = e; }
// code that uses this->engine
}
(Note that the actual situation is a bit more involved, I can't use a simple solution like creating a separate list for EngineParts)
Thanks
Virtual functions in modern compilers (from about the last 10 years) are very fast, especially for desktop machine targets, and that speed should not affect your design.
You still need a clone method regardless, if you want to copy from a pointer-/reference-to-base, as you must allow for (unknown at this time) derived classes to copy themselves, including implementation details like vtable pointers. (Though if you stick to one compiler/implementation, you can take shortcuts based on it, and just re-evaluate those every time you want to use another compiler or want to upgrade your compiler.)
That gets rid of all the criteria you've listed, so you're back to not knowing how to choose. But that's easy: choose the one that's simplest for you to do. (Which that is, I can't say based of this made-up example, but I suspect it's the first.)
Too bad that the reply stating that 'a part cannot hold the engine' is deleted because that was actually the solution.
Since not the complete Engine is needed, I found a third way:
class Part;
class EngineSettings {
private:
Engine *engine
friend class Engine;
void SetEngine(Engine *e) {engine = e}
public:
Value* GetSomeValue(params) { return engine->GetSomeValue(params); }
};
class Clutch : public Part, public EngineSettings {
// code that uses GetSomeValue(params) instead of engine->GetSomeValue(params)
}
Because GetSomeValue() needs a few params which Engine cannot know, there is no way it could "inject" this value like the engine pointer was injected in option 1 and 2. (Well.. unless I also provide a virtual GetParams()).
This hides the engine from the Clutch and gives me pretty much only one way to code it.