Coding Style – Arranging If/Else Statements by Rareness or Difficulty

coding-style

In some code I'm writing right now, I have something like this:

if (uncommon_condition) {
    do_something_simple();
} else {
    do();
    something();
    long();
    and();
    complicated();
}

Part of me thinks "It's fine the way it's written. Simple cases should go first and more complicated cases should go next." But another part says: "No! The else code should go under the if, because if is for dealing with unusual cases and else is for dealing with all other cases." Which is correct or preferable?

Best Answer

Order by their likelihood of being executed. The most common, most likely, etc. condition(s) should go first.

The "difficulty of dealing with them" should be dealt with by code structure, abstraction, etc. in the example the else block could be refactored to single method call. You want your if clauses to be at the same abstract level.

if ( ! LotteryWinner ) {
    GoToWorkMonday();
} else {
    PlanYearLongVacation();
}
Related Topic