Do you really need that design pattern ?
I chanced upon a post a while back about how a switch statement should be replaced with the strategy pattern. If you have not had a chance to go through it, please do. The post is not very long. I found myself disagreeing very strongly with the author of the post and I was surprised to find that people thought this was a good idea.
The gist of the post was that using the Strategy pattern was better than using switch statements to determine which logic to execute. Here is why I think the idea used there was bad
- The introduction of the Strategy pattern, in the example, introduces three new classes. So for every case in a switch statement, we should go about replacing the corresponding code with a new class ? This could easily lead to an explosion in the number of classes.
- Distributing logic across classes makes it harder for a developer to follow. When I traverse 2 / 3 links down a code path I might lose track of where I started.
- Introducing a new case means I have to introduce one more class, remember to add that as a strategy and switch to that strategy correctly when the case is presented.
- Introducing a new class to handle a ‘case’ might not make sense. Classes are supposed to cohesively carry out a function. Introducing a new class for every function that a class is supposed to perform, dilutes the purpose of the class.
- The code that was supposed to perform the switch case is simply done else where and called a strategy.
Applying patterns where they do not belong, can be an anti pattern by itself. I can relate with what the author is trying to do. When I finished the ‘Head first design patterns’ book I was racing to implement a pattern for everything that was around me. The book stopped me right there and warned ‘HelloWorld does not need a design pattern’. And they are absolutely right. For a design pattern to succeed, you need
- The right problem to apply the pattern.
- Correct implementation of the pattern to solve the problem.
- Knowledge and relevant documentation if necessary, to let the maintenance developer down the line know that this is how you used the pattern.
Patterns are meant to solve common design problems but trying to use them everywhere can lead to overly engineered code that is hard to read and maintain. Use patterns only when they are necessary and help you solve the problem.