Static variables inside instance methods - How to fix that? - c++

Recently I inherited 10 year old code base with some interesting patterns. Among them is static variables inside instance methods. Only single instance of the class is instantiated and I can hardly find reason to justify existence of those static variables in instance methods.
Have you ever designed instance methods with static variables? And what are your rationales?
If this pattern is considered bad then how to fix it?
Note: This question is not relevant to Static variables in instance methods
EDIT:
Some reading:
static class and singleton
http://objectmentor.com/resources/articles/SingletonAndMonostate.pdf
http://www.semantics.org/once_weakly/w01_expanding_monostate.pdf

This is a classic C++ implementation of the singleton pattern, described in one of Scott Meyers C++ books.
Singleton is a controversial pattern, so there is no industry-wide consensus on singleton being good or bad.
An alternative to singletons is a purely static objects. This question has a good discussion.

About the only time I've used static fields in an instanciable class has been as constants.
Generally speaking, you would want to create your class to be either entirely static, or entirely instanciable (with perhaps the exception of constants which you may want to keep static). With a singleton class they will behave in much the same way. The danger of mixing the two techniques is if you decide to make the class no longer a singleton, you might run into some strange behaviours in your now multi-instanced class.

Having a static variable is useful in a procedural function as it can serve as a kind of global variable with limited scope.
The only reason I can see to do something like this in a method would be to have the variable persist over many calls without having to declare a member variable that serves no other purpose. Honestly, I feel like this is just lazy programming and should be avoided.

Related

Always create classes in C++? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
Coming from a Java background it is new for me to deal with the choice of creating a class or just implementing the functions I might need. Normally this is no question when it comes to modeling something which could have a state.
Now I am implementing a shared library which has no main function and exclusively static member functions. Does something speak against creating a class to encapsulate the functions?
Further I wanted to encapsulate further code, especially auxillary functions, in another file. The execute code is always the same and the state of it does not change, so I guess I would declare them also static - so the same questions arises here to.
If you find you have a class where every method is static, then perhaps a namespace would be more appropriate.
Frankly, this is philosophical, and kind of fuzzy guidelines, but I prefer to use the simplest things first then build up in terms of complexity when its needed.
My first preference is
Free, stateless, side-effect free functions that perform some operations/calculations/transformations on their arguments and return the result(s).
However, if any of those arguments evolve to become stateful, and your function become in charge of maintaining that state, consider wrapping stateful data and methods that manipulate that data into a class for good encapsulation/data hiding.
File I/O is an example of something that's stateful. You open a file, write some data to it which moves ahead a write pointer, and ultimately close it, its a good example of where you'd want a class.
The most obvious example of a place where a free functions are best are math. Other examples might be performing a regex, transforming one kind of message into another kind, etc.
(1) Is simplest because in its purest form there's no persistent state, everything is transformational, and you should consistently get the same output with the same input. Easy to test, easy to figure out how it works. Ideally we wouldn't need to persist any state and we could all program this way.
(2) Is needed because safely updating state is a necessary part of life and if you can't do any data hiding or encapsulation you lose confidence that state is being maintained correctly and safely.
You may want to define a namespace instead of a class.
namespace mycode
{
//Code for the library here
void myfunction()
{
//function definition
}
}
then when you need to use it you can either preface it or use the namespace
mycode::myfunction()
or
using mycode;
myfunction();
Not sure if I completely understand you but yes you can create a container class that provides static methods. It may be worthwhile to make the constructors private to prevent people from instantiation an instance of the class.
class HelperFunctions
{
public:
static void DoSomethingUseful() { /* useful bits */ }
// yata yata
private:
HelperFunctions(); // private default constructor
HelperFunctions(const HelperFunctions&); // private copy constructor
};
Then you could do something like this:
HelperFunctions::DoSomethingUseful();
But you couldn't do something like this:
HelperFunctions myHelperFunction; // private constructor = compile error
You also could create namespaces for the purpose of organization non-member functions.
namespace HelperFunctions
{
void DoSomethingUseful() { /* useful bits */ }
// yata yata
}
Remember you can define namespaces across multiple files as well making these particular useful for grouping objects and functions wherever they may be. This is preferable as it logically separates the functions making the design and intended use more obvious
Unlike Java where everything is a method in C++ we can have functions at a global, namespace, or member scope. You also can have non-member friend functions which can access internal members of a class without being a member of the class themselves.
Basically you can do whatever you want including shoot yourself in the foot.
Edit: Why so serious?
I wasn't suggesting what the OP should or shouldn't do. It seemed as though they were new to C++ coming from the Java world where everything is a method and all "functions" are class members. To that affect my answer was to show how firstly you can create something in C++ similar to what you might have in Java and secondly how you can do other things as well and why that is.
As others have stated it's considered good practice to prefer non-member non-friend functions when possible for various reasons. I agree if you do not need an object with state than you probably shouldn't design one. However I'm not sure if the OP was looking for a philosophical discussion on best practice in design and implementation or just a curiosity for equivalent C++.
I had hoped my last line joking about shooting yourself in the foot was enough to make the point that "just because you can, doesn't mean you should" but perhaps not with this crowd.
Actually, if the code does not belong in a class, you should not put it in a class in C++. That is, one should prefer non-friend non-member functions to member and friend functions. The reason is that pulling the method out of the class results in better encapsulation.
But don't take my word for it, see Scott Meyers' Effective C++ Item #23: Prefer non-member non-friend functions to member functions.
Careful, in C++, static functions are functions that are only visible to other functions in the same file. So basically they are auxiliary functions that cannot be part of the interface of a library.
Static methods in classes is something completely different (even though the same keyword is used in both cases). They are just like normal functions that can call protected/private methods in the same class. You can think of static methods as simple (non-static) functions that are "friends" with the class.
As for the general guideline, I don't think it matters if you have (non-static) functions or static methods as the interface of your library, this is mostly a matter of syntax: call f() or call obj::f(). You can also use namespaces for encapsulation. In this case the syntax is: ns::f() for a function and ns::obj::f() for a static method.
EDIT: Ok, I though there was a confusion around the keyword static, turns out this is more of a controversial answer than I would have wanted it to be. I personally prefer the term method for member functions (which is also the same vocabulary used in the actual question). And when I said static methods can call private methods I was referring to visibility (a.k.a. access control).

c++ global functions and OOP?

In C++ one can have a 'GLOBAL FUNCTION', which means it does not belong to any class. I wondered if that isn't just a violation of the basic principles of OOP?
What would be the difference with using a global function or function that is static in a class? I'm thinking the latter is more OOP oriented. But I may be wrong however...
Does it not make it harder when writing a multithreaded applicaton?
A static function inside a class is as OO as a global function inside a module. The thing is in JAVA, you don't have the choice.
In C++, you can encapsulate your global functions inside namespaces, you don't need a dummy class to do this. This way you have modularity.
So of course you can put functions outside namespaces this way you have really global functions. But that's not very different from a JAVA kitchen sink class with a bunch of static functions. It's also bad code, but can be just ok for small projects :)
Also in C++ you have a lot of choices to have "global" function that actually are linked to a class, as operator functions, that may be for instance friends of a class.
EDIT
As for multithreading, you have to worry about global variables, not functions.
C++ facilitates many programming paradigms: structured, OOP, functional.
It makes no sense to choose for an OO approach for a small (hello world-style) program.
It makes no sense to use a structured approach for a modular program.
Next to that, static class functions are just better organized than 'free' functions; on top of that, they have access to an object's private variables - better encapsulation.
Static methods are able to access private static fields on the class they're in, but that's about the only difference from global functions.
Global functions are there because C++ is roughly a superset of C, and C has global functions. C can be used for both OOP and non-OOP programming.
And, frankly, does it really make a difference whether you type std::Math::max or std::max?
Totally agree with other answers and i want to add my advice. Static functions and static methods are almost same things and abusing them can lead to poor oo design. If you want to keep your object model clean you should use static functions/methods only if:
they do not produce result that depends on state of object
they do not change state of object

what is the best way to use global variables in c++?

For me, I usually make a global class with all members static. All other classes will inherit from this global class.
I wonder if this is a good practice?
Anybody got any suggestions?
Generally try to avoid global variables as they introduce global state. And with global state you do not have referential transparency. Referential transparency is a good thing and global state is a bad thing. Global state makes unit tests pretty pointless for example.
When you have to though, I'd agree that most of the time the method you mentioned is fine. You can also declare the global variable in any .cpp file and then have in your .h file an extern to that global variable.
Best way? Carefully... :-)
Your suggested practice has not solved a single problem associated with global variables.
Private member data with access functions allow single point control of read/write and validation, improving robustness, maintainability, and ease of debugging.
Making the data members static simply reduces flexibility; you might want multiple independent global objects containing the same data structure. If there should only ever be one, use the singleton pattern.
Collecting unrelated global data into a single class breaks best practice regarding coupling and cohesion and is hardly OO.
This article relates to C and embedded systems, but is no less relevant to your question.
First, global state is bad. It seriously complicates understanding the program, since the behavior of any part can depend on the global variables. It makes it harder to test. It provides a way by which two far-distant functions can create an inconsistent state that may mess up another function, and that will be very difficult indeed to debug.
The nature of the global state doesn't matter. This is what's usually maligned about the Singleton pattern, for example.
However, having every class inherit from one global variable class is a bad idea. In C++, inheritance should be used sparingly, as it ties two classes together in implementation. It's usually a bad thing to have all the classes inheriting from one base class in any form, and C++ doesn't handle multiple inheritance really well. It would be really easy to get the "deadly diamond" effect, since if A inherits from B and they both inherit from Global, Global will appear twice in A's inheritance hierarchy.
There are 2 things that chagrined me: The use of global variables is bad, but sometimes it's difficult to do without, however I am chagrined by:
The clear abuse of inheritance
The wonderful dependency issue
The combination of the two has a staggering effect.
Let's say I create a class that will access a global variable, from your Anti-Pattern it gives:
#include "globals.h"
class MyClass: Globals // for my own sake I assume it's not public inheritance
{
};
Of course, the #include is mandatory in the header, since I inherit from it. Therefore each time I add / change one of the global, even one that is used by a single class... I recompile the whole application.
If we'd ever worked on the same team, that would earn you a very harsh, very stern comment... to say the least.
Ick!
A global variable is a global variable. Renaming it -- even with a name that makes it look like a member varaible, doesn't change that. Every problem that you have with a oridinary global variable you will still have with your global-variable-as-common-static-member scheme (and possibly a few new ones).
You are most likely looking for the Singleton pattern. That is not to say that all global variables need to use the pattern. But, when I have a global it is usually because I want only one instantiation for the entire program. In this case, singleton can work very well.
http://en.wikipedia.org/wiki/Singleton_pattern

Class with static members vs singleton

Isn’t a class with only static members a kind of singleton design pattern? Is there any disadvantage of having such a class? A detailed explanation would help.
This kind of class is known as a monostate - it is somewhat different from a singleton.
Why use a monostate rather than a singleton? In their original paper on the pattern, Bell & Crawford suggest three reasonns (paraphrased by me):
More natural access syntax
singleton lacks a name
easier to inherit from
I must admit, I don't find any of these particularly compelling. On the other hand, the monostate is definitely no worse than the singleton.
Robert C. Martin wrote an article some times ago about the differences between the mono state pattern and the singleton pattern.
Consider a family of Logging classes. They all implement "LogMessage(message, file, line_number). Some send messages to stderr, some send email to a set of developers, some increment the count of the particular message in a message-frequency table, some route to /dev/null. At runtime, the program checks its argument vector, registry, or environment variables for which Logging technique to use and instantiates the Logging Singleton with an object from a suitable class, possibly loading an end-user-supplied DLL to do so. That functionality is tough to duplicate with a pure static Singleton.
class with all static members/methods
a kind of singleton design pattern
Class - not pattern. When we talk about classes we can say class implements pattern.
Static functions - is not member functions, they are similar on global functions. Maybe you don't need any class?
Quote from wikipedia:
In software engineering, the singleton
pattern is a design pattern that is
used to restrict instantiation of a
class to one object.
By this definition your implementation is not singleton implementation - you don't use common idea One (or several in extended definition) instance of class.
But sometimes (not always) usage of class with all static functions and singleton pattern - not have meaningful difference.
For a singleton all constructors have to be private, so that you can access only through a function. But you're pretty close to it.

Is using too much static bad or good?

I like to use static functions in C++ as a way to categorize them, like C# does.
Console::WriteLine("hello")
Is this good or bad? If the functions are used often I guess it doesn't matter, but if not do they put pressure on memory?
What about static const?
but is it good or bad
The first adjective that comes to mind is "unnecessary". C++ has free functions and namespaces, so why would you need to make them static functions in a class?
The use of static methods in uninstantiable classes in C# and Java is a workaround because those languages don't have free functions (that is, functions that reside directly in the namespace, rather than as part of a class). C++ doesn't have that flaw. Just use a namespace.
I'm all for using static functions. These just make sense especially when organized into modules (static class in C#).
However, the moment those functions need some kind of external (non compile-time const) data, then that function should be made an instance method and encapsulated along with its data into a class.
In a nutshell: static functions ok, static data bad.
Those who say static functions can be replaced by namespaces are wrong, here is a simple example:
class X
{
public:
static void f1 ()
{
...
f2 ();
}
private:
static void f2 () {}
};
As you can see, public static function f1 calls another static, but private function f2.
This is not just a collection of functions, but a smart collection with its own encapsulated methods. Namespaces would not give us this functionality.
Many people use the "singleton" pattern, just because it is a common practice, but in many cases you need a class with several static methods and just one static data member. In this case there is no need for a singleton at all. Also calling the method instance() is slower than just accessing the static functions/members directly.
Use namespaces to make a collection of functions:
namespace Console {
void WriteLine(...) // ...
}
As for memory, functions use the same amount outside a function, as a static member function or in a namespace. That is: no memory other that the code itself.
One specific reason static data is bad, is that C++ makes no guarantees about initialization order of static objects in different translation units. In practice this can cause problems when one object depends on another in a different translation unit. Scott Meyers discusses this in Item 26 of his book More Effective C++.
Agree with Frank here, there's not a problem with static (global) functions (of course providing they are organised).. The problems only start to really creep in when people think "oh I will just make the scope on this bit of data a little wider".. Slippery slope :)
To put it really into perspective.. Functional Programming ;)
The problem with static functions is that they can lead to a design that breaks encapsulation. For example, if you find yourself writing something like:
public class TotalManager
{
public double getTotal(Hamburger burger)
{
return burger.getPrice() + burget.getTax();
}
}
...then you might need to rethink your design. Static functions often require you to use setters and getters which clutter a Class's API and makes things more complicated in general. In my example, it might be better to remove Hamburger's getters and just move the getTotal() class into Hamburger itself.
I tend to make classes that consist of static functions, but some say the "right way" to do this is usually to use namespaces instead. (I developed my habits before C++ had namespaces.)
BTW, if you have a class that consists only of static data and functions, you should declare the constructor to be private, so nobody tries to instantiate it. (This is one of the reasons some argue to use namespaces rather than classes.)
For organization, use namespaces as already stated.
For global data I like to use the singleton pattern because it helps with the problem of the unknown initialization order of static objects. In other words, if you use the object as a singleton it is guaranteed to be initialized when its used.
Also be sure that your static functions are stateless so that they are thread safe.
I usually only use statics in conjunction with the friend system.
For example, I have a class which uses a lot of (inlined) internal helper functions to calculate stuff, including operations on private data.
This, of course, increases the number of functions the class interface has.
To get rid of that, I declare a helper class in the original classes .cpp file (and thus unseen to the outside world), make it a friend of the original class, and then move the old helper functions into static (inline) member functions of the helper class, passing the old class per reference in addition to the old parameters.
This keeps the interface slim and doesn't require a big listing of free friend functions.
Inlining also works nicely, so I'm not completely against static.
(I avoid it as much as I can, but using it like this, I like to do.)