Wednesday, 2 July 2008

static or non-static?

Are static functions good or bad? Should data ever be static? Well firstly we need to say that we are talking about OO design and not structural code. Static in C++ sometimes meant that something had file visibility and sometimes that a single function existed requiring no instance of the parent class to call it.
So good or bad? We should be pragmatic about this. It is rarely correct to say that there is "never any reason to use static" or vice-versa so let us state what we know about the pros and cons of static methods:
1) Quick and dirty (bad reason)
2) Allows a consumer class to obtain a reference to something without knowing its concrete type (e.g. encapsulated constructor) means that the consumer calls something like
IMyInterface inf = HelperClass.CreateObject();
rather than
IMyInterface inf = new ConcreteClass();

3) In the case of certain scenarios such as database helper functions, it might seem neater and clearer to have
rather than
new ClassName().NonStaticFunction(whatever);
ClassName cn = new ClassName();

1) No polymorphism of function, i.e. a subclass cannot override the static method, it can only hide it.
2) If it is a non-constructor then it ties the consumer to the type of class providing the function. If you want to change the provider, you have to modify the consumer.
3) Static functions are not implicitly thread safe because all threads would access the same local variables. Instance function local variables are created on the thread stack and are isolated from each other.
4) Static functions can gloss over a badly levelled system. If you have a class called
that has a static function
Employee[] GetAllEmployees();
then levelled correctly, you should have another class called, i.e. Company and this new class would have a non-static method called GetAllEmployees() which would return an array of type Employee. The levelling has removed the need for the static function.

My own opinion is that I start with instance functions and only use static ones where the instance ones do not suit the situation for some reason. Up until this point, I have only ever used static functions to match existing code or to call static functions in libraries that I did not write although I have been convinced recently that the encapsulated constructor using a static method is a good idea (not to be confused with Singleton pattern which is similar but only permits a single instance).
Post a Comment