Guarding resources with Singleton? - c++

I have read quite a few blog posts and answers on SO pointing to Singleton being a bad design. Previously I implemented a singleton CameraControl class. This class controls a camera which is connected to the system. Under the following knowledge:
Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).
Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).
My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).
Is my choice of making this class a singleton class a bad decision?

Singletons are considered a smell because:
They are the moral equivalent of global variables, and thus their use hides dependencies in code rather than revealing them through interfaces.
They promote tight coupling because your code depends on a specific instance of a specific type. What if you wanted your UI to operate against a different camera manager some day?
They make unit testing difficult because they carry state with them for the entire lifetime of the program. When state is carried across from test to test, it can make tests state-dependent, which is a very big smell.

You can read anything, sooner or later. Regardless of what the
some people say, there's no fundamental reason against using
a singleton in the appropriate cases_. In your case, I have
serious doubts, at least the way you describe it. Regardless of
the API of the camera maker (which is probably in C), your
client code will want to treat each individual camera as
a separate object, and there's nothing inherantly unique about
cameras.
Where a singleton probably is appropriate here is if the API of
the camera maker is in C, and you decide to provide
a lightweight C++ wrapper for it, to be used (exclusively) by
your Camera classes. Such light weight wrappers are one
legitimate use of singletons---there's no way in the world you
can have several instances of the library in your code.
(Usually, however, it's easier to have the Camera class address
the API directly, and skip the intermediate wrapper.)

Is my choice of making this class a singleton class a bad decision?
Yes.
Under no circumstance will there be more than one camera (the camera API provided by the camera maker control all cameras).
That doesn't make it necessary to access the camera via a Singleton class.
Using the API of the camera maker in multiple places at the same time have caused problems in the past (e.g. one thread trying to grab an image, the other thread trying to set the shutter speed).
Using a Singleton class will not buy you anything that saves you from those problem that you cannot also do in a non-Singleton class.
My class only provides several extra methods to display the image captured in a UI. Forward the image to a face detector, ... (i.e. it is not memory intensive).
Then there's no need to create a God-like Singleton class.
Furthermore, those little nifty helper functionalities you added to the Singleton class and their interactions with other pieces of code cannot easily be unit tested when residing in a singleton class with global state that cannot properly be set up and torn down between tests.
By proper use of dependency injection in the application composition root, the concrete object lifetime can be managed as if it was a singleton, but the individual clients of that object doesn't need to know that.

I personally think it is reasonable to use Singletons when appropriate. There certainly may be overuse of them in general, but in my opinion they are useful for manager classes controlling hardware resources, which is what you are doing.

Yes and No
No because the problems you see about concurrency are problems you can't "safely" avoid while playing with threads. Sooner or later, bad synchronization mechanisms will come back at you and break your lovely code. You WILL need mutexes and semaphores and such to guard ressources.
Yes, because the singleton is a bad pattern to involve with threads. Check this page about singletons, you will see some pitfalls associated with it. Basically, you're asking for trouble.
Regarding the general "Singletons are evil", it is because it makes it much harder to figure out how it works, they are the OOP version of global variables. Suppose that you have a singleton somewhere, that gets modified in 15 places, how do you track it all? If you had a "real" object, you'd be able to see how it is passed around in parameters and such. The singleton breaks the concept of scope and is easy to transform into a mess.

Singleton and Monostate patterns are both useful in this regard. Your primary consideration (regarding your second point) is to prevent multiple accesses, and neither Singleton nor Monostate prevent this.

Yes, making it a Singleton is a bad design. If you only need one Camera object, just make one.
If you need to ensure that a camera object is used in a non-reentrant way, than that is a responsibility not of the Camera object, but of your threading model. It's a seperate job.

Related

C++ Singleton Design pattern alternatives

I hate to beat a dead horse, that said, I've gone over so many conflicting articles over the past few days in regards to the use of the singleton pattern.
This question isn't be about which is the better choice in general, rather what makes sense for my use case.
The pet project I'm working on is a game. Some of the code that I'm currently working on, I'm leaning towards using a singleton pattern.
The use cases are as follows:
a globally accessible logger.
an OpenGL rendering manager.
file system access.
network access.
etc.
Now for clarification, more than a couple of the above require shared state between accesses. For instance, the logger is wrapping a logging library and requires a pointer to the output log, the network requires an established open connection, etc.
Now from what I can tell it's more suggested that singletons be avoided, so lets look at how we may do that. A lot of the articles simply say to create the instance at the top and pass it down as a parameter to anywhere that is needed. While I agree that this is technically doable, my question then becomes, how does one manage the potentially massive number of parameters? Well what comes to mind is wrapping the different instances in a sort of "context" object and passing that, then doing something like context->log("Hello World"). Now sure that isn't to bad, but what if you have a sort of framework like so:
game_loop(ctx)
->update_entities(ctx)
->on_preupdate(ctx)
->run_something(ctx)
->only use ctx->log() in some freak edge case in this function.
->on_update(ctx)
->whatever(ctx)
->ctx->networksend(stuff)
->update_physics(ctx)
->ctx->networksend(stuff)
//maybe ctx never uses log here.
You get the point... in some areas, some aspects of the "ctx" aren't ever used but you're still stuck passing it literally everywhere in case you may want to debug something down the line using logger, or maybe later in development, you actually want networking or whatever in that section of code.
I feel like the above example would much rather be suited to a globally accessible singleton, but I must admit, I'm coming from a C#/Java/JS background which may color my view. I want to adopt the mindset/best practices of a C++ programmer, yet like I said, I can't seem to find a straight answer. I also noticed that the articles that suggest just passing the "singleton" as a parameter only give very simplistic use cases that anyone would agree a parameter would be the better way to go.
In this game example, you probably wan't to access logging everywhere even if you don't plan on using it immediately. File system stuff may be all over but until you build out the project, it's really hard to say when/where it will be most useful.
So do I:
Stick with using singletons for these use cases regardless of how "evil/bad" people say it is.
Wrap everything in a context object, and pass it literally everywhere. (seems kinda gross IMO, but if that's the "more accepted/better" way of doing it, so be it.)
Something completely else. (Really lost as to what that might be.)
If option 1, from a performance standpoint, should I switch to using namespace functions, and hiding the "private" variables / functions in anonymous namespaces like most people do in C? (I'm guessing there will be a small boost in performance, but then I'll be stuck having to call an "init" and "destroy" method on a few of these rather than being able to just allow the constructor/destructor to do that for me, still might be worth while?)
Now I realize this may be a bit opinion based, but I'm hoping I can still get a relatively good answer when a more complicated/nested code base is in question.
Edit:
After much more deliberation I've decided to use the "Service Locator" pattern instead. To prevent a global/singleton of the Service Locator I'm making anything that may use the services inherit from a abstract base class that requires the Service Locator be passed when constructed.
I haven't implemented everything yet so I'm still unsure if I'll run into any problems with this approach, and would still love feedback on if this is a reasonable alternative to the singleton / global scope dilemma.
I had read that Service Locator is also somewhat of an anti-pattern, that said, many of the example I found implemented it with statics and/or as a singleton, perhaps using it as I've described removes the aspects that cause it to be an anti-pattern?
Whenever you think you want to use a Singleton, ask yourself the following question: Why is it that it must be ensured at all cost that there never exists more than one instance of this class at any point in time? Because the whole point of the Singleton pattern is to make sure that there can never be more than one instance of the Singleton. That's what the term "singleton" is all about: there only being one. That's why it's called the Singleton pattern. That's why the pattern calls for the constructor to be private. The point of the Singleton pattern is not and never was to give you a globally-accessible instance of something. The fact that there is a global access point to the sole instance is just a consequence of the Singleton pattern. It is not the objective the Singleton pattern is meant to achieve. If all you want is a globally accessible instance of something, then use a global variable. That's exactly what global variables are for…
The Singleton pattern is probably the one design pattern that's singularly more often misunderstood than not. Is it an intrinsic aspect of the very concept of a network connection that there can only ever be one network connection at a time, and the world would come to an end if that constraint was ever to be violated? If the answer is no, then there is no justification for a network connection to ever be modeled as a Singleton. But don't take my word for it, convince yourself by checking out page 127 of Design Patterns: Elements of Reusable Object-Oriented Software where the Singleton pattern was originally described…😉
Concerning your example: If you're ending up having to pass a massive number of parameters into some place then that first and foremost tells you one thing: there are too many responsibilities in that place. This fact is not changed by the use of Singletons. The use of Singletons simply obfuscates this fact because you're not forced to pass all stuff in through one door in the form of parameters but rather just access whatever you want directly all over the place. But you're still accessing these things. So the dependencies of your piece of code are the same. These dependencies are just not expressed explicitly anymore at some interface level but creep around in the mists. And you never know upfront what stuff a certain piece of code depends on until the moment your build breaks after trying to take away one thing that something else happened to depend upon. Note that this issue is not specific to the Singleton pattern. This is a concern with any kind of global entity in general…
So rather than ask the question of how to best pass a massive number of parameters, you should ask the question of why the hell does this one piece of code need access to that many things? For example, do you really need to explicitly pass the network connection to the game loop? Should the game loop not maybe just know the physics world object and that physics world object is at the moment of creation given some object that handles the network communication. And that object in turn is upon initialization told the network connection it is supposed to use? The log could just be a global variable (or is there really anything about the very idea of a log itself that prohibits there ever being more than one log?). Or maybe it would actually make sense for each thread to have its own log (could be a thread-local variable) so that you get a log from each thread in the order of the control flow that thread happened to take rather than some (at best) interleaved mess that would be the output from multiple threads for which you'd probably want to write some tool so that you'd at least have some hope of making sense of it at all…
Concerning performance, consider that, in a game, you'll typically have some parent objects that each manage collections of small child objects. Performance-critical stuff would generally be happening in places where something has to be done to all child objects in such a collection. The relative overhead of first getting to the parent object itself should generally be negligible…
PS: You might wanna have a look at the Entity Component System pattern…

Using singleton for Resource Manager in C++ game

I've been developing a game with my company for a good few years now. However recently we have been improving the base systems of our game to make future additions easier. One change we did was add Resource Managers instead of manually loading in information inside our Screen classes which are essentially game states. We decided to implement this as a singleton. I however am aware of the controversy in the use of singletons in the programming community.
I will give an example of how we use our Font Manager down bellow. And I would like to know whether in this case a singleton is acceptable or whether you would recommend some other method.
mTextToBeDrawn.setFont(FontManager::GetInstance()->GetFont("Default"));
I am open to all suggestion and I will explain the current OOP design in order for a deeper understanding of the system. Every Manager extends from a base class called Manager with generic Add and Remove Methods. The Add and Remove Methods are then implemented in the derived classes. These classes only require one instance ever as the game will only require one State Manager, Font Manager and so forth. So should I use singletons or should I use another method in order to create better code.
Often in the programming community we hear "using X is bad" or "using X is good", but just labeling something as bad or good doesn't at all explain its' strengths and weaknesses or how something might be problem or how it could be used appropriately. If you don't understand why something might be bad, chances are you won't notice it when it creeps up in other forms or with different names.
In your example of the singleton, I would do a little research to identify criticisms and pitfalls of using of singletons and evaluate whether they will be a problem for you.
The biggest two concerns for me are:
Singletons introduce global data and global state.
With global data, access and modification can happen all over the code which makes bugs difficult to track down, and it can more easily get in messed up states. Often singletons are a result of poor design.
Singletons are often not thread safe.
In some applications the pitfalls don't really become a problem. In the Cocoa/Objective-C world Apple occasionally uses Singletons to solve problems which are, in my opinion, completely fit for the job. Some of their usages are similar to what you describe such as image management/caching.
You can read more here What is so bad about singletons?

How do I avoid "coupling" in OOP

OK, I'm not sure coupling describes truly my problem. The problem is, I'm creating my own 3d game engine based on ogre. I'm also using a physic library, PhysX, but since I need to create an abstraction layer between my main engine code and PhysX - so just in case we could use another physic engine - I decided to create a wrapper, Quantum.
So ogre have an Entity class which will control the entity on the screen
PhysX also have a PxActor class which contains the informations about the actor position in the PhysX works.
The quantum wrapper will have a QEntity class which will act as a layer between the engine and PhysX
Finally, the engine will have an Entity class which will have two members at least, the ogre entity object and the quantum entity. On each update() it will ask the QEntity what's up and update the ogre entity position.
Spot the problem? 4 classes for one entity? And remember that we need to access all four entities at least 60 times/s! So what about data partitioning? Not really optimised. Besides, there might be more classes, one for the AI,  one for the scripting engine...
Using objects of multiple classes to represent the same thing in multiple contexts is not a bad thing in itself. In fact, it would probably be worse if you had used the same object in all these contexts - for example, through some creative use of multiple inheritance.
Your QEntity class already does decoupling for you - as long as you program to its interface, and does not let classes specific to PhysX "stick out" from the interface of QEntity*, you are good.
It looks like your project introduces coupling in the "bridge" classes, which is exactly where it belongs. As long as you keep it there, your design would not have a coupling problem.
As far as 60 FPS goes, don't worry about it too much at the design stage. As long as there are no lengthy chains of responsibility relying on virtual functions, your compiler should be able to do a good job optimizing it for you.
* for example, QEntity shouldn't accept parameters or return objects that are specific to PhysX, except in a constructor that creates a "wrapper".

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.

C++ - Single local class instance for entire program duration

I'm working on a lil' game engine in C++, and decided to do it all OOPily (heavy use of classes.)
It's intended to be (theoretically) cross-platform, so I have an 'Engine' class, an instance of which is created by the 'OS Module', which is WinMain for Windows (the platform I'm developing it for first.)
I have three main questions:
Is it considered poor practice to create a class that is only going to be instantiated once in the entire application? Perhaps because there is some kind of performance hit or added overhead incurred by using a class rather than a bunch of functions?
I've been planning to have WinMain create the instance of Engine as a local variable. The Engine class will be fairly large, containing classes for rendering, script parsing, file system stuff, etc. Basically, the whole game engine, apart from OS specific code, will be contained in the Engine class in some form (possibly as an instance of another class.) Is creating a local instance of my very large Engine class within the WinMain function a bad idea? Is creating a local instance a bad idea when the class will be created when the program starts, and end when the program ends? Maybe new would be better?
My plan (i/wa)s to divide the engine up into 'modules', each of which is represented by a class. The Engine class would contain an instance of almost all the other modules, like, as mentioned above, rendering, file system interaction, etc. Is using classes as containers for huge modules a bad idea from some perspective (performance, design, readability?)
Thanks for any help :)
Game engines are not prime candidates for cross-platform'ness since they usually involve efficient interaction with low-level API's (which are not cross-platofrm).
The size of a class depends on the member variables it contains, not the number of functions it implements.
Stack space is usually small (http://msdn.microsoft.com/en-us/library/ms686774%28v=vs.85%29.aspx) while the heap is theoretically as big as available RAM. So, if you have something really big, store it on the heap (with new).
The "Splash Screen": don't do all the work at the beginning of the program. Users hate it when they run the program and nothing shows on screen because your program is busy initializing something...
Lookup lazy instantiation, basically don't do things that can wait and always show something on screen.
As for specific answers:
1. No, assuming no virtual functions, there should be no performance overhead.
2. See "Splash Screen" and "limited stack space" above.
3. Modularity is generally good, just make sure each class does/represent a single "thing". But don't have so many classes you start forgetting their names and purpose :)
Is it considered poor practice to
create a class that is only going to
be instantiated once in the entire
application? Perhaps because there is
some kind of performance hit or added
overhead incurred by using a class
rather than a bunch of functions?
Not at all. This is basically because your Application class can do things like inherit and encapsulate. There's no performance hit or added overhead.
I've been planning to have WinMain
create the instance of Engine as a
local variable. The Engine class will
be fairly large, containing classes
for rendering, script parsing, file
system stuff, etc. Basically, the
whole game engine, apart from OS
specific code, will be contained in
the Engine class in some form
(possibly as an instance of another
class.) Is creating a local instance
of my very large Engine class within
the WinMain function a bad idea? Is
creating a local instance a bad idea
when the class will be created when
the program starts, and end when the
program ends? Maybe new would be
better?
Nope- this is pretty much the way it should go. Why bother heap allocating? You want automatic destruction semantics. Unless your class has a very large size, hundreds of KB or more, in which case an RAII-based heap allocation is smarter, as stack memory is quite limited. That is, a physical per-instance static size as reported by sizeof(), not including dynamic allocations.
My plan (i/wa)s to divide the engine
up into 'modules', each of which is
represented by a class. The Engine
class would contain an instance of
almost all the other modules, like, as
mentioned above, rendering, file
system interaction, etc. Is using
classes as containers for huge modules
a bad idea from some perspective
(performance, design, readability?)
This is exactly what object-orientated design is for- encapsulation, and dividing the program up into clearly defined and separated modules, then instantiating each one that you need, is exactly the idea behind object-orientated programming. The size of the concept that a class encapsulates is usually considered to be irrelevant, as long as it's one single concept. A clear modular design is great.
I would recommend using run-time inheritance for all of the platform-dependent ones, and preferably, loading them dynamically at run-time (using the OS class to perform the dynamic loading). This enforces a solid compile-time abstraction and allows for more efficient compilation.
No, doing whatever makes your design cleaner and more maintainable is recommended.
No, direct use of the freestore should be avoided whenever possible (i.e., don't use new unless you absolutely have to)
See #1
No it isn't considered bad style. In fact I know no application frameworks that go without one, and the renowned Singleton pattern is basically around the same theme (but different, mind you)
I can't imagine that your class is actually that big. If it is, make it on the heap. However, chances are that the actual contents of that class are going to be on the heap anyway (I'm sort of assuming you'll use existing container classes, that wil 99 out of 100 do dynamic allocation; this goes for STL containers as well)
What difference would it make whether you put them in the data segment, as auto's on the stack or members of a class? I think the class emphesizes the modularity and might enable you to do things more easily (like e.g. unit testing, or reusing the engine for a network-only version etc. etc.)