在if-then-else构造中的何处放置注释? [英] Where to put comments in an if-then-else construct?

查看:84
本文介绍了在if-then-else构造中的何处放置注释?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从来没有决定最好的方法是注释 if-then-else 构造,因此我从来没有统一评论它们的一致方法。
我感谢任何见识。

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.

某些选项:

a)

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

缺点:如果有多个dothis()语句,我想对主要块,在那种情况下,IF注释是属于第一个dothis()块还是整个IF情况并不总是很清楚

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

或b)

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

缺点:仅适用于简短评论。如果无法从代码中直接清楚地了解IF和ELSE的情况,我通常会注释IF-THEN-ELSE构造,这通常需要注释长于一行。

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.

或c)

// if the following happens
if (blabla) { // then do this
   dothis();
} else { // or else do this
   dosomethingelse();
}

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

PS: I know about "the code should be self explanatory", but this isn't always the case...

推荐答案

对我来说,在 IF上方的注释解释 IF 语句本身。例如,如果要测试的条件特别复杂。

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

IF ELSE 描述了条件评估后做出的选择。

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

像这样:

//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);
}

这篇关于在if-then-else构造中的何处放置注释?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆