我从来没有决定评论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(); }
缺点:在多个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(); }
缺点:仅适用于简短评论.如果IF和ELSE情况没有直接从代码中清除,我通常会注释IF-THEN-ELSE结构,这通常需要长于一行的注释.
或c)
// if the following happens if (blabla) { // then do this dothis(); } else { // or else do this dosomethingelse(); }
PS:我知道"代码应该是自我解释的",但情况并非总是如此......
对我来说,上面的评论IF
解释了IF
声明本身.例如,如果测试的条件特别复杂.
下面的块中的注释IF
或ELSE
描述一旦评估了条件并做出选择后会发生什么.
像这样:
//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和ELSE语句之上.这使我可以很好地分离有关分支语句的注释和有关代码的注释.
// comment about the if statement if (expression) { // comment about the code doSomething(); } // comment about the else statement else { // comment about the code doSomethingElse(); }
我还注意到,到目前为止,我是唯一一个使用"开放大括号样式"的答案,虽然我更喜欢代码块的开头和结尾的视觉对齐,但我的评论风格可能会回到我的Pascal日期.可能不适用于"封闭的大括号式社区.