C++ Interfaces
- The curse of non-const global variables
- Dependency injection as a cure
- Making good interfaces
- Related rules
An interface is a contract between a service provider and a service user. Interfaces are, according to the C++ Core Guidelines, “probably the most important single aspect of code organization.” The section on interfaces has about twenty rules. Four of the rules are related to contracts, which didn’t make it into the C++20 standard.
A few rules related to interfaces involve contracts, which may be part of C++23. A contract specifies preconditions, postconditions, and invariants for functions that can be checked at run time. Due to the uncertainty of the future, I ignore these rules. The appendix provides a short introduction to contracts.
Let me end this introduction with my favorite quote from Scott Meyers:
Make interfaces easy to use correctly and hard to use incorrectly.
Of course, you should avoid non-const global variables. But why? Why is a global variable, in particular when it is non-constant, bad? A global injects a hidden dependency into the function, which is not part of the interface. The following code snippet makes my point:
int glob{2011}; int multiply(int fac) { glob *= glob; return glob * fac; }
The execution of the function multiply changes, as a side effect, the value of the global variable glob. Therefore, you cannot test the function or reason about the function in isolation. When more threads use multiply concurrently, you have to protect the variable glob. There are more drawbacks to non-const global variables. If the function multiply had no side effects, you could have stored the previous result and reused the cached value for performance reasons.
The curse of non-const global variables
Using non-const globals has many drawbacks. First and foremost, non-const globals break encapsulation. This breaking of encapsulation makes it impossible to think about your functions/classes (entities) in isolation. The following bullet points enumerate the main drawbacks of non-const global variables.
Testability: You cannot test your entities in isolation. There are no units, and therefore, there is no unit testing. You can only perform system testing. The effect of your entities depends on the state of the entire system.
Refactoring: It is quite challenging to refactor your code because you cannot reason about your code in isolation.
Optimization: You cannot easily rearrange the function invocations or perform the function invocations on different threads because there may be hidden dependencies. It’s also extremely dangerous to cache previous results of function calls.
Concurrency: The necessary condition for having a data race is a shared, mutable state. Non-const global variables are shared and mutable.
Sometimes, global variables are very well disguised.
// singleton.cpp class MySingleton { public: MySingleton(const MySingleton&)= delete; MySingleton& operator = (const MySingleton&)= delete; static MySingleton* getInstance() { if ( !instance ){ instance= new MySingleton(); } return instance; } private: static MySingleton* instance; MySingleton()= default; ~MySingleton()= default; }; MySingleton* MySingleton::instance= nullptr; int main() { std::cout << MySingleton::getInstance() << "\n"; std::cout << MySingleton::getInstance() << "\n"; }
A singleton is just a global, and you should, therefore, avoid singletons, if possible. A singleton gives the straightforward guarantee that only one instance of a class exists. As a global, a singleton injects a dependency, which ignores the interface of a function. This is due to the fact that singletons as static variables are typically invoked directly: Singleton::getInstance() as shown in the two lines of the main function. The direct invocation of the singleton has a few serious consequences. You cannot unit test a function having a singleton because there is no unit. Additionally, you cannot fake your singleton and replace it during run time because the singleton is not part of the function interface. To make it short: Singletons break the testability of your code.
Implementing a singleton seems like a piece of cake but is not. You are faced with a few challenges:
Who is responsible for destroying the singleton?
Should it be possible to derive from the singleton?
How can you initialize a singleton in a thread-safe way?
In which sequence are singletons initialized when they depend on each other and are in different translation units? This is to scare you. This challenge is called the static initialization order problem.
The bad reputation of the singleton is, in particular, due to an additional fact. Singletons were heavily overused. I see programs that consist entirely of singletons. There are no objects because the developer wants to prove that they apply design patterns.