November 14, 2008

When to use static methods

I started using Resharper again after some time. And one thing that bugs me is that it always warns me that functions can be made static. I've kinda stopped using static methods. Static methods arent injectable, static methods make code using them less modular and less testable and static methods are the devils own handywork if you want to believe some people. On the other hand they make your code simpler by not requiring an object instance to be called. This got me thinking. Do I want to use statics or just ban them completely? And if not when is it ok to use them?

I started using IoC extensively in my code with Windsor and Ninject to support this habit. I've found this makes my code more testable and because it forces me to think about introducing dependencies it nicely decouples everything it touches. Less problems with calling uninitialised classes etc. I think IoC is a big enabler of TDD. I used unit tests before I did IoC but usually it took me more time to write and maintain my tests than the time it saved me. Mostly because of dependencies in my code.

Calling static methods means tightly coupling your code to this method so when is it ok to do this? I've come up with the following rule of thumb. I thought I'd throw this out there to get some feedback.

Static functions should have no side effects, they should not change the objects you give them as parameters and should only generate a return value.

This also means no reading/writing of files, databases etc. No network access. No PInvokes (yeah i know they are static by definition, that's why I wrap them in facade classes).

The reasoning behind this is that you should have no reason to want to replace a call to a static method in your code. Not for testing and not in production because you can't. If you want to unit-test or use code that uses this method you're forced to see it as a whole with the static method call itself.

What am I left with? Mostly simple utility methods. Parsing path names for example. Simple calculations. Simple factory methods, although those are an edge case to me. 

What do you think? 

No comments:

Post a Comment