'Else' is not the counterpart of 'If'

Posted by: dhj in Software Development

Tagged in: style , Software , Programming , indentation

dhj

I can't stand it anymore. I honestly don't understand why some developers (particularly those coming from the C world) continue to vertically line up else underneath if

Nobody would ever write *

switch (expression) {
   case true:
      DoSomething;
break;

case false:
   DoSomethingElse;  break;
}

So write

if (expression)
  then DoSomething;
   else DoSomethingElse;

If you're writing in C or C++, use

#define then 

so you can use the keyword anyway. If your language doesn't allow macros, then just indent as if there was a then keyword there anyway.

if (expression)
        DoSomething;
   else DoSomethingElse;

That last might look a little odd by itself but once you need multiple statements inside the then and/or else, it makes total sense again.

if (expression)
{
DoLotsOfThings;
}
else
{
DoLotsOfOtherThings;
}

 

 

* By the way, I would normally indent everything under the switch as well but I'm ignoring that here to avoid an orthogonal issue about block structures. In case you're wondering:

switch (expression)
   {
   case true:
      DoSomething;
break;

case false:
   DoSomethingElse;
break;  }
Comments (0)Add Comment

Write comment
You must be logged in to post a comment. Please register if you do not have an account yet.

busy