在if-then-else结构中放置注释的位置?

Rab*_*ski 34 comments if-statement

我从来没有决定评论if-then-else结构的最佳方式,所以我从来没有标准化以一致的方式来评论它们.我很欣赏任何见解.

一些选择:

一个)

if (blabla) { 
   // this comment explains what happens in the IF case
   dothis();
} else { 
  // this comment explains what happens in the ELSE case
   dosomethingelse();
}
Run Code Online (Sandbox Code Playgroud)

缺点:在多个dothis()语句的情况下,我喜欢评论主要块,在这种情况下,IF-comment是否属于第一个dothis()块或整个IF情况并不总是很清楚

或b)

if (blabla) { // this comment explains what happens in the IF case
   dothis();
} else { // this comment explains what happens in the ELSE case
   dosomethingelse();
}
Run Code Online (Sandbox Code Playgroud)

缺点:仅适用于简短评论.如果IF和ELSE情况没有直接从代码中清除,我通常会注释IF-THEN-ELSE结构,这通常需要长于一行的注释.

或c)

// if the following happens
if (blabla) { // then do this
   dothis();
} else { // or else do this
   dosomethingelse();
}
Run Code Online (Sandbox Code Playgroud)

PS:我知道"代码应该是自我解释的",但情况并非总是如此......

Dav*_*ebb 31

对我来说,上面的评论IF解释了IF声明本身.例如,如果测试的条件特别复杂.

下面的块中的注释IFELSE描述一旦评估了条件并做出选择后会发生什么.

像这样:

//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);
}
Run Code Online (Sandbox Code Playgroud)

  • @pzycoman:你知道这是关于*style*而不是内容的讨论,对吧?你也知道评论真的*可以*提高可读性,对吧? (8认同)

Ric*_*ter 6

我从来没有想过这么想; 我个人并在需要时将注释放在IF和ELSE语句之上.这使我可以很好地分离有关分支语句的注释和有关代码的注释.

// comment about the if statement
if (expression)
{
    // comment about the code
    doSomething();
}
// comment about the else statement
else
{
    // comment about the code
    doSomethingElse();
}
Run Code Online (Sandbox Code Playgroud)

我还注意到,到目前为止,我是唯一一个使用"开放大括号样式"的答案,虽然我更喜欢代码块的开头和结尾的视觉对齐,但我的评论风格可能会回到我的Pascal日期.可能不适用于"封闭的大括号式社区.

  • 如果没有必要对其中一个发表评论,请省略评论.这就像功能开始时的锅炉板; 如果在某些标题下没有什么可说的,请省略标题.(我不提倡每功能锅炉板;我看到的大多数都是过时和错误的!) (2认同)