The human behind Windmill - A companion for seamless iOS development.
Identify Polymorphism Don't Abuse The If
If. One of the fundamental keywords in a programming language and most abused (close second is inheritance [Disclaimer]). Has been there since the dawn of programming so people are fond of it. A joy for juniors as it gives them power to put some logic in their code.
Now, there is nothing wrong with if per se. There are some valid cases where an if is what you need but I have come to realise [Disclaimer] that one if per method should be adequate. (A couple are ok, as long as are part of the same branch)
Usually one of the most common wrong usage of an if is failing to identify polymorphism.
Take a look at the ScaryCalculator#calculate(int, int String) method.
There are actually 2 things going on in the code.
the decision on which operation to make
the different operation based on the String operator.
When you see a code structured like that you have most likely encountered polymorphism. (You are blessed) What this means is that you have objects that the have a common method but implemented differently.
identify what those objects are. Operation(s); that's your interface.
identify the common code. Make the operation; that's your interface method.
identify the different operations that you have. Addition, Subtraction, Multiplication, Division; these are your classes implementing that interface each encapsulating the relative operation code.
Also, use a map for an index if what you actually need is a choice!
There are a couple of other wrong usages of if that will try to explore in the Don't abuse the If series, but please feel free to explore them yourself or comment below.