About Lukas Eder

Lukas is a Java and SQL enthusiast developer working for Adobe Systems in Basel, Switzerland. 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.

Share and enjoy!
Post to Facebook Post to TwitterPost to Google+Post to Delicious Post to StumbleUponAdd to LinkedInAdd to DiggAdd to RedditSend via Mail
  • Vitek Tajzich

    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

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

    • http://twitter.com/TheShopCircuit ShopCircuit

      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.

  • http://elron.us/ eaorak

    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

      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.

      • http://elron.us/ eaorak

        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 :)

    • http://twitter.com/TheShopCircuit ShopCircuit

      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

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

      • Nils Breunese

        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

      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

        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 :-)

        • http://www.facebook.com/suresh.smurthy Suresh S Murthy

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

      • http://profile.yahoo.com/DSPMDNASC262PKTDAF2KWCWXZU Heikki Leskinen

        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.

  • http://twitter.com/hoeferh Henning Hoefer

    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.

    • LukasEder

      That of course, is a valid alternative. Funny, I had never thought of that! :-)

  • http://blog.thesoftwarecraft.com/ Bart Bakker

    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.

    • LukasEder

      I guess you get paid by the length of your stack trace ;-)

  • Efstratios Xakoustos

    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.

  • Philippe Godin

    +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 :)

    • LukasEder

      Of course. Clean and simple cases make up 90%. For the remaining 10%, see also eaorak’s answer

  • scame

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

    • LukasEder

      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…

  • http://www.facebook.com/hafizanil Hafizan Aziz

    Better then tenary  and please bracket..

  • Dale Wyttenbach

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

  • http://twitter.com/TheShopCircuit ShopCircuit

    I do it exactly like you do it.

  • Stephen Gantenbein

    I usually do not use else.

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

  • Mileta Cekovic

    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

      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.

  • Kaipe

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

    • LukasEder

      That’s a nice way of putting it. I had never though of using trace-logging that way. Quite nice!

  • jmartrican

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

  • http://www.facebook.com/joseantonio.galaviz José Antonio Galaviz Castillo

    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.

  • Greglim

    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.  

  • http://www.facebook.com/profile.php?id=780190786 Dohdoh de Leon

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

  • Sid Sarasvati

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



© 2010-2012 Java Code Geeks. Licenced under a Creative Commons Attribution-ShareAlike 3.0 Unported License.
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.