C++ construct if satisfies conditions - c++

i have a design issue, not complicated actually, but i would like to find an elegant way to solve it. And i thought about this:
Issue:
i have a class A that initialize and keep a collection of B
B is just an interface and must be implemented (so we have classes C,D,E,..).
in constructor A recive a bunch of dataset and must initialize some of B (also lot of different instantiation of same or different class) given each dataset. I would like A to not to know any implementation of B.
I have several working solution, but i was thinking about a kind of "delegate in the constructor".
eg:
1. for each dataset, ds
2. for each implementation of B, bi
3. try to instantiate bi(ds)
4. if success (means no exception)
5. keep reference
this because the data and calculus i use to check if bi are pretty the same of initialization and being in a performance-critic application i would like to avoid doing that twice or doing it in collection class.
it would be really nice but obviously the problem is line 2...
...as well as the doubt about using exception for something that is not actually an exception. (line 4)
so what should be a pattern that
- let me evaluate data and construct all in one.
- avoid creating several "architectural-classes" i would like to avoid an explosion of classes ( kind of typical when exagerating with following design patterns java-style principles imho ) for such a simple task.
- as fast as possible.
- ...is elegant :)

The answer is based on my intuition right now, so it may not be perfect, but on the other hand, most of the design solutions aren't.
I would create just one additional class, call it factory or something similar. Then run all the constructions through this class. It should be able to be initialized with possible instantiations of derives of B either in run-time (by running callbacks at the beginning of the program), or, even better, by variadic template traits.
template<class ... RegisteredBImplementations>
class CFactory
{
B* Create (dataset const& d)
{
// some magical meta-ifs to create compile time conditions
// or for (auto& registered_type : registered types), and then choose one
return new T(d);
}
}
Then, A could use an instance of this class to initialize it's pointers properly:
for (auto& dataset : datasets)
{
m_BPtrs.emplace_back( std::unique_ptr<dataset> (m_FactoryInstance.Create(dataset)) );
}
The main point of this solution is that class A effectively manages "B" objects, leaving proper construction of them to the other class. They are effectively separated, and addition of a new B implementation means a change only in CFactory, not in A.

Your pseudocode suggests a solution: your use of bi is nothing more than a factory function that takes a dataset as input and returns a B* as output. So, you really just need to take bi from a collection of std::function<B* (dataset)> objects.
It would be easy enough to require that these factories are only 'conditional' factories: that sometimes they return valid objects, and sometimes they don't, returning nullptr instead. This would let you avoid exceptions, and is more faithful to the intent of your usage.

The simplest solution is to delegate to a Factory method.
std::unique_ptr<B> build(DataSet const& ds) {
if (ds.property() == value) {
return std::unique_ptr<B>(new D(ds));
}
return std::unique_ptr<B>(new C(ds));
}
Then A need only depend on the declaration of build.

Related

C++ What's the right way to run, in a superclass constructor, code that relies on lots of variables that the subclass overrides?

Say I have a superclass that, when it initializes, wants to run some code that relies on a whole bunch of class variables that may or may not be overridden by a subclass in its constructor.
What's the accepted, clean way to code that?
I feel like I'm having a brain fart; this should be a standard, beginner usage of inheritance, but I can't figure it out.
e.g. say I have a superclass that represents a vehicle, and when it starts, I want to do a whole bunch of code where it processes, say, the load per axle or something (doesn't matter) but that code uses as inputs a bunch of parameters that exist for all vehicles (and thus exist in the superclass), say weight, length, numwheels, numaxles, maybe even complicated data structures defining how many wheels per axle, etc.).
The various subclasses (sportscar, bigrig, motorcycle), want to set the weight, length, numwheels, numaxles, etc. before the superclass does its processing.
Super::Super() {
Process(var1_,var2_,var3_,var4_, ...);
}
Sub1::Sub1(): Super() {
var1_ = <some math>;
var2_ = <some math>;
...
}
doesn't work because the superclass Process() runs before the vars get set by the subclass. Right?
Super::Super(float var1, WackyDatastructureDef var2, int var3, WackyStruct2 var4, ...),
var1_(var1), var2_(var2), var3_(var3), ............... {
Process(var1_,var2_,var3_,var4_, ...);
}
Sub1::Sub1(): Super(<some math>, <some math>, <some math>, <some math>, ......) {
....
}
looks horrible for obvious reasons. Also, it looks like a pain if I only need to override 2 out of the 20 default variable values.
Super::Super() {}
void Super::Init() {
Process(var1_, var2_, var3_, var4_ ...... );
}
Sub1::Sub1(): Super() {
var1_ = <some math>;
var2_ = <some math>;
...
Init();
}
looks the cleanest but I don't like it... it's weird to have to remember to call Init() at the end of all my subclass constructors. What if another programmer wants to subclass off my superclass and doesn't know my magic rule?
What's the right way to do this?
There are many ways to solve this issue (lack of virtual constructors in C++). Each one has its own benefits and drawbacks. Most common patterns to workaround this limitation:
Pass all required arguments to base class constructor. This can be really annoying if you need more than few parameters. Code will be less and less readable and pretty hard to extend if requirements change. Of course it has a big benefit: it's not a workaround and everyone will understand it.
Change your design (this may be the best thing to do but it may require a lot of work). If you need a lot of parameters then you may pack all arguments in separate class, it'll hold object status. Base class constructor will just accept one parameter of this type and it'll contain its status (or just its initialization data but this is another story). Its benefit is to keep design clear (no workaround like for first solution) but it may involve some complexity if this initialization token will evolve with its own class hierarchy.
Add a public initialization method. Change your Init() method to public, it won't be invoke by derived constructors but by class users. This will allow you to add initialization code in each derived class (and initialization order is then controlled by implementation itself). This method is pretty old school and it requires users will call it but it has one big benefit: it's universally known and it won't astonish anyone. See this post here on SO for a small discussion about them.
Virtual constructor idiom. See this article for a reference. It works as intended and you can make it easier to use with few template methods. IMO biggest disadvantage is that it changes how you manage inheritance and initialization when you create a new derived class. This may be boring and error prone and prolix. Moreover you change how a class is instantiated too and, for me, this is always annoying.
Few notes about second solution (from comments). If you apply this I see at least these options:
Stupid entity (just data, no logic) that holds all required parameters.
Encapsulate object status in a separate object. Object you pass from derived classes is not used and dropped but it'll be part of object.
In both cases you can have or not a parallel hierarchy for parameters (BaseParametersHolder, DerivedParametersHolder and so on). Please note that holder doesn't suffer from same problem of first solution (many arguments) because creation can be delegated to a private function (example is to illustrate concept, code is far to be nice):
class Derived : public Base
{
public:
Derived() : Base(CreateParameters())
{
}
private:
ParameterHolder CreateParameters()
{
ParameterHolder parameters;
parameters.Value = 1;
parameters.AnotherValue = 2;
return parameters;
}
};
What to use? There is not an answer. I'd prefer to be consistent across code (so if you decide to use holders then use them everywhere, do not mix - for example - with v.i. idiom). Just pick proper one each time and try to be consistent.
Pass the relevant information up to the base class constructor.

reducing duplicated methods?

So I'm working on a 2D space simulator and I have the resource manager 'calc' that handles all calculations for everything. For example, from calc.hpp:
var calc::eccentricity (object A, object B);
var calc::distance (object A, object B);
var calc::orbitV (object A, object B);
etc. However, the way I have my program structured is in my calc class I have
private:
object *ship //the currently controlled ship
object *targ //target
object *ref //reference (from which speeds, position, etc. are calculated)
and to use the calculations given in the first example with these, I write three functions for each calculation function, like so:
var calc::ship_ecc (object A){
if(!ship) //catches null pointers
return NAN;
return eccentricity(*ship, A);
}
var calc::ship_ref_ecc (){
if(!ref) //catches null pointers
return NAN;
return ship_ecc(*ref);
}
var calc::ship_targ_ecc (){
if(!targ) //catches null pointers
return NAN;
return ship_ecc(*targ);
}
for eccentricity, and then the same for distance and orbitV. So I end up having four functions for every calculation. As you can see from calc.hpp this makes for plenty of duplicated code. And duplicated code is a Bad Thing.
What my question is
Is there some way to call
calc.ship.targ.eccentricity();
calc.ship.ref.eccentricity(); //or variation thereof
or
calc.ship.targ(eccentricity);
calc.ship.ref(eccentricity); //or variation thereof
instead of
calc.ship_targ_ecc();
calc.ship_ref_ecc();
? I'm wondering if you could do some fancy operator() overloading, or pass a function, or make a friend class in calc. Ideally I should only be able to access lines 31 - 53, which are all public.
Thanks!
EDIT: got an example for yall: https://ideone.com/jypJQS this is what it should output and how it is working now
Maybe this changes too much your current code. But I think that the functions in calc should be members of object. So you could things like :
ship.eccentricity(target);
What confuses me (and what is probably the big problem here) is that you seem to define some hard relations in your calc object (the private members). What are those for ? From the code, I guess there is a calc object for every "ship". If yes, it would be an other reason to add the code to object instead of maintaining 1-1 relations between object and calc.
This might require a little bit of refactoring, but I think it's worth it. For a simple game, you can use OOP and Polymorphism to fix the issue.
First of all, create an object class.
class Object {
public:
Object();
~Object();
};
This object class would be a basis for all your objects in the game (ship, character, etc...). You, then, would create a sub class for your ship.
class Ship : public Object {
};
This would allow an easy expansion to future objects that require the same principle.
In the object class, you would have some basic properties:
physical (optional)
dimensions
speed (last calculated speed)
controlled (bool - current controlling ship or not)
This would eliminate the need to have hard relationships with the calc and ship class.
Next, you would change your calc class to become general. You don't want to depend on a single ship object, this is cumbersome.
Option 1
You could create an instance of the calc class for each object. This calc instance would have access to the already available properties of the object and ship class.
Option 2
Create a general calc class that would require you to pass a reference to the ship/object instance. calc->eccentricity(&ship, target);
Option 3
Within a possible manager class, or a simple "global" variable. You could hold a reference to the currently controlled ship (if that's how your system works, I'm not sure). Or you could store the index of the ship and all instances are held inside a vector<&Ship>.
In a simplistic game, straight forward OOP will suffice, but if you want more decoupling, component based game design would be a better bet (in combination with OOP, of course).
So I took this over to /r/learnprogramming, and I got a good answer from zzyzzyxx (as always). His answer:
What's wrong with simply having functions that take the required two or three parameters? They don't have to be in any special calc class. Maybe a calc namespace. I'm not sure it makes sense with the rest of your design, but what about making it a member function so that anything can calculate what it needs given a target and potentially a reference point if there's no sensible default?
So basically, don't worry about all this calc.eccentricity(A, B), calc.ship_ecc(A), calc.ship_ref_ecc() business, just say
calc.eccentricity(*calc.targ(), B)
Also, don't make calc a singleton, make it a namespace.
I'll go do that now.

C++ design pattern to get rid of if-then-else

I have the following piece of code:
if (book.type == A) do_something();
else if (book.type == B) do_something_else();
....
else do so_some_default_thing.
This code will need to be modified whenever there is a new book type
or when a book type is removed. I know that I can use enums and use a switch
statement. Is there a design pattern that removes this if-then-else?
What are the advantages of such a pattern over using a switch statement?
You could make a different class for each type of book. Each class could implement the same interface, and overload a method to perform the necessary class-specific logic.
I'm not saying that's necessarily better, but it is an option.
As others have pointed out, a virtual function should probably be your first choice.
If, for some reason, that doesn't make sense/work well for your design, another possibility would be to use an std::map using book.type as a key and a pointer to function (or functor, etc.) as the associated value, so you just lookup the action to take for a particular type (which is pretty much how many OO languages implement their equivalent of virtual functions, under the hood).
Each different type of book is a different sub-class of the parent class, and each class implements a method do_some_action() with the same interface. You invoke the method when you want the action to take place.
Yes, it's called looping:
struct BookType {
char type;
void *do();
};
BookType[] types = {{A, do_something}, {B, do_something_else}, ...};
for (int i = 0; i < types_length; i++) {
if (book.type == types[i].type) types[i].do(book);
}
For a better approach though, it's even more preferrable if do_something, do_something_else, etc is a method of Book, so:
struct Book {
virtual void do() = 0;
};
struct A {
void do() {
// ... do_something
}
};
struct B {
void do() {
// ... do_something_else
}
};
so you only need to do:
book.do();
Those if-then-else-if constructs are one of my most acute pet peeves. I find it difficult to conjure up a less imaginative design choice. But enough of that. On to what can be done about it.
I've used several design approaches depending on the exact nature of the action to be taken.
If the number of possibilities is small and future expansion is unlikely I may just use a switch statement. But I'm sure you didn't come all the way to SOF to hear something that boring.
If the action is the assignment of a value then a table-driven approach allows future growth without actually making code changes. Simply add and remove table entries.
If the action involves complex method invocations then I tend to use the Chain of Responsibility design pattern. I'll build a list of objects that each knows how to handle the actions for a particular case.
You hand the item to be processed to the first handler object. If it knows what to do with the item it performs the action. If it doesn't, it passes the item off to the next handler in the list. This continues until the item is processed or it falls into the default handler that cleans up or prints an error or whatever. Maintenance is simple -- you add or remove handler objects from the list.
You could define a subclass for each book type, and define a virtual function do_something. Each subclass A, B, etc would have its own version of do_something that it calls into, and do_some_default_thing then just becomes the do_something method in the base class.
Anyway, just one possible approach. You would have to evaluate whether it really makes things easier for you...
Strategy Design Pattern is what I think you need.
As an alternative to having a different class for each book, consider having a map from book types to function pointers. Then your code would look like this (sorry for pseudocode, C++ isn't at the tip of my fingers these days):
if book.type in booktypemap:
booktypemap[book.type]();
else
defaultfunc();

runtime type comparison

I need to find the type of object pointed by pointer.
Code is as below.
//pWindow is pointer to either base Window object or derived Window objects like //Window_Derived.
const char* windowName = typeid(*pWindow).name();
if(strcmp(windowName, typeid(Window).name()) == 0)
{
// ...
}
else if(strcmp(windowName, typeid(Window_Derived).name()) == 0)
{
// ...
}
As i can't use switch statement for comparing string, i am forced to use if else chain.
But as the number of window types i have is high, this if else chain is becoming too lengthy.
Can we check the window type using switch or an easier method ?
EDIT: Am working in a logger module. I thought, logger should not call derived class virtual function for logging purpose. It should do on its own. So i dropped virtual function approach.
First of all use a higher level construct for strings like std::string.
Second, if you need to check the type of the window your design is wrong.
Use the Liskov substitution principle to design correctly.
It basically means that any of the derived Window objects can be replaced with it's super class.
This can only happen if both share the same interface and the derived classes don't violate the contract provided by the base class.
If you need some mechanism to apply behavior dynamically use the Visitor Pattern
Here are the things to do in order of preference:
Add a new virtual method to the base class and simply call it. Then put a virtual method of the same name in each derived class that implements the corresponding else if clause inside it. This is the preferred option as your current strategy is a widely recognized symptom of poor design, and this is the suggested remedy.
Use a ::std::map< ::std::string, void (*)(Window *pWindow)>. This will allow you to look up the function to call in a map, which is much faster and easier to add to. This will also require you to split each else if clause into its own function.
Use a ::std::map< ::std::string, int>. This will let you look up an integer for the corresponding string and then you can switch on the integer.
There are other refactoring strategies to use that more closely resemble option 1 here. For example,if you can't add a method to the Window class, you can create an interface class that has the needed method. Then you can make a function that uses dynamic_cast to figure out if the object implements the interface class and call the method in that case, and then handle the few remaining cases with your else if construct.
Create a dictionary (set/hashmap) with the strings as keys and the behaviour as value.
Using behaviour as values can be done in two ways:
Encapsulate each behaviour in it's
own class that inherit from an
interface with"DoAction" method that
execute the behavior
Use function pointers
Update:
I found this article that might be what you're looking for:
http://www.dreamincode.net/forums/topic/38412-the-command-pattern-c/
You might try putting all your typeid(...).name() values in a map, then doing a find() in the map. You could map to an int that can be used in a switch statement, or to a function pointer. Better yet, you might look again at getting a virtual function inside each of the types that does what you need.
What you ask for is possible, it's also unlikely to be a good solution to your problem.
Effectively the if/else if/else chain is ugly, the first solution that comes to mind will therefore to use a construct that will lift this, an associative container comes to mind and the default one is obviously std::unordered_map.
Thinking on the type of this container, you will realize that you need to use the typename as the key and associate it to a functor object...
However there are much more elegant constructs for this. The first of all will be of course the use of a virtual method.
class Base
{
public:
void execute() const { this->executeImpl(); }
private:
virtual void executeImpl() const { /* default impl */ }
};
class Derived: public Base
{
virtual void executeImpl() const { /* another impl */ }
};
It's the OO way of dealing with this type of requirement.
Finally, if you find yourself willing to add many different operations on your hierarchy, I will suggest the use of a well-known design pattern: Visitor. There is a variation called Acyclic Visitor which helps dealing with dependencies.

Changing behavior of an object at runtime

How can be changed the behavior of an object at runtime? (using C++)
I will give a simple example. I have a class Operator that contains a method operate. Let’s suppose it looks like this:
double operate(double a, double b){
return 0.0;
}
The user will give some input values for a and b, and will choose what operation to perform let’s say that he can choose to compute addition or multiplication. Given it’s input all I am allowed to do is instantiate Operator and call operate(a, b), which is written exactly how I mentioned before.
The methods that compute multiplication or addition will be implemented somewhere (no idea where).
In conclusion I have to change the behavior of my Operator object depending on the user's input.
The standard pattern for this is to make the outer class have a pointer to an "implementation" class.
// derive multiple implementations from this:
class Implementation
{
virtual ~Implementation() {} // probably essential!
virtual void foo() = 0;
};
class Switcheroo
{
Implementation *impl_;
public:
// constructor, destructor, copy constructor, assignment
// must all be properly defined (any that you can't define,
// make private)
void foo()
{
impl_->foo();
}
};
By forwarding all the member functions of Switcheroo to the impl_ member, you get the ability to switch in a different implementation whenever you need to.
There are various names for this pattern: Pimpl (short for "private implementation"), Smart Reference (as opposed to Smart Pointer, due to the fowarding member functions), and it has something in common with the Proxy and Bridge patterns.
I'm mentioning this only as trivia and can't unrecommend it more, but here we go...
WARNING DANGER!!!
A stupid trick I've seen is called clutching, I think, but it's only for the truely foolish. Basically you swap the virtualtable pointer to that of another class, it works, but it could theoretically destroy the world or cause some other undefined behavior :)
Anyways instead of this just use dynamic classing and kosher C++, but as an experiment the above is kind of fun...
Coplien's Envelope/Letter Pattern (in his must read book Advanced C++ Programming Styles and Idioms) is the classic way to do this.
Briefly, an Envelope and a Letter are both subclasses of an abstract base class/interfcae that defines the public interface for all subclasses.
An Envelope holds (and hides the true type of) a Letter.
A variety of Letter classes have different implementations of the abstract class's public interface.
An Envelope has no real implementation; it just forards (delegates) to its Letter. It holds a pointer to the abstract base class, and points that at a concrete Letter class instance. As the implementation needs to be changed, the type of Letter subclass pointer to is changed.
As users only have a reference to the Envelope, this change is invisible to them except in that the Envelope's behavior changes.
Coplien's examples are particularly clean, because it's the Letters, not the envelope that cause the change.
One example is of a Number class hierarchy. The abstract base declares certain operations over all Numbers, e.g, addition. Integer and a Complex are examples of concrete subclasses.
Adding an Integer and an Integer results in an Integer, but adding a Interget and a Complex results in a Complex.
Here's what the Envelope looks like for addition:
public class Number {
Number* add( const Number* const n ) ; // abstract, deriveds override
}
public class Envelope : public Number {
private Number* letter;
...
Number* add( const Number& rhs) { // add a number to this
// if letter and rhs are both Integers, letter->add returns an Integer
// if letter is a a Complex, or rhs is, what comes back is a Complex
//
letter = letter->add( rhs ) ) ;
return this;
}
}
Now in the client's pointer never changes, and they never ever need to know what the Envelop is holding. Here's the client code:
int main() {
// makeInteger news up the Envelope, and returns a pointer to it
Number* i = makeInteger( 1 ) ;
// makeComplex is similar, both return Envelopes.
Number* c = makeComplex( 1, 1 ) ;
// add c to i
i->add(c) ;
// to this code, i is now, for all intents and purposes, a Complex!
// even though i still points to the same Envelope, because
// the envelope internally points to a Complex.
}
In his book, Coplien goes into greater depth -- you'll note that the add method requires multi-dispatch of some form --, and adds syntactic sugar. But this is the gist of how you can get what's called "runtime polymorphism".
You can achieve it through dynamic binding (polymorphism)... but it all depends on what you are actually trying to achieve.
You can't change the behavior of arbitrary objects using any sane way unless the object was intended to use 'plugin' behaviour through some technique (composition, callbacks etc).
(Insane ways might be overwriting process memory where the function code lies...)
However, you can overwrite an object's behavior that lies in virtual methods by overwriting the vtable (An approach can be found in this article ) without overwriting memory in executable pages. But this still is not a very sane way to do it and it bears multiple security risks.
The safest thing to do is to change the behavior of objects that were designed to be changed by providing the appropriate hooks (callbacks, composition ...).
Objects always have the behaviour that's defined by their class.
If you need different behaviour, you need a different class...
You could also consider the Role Pattern with dynamic binding..i'm struggling with the same thing that you do..I read about the Strategy pattern but the role one sounds like a good solution also...
There are many ways to do this proxying, pImpl idiom, polymorphism, all with pros and cons. The solution that is best for you will depend on exactly which problem you are trying to solve.
Many many ways:
Try if at first. You can always change the behavior with if statement. Then you probably find the 'polymorphism' way more accurate, but it depends on your task.
Create a abstract class, declaring the methods, which behavior must be variable, as virtual.
Create concrete classes, that will implement the virtual methods. There are many ways to achieve this, using design patterns.
You can change the object behavior using dynamic binding. The design patterns like Decorator, Strategy would actually help you to realize the same.