How to use composition instead of inheritance when dependency injection is involved? - c++

I have a bunch of checkers in my program that I modelled as classes: check the RAM is OK, check the disk is OK, check the temperatures are OK, etc. These checkers have a lot in common, so I modelled them with inheritance: all that is in common goes into a base class CheckerBase that is derived from by specialised classes with checker-specific functionality and dependencies.
However I've often read that composition should be preferred over inheritance, so I'm wondering how this would be done in C++ with composition?
#include <chrono>
#include <iostream>
#include <thread>
#include <vector>
using namespace std;
/** Dependencies of various checkers that I pass in via dependency injection. */
struct ErrorReporter {
void report_error(string myMsg) {
cout << myMsg;
}
};
struct TemperatureSensor {
int get_cpu_temp() { return 42; }
int get_disk_temp() { return 32; }
};
struct DiskStressor {
void stress_disk() { }
};
/** Contains dependencies that are common to all checkers.. */
class CheckerBase {
public:
CheckerBase(ErrorReporter* errReporter ) :
mErrReporter(errReporter) { }
virtual void runTest() = 0;
protected:
ErrorReporter* mErrReporter;
};
/** Needs `TemperatureSensor` dependency. */
class TemperatureChecker : public CheckerBase {
public:
TemperatureChecker(ErrorReporter* errReporter,
TemperatureSensor* tempSensor) :
CheckerBase(errReporter), mTempSensor(tempSensor) { }
void runTest() override {
if (mTempSensor->get_cpu_temp() > 42) {
mErrReporter->report_error("CPU too hot");
}
};
private:
TemperatureSensor* mTempSensor;
};
/** Needs `TemperatureSensor` and `DiskStressor` dependencies. */
class DiskChecker : public CheckerBase {
public:
DiskChecker(ErrorReporter* errReporter, TemperatureSensor* tempSensor,
DiskStressor* diskStressor) :
CheckerBase(errReporter), mTempSensor(tempSensor) { }
void runTest() override {
mDiskStressor->stress_disk();
mTempSensor->get_disk_temp();
if (mTempSensor->get_cpu_temp() > 32) {
mErrReporter->report_error("HDD too hot after strees test");
}
};
private:
TemperatureSensor* mTempSensor;
DiskStressor* mDiskStressor;
};
/** Periodically runs each checker. */
class MasterChecker {
public:
MasterChecker() :
mTempChecker { &mErrReporter, &mTempSensor },
mDiskChecker { &mErrReporter, &mTempSensor, &mDiskStressor },
mAllCheckers({&mTempChecker, &mDiskChecker}) {};
void start() {
// In reality I use a timer that continously runs each checker at
// a certain interval.
while (true) {
for (CheckerBase *checker : mAllCheckers) {
checker->runTest();
}
this_thread::sleep_for(chrono::milliseconds(5000));
}
}
private:
ErrorReporter mErrReporter;
TemperatureSensor mTempSensor;
DiskStressor mDiskStressor;
DiskChecker mDiskChecker;
TemperatureChecker mTempChecker;
vector<CheckerBase*> mAllCheckers;
};
int main() {
MasterChecker master;
master.start();
}
EDIT: Updated to include an approximation of how the checkers are used. A MasterChecker runs all the individual checkers periodically. It has a list of the checkers and calls their runTest() member function--which all checkers override from their base class.

... composition should be preferred over inheritance
That means, where you could choose either, prefer composition. In this case, MasterChecker (correctly) composes the various concrete checkers, as your advice recommended.
The fact that the individual checkers inherit/implement an abstract base class isn't a problem, because you can't compose an interface. There's no choice here, and the advice didn't say you should never use inheritance even when composition isn't an alternative.
The case your advice actually warns against is doing something like:
class MasterChecker: public DiskChecker, public TemperatureChecker
where inheritance is abused to aggregate the base class subobjects.
In your case this probably wouldn't work well anyway, at least without changes, due to initialization order and diamond-shaped inheritance reasons.

Related

How to automatically call a method or generate code if a subclass derived from a base class?

I have some classes that describe abilities / behaviours, such as flying, or driving etc. Each of these classes has a specific method that must be called to load some data - For example, Flyable has loadFlyData(), Drivable has loadDriveData(). For each class the method name is unique.
I have many derived classes that may inherit from one or more of these behaviour classes. Each of these derived classes has a method called loadData(), in which we should call all the parent behaviour classes methods such as loadFlyData(), loadDriveData() etc.... Is there a way to automatically generate this method using metaprogramming ? Since there are many derived classes, it may be more maintainable if I can generate these methods using metaprogramming...
Behaviour classes : (An object class may have any of these behaviours, and will have to call that classes "load" method...
class Flyable {
void loadFlyData() {
}
};
class Drivable{
void loadDriveData() {
}
};
All object classes derive from Object:
class Object {
virtual void loadData() {
}
};
A derived class:
class FlyingCar : public Object, public Flyable, public Drivable {
virtual void loadData() override {
// How to automatically generate code so that the next two lines are called:
loadFlyData();
loadDriveData();
}
};
Sure is possible. You'll need however to employ some conventions so the code can be generic. See it live.
#include <iostream>
using namespace std;
struct Flyable{
int loadConcreteData(){
cout << "Flyable\n"; return 0;
}
};
struct Drivable{
int loadConcreteData(){
cout << "Drivable\n"; return 0;
}
};
class Object{
virtual void loadData(){
}
};
template<class ...CS>
struct ConcreteLoader : Object, CS... {
void loadData() override {
int load[] = {
this->CS::loadConcreteData()...
};
}
};
class FlyingCar : public ConcreteLoader<Flyable,Drivable>{
};
int main() {
FlyingCar fc;
fc.loadData();
return 0;
}
Changes that need mentioning:
The return type of each concrete Load function had to be changed. This is to facilitate the "array trick" in expanding the parameter pack.
The names of all the load functions are the same, again for the same reason.
Reason (1) may become obsolete once c++17 and fold expressions roll out.
You can make a free function loadXData() that will become a noop if your class isn't X:
namespace detail
{
void loadFlyData(Flyable* ptr) { ptr->loadFlyData(); }
void loadFlyData(...) {}
void loadDriveData(Drivable* ptr) { ptr->loadDriveData(); }
void loadDriveData(...) {}
}
class FlyingCar : public Object, public Flyable, public Drivable{
public:
virtual void loadData()override{
//How to automatically generate code so that the next two lines are called:
detail::loadFlyData(this);
detail::loadDriveData(this);
}
};
demo
Though I think using a common name loadData and just calling it for all variadic parents might be preferable:
template<typename... Policies>
struct ComposedType : Object, Policies...
{
virtual void loadData() override {
int arr[] = {
((void)Policies::loadData(), 0)...
};
(void)arr;
}
};
using FlyingCar = ComposedType<Drivable, Flyable>;
demo
The above loadData could be simplified in C++1z:
virtual void loadData() override {
((void)Policies::loadData(), ...);
}
demo

C++, a number of classes derive from a class, all the derived classes use a class derived from something else but their base uses that clase's base

I'm sorry the title is so nasty, it's very hard to explain
class BaseState {
protected:
BaseState();
public:
void Some();
void Useful();
void Methods();
};
class UsefulState: public BaseState {
public:
void moreUsefulStuff();
};
class SomeUsefulBase {
protected:
SomeUsefulBase(BaseState* pState) { state = pState; }
void UsefulMethods() { state->Some(); }
void Andthings() { state->Useful(); }
public:
virtual void doSomething() = 0;
protected:
BaseState* state;
};
class SomethingUseful: public SomeUsefulBase {
public:
SomethingUseful(UsefulState* pState): SomeUsefulBase(pState) {
usefulState = pState;
}
virtual void doSomething() { usefulState->moreUsefulStuff();}
protected:
UsefulState* usefulState;
};
then:
SomethingUseful whatever(new UsefulState());
It's not important where things are allocated but there will be a lot of classes derived from SomethingUseful that will use a UsefulState however, all the member functions of SomeUsefulBase will use the state, but as a BaseState
I am hoping there is a better way than using two members (UsefulState and BaseState pointers in the definitions), I've thought of a union and a template, but that would be ugly.
I also don't want to litter my code with casts, I'm wondering if there is a nicer notation.
There will be one UsefulState per operation, and a large tree structure will be formed of various subclasses of SomethingUseful and/or subclasses of SomethingUsefulBase where a UsefulState pointer is expected.
Addendum:
Not sure what's up with SO's syntax highlighting! It seems to be using case to decide if it wants to colour things blue or not.... not sure how that works.
Addendum 2:
In the use this example is derived from there is one state per operation but many things derived from SomeUsefulBase, the derived classes will create each other to form a large tree structure (god I sound noobish) but will all require the use of the derived state.
That sounds like the standard "abstract factory"-type situation:
struct AbstractGadget { virtual ~AbstractGadget() {} };
struct AbstractWidget { virtual ~AbstractWidget() {} };
struct AbstractThingy { virtual ~AbstractThingy() {} };
struct AbstractFactory
{
virtual ~AbstractFactory() {}
virtual std::unique_ptr<AbstractGadget> make_gadget() = 0;
virtual std::unique_ptr<AbstractGadget> make_widget() = 0;
virtual std::unique_ptr<AbstractGadget> make_thingy() = 0;
};
Usage:
struct Gadget1 : AbstractGadget { /* ... */ };
struct Widget1 : AbstractWidget { /* ... */ };
struct Thingy1 : AbstractThingy { /* ... */ };
struct Factory1 : AbstractFactory
{
virtual std::unique_ptr<AbstractGadget> make_gadget()
{
return { new Gadget1; }
}
// ...
};
And so forth for Factory2 and Widget3 etc. There's plenty of potential for eliminating boilerplate code with templates here, too.
Consumers might be given an AbstractFactory & f and call f.make_gadget() etc. to create objects of a suitable type.

Several C++ classes need to use the same static method with a different implementation

I need several C++ classes to have a static method "register", however the implementation of register varies between those classes.
It should be static because my idea is to "register" all those classes with Lua (only once of course).
Obviously I can't declare an interface with a static pure virtual function. What do you guys suggest me to do ? Simplicity is welcome, but I think some kind of template could work.
Example of what I would like to achieve
class registerInterface
{
public:
static virtual void register() = 0; //obviously illegal
};
class someClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua
}
}
class someOtherClass: public registerInterface
{
static virtual void register()
{
//I register myself with Lua in a different way
}
}
int main()
{
someClass::register();
someOtherClass::register();
return 0;
}
Based on how you've described the problem, it's unclear to me why you even need the 'virtual static method' on the classes. This should be perfectly legal.
class SomeClass {
static void register(void) {
...
}
}
class SomeOtherClass {
static void register(void) {
...
}
}
int main(int argc, char* argv[]) {
SomeClass::register();
SomeOtherClass::register();
return 0;
}
Drop the RegisterInterface, I don't think you need it.
If it helps, you could take Hitesh's answer, and add:
struct luaRegisterManager {
template <typename T>
void registrate() {
T::registrate();
// do something else to record the fact that we've registered -
// perhaps "registrate" should be returning some object to help with that
}
};
Then:
int main() {
luaRegisterManager lrm;
lrm.registrate<someClass>();
lrm.registrate<someOtherClass>();
}
More generally, if you want to introduce any dynamic polymorphism in C++, then you need an object, not just a class. So again, perhaps the various register functions should be returning objects, with some common interface base class registeredClass, or classRegistrationInfo, or something along those lines.
Could provide an example of what you feel it is that you need dynamic polymorphism for? Hitesh's code precisely matches your one example, as far as I can see, so that example must not cover all of your anticipated use cases. If you write the code that would be using it, perhaps it will become clear to you how to implement it, or perhaps someone can advise.
Something else that might help:
#include <iostream>
#include <string>
#include <vector>
struct Registered {
virtual std::string name() = 0;
virtual ~Registered() {}
Registered() {
all.push_back(this);
}
static std::vector<Registered*> all;
};
std::vector<Registered*> Registered::all;
typedef std::vector<Registered*>::iterator Iter;
template <typename T>
struct RegisteredT : Registered {
std::string n;
RegisteredT(const std::string &name) : n(name) { T::registrate(); }
std::string name() { return n; }
// other functions here could be implemented in terms of calls to static
// functions of T.
};
struct someClass {
static Registered *r;
static void registrate() { std::cout << "registering someClass\n"; }
};
Registered *someClass::r = new RegisteredT<someClass>("someClass");
struct someOtherClass {
static Registered *r;
static void registrate() { std::cout << "registering someOtherClass\n"; }
};
Registered *someOtherClass::r = new RegisteredT<someOtherClass>("someOtherClass");
int main() {
for (Iter it = Registered::all.begin(); it < Registered::all.end(); ++it) {
std::cout << (*it)->name() << "\n";
}
}
There are all sorts of problems with this code if you try to split it across multiple compilation units. Furthermore, this kind of thing leads to spurious reports from memory leak detectors unless you also write some code to tear everything down at the end, or use a vector of shared_ptr, Boost pointer vector, etc. But you see the general idea that a class can "register itself", and that you need an object to make virtual calls.
In C++ you usually try to avoid static initialisation, though, in favour of some sort of setup / dependency injection at the start of your program. So normally you would just list all the classes you care about (calling a function on each one) rather than try to do this automatically.
Your intentions are noble, but your solution is inkling towards "overengineering" (unless I am missing an obvious solution).
Here is one possibility: You can use the Virtual Friend function idiom For example,
class RegisterInterface{
friend void register(RegisterInterface* x){x->do_real_register();}
protected:
virtual void do_real_register();
}
class Foo : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
class Bar : public RegisterInterface{
protected:
virtual void do_real_register(){}
};
int main(int argc, char* argv[]) {
BOOST_FOREACH(RegisterInterface* ri, registered_interfaces)
{
register(ri);
}
return 0;
}
I know you've already accepted an answer, but I figured I would write this up anyway. You can have self-registering classes if you use some static initialization and the CRTP:
#include <vector>
#include <iostream>
using namespace std;
class RegisterableRoot // Holds the list of functions to call, doesn't actually need
// need to be a class, could just be a collection of globals
{
public:
typedef void (*registration_func)();
protected:
static std::vector<registration_func> s_registery;
public:
static void do_registration()
{
for(int i = 0; i < s_registery.size(); ++i)
s_registery[i]();
}
static bool add_func(registration_func func) // returns something so we can use it in
// in an initializer
{
s_registery.push_back(func);
return true;
}
};
template<typename RegisterableType> // Doesn't really need to inherit from
class Registerable : public RegisterableRoot // RegisterableRoot
{
protected:
static const bool s_effect;
};
class A : public Registerable<A> // Honestly, neither does A need to inherit from
// Registerable<T>
{
public:
static void Register()
{
cout << "A" << endl;
}
};
class B : public Registerable<B>
{
public:
static void Register()
{
cout << "B" << endl;
}
};
int main()
{
RegisterableRoot::do_registration();
return 0;
}
std::vector<RegisterableRoot::registration_func> RegisterableRoot::s_registery;
template <typename RegisterableType> // This is the "cute" part, we initialize the
// static s_effect so we build the list "magically"
const bool Registerable<RegisterableType>::s_effect = add_func(&RegisterableType::Register);
template class Registerable<A>; // Explicitly instantiate the template
// causes the equivalent of
// s_registery.push_back(&A::Register) to
// be executed
template class Registerable<B>;
This outputs
A
B
although I wouldn't rely on this order if I were you. Note that the template class Registerable<X> need not be in the same translation unit as the call to do_registration, you can put it with the rest of your definition of Foo. If you inherit from Registerable<> and you don't write a static void Register() function for your class you'll get a (admittedly probably cryptic) compiler error much like you might expect if there really was such a thing as "static virtuals". The "magic" merely adds the class specific function to the list to be called, this avoids several of the pitfalls of doing the actual registration in a static initializer. You still have to call do_registration for anything to happen.
How about this way? Define an interface class:
// IFoobar.h
class IFoobar{
public:
virtual void Register(void) = 0;
}
Then define the class that handles the register..
// RegisterFoobar.h
class RegisterFoobar{
public:
// Constructors etc...
IFoobar* fooBar;
static void RegisterFoobar(IFoobar& fubar){
foobar = &fubar;
}
private:
void Raise(void){ foobar->Register(); }
}
Now, then define another class like this
// MyFuBar.h
class MyFuBar : IFoobar{
public:
// Constructors etc...
void Register(void);
private:
RegisterFoobar* _regFoobar;
}
Call the code like this:
//MyFuBar.cpp
MyFuBar::MyFuBar(){
_regFoobar = new Foobar();
_regFoobar->RegisterFoobar(this);
}
void MyFuBar::Register(void){
// Raised here...
}
Maybe I have misunderstood your requirements...

Resolving a Forward Declaration Issue Involving a State Machine in C++

I've recently returned to C++ development after a hiatus, and have a question regarding
implementation of the State Design Pattern. I'm using the vanilla pattern, exactly as
per the GoF book.
My problem is that the state machine itself is based on some hardware used as part of
an embedded system - so the design is fixed and can't be changed. This results in a
circular dependency between two of the states (in particular), and I'm trying to
resolve this. Here's the simplified code (note that I tried to resolve this by using
headers as usual but still had problems - I've omitted them in this code snippet):
#include <iostream>
#include <memory>
using namespace std;
class Context
{
public:
friend class State;
Context() { }
private:
State* m_state;
};
class State
{
public:
State() { }
virtual void Trigger1() = 0;
virtual void Trigger2() = 0;
};
class LLT : public State
{
public:
LLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class ALL : public State
{
public:
ALL() { }
void Trigger1() { new LLT(); }
void Trigger2() { new DH(); }
};
// DL needs to 'know' about DH.
class DL : public State
{
public:
DL() { }
void Trigger1() { new ALL(); }
void Trigger2() { new DH(); }
};
class HLT : public State
{
public:
HLT() { }
void Trigger1() { new DH(); }
void Trigger2() { new DL(); }
};
class AHL : public State
{
public:
AHL() { }
void Trigger1() { new DH(); }
void Trigger2() { new HLT(); }
};
// DH needs to 'know' about DL.
class DH : public State
{
public:
DH () { }
void Trigger1() { new AHL(); }
void Trigger2() { new DL(); }
};
int main()
{
auto_ptr<LLT> llt (new LLT);
auto_ptr<ALL> all (new ALL);
auto_ptr<DL> dl (new DL);
auto_ptr<HLT> hlt (new HLT);
auto_ptr<AHL> ahl (new AHL);
auto_ptr<DH> dh (new DH);
return 0;
}
The problem is basically that in the State Pattern, state transitions are made by
invoking the the ChangeState method in the Context class, which invokes the
constructor of the next state.
Because of the circular dependency, I can't invoke the constructor because it's
not possible to pre-define both of the constructors of the 'problem' states.
I had a look at this article, and the template method which seemed to be the ideal solution - but it doesn't compile and my knowledge of templates is a rather limited...
The other idea I had is to try and introduce a Helper class to the subclassed states,
via multiple inheritance, to see if it's possible to specify the base class's constructor
and have a reference to the state subclasse's constructor. But I think that was rather
ambitious...
Finally, would a direct implmentation of the Factory Method Design Pattern be the best way
to resolve the entire problem?
You can define the member functions outside of the class definitions, e.g.,
class DL : public State
{
public:
void Trigger2();
};
inline void DL::Trigger2() { new DH(); }
Define the member functions that rely on later class definitions after those classes are defined. The inline keyword is only necessary if you define the member function outside of the class in the header file.
As an aside, why are you just using new DH() in your functions; you're leaking memory everywhere!

How to Elegantly convert switch+enum with polymorphism

I'm trying to replace simple enums with type classes.. that is, one class derived from a base for each type. So for example instead of:
enum E_BASE { EB_ALPHA, EB_BRAVO };
E_BASE message = someMessage();
switch (message)
{
case EB_ALPHA: applyAlpha();
case EB_BRAVO: applyBravo();
}
I want to do this:
Base* message = someMessage();
message->apply(this); // use polymorphism to determine what function to call.
I have seen many ways to do this which all seem less elegant even then the basic switch statement. Using dyanimc_cast, inheriting from a messageHandler class that needs to be updated every time a new message is added, using a container of function pointers, all seem to defeat the purpose of making code easier to maintain by replacing switches with polymorphism.
This is as close as I can get: (I use templates to avoid inheriting from an all-knowing handler interface)
class Base
{
public:
template<typename T> virtual void apply(T* sandbox) = 0;
};
class Alpha : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyAlpha();
}
};
class Bravo : public Base
{
public:
template<typename T> virtual void apply(T* sandbox)
{
sandbox->applyBravo();
}
};
class Sandbox
{
public:
void run()
{
Base* alpha = new Alpha;
Base* bravo = new Bravo;
alpha->apply(this);
bravo->apply(this);
delete alpha;
delete bravo;
}
void applyAlpha() {
// cout << "Applying alpha\n";
}
void applyBravo() {
// cout << "Applying bravo\n";
}
};
Obviously, this doesn't compile but I'm hoping it gets my problem accross.
Well, after giving in to dynamic_cast and multiple inheritance, I came up with this thanks to Anthony Williams and jogear.net
class HandlerBase
{
public:
virtual ~HandlerBase() {}
};
template<typename T> class Handler : public virtual HandlerBase
{
public:
virtual void process(const T&)=0;
};
class MessageBase
{
public:
virtual void dispatch(HandlerBase* handler) = 0;
template<typename MessageType>
void dynamicDispatch(HandlerBase* handler, MessageType* self)
{
dynamic_cast<Handler<MessageType>&>(*handler).process(*self);
}
};
template<typename MessageType> class Message : public MessageBase
{
virtual void dispatch(HandlerBase* handler)
{
dynamicDispatch(handler, static_cast<MessageType*>(this));
}
};
class AlphaMessage : public Message<AlphaMessage>
{
};
class BravoMessage : public Message<BravoMessage>
{
};
class Sandbox : public Handler<AlphaMessage>, public Handler<BravoMessage>
{
public:
void run()
{
MessageBase* alpha = new AlphaMessage;
MessageBase* bravo = new BravoMessage;
alpha->dispatch(this);
bravo->dispatch(this);
delete alpha;
delete bravo;
}
virtual void process(const AlphaMessage&) {
// cout << "Applying alpha\n";
}
virtual void process(const BravoMessage&) {
// cout << "Applying bravo\n";
}
};
int main()
{
Sandbox().run();
return 0;
}
It looks like you are trying to find some sort of double-dispatch system. Look into the Visitor pattern or other multiple-dispatch systems.
Your Bravo and Alpha classes are actually closures... Too bad C++ does not support them directly.
You could use a member pointer to do this:
typedef void (Sandbox::*SandboxMethod)();
struct BrAlpha {
BrAlpha(SandboxMethod method) : method(method){}
void apply(Sandbox sb){sb->*method();}
};
BrAlpha alpha(&Sandbox::applyAlpha);
BrAlpha bravo(&Sandbox::applyBravo);
(syntax may not be exact, but you know hat I mean)
I don't necessarily have an answer for your design pattern issue (though Modern C++ Design has a lot to say about it), but I do want to address your switch vs inheritance comment.
The problem with that simple swtich statement is maintainability. If that switch statement were in 1 location, then it's probably about the same amount of typing to create classes and inherit, but that switch statement is still a ticking time-bomb awaiting yet another state added without adding a case for it. If you assert the default:, you'll catch it at run time - eventually, but that's very poor. If you setup a bunch of function pointers and compile time assert on the table's size, you're doing better, but that's another level deeper than the switch statement. And this all goes out the window as soon as you have a second place in the code that needs to check state.
It's just that much easier once you have your interface class setup to let the compiler handle all the junk code of switching on states internally. You add the class need not worry about any other code as long as you follow the interface.