Static function leading to more static functions
I have a class that has a few functions that are useful on their own, which are static. Now these functions depend on other functions that are not useful on their own (but don't intera开发者_Python百科ct with class member variables) but are also static, so they are private. Now I have a class with many non-static functions, and couple of static public functions and a few static private functions.
Is this good practice? (should I be making this a community wiki?)
I think you should declare those functions as free functions. If they do not need the members it should be not a big deal.
Maybe you should read this article. I found it very useful to improve my class designs.
That sounds good, and would work well. There are some things to consider though.
It may be possible to make the private static functions even more private. If you just placed them in the .cpp file as free functions (not in a class, but ideally in an 'unnamed namespace'), then they wouldn't make an appearance in the .h file. This would be advantageous because another .cpp file that uses your class wouldn't see these private static variables. That would make the compile time quicker. Also, it would leave you free to alter the functions in the .cpp file, and if you made any changes, other files using the .h file wouldn't need to be recompiled on every change because you wouldn't have to change the .h file to change these functions.
Secondly, sometimes static functions can cause the writing of unit tests to be trickier. If you have a class X that uses these static functions, it's tricky to isolate class X from the static functions if you want to test class X. If instead, you used non static methods and defined an interface class that the class you're writing derives from, you could more easily use 'inversion of control' and 'dependency injection' techniques to write unit tests for your classes. I won't explain those techniques here, as there are plenty of good descriptions already floating about the internet.
Keep it simple. static
function which has nothing to do with the class can be encapsulated either in an inner class
or in a new namepsace
. e.g
struct A
{
struct Util // can also be put outside in a namespace for others to use
{
static void Independent () { }
};
static void dependent ();
};
I would look at the "many non-static functions" as well as probably you could split the class into some smaller entities related by inheritance or ideally being more independent and could be brought to the initial form by composition. Generally the word "many" is not a sign of good design.
精彩评论