Introduction
Switch... Case statement is used for conditional operations. Sometimes, it is considered in the category of code smell. Switch case is not a bad syntax, but its usage in some cases categorizes it under code smell. It is considered a smell, if it is being used in OOPS. Thus, Switch case should be used very carefully.
Why is Switch... case considered as a code smell?
Switch...case is considered as a code smell due to the reasons given below.
- Violation of Open and close principle
Each time a developer wants to add a new type then he or she has to insert new switch.. case in each section. It promotes modification of an existing code. - Difficult to maintain
Switch... case can grow on the basis of new requirements. Switch case is being kept in a single function, so function will increase and and maintenance will be hard. - Provides the chances of Redundant Code
Switch... case provides the redundant code in some cases. The code given below is an example of containing lots of redundant codes.
- switch(input)
- {
- case "a":
- CreateValue("Hello");
- myData+= "Hello";
- case "b":
- CreateValue("Hi");
- myData+= "Hi";
- case "C":
- CreateValue("Hey");
- myData+= "Hey";
- default:
- myData = string.empty;
- }
How to Refactor the issue of code smell in Case...switch?
Switch... case can be refactored by using Polymorphism and strategy pattern with pattern searching.
The code given below is an example of Switch...case statement.
- public List<string> GetSortedData(string searchType, List<string> data)
- {
- List<string> sortedData = null;
- switch (searchType)
- {
- case "BubbleSort":
- //Peform Bubble sort and assign to data.
- sortedData = data;
- break;
- case "HeapSort":
- //Peform Heap sort and assign to data.
- sortedData = data;
- break;
- case "MergeSort":
- //Peform Merge sort and assign to data.
- sortedData = data;
- break;
- case "InsertionSort":
- //Peform Insertion sort and assign to data.
- sortedData = data;
- break;
- }
- return sortedData;
- }
Thus, the code given below is an example with Polymorphism, strategy pattern, and pattern search.
Mostofa KamalPosted Feb 28, 2019, 1:32 AM
But still you will need to modify your code in SortingContext to add new strategy in sortStrategy Dictionary .
Naveen BishtPosted Jul 24, 2017, 4:21 AM
Wau cool bro, really i learn today something. thanks for sharing