Is there a better way to design this message passing code? - c++

class A was using below two functions to build and send messages 1 & 2
builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
{
}
Now, a new class B is introduced, which would like to do what A was doing in two stages
stage1->prepare
stage2->deliver
I was thinking to extend the builder class like below:
///----
builder::prepareMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareMsg2(msg2_arg1,msg2_arg2)
{
}
builder::deliverMsg1(msg1_arg1)
{
This function, inserts re-calculated msg1_arg1 into the prepared message in stage1
}
builder::deliverMsg2(msg2_arg1)
{
This function, inserts re-calculated msg2_arg1 into the prepared message in stage1
}
// These two functions are still retained for the usage of class A
builder::prepareAndDeliverMsg1(msg1_arg1,msg1_arg2)
{
}
builder::prepareAndDeliverMsg2(msg2_arg1,msg2_arg2)
{
}
//---
I would like to know, if there is any better way of designing this ?

maybe for each message, create your own class and inherit from the base message class?
class TBaseMsg
{
public:
virtual void prepare() = 0;
virtual void deliver() = 0;
}

You can take a look at Decorator design pattern.
http://en.wikipedia.org/wiki/Decorator_pattern

To expand on Darks idea you can have a base class that implements the combined prepare and delivers in terms of the separate functions and allows deriving classes to override those as required:
class base {
virtual bool prepareMsg1() = 0;
virtual bool prepareMsg2() = 0;
virtual bool deliverMsg1() = 0;
virtual bool deliverMsg2() = 0;
bool prepareAndDeliverMsg1(){
prepareMsg1();
deliverMsg1();
}
bool prepareAndDeliverMsg2(msg2_arg1,msg2_arg2){
prepareMsg2();
deliverMsg2();
}
};
You may find that a lot of the functionality from the two derived classes is the same in which case you won't want to use pure virtuals in the base class:
class base {
virtual bool prepareMsg1(args) {//not pure virtual
//do the common stuff
}
};
class derived {
bool prepareMsg1( args ) {
base::prepareMsg1(args);
//code to specailise the message
}
};
It could even be that the base class implments your original class but allows your second class to be derived without having to repeat the common code.

Your solution looks ok to me.

Related

Detecting if we are in child class or base class

I have a problem, and I tried to use RTTI to resolve it.
I have a class Base and children classes (in the example, I show only one Child)
class Base {
virtual void Eval() {
// normal treatment
+
// treatment only for Base instance
}
};
class Child : Base {
void Eval() {
// call Base Eval
Base::Eval();
//other treatment
}
};
The problem, is that in Base::Eval, there are some treatments which I dont't want to execute when I call it from Child.
What I mean, in Child::Eval, when we call the Base::Eval, we want only the normal treatment which is executed.
For this, I thought about RTTI. I don't know if it is the best way to use it, I thought to do something like this:
class Base {
virtual void Eval() {
// normal treatment
+
if (typeid(this).name() == typeid(Base).name()) {
// treatment only for Base instance
}
}
}
The question is: Is it permitted to do that?
Am I obliged to check typeid.name()?
Or would just typeid() be enough?
Situations such as this are almost always an indication of bad design. A base class should not know anything about its derived classes.
If you want to give derived classes an option to customise parts of the base behaviour, use virtual functions and the "template method" design pattern:
class Base
{
public:
virtual void Eval() {
// normal treatment
Eval_CustomisationHook();
}
protected:
virtual void Eval_CustomisationHook()
{
// Do the stuff
}
};
class Child : public Base
{
protected:
virtual void Eval_CustomisationHook()
{} // do nothing
};
Alternatively, you could delegate just the query:
class Base
{
public:
virtual void Eval() {
// normal treatment
if (doOptionalEvalPart()) {
// do it here
}
}
protected:
virtual bool doOptionalEvalPart()
{
return true;
}
};
class Child : public Base
{
protected:
virtual bool doOptionalEvalPart()
{
return false;
}
};
And to answer your original question as well: the correct form would be to compare the std::type_info objects, not their names. And don't forget you'd have to dereference this. So the code would look like this:
if (typeid(*this) == typeid(Base))
This will do what you want it to. But as I've said above, this is most probably not the proper approach.

What design pattern should I use to avoid dummy code here?

I have a base class -
class content
{
private:
int m_data;
public:
int getdbhandle() { return m_sql_db; }
void setData(int data) { m_data = data; }
virtual int getterrestrialServices { qDebug()"This is a dummy interface"; }
};
class telecontent: public content
{
virtual int getterrestrialServices { qDebug()" Real implementation here"; }
};
Now, the class content is instantiated as telecontent, when the product type is tele.
However, when the product type is generic - the dummy interface prints keep coming.
How can I avoid so? Is there any design pattern that forces the base class not to implement the dummy function? I want an efficient way so that only derived class has method. I don't want the base class to have that method. But, I can't modify the caller - code- so that the method is not called. I want the best way to strategically design such that the dummy interface can be avoided.
is there any design pattern that forces the base class not to
implement the dummy function?
Pure virtual allows this:
class content
{
private:
int m_data;
public:
virtual ~content() { }
int getdbhandle() { return m_sql_db; }
void setData(int data) { m_data = data; }
virtual int getterrestrialServices() = 0; // pure virtual
};
This means no one can create instances of content (will cause a compiler error), and so when some one inherits from content they must provide an implementation of getterrestrialServices() (else again, they'll get a compiler error).
What you need is pure virtual like so:
virtual int getterrestrialServices() = 0;
It will force every class the inherits content to implement it and you wont be able to create a content class, only classes the inherit from it so you wont have the dummy prints.

using directive and abstract method

I have a class (let's call it A) the inherits an interface defining several abstract methods and another class there to factor in some code (let's call it B).
The question is, I have an abstract method in the interface that A implements just to call the B version. Is there a way to use the keyword using to avoid writing a dull method like:
int A::method() override
{
return B::method();
}
I tried writing in A using B::method, but I still get an error that A doesn't implement the abstract method from the interface.
Is there a special technique to use in the case or am I just out of luck? (and if so, is there a specific reason why it should be that way?).
Thanks.
edit:
To clarify, the question is, why isn't it possible to just do this:
class A: public Interface, public B {
using B::method;
};
Let's make this clear. You basically have the following problem, right?
struct Interface
{
virtual void method() = 0;
};
struct B
{
void method()
{
// implementation of Interface::method
}
};
struct A : Interface, B
{
// some magic here to automatically
// override Interface::method and
// call B::method
};
This is simply impossible, because the fact that the methods have the same names is irrelevant from a technical point view. In other word's, Interface::method and B::method are simply not related to each other, and their identical names are not more than a coincidence, just like someone else called "Julien" doesn't have anything to do with you just because you share the same first name.
You are basically left with the following options:
1.) Just write the call manually:
struct A : Interface, B
{
virtual void method()
{
B::method();
}
};
2.) Minimise writing work with a macro, so that you can write:
struct A : Interface, B
{
OVERRIDE(method)
};
But I would strongly recommend against this solution. Less writing work for you = more reading work for everyone else.
3.) Change the class hierarchy, so that B implements Interface:
struct Interface
{
virtual void method() = 0;
};
struct B : Interface
{
virtual void method()
{
// implementation of Interface::method
}
};
struct A : B
{
};
if B::method is abstract you cannot call it because is not implemented... has no code.
An example:
class A
{
public:
virtual void method1( ) = 0;
virtual void method2( ){ }
};
class B : public A
{
public:
virtual void method1( ) override
{ return A::method1( ); } // Error. A::method1 is abstract
virtual method2( ) override
{ return A::method2( ); } // OK. A::method2 is an implemented method
}
Even if there were a way to do what you want, in the name of the readability of your code, I would not recommend that.
If you do not put the "B::" before "method" call, when I read that, I would say it is a recursive call.

How to call a function from a derived class in a base class?

I spent hours and hours looking online but none had the same problem as me. Basically, I have a base class called MainShop and it has 3 derived classes which are SwordShop, SpellBookShop and BowShop. I want the base class to be able to call a function from one of the derived classes but no matter what i do, it doesn't seem to work!
Here is my code:
#include "MainShop.h"
//BaseClass cpp
void MainShop::EnterShop(Hero& hero)
{
//Display Choices
switch (choice)
{
//Swords
case 1: SwordShop::soldierShop(hero);//DOES NOT WORK!!
break;
case 2: SpellBookShop::MageShop(hero);//Staffs
break;
case 3: BowShop::ArcherShop(hero);//Bows
break;
default: cout << "Error!, Please try again.";
MainShop::EnterShop(hero);
}
}
I have two other derived classes, but its basically the same concept. I have a function in one of the derived classes and i would like to call it from the base class. This is one my derived classes:
//SwordShop derived cpp
#include "SwordShop.h"
void SwordShop::soldierShop(Hero& hero)
{
/* some code here*/
}
It's not a good design to select specific sub-class instance in super-class methods, e.g., by dynamic_cast, due to runtime overhead, and future maintenance, etc.
You can offload the burden of such switch-case logic to virtual functions which are designed by the language to call a specific instance via base class pointer/reference.
For example:
class MainShop
{
public:
virtual void EnterShop(Hero &hero) = 0;
};
class SwordShop: public MainShop
{
void EnterShop(Hero &hero)
{
soldierShop(hero);
}
};
class SpellBookShop: public MainShop
{
void EnterShop(Hero &hero)
{
MageShop(hero);
}
};
int main()
{
...
MainShop *shop = new SwordShop;
// calling soldierShop
shop->EnterShop(hero);
..
shop = new SpellBookShop;
// calling MageShop
shop->EnterShop(hero);
...
}
I guess you could try something like:
Derived* derived = dynamic_cast<Derived*>(this);
if (derived) {
// this is of Derived type
} else {
// this is of base type but not Derived
}
though as suggested you'd better use virtual function, since its the right use case:
class Base {
public:
virtual void someMethod() = 0;
void anotherMethods() {
someMethod(); // determined by implementation in derived class
}
};
class Derived1 : public Base {
virtual void someMethod() override {
// body
}
};
class Derived2 : public Base {
virtual void someMethod() override {
// body
}
};
Better readability, less error prone, much more sane.
If you need to call EnterShop from any shop object (SwordShop etc.) then overriding a virtual function in the base class is the way to go.
class MainShop
{
...
virtual void process_hero(Hero& hero)
{
// add default implementation or set as pure virtual
}
...
};
void MainShop::EnterShop(Hero& hero)
{
process_hero(hero);
}
class SwordShop: public MainShop
{
public:
void process_hero(hero)
{
soldierShop(hero);
}
};
...
However, it looks to me like you want a manager object to invoke the functions depending on the 'choice' variable. If this is the case, use composition instead of inheritance.
Prefer composition over inheritance?
How about something like this?
Obviously you must implement the .shop() function:
MainShop *ms;
switch(input){
case 1:
ms = new soldierShop(); break;
case 2:
ms = new MageShop(); break
case 3:
ms = new ArcherShop(); break;
}
ms.shop();
There are 2 options usually used to achieve the required functionality:
use dynamic_cast<> to promote this pointer to the desired derived type and call whatever you want if cast succeeds.
use templated base class in conjunction with curiously recurring template pattern - basically, pass the desired derived type as template argument to base class (http://en.wikipedia.org/wiki/Curiously_recurring_template_pattern).

Extending the method pool of a concrete class which is derived by an interface

I had created an interface to abstract a part of the source for a later extension. But what if I want to extend the derived classes with some special methods?
So I have the interface here:
class virtualFoo
{
public:
virtual ~virtualFoo() { }
virtual void create() = 0;
virtual void initialize() = 0;
};
and one derived class with an extra method:
class concreteFoo : public virtualFoo
{
public:
concreteFoo() { }
~concreteFoo() { }
virtual void create() { }
virtual void initialize() { }
void ownMethod() { }
};
So I try to create an Instance of concreteFoo and try to call ownMethod like this:
void main()
{
virtualFoo* ptr = new concreteFoo();
concreteFoo* ptr2 = dynamic_cast<concreteFoo*>(ptr);
if(NULL != ptr2)
ptr2->ownMethod();
}
It works but is not really the elegant way. If I would try to use ptr->ownMethod(); directly the compiler complains that this method is not part of virtualFoo.
Is there a chance to do this without using dynamic_cast?
Thanks in advance!
This is exactly what dynamic_cast is for. However, you can usually avoid using it by changing your design. Since you gave an abstract example, it's hard to judge whether you should be doing things differently.