In my plugin-based architecture, the plugins must have access to all core components of the application, e.g. the main window, the settingswidget, the settings, the tray icon and several global immutable variables.
Since the application is a global singleton it is straight forward to subclass it and make all those components members of the application. This way I can 1. easily access them from everywhere 2. I can facade their API for the plugins 3. it feels natural that the components are members of the "app".
However reading the lessons on SO about singletons and globals it feels like bad design, but otherwise I'd have to implement a core facade and pass it around, which feels like bad design as well and is definitively less straight forward.
Your description looks like a God object. That is indeed the sign of a potentially bad design.
Depending on what your plugins actually do, things like Observer pattern may be a solution. Instead of giving access to the resources, make your objects suscribe to a mediator and let it make the connections to the resources.
Take also a look to Inversion of control.
I think it's best to take the distinction between IS A and HAS A (inheritance vs. containment) seriously in this case.
A plug-in isn't a QApplication. It uses a QApplication. I don't see any reason to make it a subclass. Just give it a pointer or reference to QApplication.
This is one of the things the observer pattern does for you, subjects (QApplication) have references to their observers (Plugin). You also can use this in a symmetric way.
But using the observer pattern isn't always necessary. Main thing is your Plugins have a reference or pointer to the QApplication instance.
Not sure how it helps but it seems singleton classes are sometimes used to access them from the outside.
In KDE they seem to be refereed to as Conltroler, and seem to be used over Plugin-Boundarys. (KDE is QT based, so i assume a KDEPlugin is similar to a QT one.)
PS: This is in answer form, because i don't have "Comment everywhere".
Related
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…
Is there anything wrong with having a central resource of pointers to act as a communication exchange within a project?
Im currently working on a multi component application in JUCE, learning C++ as I bumble along. Its gotten unwieldy and im looking to clean it up, both to decouple the components from each other and simplify / standardise communication.
The solution that seems most obvious / elegant to me would be to have a pointer manager object holding pointers to all components that need to receive external input, and just have classes reference the manager object, calling the component they need, when they need. Objects would be owned by their parents, and register themselves to the pointer manager in their constructor.
Is there anything wrong with this? Ive not seen any design pattern take this approach, which kind of suggests im about to put a lot of work into doing something stupid.
Does anyone have any downsides or alternatives to consider?
This should be actually a comment but I can't add comments.
What you are trying to do seems like something similar to observer or reactor design patter.
I've seen such solution in real live systems and it worked well. I'll also seen such address bus architecture in inter process communication solution.
Remember about providing good solution for unregistering from your dispatcher.
I often find myself in situations where objects need to communicate between each other. For example, a button might need to talk to various textboxes. Would it be proper to simply construct each widget with a pointer to the container for all of them? Would it be better to give it a pointer to a resource container map where the object can locate another object by string or something? This area has always been very vague to me. I could easily implement everything I want to do if I just constructed objects with pointers to containers of every other object, but that seems wrong. In the case of a widget, would it actually just be more proper if the widget knew nothing about the outside world and instead its action listeners were constructed with resource access?
Thanks
I understand that it is a bad idea but what are some solutions in these situations eg: good design patterns?
Any object should know as little as possible about things outside itself. What you are describing sounds alot like the ani-pattern often referred to as a 'God object'
You get better de-coupling if you use messages/events.
objects with pointers to containers of every other object, but that seems wrong.
And why do you think it is wrong?
Usually you will not just need to send messages but to do something like navigation/enumeration.
For example HTML DOM tree consists of nodes where each node contains [weak] reference to its parent. Without such reference operations like nextSibling() are just impossible.
So answer depends on set of other operations you will want to implement there.
The answer depends on how long the objects might live and how long the pointers might stick around. Anything which might change needs to go through a directory service. If the target's lifetime is short enough, you might even need to have the directory service place a hold on the target.
DON'T DO THAT!
No, seriously, your idea is analogous to the singleton pattern, with the difference that you have just one instance per "name" instead of per type.
You can collect a bunch of bad things about your idea by seeing what's wrong with singletons.
Why would a button in a dialog(?) want to know how many other objects there are in the dialog?
When the button is pressed, it sends a message to its owner. The owner will then have to coordinate the action between the widgets it owns. You don't want to change the code for you OK-button when the dialog gets another listbox, do you?
You could use dependency injection to pass the pointers you need. That way you make the dependencies explicit. http://en.wikipedia.org/wiki/Dependency_injection
This approach gives you a lot of advantages - unit testing is much easier when you don't have global state, god objects and so on. Also when new guy comes to the team, he can see what are the dependencies of a class - you make it explicit in constructor, so no magic like "you must first create this singleton to use that object or it will crash". This approach reduces coupling, thus making reuse easier.
IMO it is not possible to make every class independent of all the others (you ask if it is better when widget does not know anything about outside world). While this removes coupling making code reuse easier it also is very hard to do and leads to lot more coding.
On the other hand it is a bad idea to pursue some ideology "just because" without understanding why. Maybe in your case advantages of OOP are not worth writing additional code. If you can see that you will finish your application much quicker with "god object" then I would say "go for it".
IMO it is not as easy as "never create singletons and god objects". You must decide if additional time spent on passing all the references explicitly pays back in future.
Personally I always choose what is appropriate for program I write. It is not unusual for me to consciously break some OOP rules. Remember there are also other guidelines - I like KISS.
I'm reasonably new to using the QT framework in combination with C++. I was wondering: Is it a good idea to base my domain classes on QObject? Or should I only do this for classes higher up in the hierarchy? (closer to the user interface level). The QT documentation isn't clear on this:
Taken from the QT documentation:
The meta-object system is a C++ extension that makes the language better suited to true component GUI programming.
Obviously I want to build my application in a nice well structured way. Over the past few days I have been browsing through the QT documentation in order to find an answer to this question. I don't want to make some elementary mistake which will make my application limp for all eternity ;-).
I have already looked at the basic documentation for QObject and the Qt Object model. I also found a freshmeat article which helped but didn't really help me reach a conclusion. Something else that confuses me is that QT itself doesn't seem to be consistent on this matter because not all QT classes use QObject as a base class.
The advantages of using QObject as a base class as I see them:
Hierarchy
Signals and slots
Properties
Being able to use guarded pointers
Internationalization
However, I don't require any of these functionalities in most of my domain classes. Is there a best practise rule for this? Or should the rule be: use it if you require any of the points mentioned above?
Hope I didn't make this too confusing :-)
In general, unless there is a "compelling need," you are better off keeping your domain classes "vanilla." That gives you the most flexibility in the future (e.g. re-using them in a non-Qt environment).
"Use it if you require any of the points mentioned above" - it is difficult to say better. There is no reason to add unnecessary functionality to every class.
Think also about classes defined in shared libraries: they can be used by non-Qt clients, if you don't derive them from QObject.
This issue isn't 'as big' as you might think. It really doesn't matter all that much. I'd say if you do or don't it really won't be all that different. So, as a rule of thumb, don't, just to make things simpler. If, however, you need signal-slots or anything Qt realated, go ahead, it doesn't cost all that much anyway.
There is a good reason not to inherit from QObject unnecessarily, and it's right there in the documentation.
No copy constructor or assignment operator
QObject has neither a copy constructor
nor an assignment operator. [...]
The main consequence is that you
should use pointers to QObject (or to
your QObject subclass) where you might
otherwise be tempted to use your
QObject subclass as a value. For
example, without a copy constructor,
you can't use a subclass of QObject as
the value to be stored in one of the
container classes. You must store
pointers.
I would almost like to answer the opposite of your question, it is not a bad idea. Whether they should be QObjects depends on you needs. For me the ability to use properties and reflection is almost worth more that signal and slots. QMetaObject can be very helpful to for flexible programming strategies
I'm learning (reading document) but not started using Qt yet, here is my opinion on your question.
It's always good to have a single root object (CObject in MFC, TObject in VCL), so define a your own root object, such like YourOwnRootObject.
If you think you need QObject most time, make YourOwnRootObject inherite from QObject, otherwise, leave YourOwnRootObject alone until you need QObject.
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