I never decided on what the best way is to comment if-then-else
constructs, so I never standardized on a consistent way to comment them.
I appreciate any insights.
Some options:
a)
if (blabla) {
// this comment explains what happens in the IF case
dothis();
} else {
// this comment explains what happens in the ELSE case
dosomethingelse();
}
drawback: in case of multiple dothis() statements, I like to comment the major blocks, and in that case it isn't always clear if the IF-comment belongs to the first dothis() block or to the whole IF case
or b)
if (blabla) { // this comment explains what happens in the IF case
dothis();
} else { // this comment explains what happens in the ELSE case
dosomethingelse();
}
drawback: only works for short comments. I usually comment IF-THEN-ELSE constructs if the IF and ELSE case isn't directly clear from the code, which typically requires a comment longer than one line.
or c)
// if the following happens
if (blabla) { // then do this
dothis();
} else { // or else do this
dosomethingelse();
}
PS: I know about "the code should be self explanatory", but this isn't always the case...
I'd do case a) but with an extra bit of whitespace:
Use what makes sense to you, I guess (unless you're working under a coding standard that specifies commenting style). Personally I don't use (c) because it's inconsistent between the first and following cases. I do occasionally use (b) when a short comment will do but generally I prefer (a). If I'm commenting several sub-blocks within the if block, I might leave a blank line after the case comment:
and so on.
just to add the missing answer for the else's comment placement, which in my opinion is the best placement for code readability for the following reasons:
It looks really good if you collapse the blocks
I never gave it very much thought; personally and when required I have put comments above the IF and ELSE statements. This gives me nice separation between the comments about the branch statements and comments about the code.
I also note that I am the only answer so far to use the "open curly brace style", which might be a throw back to my Pascal days although I do prefer the visual justification of begin and ends of code blocks, so my comment style may not work for the "closed curly brace style community.
Personally, I findi it better to write code that doesn't require little comments that say "about do do x", followed by "DoX()". If necessary, rather than write a comment saying "do x because of y", I'd prefer to write a method named "DoXBecauseOfY". If later refactoring removes the "BecauseOfY" part, then it still makes better sense to put a comment before the if statement, documenting the overall logic.
Of course, you then need to reduce the amount of code within each branch to the point where you can read the entire if statement at once.