The following post is going to be an advanced curly-braces discussion with no right or wrong answer, just more “matter of taste”. It is about whether to put “else” (and other keywords, such as “catch”, “finally”) on a new line or not.
Some may write
if (something) { doIt(); } else { dontDoIt(); }
I, however, prefer
if (something) { doIt(); } else { dontDoIt(); }
That looks silly, maybe. But what about comments? Where do they go? This somehow looks wrong to me:
// This is the case when something happens and blah // blah blah, and then, etc... if (something) { doIt(); } else { // This happens only 10% of the time, and then you // better think twice about not doing it dontDoIt(); }
Isn’t the following much better?
// This is the case when something happens and blah // blah blah, and then, etc... if (something) { doIt(); } // This happens only 10% of the time, and then you // better think twice about not doing it else { dontDoIt(); }
In the second case, I’m really documenting the “if” and the “else” case separately. I’m not documenting the call to “dontDoIt()”. This can go further:
// This is the case when something happens and blah // blah blah, and then, etc... if (something) { doIt(); } // Just in case else if (somethingElse) { doSomethingElse(); } // This happens only 10% of the time, and then you // better think twice about not doing it else { dontDoIt(); }
Or with try-catch-finally:
// Let's try doing some business try { doIt(); } // IOExceptions don't really occur catch (IOException ignore) {} // SQLExceptions need to be propagated catch (SQLException e) { throw new RuntimeException(e); } // Clean up some resources finally { cleanup(); }
It looks tidy, doesn’t it? As opposed to this:
// Let's try doing some business try { doIt(); } catch (IOException ignore) { // IOExceptions don't really occur } catch (SQLException e) { // SQLExceptions need to be propagated throw new RuntimeException(e); } finally { // Clean up some resources cleanup(); }
I’m curious to hear your thoughts…