When I have state to maintain and share across compilation units, there are basically three main types of variables I can create. (Non-static Local variables are simple and don’t maintain state.)
- nonstatic field of a singleton class — Note any user of this variable need a reference to the single object 😦
- file scope var in a *.cpp — relatively simple usage, but don’t put in a shared header , as explained in global^file-scope variables]c++
- public static fields — most versatile design. Any user can access it after they #include the class header file.
- — non-contenders
- local static variables — (niche usage) You can create a local static var in myfunc(). To share the variable across compilation units, myfunc() can return a reference to this object, so from anywhere you can use the return value of myfunc(). This is a simple for of singleton.
- global variables — monster. Probably involves “extern”. See my other blogposts
The advantages of static field is often applicable to static methods too.
In fact, java leaves you with nothing but this choice, because this choice is versatile. Java has no “local static”, no file-scope, no global variables.