Question

I now trying to get rid of god objects from my server code.

At first of my server design, I decided to do World, and const containers objects as singleton.

But my server is multithreaded, and singletons there aren't good solution.

So I managed it and I moved that classes as Core class instance.

For example:

class Core
{
...
private:
World world;
CExpTable exptable;
...
};

Core on new connection is giving references to object for Session class.

new Session(io_pool.getService(), world, exptable ...);

I need only one instance of that objects. But god object is bad design pattern, so I would to ask, how I can redesign that object, to avoid it, and is singleton pattern design good?

Was it helpful?

Solution

First of all, you can read many posts on why singletons are bad, for example this. There are many more with lots of valid points on why this pattern in most cases isn't really useful.

As for your refactoring: the best way is to go step by step. Large revolutions usually create bugs. From my experience, dismantling a god-object isn't very hard.

You can proceed as follows:

  • identify a small responsibility you'd like to extract from the god-object
  • design a new interface for this responsibility:
    • start writing unit-tests for the new class implementing this new interface. Make tests passing by an instance of the god-object enclosed in the new object, and just forward the calls
  • having a set of unit-tests you can cut-out pieces of code from the god-object into the new object

The next step is to replace all uses of god-object class with the new interface in the context of the new responsibility, and then do it again.

If you have some state that needs to be used/handled by these responsibilities (like the World instance in your example), then you will have to make it shared. You can convert it to a shared_ptr for example, so it will be possible to leave it in the god-object for the course of the refactoring, and also use it in new classes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top