About 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.

if – else coding style best practices

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.

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

JPA Mini Book

Learn how to leverage the power of JPA in order to create robust and flexible Java applications. With this Mini Book, you will get introduced to JPA and smoothly transition to more advanced concepts.

JVM Troubleshooting Guide

The Java virtual machine is really the foundation of any Java EE platform. Learn how to master it with this advanced guide!

Given email address is already subscribed, thank you!
Oops. Something went wrong. Please try again later.
Please provide a valid email address.
Thank you, your sign-up request was successful! Please check your e-mail inbox.
Please complete the CAPTCHA.
Please fill in the required fields.

36 Responses to "if – else coding style best practices"

  1. Vitek Tajzich says:

    If you have to write comment to if-else statement then there is something wrong. It leads to spaghetti code and you should  create new methods for each statement which describes themselves instead.

    • LukasEder says:

      I agree, sometimes methods can “resolve” such problems. But sometimes, the if-else really needs explanation, because some condition is quite subtle to understand…

    • You can comment if-else to clarify why you do something else. I see no reason why you can’t comment ANY code. If it’s useful for the next guy taking over your work, it’s useful.

  2. eaorak says:

    I prefer not to comment code at all. Code should comment itself without the need for extra explanation. When I see a comment inside a code block, I always think that code is not written well enough. I think a developer should strive for the clearness of code itself, not the way it looks with comments.

    • LukasEder says:

      That’s true in 90% of the code. But you’ll always run into situations (10%), where there is no really really clean way to express what you have to do in code. And there are two main reasons for that: Lack of time to refactor, lack of simplicity in the problem / requirement itself. That’s where comments really help.

      • eaorak says:

        I agree that sometimes we may need to comment code as mentioned, but as you’ve said that is rare (and it should be). So to keep this kind of comments rare, I think it’s better the code look ugly with comments. In this way, every time when you look at the code, you will desire to refactor it, rather than thinking that code looks good as it is :)

    • I find not commenting a very bad habit. Depending on your language choice of course a lot is clear. And you should indeed write understandable code. But for example I comment every function to explain what it does or why it’s needed. Also, often I make “smart decisions” that another developer might not understand or mess up, so I comment to explain my motivations.

      • LukasEder says:

        True. And depending on the amount of time that passed since that “smart decision”, I might mess up myself, again ;-)

      • Nils Breunese says:

        Put your “smart decisions” in methods that have names that describe exactly what they do and you really don’t those comments. If another developer using your API might mess up if he doesn’t understand those “smart decisions” then those decisions apparently didn’t result in clean code. And I wouldn’t call those decisions smart in that case. Refactoring is the first thing I’d do instead of writing comments about all the tricky things one should know before being able to use the code.

    • Ian Littlewood says:

      Lack of comments is one thing and only one thing… bad style. Code is NOT self documenting because all it can tell you is what it does. A comment should not simply answer “what?”, it should answer, “why?”

      • LukasEder says:

        I like your comparison of “what” vs “why”. I don’t know how on earth I could write code in a way that it communicates precisely “why” a stock exchange order of clearing type code 27 needs to be grouped with all other subsequent orders of type code 27 (if and only if they have a rounding lot below 0.01), before actually unloading them within a time-frame of at most 35 seconds (fictional example in a real-life application).

        But of course, not everyone goes far beyond writing “Hello World” programs where comments are indeed unnecessary :-)

        • Whoever says comments are redundant or code should be self documenting must really be taking the advice of TDD/Agile coach’s words LITERALLY!!! In real world people do use if-else conditions a lot and it WORKS!!

          LukasEder: I liked your tongue-in-cheek response :)

          P.S. I know someone will come and bite me for my comments here :P For all those who do, I do know all those golden principles of OO and et al..

      • You kinda have a point. Code tells you *what* it does, *why* (also known as specifications) is told by the tests. There is a very very narrow reason for commenting your code, business specification is not one of them. Everything that has business value, must be in *live* documentation aka. unit or acceptance tests.

  3. If you write the first comment also *inside* the block (be it an if- or a try-block) then everything is consistent again — no need for the additional linebreaks.

  4. If you’d stop over-commenting your code and improve the names of your methods, you wouldn’t need these comments at all. If you want to communicate that you are cleaning up resources, don’t call your method ‘cleanup’ but call it ‘cleanupResources’ instead. Using comments is a symptom that your code fails to communite its intend.

    On the curly braces discussion; it is better to eliminate them for if-then-else and loops. Make sure you only call one method in each branch or loop, and communite its intend with the name of that method.

  5. Efstratios Xakoustos says:

    This goes out to me as well as I have spent countless hours formatting code:

    Take the damn OCB pills in the morning and stop caring about the details.

  6. Philippe Godin says:

    +1 On the comments that states that it’s better not to comment! I would see something like this

    if(itNeedsToBeDone())
       doIt();

    Thats it. Clean, simple, easy to test

    I rest my case :)

  7. scame says:

    Ok. Is it Java style? No. Follow conventions and you’ll be happy!

    • LukasEder says:

      Can you give an example of if-else (with comments) in “Java style”? What about commented try-catch-finally following conventions? I’m not aware of any strict conventions, so I’m glad to have a pointer…

  8. Better then tenary  and please bracket..

  9. Dale Wyttenbach says:

    A better argument for your style might be that it is easier to comment out blocks out code

  10. I do it exactly like you do it.

  11. Stephen Gantenbein says:

    I usually do not use else.

    void methodWithDescribingName() {
      if (!something) {
        dontDoIt();
        return;
      }
      doIt();
    }

  12. Mileta Cekovic says:

    This is far from best practices for If-Else statement IMHO. This is similar to ‘best practices’ that we can see in fragile programming books of old and should be better called ‘worst ceremonies’ for If-Else statement!

    Why is this so? There are several well known reasons, I’ll only repeat them here:

    1. Code is read much more then it is written. So it should be readable and telling. Bunch of comments around If-Else will not help with reading, it will most probably create a mess instead. Code is written in a language, and that language should tell the reason why code is written in the way it is written, not comments. If you need comments to clarify code, better think how to write code differently, so it is more understandable. You do not need yet another language (comments) to mess with the primary language (code).

    2. The style with curly braces on separate line is fragile as it takes one more line in precious screen space, the line that is much better used to get more code on screen, making greater portion of code and the code context available to the reader at the same time. Further, having curly braqces for one line block is a waste and as such is against YAGNI principle.
    You would say that putting curly braces for one line block make it less error prone when adding additional line to the block.
    True, but value of this is only when changing this particular piece of code, while it creates burden when reading not only this part of the code, but the code around (as less lines will fit in screen, reducing code context available), and reading we do more!
    You would also say that today’s monitor is large, we have already enough space. How wrong! I have 1050p vertical space in my monitors at work and every day I wish I have more. 1200p ? It may be enough, but I would prefer 27″ and 1440p :).

    • LukasEder says:

      How would you write this business logic down into code, such that you can live without comments?

      A stock exchange order of clearing type code 27 needs to be grouped with all other subsequent orders of type code 27 (if and only if they have a rounding lot below 0.01), before actually unloading them within a time-frame of at most 35 seconds (fictional example in a real-life application).

      I find that pretty tough. See also Ian Littlewood’s remark about the difference between code communicating “what” it does, as opposed to code communicating “why” it does it.

  13. Kaipe says:

    (If it is not javadoc) I prefer to write the comment where I would write the log-output.

    In fact – I prefer log-output and for your last example it would be much better:
    log.trace(“Do some business”);

    log.error(“IOException should not happen – ignored”, ignore);

    log.fatal(“Propagate SQLException”);

    log.trace(“Clean up some resources”);

    etc … Also, my experience is that log-output is usually better maintained by the next developer who works with the code-base, while comments are usually ignored and might after a while end up in very bad places.

  14. jmartrican says:

    I agree with the author that commenting the code looks better with the extra line.  I’ll consider it.

  15. I think that commenting goes for the whole block since it is a full conditional unit. It will help you understand the problem to solve and not necessarily all of the probable scenarios.

  16. Greglim says:

    On the If sample, for clarity I never use IF ELSE IF ELSE ELSE …… I use just IF ELSE one time and I put the comment on the top for both the If and the else if any. I prefer using CASE (switch) or several IFs. 
    On the try sample I prefer the first one, this is because I like to follow an standard. If every statement has a left curly bracket at the end and you close that statement with a right curly bracket  in a standalone line. In a Try I should follow the same logic , this is closing the TRY with a rcb and every catch must have its own sets of curly brackets.
    Now this helps me a lot because I do programming in several languages, now on Java (new for me) I want to use the same standard as in the others.  

  17. i actually write my code the same way as you do. much easier to read imo.

  18. Sid Sarasvati says:

    How about this?

    // 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();
    }

  19. Eric Majerus says:

    I try to use your way where I work but they “correct” me before I can commit. More than once there’s been logic errors due to a nested if block and developers mistakenly think the following else belongs to the inner if, not the outer. That has nothing to do with naming of methods or comments, simply scanning with your eyes quickly the structure is unclear without else on a new line.

Leave a Reply


− three = 6



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy | Contact
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.
Do you want to know how to develop your skillset and become a ...
Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you two of our best selling eBooks for FREE!

Get ready to Rock!
You can download the complementary eBooks using the links below:
Close