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