3 ms·
Single entry, single exit is important. Your code snippet essentially have three (3) exits. The two returns and the alert, which we can assume it throws an Exce
by 100011_100001 6y ago
Single entry, single exit is important. Your code snippet essentially have three (3) exits. The two returns and the alert, which we can assume it throws an Exception or error that halts the code.
This is problematic because you have added excess code that doesn't help readability and makes bugs harder to track if an issue does come up. If anyone wants to add more rules the code will get even worse. Instinctually you recognize this because you added 'alert' it's your way of saying, if I have a bug I want to do something about it. Why is that? It's because you recognize that both if clauses might be false. If the alert triggers is it because 'canDrink' has a bug or 'underAge'?
Let's say 'underAge(age)' returns true if age < 21, because you live in the United States. That also implies that 'canDrink(age), returns true if age >= 21. Hopefully you can see that both methods test the same thing. That usually makes my spider sense tingle, I am doing something programmatically wrong. However for the sake of this example let's say this got merged.
New feature comes in, the age of drinking in another country is 16. We need to support their localization. If you updated only 'canDrink(age)' method (age >= 16), everything will work as expected, the if would be true and give them beer. If you only updated 'underAge(age)' (age < 16) you would have problems, 'canDrink' would return false (16 is not greater than 21) and underAge would return false (16 is not less than 16), and you would hit your alert.
However if you were using a simple if/else clause
if canDrink(age) {
okGiveBeer()
} else {
underAgeAlert()
}
There is one method to deal with, 'canDrink'. Which means for the example of need to localize to country X with drinking age of 16 would have a single method to update. That reduces the chance of bugs. If bugs do appear they are easier to locate (is my if evaluating true when it's not? Why?). As an added benefit you have less lines of code, there is no code jumps or incomplete flows and you never need an alert in the end just in case.