How to solve the problem of global access? - c++

I'm building an app, and I need the wisdom of the SO community on a design issue.
In my application, there needs to be EXACTLY one instance of the class UiConnectionList, UiReader and UiNotifier.
Now, I have figured two ways to do this:
Method 1:
Each file has a global instance of that class in the header file itself.
Method 2: there is a separate globals.h file that contains single global instances of each class.
Example code:
Method 1
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
namespace Globals {
UiConnectionList connectionList;
}
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
namespace Globals {
UiNotifier uiNotifier;
}
#endif // UINOTIFIER_H
Method 2:
file: uiconnectionlist.h
#ifndef UICONNECTIONLIST_H
#define UICONNECTIONLIST_H
#include <QObject>
#include <QList>
class UiConnection;
class UiConnectionList : public QObject
{
Q_OBJECT
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
#endif // UICONNECTIONLIST_H
file: uinotifier.h
#ifndef UINOTIFIER_H
#define UINOTIFIER_H
class UiNotifier
{
public:
UiNotifier();
};
#endif // UINOTIFIER_H
file: globals.h
#ifndef GLOBALS_H
#define GLOBALS_H
#include "uiconnectionlist.h"
#include "uinotifier.h"
namespace Globals {
UiConnectionList connectionList;
UiNotifier uiNotifier;
}
#endif // GLOBALS_H
My Question
What is the better/right way to do this?
PS: I don't think that singleton is the right answer here, is it?
Thanks
Okay, so two answers have told me to make instances of UiConnectionList and UiNotifier, optionally wrap it in a UiContext and pass it around wherever required.
Could someone enumerate reasons (with examples) why passing around the context is better than having globally accessible variables.
This will help me judge what method is better (or better suited for my app).
Thanks

With your usage in globals.h you are going to have a multiple definition of Globals::UiConnectionList and Globals::UiNotifier for each compilation unit (.cc or .cpp file) that you use. This is not the way to make exactly one instance of those clases. You should use the singleton pattern as previous posters suggested.
If you didn't want to use the singleton pattern, the correct way is to define both clases in one compilation unit and then declare them as extern in the header file, the result is your intended one global instance of the class, but that won't prevent it from being copied or copy constructed. From your example you don't know the difference between declaration and definition.

I wouldn't do them global, instead create the three objects in your main and pass them to wherever they are needed. It is easier to follow for some other programmer because he sees when/where they are used. It gives you also better control when to create and destroy them than if you declare them global.
EDIT: to clarify normally programs get more and more complex as time goes by code being added by various developers with different ideas about design etc. In general (IMHO) once you start introducing globals in a program it encourages other programmers to do the same. That is why I prefer to have data passed to wherever it is used, in a procedural language as an argument or in an OOP language passed in via the ctor. It is then easier to see the dependencies.

First of all, you're right. This question has nothing to do with the Singleton pattern. It is a question of class design.
In this case i would prefer a different implementation than yours. In both of your examples you use a namespace called "Global". This is breaking the single concern principle, because here are a lot of objects having nothing else in common than being global accessible singletons. Instead of doing this you should encapsulate your singletons in the class declaration itself.
Look at this:
class UiConnectionList : public QObject
{
Q_OBJECT
public:
static UiConnectionList Connections; // This is your global varaible
public:
UiConnectionList();
void addConnection(UiConnection* conn);
void removeConnection(UiConnection* conn);
private:
QList<UiConnection*> connList;
};
Now your global connections can be accessed via UiConnectionList::Connections. The singleton implementation as a static variable isn't really good and should be done better. Especially to prevent the change of the pointer. But this is a different question.

The least you can do is to create a UiContext class/structure. Define all other things as member variables of this class. Then create a instance of UiContext in your main class and pass it to whichever class that requires it.

Even though, as people have mentioned already, your solution is faulty, I would avoid using a singleton. Using singleton to achieve your goal will make your code hard to test. Instead classes should depend on a pure virtual interface IConnetion or the like. Would sending instances to objects when they are created be implausible? You should at least have the option to do so (or preferably using a setter) to make your code testable. Note that the "extern" solution propsed by piotr more or less is the same as a singleton.

A lot of people disagree on whether to use the global/singleton pattern. I personally don't like it merely because it goes against the concept of loosely coupled class design.
Each class should do one thing, and should be able to exist by itself as much as possible. Having classes use a global UiConnectionList instance is not only creating maintainability issues, but its also means that the classes have to know where they're getting their instance from when they should preferably be told what list to use when they are created.
Think of a resource and its manager.
Resource *ResouceManager::createResource (string name)
{
Resource *res = new Resource(this);
res->SetName(name);
resourceList->Add(res);
return res;
}
In this example, the resource and its manager are very modestly coupled. The manager can find its created resources, and the resource knows which manager it was created in, but the resource is told which manager its owned by, not defining it itself (through a global manager).
The other way is to create a Resource (or a subclass) then ask a Manager to add it to its list essentially temporary coupling them, but until then they exist separately and aren't relying on pre-defined instances.

The better way to do this is to use the Singleton method. It has been tested and proven. Besides, the class would fail if I defined another UiConnectionList variable for example in my local scope.
void myfunction()
{
UiConnectionList connectionList;
// Any usage to connectionList would be cleared after this function exits.
}
Always remember when creating a singleton class. Lock (Private-tify?) the big four: Constructor, Copy Constructor, Assignment Operator, Destructor
Also, since you're using global variables, I'm assuming you don't need scoping or hiding. So the singleton method is the better way to do it.
Here's an example on implementing a singleton.
// Meyers singleton
static UiConnectionList* UiConnectionList::getSingletonPtr()
{
static UiConnectionList x;
return &x;
}

Related

Free functions vs singleton vs static class members [duplicate]

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

C++, static vs. namespace vs. singleton

I already read a lot of posts and articles all over the net, but I couldn't find a definite answer about this.
I have some functions with similar purposes that I want to have out of the global scope. Some of them need to be public, others should be private (because they are only helper functions for the "public" ones).
Additionally, I don't have only functions, but also variables. They are only needed by the "private" helper functions and should be private, too.
Now there are the three ways:
making a class with everything being static (contra: potential "Cannot call member function without object" - not everything needs to be static)
making a singleton class (contra: I WILL need the object)
making a namespace (no private keyword - why should I put it in a namespace at all, then?)
What would be the way to take for me? Possible way of combining some of these ways?
I thought of something like:
making a singleton, the static functions use the helper function of the singleton object (is this possible? I'm still within the class, but accessing an object of it's type)
constructor called at programm start, initializes everything (-> making sure the statics can access the functions from the singleton object)
access the public functions only through MyClass::PublicStaticFunction()
Thanks.
As noted, using global variables is generally bad engineering practice, unless absolutely needed of course (mapping hardware for example, but that doesn't happen THAT often).
Stashing everything in a class is something you would do in a Java-like language, but in C++ you don't have to, and in fact using namespaces here is a superior alternative, if only:
because people won't suddenly build instances of your objects: to what end ?
because no introspection information (RTTI) is generated for namespaces
Here is a typical implementation:
// foo.h
#ifndef MYPROJECT_FOO_H_INCLUDED
#define MYPROJECT_FOO_H_INCLUDED
namespace myproject {
void foo();
void foomore();
}
#endif // MYPROJECT_FOO_H_INCLUDED
// foo.cpp
#include "myproject/foo.h"
namespace myproject {
namespace {
typedef XXXX MyHelperType;
void bar(MyHelperType& helper);
} // anonymous
void foo() {
MyHelperType helper = /**/;
bar(helper);
}
void foomore() {
MyHelperType helper = /**/;
bar(helper);
bar(helper);
}
} // myproject
The anonymous namespace neatly tucked in a source file is an enhanced private section: not only the client cannot use what's inside, but he does not even see it at all (since it's in the source file) and thus do not depend on it (which has definite ABI and compile-time advantages!)
Don't make it a singleton
For public helper functions that don't directly depend on these variables, make them non-member functions. There's nothing gained by putting them in a class.
For the rest, put it in a class as normal non-static members. If you need a single globally accessible instance of the class, then create one (but don't make it a singleton, just a global).
Otherwise, instantiate it when needed.
The classic C way of doing this, which seems to be what you want, is to put the public function declarations in a header file, and all the implementation in source file, making the variables and non-public functions static. Otherwise just implement it as a class - I think you are making a bit of a mountain out of a molehill here.
What about using a keyword static at global scope (making stuff local to the file) as a privacy substitute?
From your description it looks like you have methods and data that interact with each other here, in other words it sounds to me like you actually want a non-singleton class to maintain the state and offer operations upon that state. Expose your public functions as the interface and keep everything else private.
Then you can create instance(s) as needed, you don't have to worry about init order or threading issues (if you have one per thread), and only clients that need access will have an object to operate upon. If you really need just one of these for the entire program you could get away say a global pointer that's set in main or possibly an instance method, but those come with their own sets of problems.
Remember that the singleton instance of a singleton class is a valid instance, so it is perfectly able to be the recipient of nonstatic member functions. If you expose your singleton factory as a static function then have all of your public functionality as public nonstatic member functions and your private functionality as private nonstatic member functions, anyone that can get at the class can access the public functionality by simply invoking the singleton factory function.
You don't describe whether all of the functionality you're trying to wrap up is as related as to justify being in the same class, but if it is, this approach might work.
If you take a "C-like" approach and just use top-level functions, you can make them private by declaring them in the .cpp file rather than the publicly-included .h file. You should also make them static (or use an anonymous namespace) if you take that approach.

Singleton in my C++ program

I wrote 2 classes, Agent and Timing. The third class will contain the main() function and manage it all. The goal is to create n instances of Agent and a SINGLE instance of Timing. It's important to mention that Agent uses Timing fields and Timing uses Agent functions.
How can I turn Timing to singleton?
//Agent.h
#ifndef Timing_h
#define Timing_h
#include <string>
#include "Timing.h"
class Agent{
public:
Agent(std::string agentName);
void SetNextAgent(Agent* nextAgent);
Agent* GetNextAgent();
void SendMessage();
void RecieveMessage(double val);
// static Timing runTime;
What I thought would solve my problem but I got:
'Timing' does not name a type
~Agent();
private:
std::string _agentName;
double _pID;
double _mID;
Agent* _nextAgent;
};
#endif
//Timing.h
#ifndef Timing_h
#define Timing_h
class Timing{
private:
typedef struct Message{
Agent* _agent;
double _id;
}Message;
typedef Message* MessageP;
Message** _messageArr;
static int _messagesCount;
public:
Timing();
void AddMessage(Agent* agent, double id);
void LeaderElected(string name);
void RunTillWinnerElected();
~Timing();
};
#endif
Is this really the way to create a singleton and if it is what is the problem?
And if not, how can I turn it to a singleton?
This bit looks suspicious in Agent.h ...
#ifndef Timing_h
#define Timing_h
Seems like it's the same define-guard in Timing.h. Therefore Timing will not be included in Agent.
Change it to
#ifndef Agent_h
#define Agent_h
Nope, the wikipedia page on the singleton pattern has a good example as well as a nice write up of how a singleton is actually constructed.
Your Timing is not a singleton. Multiple objects can be created. Singleton's typically rely on a static method and a private ctor and no copy ctor or op=. You have two choices:
Either create a static member Timing for Agent
Or, create a Timing& member for Agent and convert Timing to a proper singleton
Depending on your design, if the Timing object is never changed by the Agent objects you may go ahead const qualify the member.
The most conventional way to create a singleton has following requirements:
1) The constructor should be private and a static interface shall be provided which in turn creates a static object of the singleton class (which is a member of the class itself) and return it. Basically provide a global point of access.
2) You have to decide in advance if you want the users of the class to be able to extend it and design your class to support it if required.
If the above two requirements are met, there are a number of ways a singleton can be designed including the ones which would work with multi threaded applications.
A singleton has to have a private constructor, and then a static method to get an instance of the class, which is a private field in the class itself.
Since somebody already mentioned the wikipedia page, I'll also mention another implementation of the Singleton pattern done slightly differently.
If you look at the Ogre::Singleton class you'll see it done in a different way. It allows you to only call the constructor once (or an assertion happens). So in your setup, you call the constructor. Then at the end of the program, you get this instance and delete it.
It allows you to make a singleton instance, but allow it to be instantiated with different parameters. I don't like it nearly as much as the wikipedia implementation though since it requires you to manage the constructor/destructor of the singleton.
Define a static member of Agent that is of type Timing and initialize the member where it is defined. This is not strictly a Singleton any more but may model the behaviour you want better.

OO Programming Question: Global Object

I have probably a quite simple problem but I did not find a proper design decision yet.
Basically, I have 4 different classes and each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this object keeps a socket open to the server throughout program execution. My idea was to have the TCP obejct declared as "global" so that all other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
...
};
class classB
{
private:
public:
classB();
...
};
Unfortunately, when declaring it like this my C++ compiler gives me an error message that some initialized data is written in the executable (???). So I am wondering if there is any other way I could declare this TCP object so that it is available for ALL the other classes and its methods?
Many thanks!
I'd suggest you keep the instance in your initialization code and pass it into each of the classes that needs it. That way, it's much easier to substitute a mock implementation for testing.
This sounds like a job for the Singleton design pattern.
The me sounds more for the right time to use Dependency Injection as i tend to avoid Singleton as much as i can (Singleton are just another way for accessing GLOBLAS, and its something to be avoided)
Singleton vs Dependency Injection has been already discussed on SO, check the "dependency injection" tag (sorry for not posting some links, but SO doens't allow me to post more than one link being a new user)
Wikipedia: Dependency Injection
As per your current code example, should be modified to allow injecting the Socket on the constructor of each Class:
class classA
{
private:
public:
classA(TCPSocket socket);
...
};
class classB
{
private:
public:
classB(TCPSocket socket);
...
};
Pass the socket into the constructor of each object. Then create a separate factory class which creates them and passes in the appropriate socket. All code uses the set of objects which are required to have the same socket should then create them via an instance of this factory object. This decouples the classes that should be using the single socket while still allowing the enforcement of the shared socket rule.
The best way to go about doing this is with a Singleton. Here is it's implementation in Java
Singleton Class:
public class SingletonTCPSocket {
private SingletonTCPSocket() {
// Private Constructor
}
private static class SingletonTCPSocketHolder {
private static final SingletonTCPSocket INSTANCE = new SingletonTCPSocket ();
}
public static SingletonTCPSocket getInstance() {
return SingletonTCPSocket.INSTANCE;
}
// Your Socket Specific Code Here
private TCPSocket mySocket;
public void OpenSocket();
}
The class that needs the socket:
public class ClassA {
public ClassA {
SingletonTCPSocket.getInstance().OpenSocket();
}
}
When you have an object which is unique in your program and used in a lot of places, you have several options:
pass a reference to the object everywhere
use a global more or less well hidden (singleton, mono-state, ...)
Each approach have its drawbacks. They are quite well commented and some have very strong opinions on those issues (do a search for "singleton anti-pattern"). I'll just give some of those, and not try to be complete.
passing a reference along is tedious and clutter the code; so you end up by keeping these references in some long lived object as well to reduce the number of parameters. When the time comes where the "unique" object is no more unique, you are ready? No: you have several paths to the unique object and you'll see that they now refer to different objects, and that they are used inconsistently. Debugging this can be a nightmare worse than modifying the code from a global approach to a passed along approach, and worse had not be planned in the schedules as the code was ready.
global like approach problem are even more well known. They introduce hidden dependencies (so reusing components is more difficult), unexpected side-effect (getting the right behaviour is more difficult, fixing a bug somewhere triggers a bug in another components), testing is more complicated, ...
In your case, having a socket is not something intrinsically unique. The possibility of having to use another one in your program or to reuse the components somewhere were that socket is no more unique seems quite high. I'd not go for a global approach but a parametrized one. Note that if your socket is intrinsically unique -- says it is for over the network logging -- you'd better encapsulate it in a object designed for that purpose. Logging for instance. And then it could make sense to use a global like feature.
As everyone has mentioned, globals are bad etc.
But to actually address the compile error that you have, I'm pretty sure it's because you're defining the global in a header file, which is being included in multiple files. What you want is this:
something.h
extern classTCP TCPSocket; //global is DECLARED here
class classA
{
private:
public:
classA();
...
};
something.cpp
classTCP TCPSocket; //global is DEFINED here

OO Programming Design question: Global Object part II

Sorry for reposting this, but for some reason I can not add comments to my older
post. Some people wanted to know the exact error message I get when trying to do
the following:
I have probably a quite simple problem but I did not find a proper
design decision yet. Basically, I have 4 different inherited classes and
each of those classes has more than 10 methods.
Each of those classes should make use of the same TCP Socket; this
object keeps a socket open to the server throughout program execution.
My idea was to have the TCP obejct declared as "global" so that all
other classes can use it:
classTCP TCPSocket;
class classA
{
private:
public:
classA();
virtual void method1();
...
};
class classB
{
private:
public:
classB();
virtual void method1();
...
};
and so on for classC and classD...
Unfortunately, when declaring it like this my Symbian GCC-E compiler gives me the
following error message
elf2e32 : Error: E1027: ELF File contains initialized writable data.
So I am wondering if there is any other way I could declare this
TCP object so that it is available for ALL the other classes and its
methods? classA() is the first method that will be called when
initialising this subsystem.
Many thanks!
There is very elegant way to retrieve static instances on demand.
classTCP& SingletonInstance()
{
static classTCP instance;
return instance;
}
Idea is using c++ feature to initialize local static variables only on demand.
You can support a class-wide static member by allowing both classA and classB to inherit from the same parent.
class BaseTCP {
static classTCP tcp;
// ...
};
class classA : BaseTCP {
// ...
};
class classB : BaseTCP {
// ...
};
Now classA and ClassB both share the same static member. The stipulation is that you now have to declare the static member outside of the BaseTCP class someplace, similar to:
classTCP BaseTCP::tcp;
Depending on your situation, this may be overkill...
Instead of using singletons, why don't you just create a classTCP instance and pass references to the other objects, each of which owns a reference (or pointer) to the single instance of classTCP.
This offers a much more flexible design - I think singletons generally suck and have much more limited use that generally believed. If you use a singleton, your classes classA, classB etc... have no option but to use the singleton instance. Using a more standard object composition design, you free the whole thing up.
Ask yourself questions like, what if I want the application to talk to >1 server? or what if I want to write some unit test code for classA? Writing unit test code for networking applications is a lot easier when you don't need to use real sockets but can use dummy ones that simply hold the chunks of data in ram. Add a comment if you want an example, because I'm off for lunch now:)
Doing it the way I suggest does not add significant complexity to the overall design but makes it much more open.
A Singleton pattern.