The Simplest Anti-IF Code

08/04/2009
Francesco Cirillo XPLabs

The basic problem is that IFs create dependencies, coupling between modules (methods, objects, components, etc.) and increases possible paths inside our code (which reduces legibility).

An IF seems like a quick and easy way to make changes, but for the reasons listed above, IF after IF, we create software full of duplications that can’t be modified.

Here’s a simple example:

                // Bond class
                double calculateValue() {
                       if(_type == BTP)  { 
                        return calculateBTPValue();
                       } else if(_type == BOT) { 
                                 return calculateBOTValue();    
                              } else {
                                 return calculateEUBValue();
                              }
                }
                

Every change in bond type, for example, a new bond to evaluate, leads to a modification in our piece of code. Imagine what it would take to modify methods with built-in IFs and SWITCHes!

                 // Bond class
                double calculateValue() {
                    _bondProfile.calculate();
                }
                // AbstractBondProfile class
                abstract double calculate();
                
                // classe BTPBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }
                // classe BOTBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }
                // classe EUBondProfile >> AbstractBondProfile
                double calculate() {
                    ...
                }

      
What do we gain by taking out IFs?

The advantage is that tomorrow, we can fulfill the request for a new type of bond by simply creating a new class, with the single required logic to calculate the value of that new bond.

The solution isn’t always to create a new abstract class or an interface. But the solution will always make the software flexible, communicative, testable, ready for change.