how to refactor gui and business logic in C++ - c++

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

Related

Creating classes to represent different permutations of a type

Suppose I have a class structure like (simplifying the actual classes I have):
class Graph
{
};
class DerivedGraph : public Graph
{
};
class DerivedGraph2 : public Graph
{
};
I want to expand this structure to account for different variations of the same graph. Ideally I would like to be able to do something like:
class Graph
{
};
// Removed
//class DerivedGraph : public Graph
//{
//};
// Removed
//class DerivedGraph2 : public Graph
//{
//};
class DerivedGraph3 : public Graph // really just a mode of DerivedGraph
{
};
class DerivedGraph4 : public Graph // really just a second mode of DerivedGraph
{
};
class DerivedGraph5 : public Graph // really just a mode of DerivedGraph2
{
};
class DerivedGraph6 : public Graph // really just a second mode of DerivedGraph2
{
};
But you can quickly see the problem here -- I am having to create too many classes here. Also, the base class is extremely complex and large (the bottom line is that it just plain sucks) ... so I don't want to make too many structural changes. I want the flexibility of defining things at the level of just the graph itself but at the same time have the flexibility of defining things for a particular mode of one graph type. I would like to be able to use virtual functions such as DoesGraphSupportNormalizedData() or something like that (this is just a simple example). Each class would then override this method.
Another idea I had was to create a separate class structure for the modes themselves (the Graph class would create an instance of it), like:
class BaseMode
{
};
class Mode1 : public BaseMode
{
};
class Mode2 : public BaseMode
{
};
Now the problem is that these mode classes need access to several pieces of data from the Graph class ... and I really don't want to pass all of that information. The mode class would then become just as useless and wouldn't be flexible at all. I just can't think of a clean way to deal with this. The best I could come up with is to have the mode classes do what it can without having to pass all kinds of crap to it but now the interface is just goofy and awkward. Any ideas?
You can either user and interface or use inherited classes from what I can gather from your description.
If you use a base-class and inherit off of it just have the things you don't want derived classes to have just give them the private access modifier and then protected or public for the others (depending on the situation of course). That way your derived classes only take what information they need. You could also have a instance variable that needs to be set in each of lower classes to define things about each derived class. Access modifiers are your friends.
If you use an interface just include everything each graph will need and then when building the individual classes just customize them from there to include the specialties.
If it were up to me, personally, I would go with inheritance over an interface but that's just me.
I ran in this kind of a problem before (and still now and then...)
In this case, you may be taking it the wrong way, what you're looking into is device a specialized function depending on the type of graph and mode. Inheritance is nice, but it has its limits as you mentioned. Especially because the user may want to switch the type of graph, but keep is existing graph object. Inheritance is not helpful in that case.
One way to do something like this is to create functions that get called depending on the current type and mode. Say you have to draw lines and the mode can be set to LINE or DOTS. You could have two functions that draw a line and are specific to a mode or another:
void Graph::draw_line_line(line l)
{
// draw a line
}
void Graph::draw_line_dots(line l)
{
// draw a dots along the line
}
Now you can define a type which represents that type of render functions and a variable member for it:
typedef void (Graph::*draw_line_func)(line l);
draw_line_func m_draw_line;
With that in hands, you can program your set_mode() function, something like this:
void Graph::set_mode(mode_t mode)
{
m_mode = mode; // save for get_mode() to work
switch(mode)
{
case LINE:
m_draw_line = &Draw::draw_line_line;
break;
case DOTS:
m_draw_line = &Draw::draw_line_dots;
break;
...
}
}
Now when you want to render the line, you do call this specialized function and you do not need to know whether it is a LINE or a DOTS...
void Graph::draw_line(line l)
{
this->*m_draw_line(l);
}
This way you create an indirection and make it a lot cleaner in the existing large functions that have large switch or many if() statements without breaking up the existing "powerful" class in many pieces that may become hard to use (because if it's that big it's probably already in use...)

Does cocos2d-x force multiple inheritance?

I have a class,
class Ticket : public cocos2d::CCNode, public cocos2d::CCTargetedTouchDelegate { ... };
Which works fine when I register for touch events on that node using:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
However, if I alter my class so that it uses composition rather than inheritance for the CCNode bit:
class Ticket : public cocos2d::CCTargetedTouchDelegate {
private:
cocos2d::CCNode* node_;
public:
Ticket() { node_ = new CCNode(); node_->init(); }
cocos2d::CCNode* node() { return node_; }
...
};
Then the following blows up with a SIGSEGV 11:
CCDirector::sharedDirector()->getTouchDispatcher()->addTargetedDelegate(ticket_, 0, true);
I have added ticket_->node() to the current layer, but I am wondering if the touch dispatcher somehow doesn't like the node and the delegate to be different things. Or to put it another way, is touch dispatcher is expecting the node and the delegate to be the same thing?
So in short, my code works when I use multiple inheritance, but it doesn't when I use composition. Without delving into the framework, can anyone say that this is true, or have I just missed something obvious? I am using cocos2d-2.1rc0-x-2.1.2
Yes, it seems cocos2d-x indeed does force multiple inheritance. It expects the touch delegate to be dynamically castable to a CCObject, which your Ticket class isn't when you use composition. When you inherit from CCNode, which itself inherits from CCObject, you're in the clear. You can see the problem here on github.
This does not seem to be a mistake though, since the documentation actually hints at this by noting
IMPORTANT: The delegate will be retained.
for CCTouchDispatcher::addTargetedDelegate.

C++ Help on refactoring a monster class

I have a C background and am a newb on C++. I have a basic design question. I have a class (I'll call it "chef" b/c the problem I have seems very analogous to this, both in terms of complexity and issues) that basically works like this
class chef
{
public:
void prep();
void cook();
void plate();
private:
char name;
char dish_responsible_for;
int shift_working;
etc...
}
in pseudo code, this gets implemented along the lines of:
int main{
chef my_chef;
kitchen_class kitchen;
for (day=0; day < 365; day++)
{
kitchen.opens();
....
my_chef.prep();
my_chef.cook();
my_chef.plate();
....
kitchen.closes();
}
}
The chef class here seems to be a monster class, and has the potential of becoming one. chef also seems to violate the single responsibility principle, so instead we should have something like:
class employee
{
protected:
char name;
int shift_working;
}
class kitchen_worker : employee
{
protected:
dish_responsible_for;
}
class cook_food : kitchen_worker
{
public:
void cook();
etc...
}
class prep_food : kitchen_worker
{
public:
void prep();
etc...
}
and
class plater : kitchen_worker
{
public:
void plate();
}
etc...
I'm admittedly still struggling with how to implement it at run time so that, if for example plater (or "chef in his capacity as plater") decides to go home midway through dinner service, then the chef has to work a new shift.
This seems to be related to a broader question I have that if the same person invariably does the prepping, cooking and plating in this example, what is the real practical advantage of having this hierarchy of classes to model what a single chef does? I guess that runs into the "fear of adding classes" thing, but at the same time, right now or in the foreseeable future I don't think maintaining the chef class in its entirety is terribly cumbersome. I also think that it's in a very real sense easier for a naive reader of the code to see the three different methods in the chef object and move on.
I understand it might threaten to become unwieldy when/if we add methods like "cut_onions()", "cut_carrots()", etc..., perhaps each with their own data, but it seems those can be dealt with by having making the prep() function, say, more modular. Moreover, it seems that the SRP taken to its logical conclusion would create a class "onion_cutters" "carrot_cutters" etc... and I still have a hard time seeing the value of that, given that somehow the program has to make sure that the same employee cuts the onions and the carrots which helps with keeping the state variable the same across methods (e.g., if the employee cuts his finger cutting onions he is no longer eligible to cut carrots), whereas in the monster object chef class it seems that all that gets taken care of.
Of course, I understand that this then becomes less about having a meaningful "object oriented design", but it seems to me that if we have to have separate objects for each of the chef's tasks (which seems unnatural, given that the same person is doing all three function) then that seems to prioritize software design over the conceptual model. I feel an object oriented design is helpful here if we want to have, say, "meat_chef" "sous_chef" "three_star_chef" that are likely different people. Moreover, related to the runtime problem is that there is an overhead in complexity it seems, under the strict application of the single responsibility principle, that has to make sure the underlying data that make up the base class employee get changed and that this change is reflected in subsequent time steps.
I'm therefore rather tempted to leave it more or less as is. If somebody could clarify why this would be a bad idea (and if you have suggestions on how best to proceed) I'd be most obliged.
To avoid abusing class heirarchies now and in future, you should really only use it when an is relationship is present. As yourself, "is cook_food a kitchen_worker". It obviously doesn't make sense in real life, and doesn't in code either. "cook_food" is an action, so it might make sense to create an action class, and subclass that instead.
Having a new class just to add new methods like cook() and prep() isn't really an improvement on the original problem anyway - since all you've done is wrapped the method inside a class. What you really wanted was to make an abstraction to do any of these actions - so back to the action class.
class action {
public:
virtual void perform_action()=0;
}
class cook_food : public action {
public:
virtual void perform_action() {
//do cooking;
}
}
A chef can then be given a list of actions to perform in the order you specify. Say for example, a queue.
class chef {
...
perform_actions(queue<action>& actions) {
for (action &a : actions) {
a.perform_action();
}
}
...
}
This is more commonly known as the Strategy Pattern. It promotes the open/closed principle, by allowing you to add new actions without modifying your existing classes.
An alternative approach you could use is a Template Method, where you specify a sequence of abstract steps, and use subclasses to implement the specific behaviour for each one.
class dish_maker {
protected:
virtual void prep() = 0;
virtual void cook() = 0;
virtual void plate() = 0;
public:
void make_dish() {
prep();
cook();
plate();
}
}
class onion_soup_dish_maker : public dish_maker {
protected:
virtual void prep() { ... }
virtual void cook() { ... }
virtual void plate() { ... }
}
Another closely related pattern which might be suitable for this is the Builder Pattern
These patterns can also reduce of the Sequential Coupling anti-pattern, as it's all too easy to forget to call some methods, or call them in the right order, particularly if you're doing it multiple times. You could also consider putting your kitchen.opens() and closes() into a similar template method, than you don't need to worry about closes() being called.
On creating individual classes for onion_cutter and carrot_cutter, this isn't really the logical conclusion of the SRP, but in fact a violation of it - because you're making classes which are responsible for cutting, and holding some information about what they're cutting. Both cutting onions and carrots can be abstracted into a single cutting action - and you can specify which object to cut, and add a redirection to each individual class if you need specific code for each object.
One step would be to create an abstraction to say something is cuttable. The is relationship for subclassing is candidate, since a carrot is cuttable.
class cuttable {
public:
virtual void cut()=0;
}
class carrot : public cuttable {
public:
virtual void cut() {
//specific code for cutting a carrot;
}
}
The cutting action can take a cuttable object and perform any common cutting action that's applicable to all cuttables, and can also apply the specific cut behaviour of each object.
class cutting_action : public action {
private:
cuttable* object;
public:
cutting_action(cuttable* obj) : object(obj) { }
virtual void perform_action() {
//common cutting code
object->cut(); //specific cutting code
}
}

Tightly coupled parallel class hierarchies in C++

For context, I'm working on a C++ artificial-life system involving agents controlled by recurrent neural networks, but the details aren't important.
I'm facing a need to keep two object hierarchies for the "brain" and "body" of my agents separate. I want a variety of different brain and body types that can be coupled to each other at run-time. I need to do this to avoid a combinatorial explosion caused by the multiplicative enumeration of the separate concerns of how a body works and how a brain works.
For example, there are many topologies and styles of recurrent neural network with a variety of different transfer functions and input/output conventions. These details don't depend on how the body of the agent works, however, as long as sensory inputs can be encoded into neural activity and then decoded into actions.
Here is a simple class hierarchy that illustrates the problem and one potential solution:
// Classes we are going to declare
class Image2D; // fake
class Angle2D; // fake
class Brain;
class Body;
class BodyWithEyes;
class BrainWithVisualCortex;
// Brain and Body base classes know about their parallels
class Brain
{
public:
Body* base_body;
Body* body() { return base_body; }
virtual Brain* copy() { return 0; } // fake
// ...etc
};
class Body
{
public:
Brain* base_brain;
Brain* brain() { return base_brain; }
virtual Body* reproduce() { return 0; } // fake
// ...etc
};
// Now introduce two strongly coupled derived classes, with overloaded access
// methods to each-other that return the parallel derived type
class BrainWithVisualCortex : public Brain
{
public:
BodyWithEyes* body();
virtual void look_for_snakes();
virtual Angle2D* where_to_look_next() { return 0; } // fake
};
class BodyWithEyes : public Body
{
public:
BrainWithVisualCortex* brain();
virtual void swivel_eyeballs();
virtual Image2D* get_image() { return 0; } // fake
};
// Member functions of these derived classes
void BrainWithVisualCortex::look_for_snakes()
{
Image2D* image = body()->get_image();
// ... find snakes and respond
}
void BodyWithEyes::swivel_eyeballs()
{
Angle2D* next = brain()->where_to_look_next();
// ... move muscles to achieve the brain's desired gaze
}
// Sugar to allow derived parallel classes to refer to each-other
BodyWithEyes* BrainWithVisualCortex::body()
{ return dynamic_cast<BodyWithEyes*>(base_body); }
BrainWithVisualCortex* BodyWithEyes::brain()
{ return dynamic_cast<BrainWithVisualCortex*>(base_brain); }
// pretty vacuous test
int main()
{
BodyWithEyes* body = new BodyWithEyes;
BrainWithVisualCortex* brain = new BrainWithVisualCortex;
body->base_brain = brain;
brain->base_body = body;
brain->look_for_snakes();
body->swivel_eyeballs();
}
The trouble with this approach is that it's clunky and not particularly type-safe. It does have the benefit that the body() and brain() member functions provide a bit of sugar for derived classes to refer to their partners.
Does anyone know of a better way of accomplishing this tight coupling between 'parallel' hierarchies of classes? Does this pattern come up often enough to have warranted a well-known general solution? A perusal of the usual sources didn't reveal any established patterns that match this problem.
Any help appreciated!
I think what you are doing is approximately correct. You would want the members such as reproduce to be pure virtual, though, so the base classes cannot be created. What is your issue with type-safety? You don't want the Brain subclass and the Body subclass to depend on each others' types.

C++ Object Design issue: efficiently and safely construct objects and save/load with database

my English is not good enough to explain my problem. But I will try my best.
I used to be a Java programmer but have been using C++ more than a year. The one thing always bothers me is the strategy of creating business objects from network(like through SNMP, Web Service or other data sources...) and save it to database and load it when application startup. Usually my design is like following :
class Object{
/* this is just a demonstration, in real code, there are all kinds of Object and has relationships*/
friend class DBConnection;
friend class SNMPConn
private:
std::string& m_strName;
//... all kinds of properties
}
class DBConnection
{
int load(Object& obj);
int save(Object& obj);
int modify(Object& obj);
int loadAll(std::vector);
}
class SNMPConn
{
int load(Object& obj);
...
}
The thing I am not conmforable with is the line of "friend class ..." . It breaks the encapsulation.I found some framework, like litesql(sourceforge.net/apps/trac/litesql) and other commercial ones, but these frameworks are difficult to integrate with my existing code. I am trying to do it manually and trying to find a common strategy for this kind of work.
I was a Java deveoper, design in C++ is the thing I'm not good at. I don't know what's the best practice for this kind of design work.
As I understand from this problem (breaking encapsulation during reading and writing to DB or SNMP connection), first you need a proper design to eliminate these "friend"s. please define an abstract class for connections (i.e. IDBConnection) also persistent objects (i.e. IPersistent). You may use "Abstract Factory" pattern to create them. Furthermore, isolate load and save methods to another class and use "visitor pattern" to initialize or save your objects from/to your DB.
Another point, if you need an embedded DB for your application, use SQLite there are tons of good C++ wrappers for it. Hope it helps
Here's how I might do it in pseudo-code:
class Result {
public:
int getField(name);
string getField(name);
}
class Connection {
public:
void save(list<pair<string, string>> properties);
Result query();
}
class DBConnection {
private:
class DBResult : public Result {
}
public:
Result query() {
return ( DBResult );
}
void save
}
class Object {
public:
void load(Result);
void save(Connection) {
// make properties list
connection.save(properties);
}
}
Without Java-style reflection, that's probably how I'd do it without getting into "friend"-ship relationships. Then you're not tightly coupling the knowledge of connection logic into the connection classes.
...
You could also build template functions to do it, but you'd still need a friend relationship.
class Object {
public:
friend template<class Conn, class Obj> load(Conn c, Obj o);
friend template<class Conn, class Obj> save(Conn c, Obj o);
}
load<Connection, Object>(Connection c, Object o) {
//access o.private to load into c
}
I'm not sure which way I'd go. In one respect, you encapsulate load/save logic in your Object classes, which is great for locality, but it might tightly couple your persistence and business logic all in one location.