Tuesday, February 3, 2009

Static classes and methods?

Hi,

Here's something that I really feel most people miss - questioning why they do something design wise.
A lot of people use static classes for reasons of laziness, it's easier to declare something as static than to create an instance and call methods on that.

Here's the thing, static classes generally go against OO design, you can't put an interface to a static class. That means that the code is going to be coupled to implementation, and so is not as easily maintainable.

I love unit testing, ideally with mocking, so my natural inclination is toward dependency injection. The resulting code due to following this approach with TDD is naturally a lot cleaner.

All static classes should be a thin veneer on an instance class, and so are then implementing a singleton pattern. I can see no other need for a static class - there's always an easy way around any other argument I have come across.

Take for example that it's nice to have access to a static class such as, MyDataLayer.Save(data). Instead how about defining a private property within the class, and lazy instantiating the reference within the property get? So for example:

private IDataLayer DataLayer
{
get
{
if (_dataLayer == null)
{
_dataLayer = new MyDataLayer();
}
return _dataLayer;
}
}

The only excuse you could have here for not using this approach is being lazy. This also allows you to inject dependencies through a special constructor, and the code will still work, so you can still unit test, and still get the easiness of static classes without all the drawbacks!

Happy Coding!

Martin.

No comments: