Explicit else
block
I disagree with this as a blanket statement covering all if
statements but there are times when adding an else
block out of habit is a good thing.
An if
statement, to my mind, actually covers two distinct functions.
If we are supposed to do something, do it here.
Stuff like this obviously does not need an else
part.
if (customer.hasCataracts()) {
appointmentSuggestions.add(new CataractAppointment(customer));
}
if (customer.isDiabetic()) {
customer.assignNurse(DiabeticNurses.pickBestFor(customer));
}
and in some cases insisting on adding an else
might mislead.
if (k > n) {
return BigInteger.ZERO;
}
if (k <= 0 || k == n) {
return BigInteger.ONE;
}
is not the same as
if (k > n) {
return BigInteger.ZERO;
} else {
if (k <= 0 || k == n) {
return BigInteger.ONE;
}
}
even though it is functionally the same. Writing the first if
with an empty else
may lead you to the second result which is unnecessarily ugly.
If we are checking for a specific state, it is often a good idea to add an empty else
just to remind you to cover that eventuality
// Count wins/losses.
if (doors[firstChoice] == Prize.Car) {
// We would have won without switching!
winWhenNotSwitched += 1;
} else {
// We win if we switched to the car!
if (doors[secondChoice] == Prize.Car) {
// We picked right!
winWhenSwitched += 1;
} else {
// Bad choice.
lost += 1;
}
}
Remember that these rules apply only when you are writing new code. IMHO The empty else
clauses should be removed before checkin.
Test for true
, not for false
Again this is good advice at a general level but in many cases this makes code unnecessarily complex and less readable.
Even though code like
if(!customer.canBuyAlcohol()) {
// ...
}
is jarring to the reader, but making it
if(customer.canBuyAlcohol()) {
// Do nothing.
} else {
// ...
}
is at least as bad, if not worse.
I coded in BCPL many years ago and in that language there is an IF
clause and an UNLESS
clause so you could code much more readably as:
unless(customer.canBuyAlcohol()) {
// ...
}
which is significantly better, but still not perfect.
My personal process
Generally, when I am writing new code I will often add an empty else
block to an if
statement just to remind me that I have not yet covered that eventuality. This helps me avoid the DFS
trap and ensures that when I review the code I notice that there is more to do. However, I usually add a TODO
comment to keep track.
if (returnVal == JFileChooser.APPROVE_OPTION) {
handleFileChosen();
} else {
// TODO: Handle case where they pressed Cancel.
}
I do find that generally I use else
rarely in my code as it can often indicate a code smell.