if – else coding style best practices (original) (raw)

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…

References: if – else coding style best practices from our JCG partner Lukas Eder at the JAVA, SQL, AND JOOQ blog.

Photo of Lukas Eder

Lukas is a Java and SQL enthusiast developer. He created the Data Geekery GmbH. He is the creator of jOOQ, a comprehensive SQL library for Java, and he is blogging mostly about these three topics: Java, SQL and jOOQ.