Reducing the number of ifs

I've often encountered code which was repeatedly checking a condition and then doing some action (action1) in some part of the code, and then doing some other action (action2) in another part of the code.

This principle states that you should avoid doing that, and instead extract the two actions in two different methods of the same class, and pull “the if” higher up in the architecture.

In practice, you would move “the if” in a factory, and based on the value of the condition, create an object of the appropriate class.

This is also a good opportunity to create null objects – they are objects which implement the full contract, but they don't have any executable code.

By combining these ideas – pulling up the if into a factory, extracting a common contract, and implementing it in various classes, some of which can be null objects, you can achieve the minimal number of IFs, which are ideally not repeated, but written only once in the code.

The principles outlined above are: