在IF THEN ELSE结构中放置注释的位置 [英] Where to put comments in an IF THEN ELSE construct

查看:1430
本文介绍了在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-THEN-ELSE结构,如果IF和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 code> 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.



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

这篇关于在IF THEN ELSE结构中放置注释的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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