<= Home

The Evil Static Member

Posted about over 2 years ago

Anyone I have worked with knows my distaste for static methods in C# or Shared in VB.Net. Not surprisingly I get lots of resistance on this, made evident by challenges from fellow coworkers.

As a developer that values the agile manifesto, I try my hardest during development to make the systems I work on resilient and adaptable so that they can respond to change. With this comes the need for good class design (a class handling specific responsibilities), using OOP techniques (i.e. polymorphism), and following popular time proven positions like “code to an interface, not an implementation”.

Now I do recognize that there is some value in static/shared class members, I use them myself when appropriate. But the reason I do not like prolific use of static members is because there is nothing resilient or adaptable about them. You can not override static members, they can not be declared in Interfaces, any client of a shared method is tightly coupled to that implementation, and the list goes on and on.

The common argument though when I bring this up is that a developer will say about his/her class that “it’s not going to change so why would I need to ever override it in a derived class or extract an interface from it”. I have no answer for them because they appear to be fortune tellers that can predict the future. But because of my lack psychic abilities I presume that any of my code may change at anytime in the future. When that change request comes, those static members will become a major thorn in someone’s side.

The GoF offers up a tasty pattern called the Singleton. Now the singleton should come with its’ own disclaimer too, but none the less I will quote from the wise book:

“Another way to package a singleton’s functionality is to use class operations (that is, static member functions in C++ or class methods in Smalltalk). But both of these language techniques make it hard to change a design to allow more than one instance of a class. Moreover, static member functions in C++ are never virtual, so subclasses can’t override them polymorphically.”

I am sure that this will bring an onslaught of criticism from many. Because overuse of static methods is very reminiscent of the old VB6 function bag module, I have created a new organization for my critics. FBF (Function bag Foundation) – accepting members now.