How should one comment an if-else structure?

31,033

Solution 1

If it is needed to comment if else statements, I prefer to describe the case what made the code reach that point. Especially in code with a high cyclomatic complexity

if (condition) { 
// User is taking a course at college x:
    i = 1;
} else { 
// User is not taking any course at college x:
    i = 2;
}

Solution 2

Another option is:

if(condition) { //check for condition
    i = 1;
} else { //condition isn't met
    i = 2;
}

Solution 3

You should only only annotate if the code is not self explanatory. So make the if self explanatory. Like this perhaps

bool fooIsNotReallyGood = ....;

if(fooIsNotReallyGood) {
...
} else {
...
}

Solution 4

If the code is not already self-documenting, then I would structure it as follows:

if (someCondition) {
    // If some condition, then do stuff 1.
    doStuff1();
}
else {
    // Else do stuff 2.
    doStuff2();
}

But again, it doesn't make much sense if the code is already self-documenting. If you would like to add comments because of some complex condition like:

if (x == null || x.startsWith("foo") || x.endsWith("bar") || x.equals("baz")) {
    doStuff1();
}
else {
    doStuff2();
}

Then I would consider to refactor it as:

boolean someCondition = (x == null || x.startsWith("foo") || x.endsWith("baz") || x.equals("waa");

if (someCondition) {
    doStuff1();
} else {
    doStuff2();
}

Wherein the variable name someCondition actually summarizes the whole condition in a nutshell. E.g. usernameIsValid, userIsAllowedToLogin or so.

Solution 5

Comments are very much a personal thing, and (as can be seen by some of the earlier answers) generate as much debate as the code.

In simple cases, comments detract from the code. But assuming a more complex condition, I prefer:

/*
** Comment explaining what the condition
** is trying to determine
*/
if ( condition )
{
    /*
    ** Comment explaining the implications
    ** of the condition being met
    */
    do_something();
}
else
{
    /*
    ** Comment explaining the implications
    ** of the condition not being met
    */
    do_something_else();
}

In any case, the comments must not just repeat the code.

Share:
31,033
user2012801
Author by

user2012801

Open source projects: Java HTML compressor/minifier jQuery loading mask plugin Chrome extensions: A whole bunch Feel free to contact me at: [email protected]

Updated on July 05, 2022

Comments

  • user2012801
    user2012801 almost 2 years

    Lets say you have:

    if(condition) {
        i = 1;
    } else {
        i = 2;
    }
    

    and you need to put comments explaining if and else blocks. What's the most readable way of doing it so someone can easily pick them up at first glance?

    I usually do it like this:

    //check for condition
    if(condition) {
        i = 1;
    } else {
        //condition isn't met
        i = 2;
    }
    

    which I find not good enough as comments are located at different levels, so at quick glance you would just pick up if comment and else comment would look like it belongs to some inner structure.

    Putting them like this:

    if(condition) {
        //check for condition
        i = 1;
    } else {
        //condition isn't met
        i = 2;
    }
    

    doesn't look good to me either as it would seem like the whole structure is not commented (condition might be big and take multiple lines).

    Something like that:

    //check for condition
    if(condition) {
        i = 1;
    //condition isn't met
    } else {
        i = 2;
    }
    

    would be probably the best style from comments point of view but confusing as a code structure.

    How do you comment such blocks?

    PS. I am not asking about refactoring this two lines of code, only about code style and comment formatting.

  • mpen
    mpen about 14 years
    this is the option I like... unless the comments are really long, then you're screwed...... i get frustrated and delete the comments because the look ugly.
  • Aoi Karasu
    Aoi Karasu about 14 years
    Lol, in such case isn't it better to do something like this? if (condition) conditionIsMet(); else conditionIsNotMet();
  • David Johnstone
    David Johnstone about 14 years
    +1 I do my best to have my code understandable without comments
  • helpermethod
    helpermethod about 14 years
    +1 Best solution in my opinion.
  • Faken
    Faken about 14 years
    I like this method of doing things. It may take up more space but it makes it absolutely clear what is covered in a loop/if statement.
  • drawnonward
    drawnonward about 14 years
    This is what I do. If the comments are long then put a comment block above the conditional explaining the whole thing.
  • user2012801
    user2012801 about 14 years
    I like all comments start at the same position (at top level preferably). Having them all over the place is much harder to read to me.
  • user2012801
    user2012801 about 14 years
    Thanks, but it is not what question is about.
  • Mike Burton
    Mike Burton about 14 years
    @serg555: You may not explicitly ask this question, but this is the answer all the same. If you were using actual comments in your examples above, it would immediately be clear that it depends completely on what the specific comment related to. An actual comment at the outer level, for example, might explain that when you have a particular graphics card installed a bug arises that is otherwise not a problem, so you do things differently based on that condition. An inner comment might explain a particularly complex algorithm and how it's tied to that particular branch of the if statement.
  • mmc
    mmc over 11 years
    This is fine in an ideal world of simple code. However, if the first block is long, it might no longer be as clear what the "else" block refers to (also in the case of nested ifs). He might also be cleaning up someone else's code that he'd rather not refactor. It's a perfectly legitimate question.
  • mmc
    mmc over 11 years
    I like this... specifically the comment in the "else" block. Your condition should be clear, but depending on the length and complexity (especially nesting) of the code, the meaning of the "else" may not be obvious at all.
  • Preet Sangha
    Preet Sangha over 11 years
    @mmc - that's what I added the bool variable. All tests can be reduced to to a single variable. If you need multiple variables to reduce the test to improve readability and so be it. This works in all cases. If you think that some code is too complex then you should be able create a simple expression and it only needs to be done once to ensure that future readers can see how the test works. Also I cannot imagine any piece of code where you can't simplify the code. If the simplification results in performance issues - that's when you introduce complex code with copious comments.
  • Andrew
    Andrew over 11 years
    To me, "Check for condition" isn't helpful, either in its own right or as a generic place-holder. Comments MUST be helpful, and not just repeat the code, hence my preference (detailed below) of "Comment explaining what the condition is trying to determine"
  • s3m3n
    s3m3n about 11 years
    I also prefer comment above else on the same tab level. I don't agree with not commenting code, if statement might be easy as someCondition, but inside its structure there are for example 300 lines and in this case NOT commenting else statement would be stupid, because you need to scroll 300 lines top and another 300 bottom..
  • Jonathan Potter
    Jonathan Potter about 9 years
    This is a useful technique but it definitely does not eliminate the need for if/else comments in all situations.
  • aandis
    aandis almost 9 years
    This wouldn't work if for example, you wanted to put some comment for i = 2 as well inside the else block. It would look like both of them are for i = 2 or both are for the else block.
  • Daniel Saner
    Daniel Saner almost 6 years
    There are many problems with this code. First, the "either/or" relationship between your two functions (the fact that always only one of them will take effect) is obscured in main(). You have to look up the actual statements in several places, and don't immediately see if there could be any side effects. You're also checking the condition twice, which is potentially expensive. And it adds the overhead of two function calls, which will probably also want to return something back to main. — I know the answer is old, but thought it couldn't hurt to back up the downvotes in some way.
  • Daniel Saner
    Daniel Saner almost 6 years
    @aandis You could indent the comment relating to i = 2; to differentiate. Although I think that in any real-world situation, the comment itself should leave little doubt about whether it refers to the condition or the first statement.
  • Guimo
    Guimo almost 5 years
    @aandis Or for that case you could put two comments separated by a single line. Vertical space should not be a problem since long or unclear methods should be refactored into smaller/clearer ones.