Tuesday, January 25, 2011

Should a method that can be static be static?

http://stackoverflow.com/questions/731763/should-c-methods-that-can-be-static-be-static/731779


It depends. There are really 2 types of static methods:
  1. Methods that are static because they CAN be
  2. Methods that are static because they HAVE to be
In a small to medium size code base you can really treat the two methods interchangeably.
If you have a method that is in the first category (can-be-static), and you need to change it to access class state, it's relatively straight forward to figure out if it's possible to turn the static method into a instance method.
In a large code base, however, the sheer number of call sites might make searching to see if it's possible to convert a static method to a non static one too costly. Many times people will see the number of calls, and say "ok... I better not change this method, but instead create a new one that does what I need".
That can result in either:
  1. A lot of code duplication
  2. An explosion in the number of method arguments
Both of those things are bad.
So, my advice would be that if you have a code base over 200K LOC, that I would only make methods static if they are must-be-static methods.
The refactoring from non-static to static is relatively easy (just add a keyword), so if you want to make a can-be-static into an actual static later (when you need it's functionality outside of an instance) then you can. However, the inverse refactoring, turning a can-be-static into a instance method is MUCH more expensive.
With large code bases it's better to error on the side of ease of extension, rather than on the side of idealogical purity.
So, for big projects don't make things static unless you need them to be. For small projects, just do what ever you like best.