views:

96

answers:

2

There is a website (called the Anti-if campaign) that talks about how to replace big nested if-statements with something more maintainable (through the use of a 'bond class' see example). I understand the concept, but I don't know how to implement it (even with the example).

Question: May I get a concrete example of how to implement this (ie, the bond class)? - it has been bugging me for some time now. Java is my preference, but any examples are welcome.

note I have found one more article on this in stack overflow here

+6  A: 

Unless I'm missing something, I'm not sure how that idea even merits a website of it's own.

It just reads like Polymorphism, which is a fundamental part of good, nay any, OO design.

To steal a link from the other question you posted:

Replace Condition With Polymorphism

Bond is just the example they have used to demonstrate with. It represents a financial Bond rather than some OO concept or pattern.

Hmmmm, I think I miss-read the anti-if web site in that case. It makes more sense to me now (bond class... *embarresed*). For some reason I thought that his example was suggesting something like what C# now has with its somewhat scary [extension methods](http://msdn.microsoft.com/en-us/library/bb383977.aspx)... cheers
lindon fox
+2  A: 

This special technique to avoid if-else-if constructs like shown in the example on that campaigns website can be found in in Clean Code by Robert C. Martin. If you follow his basic advices, you don't need to join the campaign ;)

The example at the referenced page looks dramatic mainly because the code is poorly formatted. This is how it should look like:

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

The recommendation is to replace the condition with polymorphism, which isn't even the best ideas. A better design is to use composition:

public interface BondType {
  public double calculate();
}

public class BOT implements BondType { 
  //...
}

public class Bond {
  private BondType type;
  public Bond(BondType type) {
    this.type = type;
  }
  public doublce calculateValue() {
    return type.calculate();
  }
}

Here we got rid of the conditions and delegated the calculation to a new type class.

Andreas_D