I have many classes designed like below and they have to be accessible everywhere at any time (also just as a single instance). Currently Ive done that using a namespace which stores pointer to all classes. Is there any better way to solve/design such problems/structures?
// AbcManager.h
class AbcManager
{
public:
void printTest();
private:
char text[] = "Hello world";
}
// ManagerNamespace.h
namespace Manager
{
AbcManager* abc;
}
// somewhere.h
{
Manager::abc->printTest();
}
Two requisites are demanded:
SRP
Readability
After giving some careful thought it is clear that SRP is not an issue, since, as OP stated:
they have to be accessible everywhere at any time
Which means there is absolutely no need to have separate objects. If the namespace stores all the pointers, but the initialization of different objects is done stack-wise? At any time, some might be missing, pointing to null. Which only leaves the following trivial possibilities:
With no information hiding: Nested namespaces wrapping static functions and variables.
With information hiding: Single 'big' singleton manager class. For additional readability, use prefixes in the name of variables and member functions.
Keep what you already have
I would recommend making the distinction between a singleton (object that can have only a single instance) and a normal object which gets instantiated only once by your code (the latter is not a singleton).
Would a template be a good fit, considering you have "many classes designed like below". Just instantiate each template with the type/nontype parameter you need. Not sure if this is what you're asking though.
Related
(This questions assumes that a global + unique object is the goal. I would like to clarify that this does not mean it is asking about or advocating the if/why/when of using/not-using singletons or globals.)
I am wondering if there's a technicality about C++ that I'm missing, so my question is:
Is a namespace implementation of the singleton pattern in C++ valid? And if so, is there a reason why it is not often suggested as the better approach?
From Google's style guidelines, we see namespace non-member functions recommended over static member function, but only when not sharing static data:
"Rather than creating classes only to group static member functions
which do not share static data, use namespaces instead."
Why shy away from letting non-member functions share static data, declared in an unnamed namespace? Is there something wrong about this that explains why namespaces aren't generally suggested as a better alternative to writing a singleton class in C++?
Because I can't find recommendations of the namespace approach, but it is very easy to find the class approach despite C++ not enforcing the use of classes:
C++ Singleton design pattern
Can any one provide me a sample of Singleton in c++?
Singleton instance declared as static variable of GetInstance method
http://www.aristeia.com/Papers/DDJ_Jul_Aug_2004_revised.pdf
Singleton: How should it be used
Using a named namespace with an unnamed namespace in its source file:
You can have 'state' via static data
You can gain the extra privacy of putting things in an unnamed namespace
You can still control the construction order of its static objects by using static pointers, and constructing from function calls.
You don't need to implement a singleton class
Edit - Example of namespace approach I was thinking:
SingleThing.h:
namespace single_thing // The singleton (if this is actually valid)
{
void GrowSomeCats(int amount); // Typical setter
int GetNumCats(); // Typical getter
}
SingleThing.cpp:
#include "Balloon.h"
namespace // Acting like private members and functions
{
int numCats = 4; // POD
Balloon* wilson = NULL; // Not POD (and not a singleton)
// Contrived 'private' function
bool CanGrowCats()
{ return wilson && wilson->LikesCats(); }
// Contrived excuse to instantiate non-POD 'members'
void RandomlyCreateOtherObjects()
{
if (!wilson /* && someRandomiserImTooLazyToType()*/ )
wilson = new Balloon();
}
}
namespace single_thing // 'Public' functions
{
void GrowSomeCats(int amount)
{
RandomlyCreateOtherObjects();
if (CanGrowCats())
numCats += amount;
}
GetNumCats()
{ return numCats; }
}
(I assume we can agree that global state is a dangerous thing that has to be used with special care.)
Technically your singleton namespace is equivalent to a singleton class. However it has one major drawback that makes it a no-go in my opinion: It hides the fact that it is stateful. Ever used std::strtok()? Remember what an atrocious mess it is? That’s because it hides its statefulness, too.
Because global state is inherently dangerous, any piece of functionality that uses it should make that fact abundantly clear at the call site, preferrably by using language constructs – because nobody reads comments or documentation. A Foo::instance()->do_work(); is a known pattern that makes it quite clear that something special is going on; a foo::do_work(); does not.
Singleton design pattern is about creation the only instance of a useful class (there is no need in creation of useless objects). In C++ classes are defined with class and struct keywords. To be useful a singleton class, beside creation and destruction, should also implement some methods that operate with the instance. To ensure singularity, a singleton class should hide its constructors and expose a static method for accessing the instance.
Using only namespaces one would not be able to define useful methods of the singleton. Implementing the instance access method as a function in a namespace instead of the class itself is possible, but would require 'friending' that function, and does not make sense because the class is already defined.
Implementing a non-object singleton (e.g. of a plain data type) would assume that the instance does not require construction and thus there is no need for singleton.
class AA
{
public:
AA ();
static void a1 ();
static std :: string b1 ();
static std :: string c1 (unsigned short x);
};
My class won't have different objects interacting with among themselves or with others.
Of course I need to have at least one object to call the functions of this class, so I thought of making the members static so that unnecessary object creation can be avoided.
What are the pros and cons of this design? What will be a better design?
To access to static members, you don't even need an object, just call
AA::a1()
This patterns is called "Monostate", the alternative being Singleton, where you actually create an object, but make sure it's only done once, there are tons of tutorials on how to do that, just google it.
Should members of a class be turned static when more than one object creation is not needed?
You make members of the class static when you need only one instance of the member for all objects of your class. When you declare a class member static the member becomes per class instead of per object.
When you say you need only one object of your class, You are probably pointing towards the singleton design pattern. Note that pattern is widely considered an anti pattern and its usefulness if any is dependent to specific situations.
The reason you mention in Q is no way related to whether you should make a member static or not.
Your class has no data members, so I don't see any good reason to use a class at all:
namespace AA
{
void a1 ();
std :: string b1 ();
std :: string c1 (unsigned short x);
};
Of course I need to have at least one object to call the functions of this class
That's not true. You can call static member functions without an instance of the class.
A note on the Singleton pattern: it has a bad reputation, it is often mis-used, and in my experience it is only very rarely useful. What it does is enforce that there can only be one instance of the class, and that this instance is globally accessible.
People often think, "I only need one instance, therefore I should use Singleton", especially when Singleton is the first Capitalized Design Pattern they're introduced to. This is wrong -- if you only need one instance, create one instance and use it. Don't unnecessarily limit all future users of the class to only create one instance. Don't unnecessarily create shared global state. Both things make your code less flexible, harder to use in different ways and therefore in particular harder to test. Some people would argue that for these reasons, Singleton is strictly never useful.
In this case you don't seem to need even one instance. If that's the case I'd use free functions as above.
I have many small functions which every is doing a single thing like for example:
pingServer, checkUserValidAccount, countDistance.
It is not worth of wrapping every function into single class.
What is the best practice in c++ to handle such a different many small functions?
Maybe writing some class called Helpers like for example NetworkHelpers?
Placing them in a namespace is an option. I don't see the need for a class. An instance of a class is mean to represent a state, but you're describing a bunch of free functions, so a stateless system.
"It is not worth of wraping every function into single class." - this is not a valid argument for making the decision not to write a class. A class can have a single member and a single method, but if there is logic behind it, you should write it.
If your functions and your logic mandates the use of a class, where your functions have the same logic but operate differently depending on the object, by all means, write a class. If your sole purpose is to group the functions together, when their logic doesn't really rely on the same instance of a class, group them in a namespace.
An example based on your question:
namespace NetworkHelpers
{
//free function, use a namespace
bool pingServer(std::string hostname);
}
//alternative, where the object has a state:
class ServerConnection
{
std::string _hostname;
public:
NetworkHelpersClass(std::string hostname)
{
_hostname = hostname;
}
bool pingServer()
{
return NetworkHelpersNamespace::pingServer(_hostname);
}
};
As you can see, inside the namespace, the function doesn't depend on anything other than the parameter.
Inside the class, since it has a state and you create an object for each server (so similar behavior, yet different depending on the object), you call the function with no parameters as the object has a state.
I hope this makes it clear.
Unlike some languages, C++ does not require that you put every function in a class. If you have functions that don't belong in a class, put them in a namespace.
If I may add another best practice other than namespaces: group your functions in DLLs minding their dependencies.
Avoid circular linking and create low-level libraries with the smallest number of dependencies as possible.
I have about 15~20 member variables which needs to be accessed, I was wondering
if it would be good just to let them be public instead of giving every one of them
get/set functions.
The code would be something like
class A { // a singleton class
public:
static A* get();
B x, y, z;
// ... a lot of other object that should only have one copy
// and doesn't change often
private:
A();
virtual ~A();
static A* a;
};
I have also thought about putting the variables into an array, but I don't
know the best way to do a lookup table, would it be better to put them in an array?
EDIT:
Is there a better way than Singleton class to put them in a collection
The C++ world isn't quite as hung up on "everything must be hidden behind accessors/mutators/whatever-they-decide-to-call-them-todays" as some OO-supporting languages.
With that said, it's a bit hard to say what the best approach is, given your limited description.
If your class is simply a 'bag of data' for some other process, than using a struct instead of a class (the only difference is that all members default to public) can be appropriate.
If the class actually does something, however, you might find it more appropriate to group your get/set routines together by function/aspect or interface.
As I mentioned, it's a bit hard to tell without more information.
EDIT: Singleton classes are not smelly code in and of themselves, but you do need to be a bit careful with them. If a singleton is taking care of preference data or something similar, it only makes sense to make individual accessors for each data element.
If, on the other hand, you're storing generic input data in a singleton, it might be time to rethink the design.
You could place them in a POD structure and provide access to an object of that type :
struct VariablesHolder
{
int a;
float b;
char c[20];
};
class A
{
public:
A() : vh()
{
}
VariablesHolder& Access()
{
return vh;
}
const VariablesHolder& Get() const
{
return vh;
}
private:
VariablesHolder vh;
};
No that wouldn't be good. Image you want to change the way they are accessed in the future. For example remove one member variable and let the get/set functions compute its value.
It really depends on why you want to give access to them, how likely they are to change, how much code uses them, how problematic having to rewrite or recompile that code is, how fast access needs to be, whether you need/want virtual access, what's more convenient and intuitive in the using code etc.. Wanting to give access to so many things may be a sign of poor design, or it may be 100% appropriate. Using get/set functions has much more potential benefit for volatile (unstable / possibly subject to frequent tweaks) low-level code that could be used by a large number of client apps.
Given your edit, an array makes sense if your client is likely to want to access the values in a loop, or a numeric index is inherently meaningful. For example, if they're chronologically ordered data samples, an index sounds good. Summarily, arrays make it easier to provide algorithms to work with any or all of the indices - you have to consider whether that's useful to your clients; if not, try to avoid it as it may make it easier to mistakenly access the wrong values, particularly if say two people branch some code, add an extra value at the end, then try to merge their changes. Sometimes it makes sense to provide arrays and named access, or an enum with meaningful names for indices.
This is a horrible design choice, as it allows any component to modify any of these variables. Furthermore, since access to these variables is done directly, you have no way to impose any invariant on the values, and if suddenly you decide to multithread your program, you won't have a single set of functions that need to be mutex-protected, but rather you will have to go off and find every single use of every single data member and individually lock those usages. In general, one should:
Not use singletons or global variables; they introduce subtle, implicit dependencies between components that allow seemingly independent components to interfere with each other.
Make variables const wherever possible and provide setters only where absolutely required.
Never make variables public (unless you are creating a POD struct, and even then, it is best to create POD structs only as an internal implementation detail and not expose them in the API).
Also, you mentioned that you need to use an array. You can use vector<B> or vector<B*> to create a dynamically-sized array of objects of type B or type B*. Rather than using A::getA() to access your singleton instance; it would be better to have functions that need type A to take a parameter of type const A&. This will make the dependency explicit, and it will also limit which functions can modify the members of that class (pass A* or A& to functions that need to mutate it).
As a convention, if you want a data structure to hold several public fields (plain old data), I would suggest using a struct (and use in tandem with other classes -- builder, flyweight, memento, and other design patterns).
Classes generally mean that you're defining an encapsulated data type, so the OOP rule is to hide data members.
In terms of efficiency, modern compilers optimize away calls to accessors/mutators, so the impact on performance would be non-existent.
In terms of extensibility, methods are definitely a win because derived classes would be able to override these (if virtual). Another benefit is that logic to check/observe/notify data can be added if data is accessed via member functions.
Public members in a base class is generally a difficult to keep track of.
I have to implement a set of 60 functions, according to the predefined signatures. They must be global functions, and not some class's member functions. When I implement them, I use a set of nicely done classes provided by 3rd party.
My implementation of most functions is quite short, about 5-10 lines, and deals mostly with different accesses to that 3rd party classes. For some more complicated functions I created a couple of new classes that deal with all the complicated stuff, and I use them in the functions too. All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
Question: Would it be better if I implement one big class with 60 member functions, and do all the implementation (that is now in the global functions) there? And each of the functions that I have to write will just call to the corresponding member function in the class.
All the state information is stored in the static members of my and 3rd party's classes, so I don't have to create global variables.
That is the keypoint. No, they should definitely not be put into classes. Classes are made to be used for creating objects. In your situation, you would use them just as a scope, for the data and functions. But this is what namespaces already solve better:
namespace stuff {
... 60 functions ...
namespace baz {
... if you want, you can have nested namespaces, to ...
... categorize the functions ...
}
namespace data {
... you can put data into an extra namespace if you want ...
}
}
Creating classes that consist purely only of static members is a bad idea.
Do the users of your code really need this big class?
If yes, implement it.
If no, don't waste your time on implementing it and don't waste the time of others mandated to test it or trying to understand what is the exact role of this class beyond the OOP look.
litb is probably correct. The only reason that you would even consider wrapping a class around a bunch of free functions is if you need to attach some of your own data for use in your wrappers. The only thing that pops into my head is if need a handle to a log file or something similar in the wrappers.
On a related note, fight the temptation of using namespace stuff;! Always refer to the functions using namespace qualification:
#include <stuff.h>
void some_function() {
stuff::function_wrapper();
}
instead of:
#include <stuff.h>
using namespace stuff;
void some_function() {
function_wrapper();
}
The benefit is that if you ever need to convert the namespace to a class full of static methods, you can do it easily.
I think that the "one class one responsibility" rule should guide you here. The 60 functions can probably be divided into different responsibilities, and each of those deserves a class. This will also give a more OO interface to clients of the API that are not constrained by the need of global functions.