PBP: 014 Elses

The PBP suggests that you don’t “cuddle” an else.  This means that the else and it’s opening parenthesis starts on its own line:

# We might have to do something complicated

if (...) {



# We didn't have to be complicated, now we get to do something different.

else {



I agree with the reasons of scanability and readability given by the PBP.  There’s two other reasons I like to see the “else” or “elsif” clause begin a new line.

Firstly, if you are trying to remove the else, or comment it out, or any other form of modification, it can be easier to work in whole lines.  Many editors make moving and selecting lines and groups of lines easier.  Having to move part of a line is possible, but harder to do.

Secondly, if the else is a long way from the if, I like to put a comment in front of it.  If the if was complex, the extremely simple ‘else’ can be lost, but saying, “If the frobnicator wasn’t enabled, we have to engage the widget filter” in front of the block can be useful to remind you what you’re doing.  A full-line comment, at the indentation level of the else works well for this, rather than sticking out past the else.  It keeps it consistent with the comment in front of the if, if there was one.


2 Responses to “PBP: 014 Elses”

  1. Stocken says:

    I don’t agree with your second argument. In my opinion long blocks should be refactored into a separate function to increase readability. That way you can skip the whole block by reading a few lines if you’re not interested in the function.

  2. Laufeyjarson says:

    You have a valid point, and that is sometimes an excellent idea.

    If every block is refactored into a function (to take it to extremes), I find each function may be readable, but the program is no longer understandable. I can only hold so much call stack in my head when I’m reading code, and if it gets too deep, I’m not able to follow what is going on.

    I’ve worked with codebases that were factored out to that degree, and didn’t find it beneficial at all.

    The middle ground is very workable, but harder to explain and difficult to boil down into a pithy “best practice”.

    That’s just my opinion, though, and yours may be different. Your point is good, and there’s definitely a time and place for it.

Leave a Reply