I think I've figured out their issue (or one of their issues) with if statements after a lot of thinking... but I see a problem with their problem.
They show an image of the following example on their front page:
Code:
// Bond class
double calculateValue() {
if(_type == BTP) {
return calculateBTPValue();
} else if(_type == BOT) {
return calculateBOTValue();
} else {
return calculateEUBValue();
}
}
The first thing I saw that was wrong with this was that it's absolutely horribly indented and not very well spaced, but on closer inspection, it looks like their problem here is making a generic method that checks a state attribute and calls the correct method based on that. Now, I'm not very familiar with Java at this point and don't know if there is any other way that's simple. In Python, I would actually do something like this:
Code:
class Bond(object):
def __init__(self):
self.calculate_value = calculate_BTP_value
def calculate_BTP_value(self):
do_stuff()
return stuff()
def calculate_BOT_value(self):
do_stuff()
return other_stuff()
def calculate_EUB_value(self):
do_stuff()
return third_stuff()
# Example usage
if __name__ == '__main__':
foo = Bond()
print(foo.calculate_value())
This is simply because it's easier in Python than making a fourth "calculate_value" method and figuring out what to do based on a variable. But AFAIK, Java doesn't just allow you to stuff anything you want into a variable like that (much less call a variable like a function/method), and I'm pretty sure C++ doesn't. I don't know if something like this is
possible, but just because something is possible doesn't make it better.
Back to that mess of a code, it's a lot less of a mess if you write it normally, with an accepted indentation style:
Code:
// Bond class
double calculateValue() {
if (_type == BTP) {
return calculateBTPValue();
} else if (_type == BOT) {
return calculateBOTValue();
} else {
return calculateEUBValue();
}
}
And it looks even better if you just take out the unnecessary braces:
Code:
// Bond class
double calculateValue() {
if (_type == BTP)
return calculateBTPValue();
else if (_type == BOT)
return calculateBOTValue();
else
return calculateEUBValue();
}
(As an aside, I absolutely despise that coding style of putting the else statement on the same line as the previous if statement's closing brace. It's horrendously ugly! C-style syntax looks much nicer to my eyes!)
EDIT: Why is all my code being shown with indents of multiples of 8 spaces...? It actually makes the Python code you see completely invalid and everything else unreadable. Oh well... I guess you'll just have to quote my post to see the actual code that I wrote instead of the indent rape that the code tag resulted in...