Repeated Conditional Complexity
When you encounter repeated complex "switch" statements or sequences of "if" statements in your code.
Sign of Smell
Switch Statements is a code smell that occurs when conditional statements such as a switch or case statements (or "if-else" statements) are used to control the flow of a program based on different values or conditions. Although these statements are a fundamental part of many programming languages, relying too heavily on them can result in code that is less maintainable, less extensible, and more error-prone.
Reason of Smell
Reduced Readability: Switch statements can become long and complex, making the code harder to read and understand. Each case can have different logic, and it becomes challenging to follow the flow of the code.
Duplication: Similar code might be repeated across different cases, leading to code duplication. This duplication can introduce inconsistencies and make it harder to maintain.
Limited Extensibility: If you need to add new behavior or conditions in the future, adding them to an existing switch statement can lead to a more convoluted and complex code structure.
Low Maintainability: As the number of cases in a switch statement grows, it becomes harder to maintain. Any changes or additions to the cases can lead to cascading changes throughout the codebase, increasing the risk of introducing bugs.
Violation of Open/Closed Principle: The Open/Closed Principle suggests that software entities (classes, modules, functions) should be open for extension but closed for modification. Switch statements often require modification whenever a new case is added, violating this principle.
Lack of Encapsulation: Switch statements tend to centralize decision-making logic, leading to tight coupling between different parts of the code. This lack of encapsulation can make the codebase more brittle and harder to refactor.
Testability: Testing different cases within a switch statement can be more challenging, as each case might have unique logic that needs to be tested individually.
Refactoring Recipe
To address the "Switch Statements" code smell, you can use several strategies:
Move Accumulation to Visitor
Replace Conditional Dispatcher with Command
Replace Conditional with Polymorphism
Replace Type Code with Subclasses
Replace Type Code with State/Strategy
Replace Parameter with Explicit Methods
Introduce Null Object
Reference
https://refactoring.guru/smells/switch-statements
https://www.jianshu.com/p/50a9510673b7
https://www.informit.com/articles/article.aspx?p=2952392&seqNum=12