Quick question - how to comment if-else structure?

Posted by serg555 on Stack Overflow See other posts from Stack Overflow or by serg555
Published on 2010-04-13T06:11:37Z Indexed on 2010/04/13 6:12 UTC
Read the original article Hit count: 450

Filed under:
|
|

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?

© Stack Overflow or respective owner

Related posts about comments

Related posts about coding-style