Refactoring Switch or IF/ELSE statements
It is not unusual to see a lot of switch statements or multiple if else statements in OO codes. From the view of code maintainability, probably some of such codes need refactoring. Strategy pattern is a good replacement.
For example, the old code is like:
internal void Run()
{
int[] numbers = { 2, 1, 5, 6 };
Sort(numbers, SortType.QuickSort);
}
void Sort(int[] numbers, SortType type)
{
switch (type)
{
case SortType.QuickSort:
QuickSort(numbers);
break;
case SortType.MergeSort:
MergeSort(numbers);
break;
....
}
....
}
Thus, it is a good chance to apply strategy pattern here. The new code is like:
internal void Run()
{
int[] numbers = { 2, 1, 5, 6 };
Context context= new Context (new QuickSort(numbers));
context.Sort();
}
There are a lot of resources about strategy pattern, so here I will skip other parts to complete the above code. As you can see, in the future, if we have new Sort algorithm, we do not need to modify the implementation big Sort(int[] numbers, SortType type) method (described in the old code). Instead, we just need to add a new class to implement the ISortAlgorithm interface. It reflects the open-close principle and improves maintainability of codes.
Comments
- Anonymous
February 27, 2008
PingBack from http://www.biosensorab.org/2008/02/27/refactoring-switch-or-ifelse-statements/