Bad Smells: Conditional logic


It is difficult to reason since we have to consider multiple paths through the code. It is tempting to add special use cases instead of developing a general use case. Sometimes used as a poor substitute for object-oriented mechanisms.

The bad smells derived from misuse of conditional logic are:

Null Check

To do

Rewards

Contraindications

Complicated Boolean Expression

To do

DeMorgan’s law applies.

Rewards

Improve communication.

Contraindications

You may find other ways to simplify the expression, or rewrite it to communicate more with less code.

Special Case

Symptoms

To do

Rewards

Contraindications

Simulated Inheritance (Switch Statement)

Symptoms

To do

Don’t pretend inheritance. It uses native mechanisms of the language itself.

If a switch for the same condition appears in different places, it is usually using a type code. Replace it with polymorphism:

  1. Extract the code for each branch with Extract Method.
  2. Move the code to the correct class with Move Method.
  3. Configure the inheritance structure with Replace Type Code with Subclass or Replace Type Code with State/Strategy.
  4. Remove conditionals with Replace Conditional with Polymorphism.

If the conditions occur within a single class, you can replace the conditional logic with Replace Parameter with Explicit Method or Enter Null Object.

Rewards

Contraindications

2019-03-19
Written by Samuel de Vega.
Tags