If I’ve got code similar to this (although perhaps not as constrained as warning levels):
switch(item.StatusCode)
{
case StatusCode.SUCCESS:
CallSuccess(item);
break;
case StatusCode.WARNING:
CallWarning(item);
break;
case StatusCode.ERROR:
CallError(item);
break;
}
I often find myself converting it to something more like:
var behaviors = new Dictionary<StatusCode, Action<Item>>
{
{StatusCode.SUCCESS, (item) => CallSuccess(item)},
{StatusCode.WARNING, (item) => CallWarning(item)},
{StatusCode.ERROR, (item) => CallError(item)},
}
behaviors[item.StatusCode](item);
I find that in a lot of cases this makes for more maintainable code. Is this a pattern, does it actually help like I think it does, and what’s its name?
Strategy pattern & Open Closed Principle
It looks like Open Closed Principle is pretty good to solve described routine issue. This is a part of S.O.L.I.D. principles. One of its applications is in strategy pattern, also mentioned in (GoF).
This principle usually works when an existing codebase is written, but yet it’s easier to write all new code than it is to change old code.
Wouldn't you like extending an existing codebase to be as productive and frustration-free as writing all new code?
– This is where the Open Closed Principle comes into play. To paraphrase, the Open Closed Principle is stated as: software entities should be open for extension but closed for modification.
What Benefits does it provide ?
- The code is easier to read. I don’t need to go and read (or
search) an “endless” switch statement to understand each aspect of the code. - The code is more maintainable. I only need to go to the relevant class that implement the logic in order to change it or refactor it when needed.
- It is easier to add more logic. I only need to add more classes
to the pile of existing logic and that is it. Doing so helps us to imply
the Open / Closed Principle because in if/switch statements we are going
to have to change our code (add another case statement) in opposed
to Strategy which we do not change existing logic. - Strategy Pattern is more testable. Unit testing can be easily done.
Some references:
- The Strategy Pattern in .NET
- The Open Closed Principle
- LOS Techies
- Applying Strategy Pattern Instead of Using Switch Statements
I believe this is usually considered an application of the Strategy Pattern.
The whole point of this is more maintainable code – among other things, it makes it trivial to add new behaviors at runtime (to say nothing of compile time). There is (usually) some loss in terms of performance, but this tends to be outweighed by the increase in maintainability.
1