Avoid configuration class as a Singleton - c++

I need to use kind of Configuration class, which is used across several other. Part of them are using Configuration to read values, some of them are changing them.
What is important - all "read" classes has to stay up to date with configuration. What means - all of them are observing Configuration instance.
The first approach - use Singleton pattern. Then Configuration is consistent across all other classes.
Unfortunately it is hard to test such classes. I want to avoid coupling between Singleton and the rest of my application. Here is my new approach:
*ConfigurationProxy is created at each class and it is the only one, which is coupled with Configuration
Is there a better way to avoid coupling with such a Singleton?

Is there a better way to avoid coupling with such a Singleton?
Yes, don't have a singleton.
This is one reason why I avoid global variables (whether or not you disguise them with some weird antipattern). You tie your code to a particular object, and it can't be tested without that object.
Just define an abstract interface for the configuration, and pass that to everything that needs it. Your tests provide a stub; your real programs provide a real configuration.

Related

Avoiding singletons in plugins to be shared among all the instances

I'm building a plugin which will be used in a host. This plugin is using a singleton for services I would like to easily access anywhere. The problem comes when I instance several times the same plugin, the same (static) singleton, being specific to the runnable, will be shard among all the instanced plugins. Is there, generally speaking, a way to reduce the scope of the singleton (c++) ?
As each plugin is an instance in itself, I could obviously pass the root class of the plugin to all of it's subclasses but I would like to keep the same global singleton design as possible.
Is there a reason for having a singleton? The rationale is when you need to enforce that there is only one, and need to provide a single point of access. If these aren't really requirements, then just create one and pass it around where needed.
I would gradually get rid of the singleton.
Does the singleton do a lot, or not much?
You might need to divide it up into parts.
If it doesn't do much, just pass it where is is needed, and get rid of its singleton-ness.
If it provides lots of services, create interfaces for each service and pass those around where they are needed. Your design will improve and become more testable and easier to comprehend.
At first, the implementations of the interfaces could delegate to the original singleton, but you want to make them self contained eventually.
A singleton do internally make use of a static variable.
The scope of this static variable is specified by the source file where it is defined and partitioned by its current runnable. For those reason, while running under the same host (and then the same runnable) both plugins (which are the same code) do share the same static variable (and by extension the same singleton).
As we assume in this question the code to be the same for each plugin, the only way to split those singletons would then be to run a new executable. This could be done using the fork unix command for example where both process will then hold their own memory range.
Obviously (as most of you commented) it is a much better approach to avoid using singletons in this case as forking a process is just adding useless complexity.

Best option for managing module classes

My game base consists of a series of modules, organized as classes, that are created, updated and interact when needed.
A few examples could be: CWindowManager, CGraphicsManager, CPhysicsManager, and so on.
I'm ashamed to have to say that I currently use global pointers for them (extern CWindowManager* g_WindowManager;), and I know that this is probably a bad thing to do.
In any case, the thing is that these modules need to be created and deleted dynamically, and that in the right order of course. Theres also the problem that modules like CPhysicsManager are scene-dependent, therefore they are deleted when the scene is switched and then created again.
Now, I'd like to switch away from using globals for working with modules in my game.
I'm not afraid of the refactoring, but I can't really think of what would be the best alternative to globals.
I have thought about creating a CModuleManager class and storing instances of the modules in there as members, which are then derived from a CModule base class. Although I can't really think of how this would work in detail.
This seems like a common problem in software development and especially game development, so:
- What is the best option for managing modules, compared to simply using global pointers?
Some things to consider when using global data:
multi-threading. You need to be careful if the global data can be accessed by different threads concurrently.
testability. If you are writing unit tests, then the global data needs to be initialized before any code accesses the global data.
An alternative to using global data is to pass the object instances that each class/method requires as a parameter. This has the benefit that all the dependencies of a class are visibly from the API. It also makes writing unit tests much easier. The disadvantage is that the code can get messy if you are passing objects all over the place.
Your idea of having a ModuleManager sounds like the Service Locator pattern - which I think is a feasible solution. This link may help: http://gameprogrammingpatterns.com/service-locator.html.
If you choose to carry on using global pointers, then dynamically deleting the global data can be achieved in C++ using smart pointers (auto_ptr).

What are global states? How do they affect testability and how to avoid them?

List down the various global states like global variable, singleton object etc.,
I read that they affect the testability of code. Can you explain alternatives to global states that help in improving the testability of the code?
Global variables and singletons are so similar from the testability viewpoint that they don’t have to be treated separately. Good OO design should be like bricks of Lego that fit together to create the resulting system. The main problem with globals is that you lose isolation. When you access your collaborators using globals or singletons, the classes are no longer separate bricks that you can easily take and reorganize, use in isolation or reuse in another project. When you take some class that depends on globals, you drag the rest of the design with it. In testing this makes problems because you have to take extra steps to cut the connections from your class to its collaborators, so that you can test it in isolation. (I’ve written more about this on my blog.)
A nice solution to the problem is supplying the class dependencies from the outside. You simply introduce some kind of mechanism (maybe a simple class) that will take all the isolated bricks and connect them into the object graph that makes up your application. This is what Inversion of Control and Dependency Injection is all about.
Start by reading singletons are pathological liars.
There are no various global states. Either something is global state or it isn't. The Singleton anti-pattern just removes various initialization headaches, but it's just the same as a global variable.
How to avoid global state? Make some local state and pass a reference or pointer to it around. In the vast, vast majority of occurrences, global state is needless. There are some instances of necessary global state, like the heap, but they're very rare and if you need to ask, then you almost certainly don't know enough to know when it's correct.

Is it good programming to have lots of singleton classes in a project?

I have a few classes in a project that should be created only once.
What is the best way to do that?,
They can be created as static object.
Can be created as singleton
Can be created as global.
What is the best design pattern to implement this?
I am thinking of creating all classes as singleton, but that would create lot of singletons. Is it good programming practice to have lot of singletons?
What are the pros and cons for using singletons?
Take a look at Steve Yegge's blog post about this - Singleton Considered Stupid
If they only need to be created once, that doesn't mandate they should be singletons.
If X is a singleton, it's implied there is one instance.
If X has one instance, that doesn't mean it should be a singleton.
Use a singleton if you require there be only one instance of the class, and that it be globally accessible. In your case, simply only needing one isn't reason enough. Globals are bad, singletons are glorified globals.
Most often, you don't need them. You'll see it a lot in bad code because of the very mentality: I only need one, that must mean I should make it singleton! (Wrong) For example, I've finished the technical design of the most powerful game engine I've ever done to date. It has 2 singletons, for memory and threading. A very large project, and I only have two!
More context would help us give you better information.
I suggest you look at some of the videos and articles that Miško Hevery of Google has done. First a video: "Clean Code Talks: Global State and Singletons" and his blog.
The general concensus is that Singletons are OK in a few rare instances, for example logging, but in most other situations you want to use dependency injection. Singletons make it harder to test your code and they hide dependencies so that your classes cannot be instantiated easily in isolation.
Singletons have a few problems -- they're hard to test, hard to replace, and hard to extend. There's usually a better way.
One of my favourite articles on the singleton is Singletons are Pathological Liars by Miško Hevery. Essentially, they encourage "hidden" behaviour that is very hard to learn and test.
There are projects where you can't practically avoid using globals. All kinds of service locators or dependency-injection frameworks still rely on global (not always static variable, but always global of some sort) storage of objects.
However, singletons are a sign of a problem:
First, singleton as a canonical pattern doesn't go well with interfaces and abstraction. It can be fixed though - accessing it through factory.
Worse, singletons are inflexible - they don't have any means of identifying object beyond its type. ( Well, in C++ they do through templates, but it's a different story). In that sense they are actually worse than static variables. In the long run it pays off using a framework where many instances of the same type can be accessed.
And most importantly, lots of singletons means lots of distant relationships between objects. Which means your system is probably more complex than it needs to be and will be much harder to develop, test and manage. Simply switching to locators or DI won't help there, it's a matter of underlying design principles.
A singleton is effectively global state. If you're going to create lots of singletons you're going to create lots of global state, only in won't necessarily look like global state.
This makes it hard to do things like build unit tests, provide mock classes and reuse code because its really easy to
couple the current state to a function. i.e. function foo is only valid when class X is in state Z, otherwise it doesn't work.
It's also problematic to build a thread safe singleton correctly.
Singletons can be good for coordinating access to a resource, particularly one that doesn't have much state and is expensive to construct.
So why do you think you need lots of singletons? you may get better responses if you ask about your problem domain and what issue you are hitting.
In programming there are no silver bullets. Making every class a singleton will not magically make your code "better". Singletons are a tool for that solve a specific problem I studying more about singletons.
To use singleton pattern in your project should be a well thought out and careful design decision, because its a one way track with very little scope for backtracking. I have practically used it in one of my project for a commercial product in a multithreading environment and faced multitude of problems. But this doesn't mean it's an untouchable pattern. The point is anything which can be achieved with singleton can be achieved without it, with less hassles and complexity. For more on this you can track this question I asked some months back. It has interesting links and insight into the singleton pattern

Best way to create an Environment object in C++

I want to create an environment class that is accessible from all of my classes in my program but I dont want to initialize the environment object everytime I want to access its members from my other classes. What is the best way to go around doing this in C++?
I want to do this because I have the environment object store all my config values that other classes may use. Those values are read from multiple places, including different files. I dont want to parse the files every time I create a new environment object in my classes.
A Singleton object isn't always the solution. While sometimes it seems like an easy solution, it does have some disadvantages (see this question for example).
How many of your classes actually need access to this Environment object? If you literally meant that every class you have do then it sounds like your design is flawed.
Quite often a better alternative to a singleton is just to pass the object around to those who actually need it.
What you need to do is to wrap your environment class in a Singleton Pattern. See this SO question for more info: C++ Singleton design Pattern
As has been pointed out, what you are looking for is the Singleton pattern. However, the Singleton pattern is frequently the result of poor design. Whenever you find yourself using the Singleton pattern, or, for that matter, any pattern that requires what are, in effect, global variables, you should consider whether there might be a better approach to the problem. With respect to your particular problem, I recommend you take a look at the QSettings class, which is a part of the Qt Framework, a free and high quality open source library.
The QSetttings class will allow you to load/save configuration settings using the preferred native mechanism (the registry on Windows, a property list file on Mac OS X, and a gconf XML file on Linux). Also, you might want to see my post Environment Variables are Evil, in case you were considering using environment variables for the configuration (the name "environment" for the configuration sounds awfully ominous).
Sounds like you want a singleton pattern. This will let you create and use one object/instance of a class, but no more, even if you access it many times. See:
http://www.infernodevelopment.com/singleton-c
You can create a service which is a static singleton. This service contains all your object collection(s) and provide functions to access these objects.