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
?
Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous.
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.
you are abusing static, if you are trying to do OOP and instead are making it reference programming by never having to create a new object and instead just need to call the class without ever making an instance. – jgr208. May 18, 2015 at 15:16.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With