Branching efficiency

The a couple weeks ago I submit a function for code review that looked like this.

Function{
If (condition)
Else If (condition)
Else if (condition)
Else
return value
}

My lead giving the code review said “I hate else if,” but he didn’t say why or what I should have done instead. He just gave me the go ahead to upload this function.

My question is what are some alternatives to a bunch of “else ifs” that would make the code look more elegant and maybe perform better?

I tried pulling up his code to get an idea of what he would have done and I noticed several times he did

If (condition)
If (condition)
If (condition)

Should I avoid writing “else”? I was going to ask him but he no longer works here.

Thank you

Answer

I try to avoid “else”, “else if” and also “if” and “for”. In my point of view, branching and looping add complexity to code. But it’s everytime depends on what you want to do. Some examples:

If you do thing like:

if fruit.isBanana() then fruit.eatBanana()
else if fruit.isOrange() then fruit.eatOrange()
...

Instead of this, you can use inheritance:

class Banana extends Fruit {
    function eat() {
        ... yum yum yum banana ...
    }
}
class Orange extends Fruit {
    function eat() {
        ... yum yum yum orange ...
    }
}

And then, if you have an instance:

fruit.eat()

Another example: If you use “if” and “for” for filtering:

longFruits = []
for fruit in fruits {
    if fruit.isBanana() then longFruits.add(fruit)
}

then you can work with collections instead:

longFruits = CollectionUtils.select(fruits, Precicate.isBanana)

This is just a couple examples and technics.

Leave a Reply

Your email address will not be published. Required fields are marked *