Where to put comments in an IF THEN ELSE construct

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


For me, a comment above the IF explains the IF statement itself. For example, if the condition being tested is particularly complex.

A comment in the block below the IF or ELSE describes what's going once the condition has been evaluated and a choice made.

So like this:

//Is this a favoured customer and do we have a promotion?
if customer.special() and monthly.hasOffer() {
  //Add discount
  invoice.addDiscount();
} 
else {
  //Add note about favoured customer scheme
  invoice.addNotes(JOIN_OUR_DISCOUNT_SCHEME);
}

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.

// comment about the if statement
if (expression)
{
    // comment about the code
    doSomething();
}
// comment about the else statement
else
{
    // comment about the code
    doSomethingElse();
}

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.


我会做案例a),但有一点额外的空白:

if (blabla) {
   // This explains the whole if case

   // Can comment here for specific block comments
   doThis();
} else {
   // This explains the else case

   // Same again
   doSomethingElse();
}
链接地址: http://www.djcxy.com/p/85284.html

上一篇: asp.net mvc 3

下一篇: 在IF THEN ELSE构建中放置注释的地方