Refactoring techniques. Simplify conditional expressions

Lecture



The logic of conditional execution tends to become complicated, so a number of refactorings are intended to simplify it.

Splitting a conditional statement

Problem: You have a complex conditional statement (if-then / else or switch).

Solution: Select into separate methods all complex parts of the operator: condition, then and else.

Combining conditional statements

Problem: You have several conditional statements leading to the same result or action.

Solution: Combine all the conditions in one conditional statement.

Merging duplicate fragments in conditional statements

Problem: The same code fragment is in all branches of the conditional operator.

Solution: Move it beyond the operator.

Remove control flag

Problem: You have a boolean variable that plays the role of a control flag for several boolean expressions.

Solution: Use break, continue and return instead of this variable.

Replacing nested conditional operators with a boundary operator

Problem: You have a group of nested conditional statements, among which it is difficult to distinguish the normal course of code execution.

Solution: Select all the checks for special or boundary cases of execution in separate conditions and place them in front of the main checks. Ideally, you should get a “flat” list of conditional statements, one after another.

Replacing a Conditional Operator with Polymorphism

Problem: You have a conditional statement that, depending on the type or properties of the object, performs various actions.

Solution: Create subclasses with which the branches of the conditional operator correspond. In them, create a common method and move the code into it from the corresponding branch of the conditional operator. Subsequently, replace the conditional operator with a call to this method. Thus, the desired implementation will be selected through polymorphism, depending on the class of the object.

Introducing a Null Object

Problem: Due to the fact that some methods return null instead of real objects, you have many null checks in your code.

Solution: Instead of null, return a Null object that provides default behavior.

Introduction of Approval Verification

Problem: The correct operation of the code section assumes the presence of some specific conditions or values.

Solution: Replace these assumptions with specific tests.


Comments


To leave a comment
If you have any suggestion, idea, thanks or comment, feel free to write. We really value feedback and are glad to hear your opinion.
To reply

Refactoring theory

Terms: Refactoring theory