Can Patterns Be A Bad Thing?

posted on 11/14/07 at 12:35:25 am by Joel Ross

Anyone who's talked with me about software development will probably quickly realize that I am a big fan of design patterns. There's a a couple of reasons for that, mainly ease of communicating system design among developers and using proven techniques to solve common problems.

But like most things, there is a dark side to design patterns, and Alex Miller pointed out the downsides of a few patterns recently on his blog. First, he attacks probably the most widely known design pattern: The Singleton. He lists out some very key points that make the design pattern potentially problematic, but the biggest downside he lists to me is that it hides dependencies. When you build one, you usually think of a Singleton in terms of only wanting one instance of a class, rather than from the other side - any part of your code can use that one instance, and since that instance is (usually) global in scope, you can quickly lose track of how and where it's being used. Fast forward in your project, and that class becomes a brittle part of your system. Because it's potentially used everywhere in the system, changing it can easily break parts of the software you weren't thinking about - which brings up another one of Alex's points - they're hard to test because you can't mock it easily.

His alternative? Create an interface, and a class that implements that interface. Then create one instance of the class at the top level of your system and use Dependency Injection so all of your code uses that same instance. Now your code isn't using a "global variable" and is less coupled to the class itself, meaning you can now mock it to test it, because your code is based on interfaces rather than implementations.

Then he goes after Template methods. His basic argument is that it's not clear what your intent is, nor is it clear how the program logic flows. And again, his solution is interfaces and Dependency Injection.

Bottom line: understand the patterns you're using and understand more than just the pattern's strengths. You also need to know the downside, so you can code defensively to try to limit the impact of those downsides.

Oh, and use Dependency Injection!

Categories: Development