Repeated Conditional Complexity
When you encounter repeated complex "switch" operators or sequences of "if" statements.
Sign of Smell
Repeated Conditional Complexity has many different names. One of the reasons for this is that I combined two code smells: "Switch Statements" and "Conditional Complexity". Switch Statements, also known as "Repeated Switches" in later versions, focuses on repeated conditional logic. On the other hand, "Conditional Complexity" is more focused on complexity itself. I understand that "repeated" and "complex" are not the same, but I believe it is unnecessary for them to coexist as two separate code smells.
It occurs when conditional logic such as switch 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 less maintainable, extensible, and error-prone code.
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 code flow.
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 this code smell, you can use several strategies:
Move Accumulation to Visitor
Move Embellishment to Decorator
Replace Conditional with Polymorphism
Replace Conditional Dispatcher with Command
Replace Conditional Logic with Strategy
Replace Type Code with Subclasses
Replace Type Code with State/Strategy
Replace Parameter with Explicit Methods
Replace State-Altering Conditionals with State
Introduce Null Object
Reference
Last updated