Original article address: the simplest anti-If code
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
The reasons listed above, if after if, we create software full
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 wocould 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
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
Interface. But the solution will always make the software flexible,
Communicative, testable, ready for change.