Pretty code: Skeptical of elses
Some examples...
Testing a boolean to return a boolean
if (x == true)
{
return true;
}
else
{
return false;
}
becomes
return x;
If you need to swap those,
return !x;
That's a pattern. Recall that comparison operators (less than, greater than, equal to) return a boolean. So this also applies here:
if (myPropertyToCheck == someValue)
{
return true;
}
else
{
return false;
}
becomes
return myPropertyToCheck == someValue;
Guard clauses
You can use a guard clause when you are testing if it is safe to do something, and if not, you want to exit.
if (safeToDoThis)
{
DoThis();
}
else
{
return;
}
becomes
if (!safeToDoThis) return;
DoThis();
When the DoThis() is rather involved, guard clauses greatly help the readability for your future teammates (even when that's you). Step 1, check if we're in an okay state, and if not, just get out of there. This saves you from the Hunt The Else game (although, if that matching else is that hard to find, you could break up your method into smaller pieces with more specific responsibilities).
Comparisons
Compare() and CompareTo() methods need to return -1, 1, or 0. It's handy that these are integers, because now you can harness the Power of Arithmetic to do your bidding. Also when you are comparing your own classes, you often want to compare a property that is a value type or a string. Those already have their own CompareTo() methods, which you can borrow.
Say you want to sort your children by their ages. You don't need
if (child1.age < child2.age)
{
return -1;
}
else if...
(Not just an if/else, but an if/elseif/else. Aaah!) Use instead:
return child1.Age.CompareTo(child2.Age);
If you want to sort them from oldest to youngest, this is where the arithmetic comes in. To flip a negative 1 into a 1, multiply it by negative 1. Same for flipping positive 1 into a negative 1. And zero, conveniently, doesn't mind being multiplied by anything. So you could say:
return -1 * child1.Age.CompareTo(child2.Age);
You can get it even simpler. Because -(-1) = 1, and -(1) = -1, your Compare() method becomes:
return -child1.Age.CompareTo(child2.Age);
Not only no elses, but also no ifs! Very pretty.
Reducing the number of paths through your code (i.e., reducing cyclomatic complexity) gets it closer to being read like prose. Simpler code has fewer bugs, and your successors who have to read your code will think you are smart and good looking. Keep a healthy mistrust of else statements, and write pretty code.
Labels: code
