Static function leading to more static functions

I have a class that has several functions that are useful in themselves, which are static. Now these functions depend on other functions that are not useful in themselves (but do not interact with class member variables), but are also static, so they are private. Now I have a class with many non-static functions and a couple of static public functions and several static private functions.

Is this a good practice? (should i do this wiki community?)

+6
source share
4 answers

I think you should declare these functions as free functions. If they do not need members, this should not be a big problem.
Perhaps you should read the article. It was very useful for me to improve the design of my class.

+10
source

This sounds good and will work well. There are some things to consider.

Private static functions can be made even more private. If you simply placed them in a .cpp file as free functions (not in a class, but ideally in an "unnamed namespace"), then they will not appear in the .h file. This would be beneficial because another .cpp file that your class uses will not see these private static variables. This will speed up compilation time. In addition, it will allow you to freely change the functions in the .cpp file, and if you make any changes, other files using the .h file will not need to be recompiled with each change, because you do not have to change .h to change these functions.

Secondly, sometimes static functions can make writing unit tests difficult. If you have an X class that uses these static functions, it is difficult to isolate the X class from static functions if you want to test the X class. If you used non-static methods instead and defined an interface class which class you are writing, you can more it’s easy to use the “inverse control” and “dependency injection” methods to write unit tests for your classes. I will not explain these methods here, as there are many good descriptions that already float on the Internet.

+4
source

Keep it simple. The static function, which has nothing to do with the class, can be encapsulated in either the inner class or the new namepsace . eg

 struct A { struct Util // can also be put outside in a namespace for others to use { static void Independent () { } }; static void dependent (); }; 
0
source

I would look at “many non-static functions”, and also, maybe you could break the class into some smaller objects related to inheritance, or ideally be more independent and can be transferred to the original form by composition. As a rule, the word "many" is not a sign of good design.

0
source

Source: https://habr.com/ru/post/888324/


All Articles