Saturday, October 22, 2011

If Statements

Its amazing how something simple like an if statement can have so many different permutations and different options. Here are some of my general rules to follow:
  • Always put the true condition first. Some people prefer the shorter block first (or last) but I think if you consistently put the true condition first it leads to less confusion when looking at the code later.
if (trueCondition) {
    DoSomething();
} else {
    DoSomethingElse();
}
  • Always take advantage of short-circuit evaluation and put the most cached or simplest conditions first.
if (localVar && string.IsNullOrEmpty(s) && expensiveTest()) {
  • Don't explicitly return true or false
// Argh, don't do this.
if (condition) {
  return true;
} else {
  return false;
}
// Just return the result of the condition
return condition;

// Or even worse I've seen this:
bool value = condition ? true : false;
// Just set the value:
bool value = condition;
  • Unless it is a one line if statement always bracket the blocks. This protects against the case where you write the one line case and later another developer has to add another statement to the if condition and doesn't notice the missing brackets and then introduces a bug. For example this is ok:
if (arg == null) return;
but not this:
if (condition) 
  x = 4;
Because too often I've seen another developer later add a line of code thinking it's part of the branch:
if (condition)
    x = 4;
    y = 6;