Is using an empty base class justified in this example? - c++

I'm writing a Window class which propagates different types of events, listed in
enum Event {WINDOW_ClOSE=0x1, WINDOW_REDRAW=0x2, MOUSE_MOVE=0x4, ...};
to objects which have registered for notification with the window. For each type of event, I have an abstract class which any object must extend in order to allow notification. To react to, say, a MOUSE_MOVE event, my object would inherit from MouseMoveListener, which has a process_mouse_move_event() method which is called by Window. Listening to many events can be combined by extending multiple of these classes, which all inherit from the EventListener base class. To register an object, I would call
void Window::register(EventListener* object, int EventTypes)
{
if(EventTypes&WINDOW_CLOSE)
/* dynamic_cast object to WindowCloseListener*, add to internal list of all
WindowCloseListeners if the cast works, else raise error */
if(EventTypes&MOUSE_MOVE)
/* dynamic_cast object to MouseMoveListener*, add to internal list of all
MouseMoveListeners if the cast works, else raise error */
...
}
This works fine, but my gripe is that EventListener is completely empty and that seems code smelly to me. I know I could avoid this by removing EventListener altogether and having a separate Window::register for each type of event, but I feel that this would blow up my interface needlessly (especially since methods other than register might crop up with the same problem). So I guess I am looking for answers that either say:
"You can keep doing it the way you do, because ..." or
"Introduce the separate Window::register methods anyway, because ..." or of course
"You are doing it all wrong, you should ...".
EDIT:
From the link in Igors comment: What I do above only works if there is at least one virtual member in EventListener for example a virtual destructor, so the class is not technically completely empty.
EDIT 2:
I prematurely accepted n.m.'s solution as one of the type "I'm doing it all wrong". However, it is of the second type. Even if I can call EventListener->register(Window&) polymorphically, Window needs to implement a highly redundant interface (in terms of declared methods) that allows EventListeners to register for selective notification. This is equivalent to my alternative solution described above, only with the additional introduction of the EventListener class for no good reason. In conclusion, the canonical answer seems to be:
Don't do dynamic_cast + empty base class just to avoid declaring many similar functions, it will hurt you when maintaining the code later. Write the many functions.
EDIT 3:
I found a solution (using templates) which is satisfactory for me. It does not use an empty base class any more and it does not exhibit the maintenance problem pointed out by n.m.

object->registerWindow (this, EventTypes);
Of course you need to implement registerWindow for all EventListener heirs. Let them check for event types which are relevant to them.
UPDATE
If this means you need to redesign your code, then you need to redesign your code. Why is it so? Because dynamic_cast is not a proper way to do switch-on-types. It is not a proper way because every time you add a class in your hierarchy, you need to go over and possibly update all switches-by-dynamic-cast in your old code. This becomes very messy and unmaintainable very quickly, and this is exactly the reason why virtual functions were invented.
If you do your switch-on-types with virtual functions, every time you change your hierarchy you have to do... nothing. The virtual call mechanism will take care of your changes.

This is what I ended up doing:
template <int EventType> void register_(EventListener<EventType> Listener)
{
// do stuff with Listener, using more templates
};
It turned out that static polymorphism was better suited for my needs - I just wanted to avoid writing
register_mouse_motion_event(...)
register_keyboard_event(...)
and so on. This approach also nicely eliminates the need for an empty base class.

Related

Programming pattern for components that are toggleable at runtime

I'm wondering if there is some kind of logical programming pattern or structure that I should be using if sometimes during runtime a component should be used and other times not. The obvious simple solution is to just use if-else statements everywhere. I'm trying to avoid littering my code with if-else statements since once the component is toggled on, it will more than likely be on for a while and I wonder if its worth it to recheck if the same component is active all over the place when the answer will most likely not have changed between checks.
Thanks
A brief example of what I'm trying to avoid
class MainClass
{
public:
// constructors, destructors, etc
private:
ComponentClass m_TogglableComponent;
}
// somewhere else in the codebase
if (m_TogglableComponent.IsActive())
{
// do stuff
}
// somewhere totally different in the codebase
if (m_TogglableComponent.IsActive())
{
// do some different stuff
}
Looks like you're headed towards a feature toggle. This is a common occurrence when there's a piece of functionality that you need to be able to toggle on or off at run time. The key piece of insight with this approach is to use polymorphism instead of if/else statements, leveraging object oriented practices.
Martin Fowler details an approach here, as well as his rationale: http://martinfowler.com/articles/feature-toggles.html
But for a quick answer, instead of having state in your ComponentClass that tells observers whether it's active or not, you'll want to make a base class, AbstractComponentClass, and two base classes ActiveComponentClass and InactiveComponentClass. Bear in mind that m_TogglableComponent is currently an automatic member, and you'll need to make it a pointer under this new setup.
AbstractComponentClass will define pure virtual methods that both need to implement. In ActiveComponentClass you will put your normal functionality, as if it were enabled. In InactiveComponentClass you do as little as possible, enough to make the component invisible as far as MainClass is concerned. Void functions will do nothing and functions return values will return neutral values.
The last step is creating an instance of one of these two classes. This is where you bring in dependency injection. In your constructor to MainClass, you'll take a pointer of type AbstractComponentClass. From there on it doesn't care if it's Active or Inactive, it just calls the virtual functions. Whoever owns or controls MainClass is the one that injects the kind that you want, either active or inactive, which could be read by configuration or however else your system decides when to toggle.
If you need to change the behaviour at run time, you'll also need a setter method that takes another AbstractComponentClass pointer and replaces the one from the constructor.

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.

Is there any way to avoid declaring virtual methods when storing (children) pointers?

I have run into an annoying problem lately, and I am not satisfied with my own workaround: I have a program that maintains a vector of pointers to a base class, and I am storing there all kind of children object-pointers. Now, each child class has methods of their own, and the main program may or not may call these methods, depending on the type of object (note though that they all heavily use common methods of the base class, so this justify inheritance).
I have found useful to have an "object identifier" to check the class type (and then either call the method or not), which is already not very beautiful, but this is not the main inconvenience. The main inconvenience is that, if I want to actually be able to call a derived class method using the base class pointer (or even just store the pointer in the pointer array), then one need to declare the derived methods as virtual in the base class.
Make sense from the C++ coding point of view.. but this is not practical in my case (from the development point of view), because I am planning to create many different children classes in different files, perhaps made by different people, and I don't want to tweak/maintain the base class each time, to add virtual methods!
How to do this? Essentially, what I am asking (I guess) is how to implement something like Objective-C NSArrays - if you send a message to an object that does not implement the method, well, nothing happens.
regards
Instead of this:
// variant A: declare everything in the base class
void DoStuff_A(Base* b) {
if (b->TypeId() == DERIVED_1)
b->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
b->DoDerived12Stuff();
}
or this:
// variant B: declare nothing in the base class
void DoStuff_B(Base* b) {
if (b->TypeId() == DERIVED_1)
(dynamic_cast<Derived1*>(b))->DoDerived1Stuff();
else if if (b->TypeId() == DERIVED_2)
(dynamic_cast<Derived2*>(b))->DoDerived12Stuff();
}
do this:
// variant C: declare the right thing in the base class
b->DoStuff();
Note there's a single virtual function in the base per stuff that has to be done.
If you find yourself in a situation where you are more comfortable with variants A or B then with variant C, stop and rethink your design. You are coupling components too tightly and in the end it will backfire.
I am planning to create many different children classes in different
files, perhaps made by different people, and I don't want to
tweak/maintain the base class each time, to add virtual methods!
You are OK with tweaking DoStuff each time a derived class is added, but tweaking Base is a no-no. May I ask why?
If your design does not fit in either A, B or C pattern, show what you have, for clairvoyance is a rare feat these days.
You can do what you describe in C++, but not using functions. It is, by the way, kind of horrible but I suppose there might be cases in which it's a legitimate approach.
First way of doing this:
Define a function with a signature something like boost::variant parseMessage(std::string, std::vector<boost::variant>); and perhaps a string of convenience functions with common signatures on the base class and include a message lookup table on the base class which takes functors. In each class constructor add its messages to the message table and the parseMessage function then parcels off each message to the right function on the class.
It's ugly and slow but it should work.
Second way of doing this:
Define the virtual functions further down the hierarchy so if you want to add int foo(bar*); you first add a class that defines it as virtual and then ensure every class that wants to define int foo(bar*); inherit from it. You can then use dynamic_cast to ensure that the pointer you are looking at inherits from this class before trying to call int foo(bar*);. Possible these interface adding classes could be pure virtual so they can be mixed in to various points using multiple inheritance, but that may have its own problems.
This is less flexible than the first way and requires the classes that implement a function to be linked to each other. Oh, and it's still ugly.
But mostly I suggest you try and write C++ code like C++ code not Objective-C code.
This can be solved by adding some sort of introspection capabilities and meta object system. This talk Metadata and reflection in C++ — Jeff Tucker demonstrates how to do this using c++'s template meta programming.
If you don't want to go to the trouble of implementing one yourself, then it would be easier to use an existing one such as Qt's meta object system. Note that this solution does not work with multiple inheritance due to limitations in the meta object compiler: QObject Multiple Inheritance.
With that installed, you can query for the presence of methods and call them. This is quite tedious to do by hand, so the easiest way to call such a methods is using the signal and slot mechanism.
There is also GObject which is quite simmilar and there are others.
If you are planning to create many different children classes in different files, perhaps made by different people, and also I would guess you don't want to change your main code for every child class. Then I think what you need to do in your base class is to define several (not to many) virtual functions (with empty implementation) BUT those functions should be used to mark a time in the logic where they are called like "AfterInseart" or "BeforeSorting", Etc.
Usually there are not to many places in the logic you wish a derived classes to perform there own logic.

Which is better: Function overriding or passing a function pointer for event handling

So, I'm writing code for a class that will go into a library that will be used by others. This class will intercept and process incoming messages (details are not important but it's using the activemq-cpp library). The outline of this consumer class is
class MessageConsumer {
...
public:
void runConsumer();
virtual void onMessage(const Message* message);
}
where runConsumer() sets up the connection and starts listening and onMessage() is called when a message is received.
My questions is this: People who'll use this code will each have their own way of processing the different messages. How can I keep MessageConsumer generic but offer this flexibility, while keeping their code simple?
Two options:
Should they inherit a new class from MessageConsumer and write their own onMessage()?
Should they pass a pointer to a message handling function to MessageConsumer?
What do you think, which option is better and why?
Thanks!
In one approach, clients are allowed to register a callback and then the MessageConsumer invokes the registered callback. This is something like an observer/broadcast design pattern.
The second approach, where clients have to inherit and override MessageConsumer would be something like Strategy design pattern.
Basic design goals suggest to use the weakest relationship to promote loose coupling. Since inhertiance is a stronger relationship as compared to a simple association, everything else being the same Approach 1 is preferred.
From Herb's article
"Inheritance is often overused, even
by experienced developers. Always
minimize coupling: If a class
relationship can be expressed in more
than one way, use the weakest
relationship that's practical. Given
that inheritance is nearly the
strongest relationship you can express
in C++ (second only to friendship),
it's only really appropriate when
there is no equivalent weaker
alternative."
But as James points out, it is tough to comment unless the overall design constraints are known clearly.
Inheritance will make your library more OO-friendly and may improve readability. But really, the choices are about the same since the compiler will check that the user has supplied the function (assuming you declare a pure virtual handler in the base class), and the underlying mechanism will be accomplished via a pointer anyway (virtual table in the case of inheritance).
Pure virtual functions allow the compiler to check that the client code implements the handler. Virtual dispatch is active immediately after an object is constructed, and someone looking at the derived class can reason accurately about its handling. Data needed for the handling can be conveniently and clearly grouped into the derived class. Factories can still select a particular derived class to instantiate.
Function pointers are run-time state, so there's a little more care needed to initialise them in a timely fashion, for optional run-time checks on their being set and error handling, and to reason about which set is in effect during program execution. With that comes more freedom to vary them within the lifetime of the object.
A third alternative is a template policy class, or the Curiously Recurring Template Pattern, to lock in the behaviours at compile time. This potentially allows inlining of callbacks, dead-code elimination and other optimisations.
virtual function or tepmlated functor are the way to go. These approaches give greater flexibility ad looser coupling than function pointer one.
To illustrate that - function pointer approach can be wrapped with first two, but not vice-versa.
void cbFunction();
class Interface {
virtual void act() =0 ;
};
class CbFuctionWrapper:public Interface {
public:
virtual void act() {cbFunction()};
};
class AnotherImpl: public Interface {
Context _c; // You can't pass additional context with usual function without downcasting, but OO is all about that.
public:
virtual void act() {...}
}

Best way to organize a class hierarchy including an overridable "Update" function

I have a base class "Foo" that has an Update() function, which I want to be called once per frame for every instance of that class. Given an object instance of this class called "foo", then once per frame I will call foo->Update().
I have a class "Bar" derived from my base class, that also needs to update every frame.
I could give the derived class an Update() function, but then I would have to remember to call its base::Update() function - nothing enforces my requirement that the base::Update() function is called because I have overriden it, and could easily just forget to (or choose not to) call the base:Update function.
So as an alternative I could give the base class a protected OnUpdate() function, which could be made overrideable, and call it from the base::Update() function. This removes the onus on me to remember to call base::Update() from the derived update function because I'm no longer overriding it. A Bar instance called "bar" will have bar->Update() called on it; this will first call the base class' Update() method, which will in turn call the overriden OnUpdate() function, performing the derived class' necessary updates.
Which solves everything. Except. What if I want to derive yet another updatable class, this time from the "Bar" class.
Baz (which derives from Bar) also has update requirements. If I put them in Baz's OnUpdate() function, I'm back to the original problem in that I'd have to remember to tell Baz's OnUpdate() function to call Bar's OnUpdate() function, otherwise Bar's OnUpdate() function wouldn't get called.
So really, I'd want Bar's OnUpdate() function to be non-overridable, and instead for it to call an overridable function after it has done whatever it needed to do, perhaps called OnUpdate2()...
And if I wanted to derive yet another class? OnUpdate3? OnUpdate4? AfterUpdate?
Is there a Better Way?
Further Info:
My specific problem domain is a 3d world. I've decided my base class is a "Locator" (an object with a location and orientation).
My first derived class is a "PhysicsObject" - a Locator that also has mass, velocity, collision information, etc.
My next derived class is a "Camera" - which derives from PhysicsObject. As well as position, and velocity, it also has information about the viewport, depth of field, etc.
MattK suggests simplifying the hierarchy - if a Locator is never referred to, incorporate it into PhysicsObject.
I'm also thinking about how I would go about turning the layout upside down and using composition instead of inheritance.
Perhaps a Camera HAS physics properties.
Perhaps a PhysicsObject HAS a location.
I'll have to think some more about this problem.
I like Uri's approach: "Observe the contract." Here's the rule - please follow it. Uri is right in that whatever kind of safeguards I try to put in, anyone could circumvent them, so perhaps in this case, the simplest solution is best. All my update() functions are going to have the requirement of calling their base::update() function.
Thanks for the help everyone!
Sounds like you want composition instead of inheritance. What if there was an interface IUpdateable, and Foo held a collection of IUpdateable objects, and called an Update method on each one every tick? Then Bar and Baz could just implement Update; your only worry would be how best to register them with Foo.
Based on your further info: You might want to consider your main object being analagous to your PhysicsObject, and using composition to include objects that implement specific behaviors, such as those of the Camera object.
That's a great question, I've encountered it many many times.
Unfortunately, there are at present no language mechanisms that I am familiar with for mainstream languages like C++ to do that, though I expect (at least in the future) for Java to have something with annotations.
I've used a variety of techniques including what you've suggested, each with pros and cons. Convulted approaches are not always worth the cost.
My view today is that if you really need to use inheritance (rather than composition), as it sounds here, then it is better to go for the elegant solution and observe the written contract. I admit, it's dangerous, but there are risks to the other approaches as well.
Generally speaking people are more careful reading the documentation of an overridden method than they are of a method they are using. In other words, while you would want to avoid "surprising" the user of your class, and can't count on him reading docs, you can count a little more on that in the case of inheritance, especially if you are the only user.
If you are presenting an API function and you expect many other individuals to override your subclass, you could put all kinds of sanity checks to ensure that the method was called, but in the end, you have to rely on the contract, just as so many standard library classes do.
I think that what you want is not easily doable with a class hierarchy.
One possible solution is to use a library that handle signal/slots (I've use sigslot http://sigslot.sourceforge.net/).
In the base class you declare a signal.
class Base : has_slots<> {
public:
Base() { SignalUpdate.connect(this, &Base::OnUpdate); }
void Update() { SignalUpdate.emit(); }
void OnUpdate() { cout << "Base::OnUpdate" << endl; }
private:
signal0<> SignalUpdate;
};
Now on each "derived" class you connect such signal with you own method
class Derived : public Base {
public:
Derived() { SignalUpdate.connect(this, &Derived::OnDerivedUpdate); }
void OnDerivedUpdate() { cout << "Derived::OnDerivedUpdate" << endl; }
};
(Note that this class no longer need to be a derivated from Base).
Now each time Update is called all methods that are connected will be called.
There are other framework that implement a similar behavior: boost signals, qt slots, libsigc++. You should try to take a look at these an see if they fit your needs.