Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is using too much static bad or good?

Tags:

c++

static

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?

like image 927
CiNN Avatar asked Aug 27 '08 19:08

CiNN


People also ask

Is it bad to use static methods?

Static methods are bad for testability. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous.

Is static bad 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.

What is static abuse?

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.


1 Answers

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.

like image 185
Andrew Avatar answered Sep 29 '22 06:09

Andrew