Search code examples
coding-stylefunction-exit

What to put in the IF block and what to put in the ELSE block?


This is a minor style question, but every bit of readability you add to your code counts.

So if you've got:

if (condition) then
{
   // do stuff
}
else
{
   // do other stuff
}

How do you decide if it's better like that, or like this:

   if (!condition) then
   {
     // do other stuff
   {
   else
   {
     // do stuff
   }

My heuristics are:

  1. Keep the condition positive (less mental calculation when reading it)
  2. Put the most common path into the first block

Solution

  • I prefer to put the most common path first, and I am a strong believer in nesting reduction so I will break, continue, or return instead of elsing whenever possible. I generally prefer to test against positive conditions, or invert [and name] negative conditions as a positive.

    if (condition)
        return;
    
    DoSomething();
    

    I have found that by drastically reducing the usage of else my code is more readable and maintainable and when I do have to use else its almost always an excellent candidate for a more structured switch statement.