如何注释 if-else 结构?

假设你有:

if(condition) {
i = 1;
} else {
i = 2;
}

并且您需要放置解释 ifelse块的注释。什么是最容易阅读的方式,这样别人可以很容易地拿起他们第一眼?

我通常是这样做的:

//check for condition
if(condition) {
i = 1;
} else {
//condition isn't met
i = 2;
}

我觉得这不够好,因为评论位于不同的层次,所以快速浏览你只会拿起 if评论和 else评论会看起来像它属于某种内部结构。

这么说吧:

if(condition) {
//check for condition
i = 1;
} else {
//condition isn't met
i = 2;
}

在我看来也不太好,因为整个结构似乎没有注释(条件可能很大,需要多行)。

差不多是这样:

//check for condition
if(condition) {
i = 1;
//condition isn't met
} else {
i = 2;
}

从注释的角度来看,这可能是最好的样式,但作为一种代码结构,这种样式令人困惑。

如何对这些块进行注释?

我不是在问重构这两行代码的问题,只是问代码样式和注释格式。

34050 次浏览

I wouldn't comment in those particular cases at all--the comments don't add any value over your already clear code. If you have a really complex condition that's difficult to read, I'd consider factoring it into a function (probably inline) with a very clean name of its own.

You should only only annotate if the code is not self explanatory. So make the if self explanatory. Like this perhaps

bool fooIsNotReallyGood = ....;


if(fooIsNotReallyGood) {
...
} else {
...
}

//condition isn't met seems to be a useless comment. But in the case where such a comment is required I do it like this (C#):

//check for condition
if(condition)
{
i = 1;
}
//some other condition
else
{
i = 2;
}

However, if the block is just if-else, than I would merge both comments before if.

For javascript I prefer

//check for condition
if(condition) {
i = 1;
} else { //some other condition
i = 2;
}

P.S. Seems there is as many opinions as there are people :)

You may extract if-else code to methods and name them properly:

function main() {
checkForCondition(condition);
conditionIsNotMet(condition);
}


function checkForCondition(boolean condition) {
if (condition) {
i = 1;
}
}


function conditionIsNotMet(boolean condition) {
if (!condition) {
i = 2;
}
}

In such a trivial case this seems like an overkill, but imagine having more than one line per if-else branch.

Another option is:

if(condition) { //check for condition
i = 1;
} else { //condition isn't met
i = 2;
}

The variables are important, not the conditions themselves.

if condition: # <condition dependent variable> was <predicated>
dosomething()
elif othercondition: # <othercondition dependent variable> <predicated>
dootherthing()
else: # <all variables> <not predicated>
doelsething()

This is how I do my comments for if then statements, although I usually find it isn't needed. I like putting it in line with the if/else, and tabbed to the same spot

if ( condition )    //if above the bar
{
i = 0;
k = 1;
}
else                //else if below
{
i = 1;
k = 2;
}

Go for self-commenting conditions,then additional comments aren't necessary. Let's say the condition is that the maximum loan to value is reached. This gives us:

if (maximumLoanToValueIsReached)
{
i=1;
}
else
{
i=2;
}

No need to specify when i=2 that the maximum loan to value hasn't been reached as that is self explanitory. As an aside, I'd also rename i to something more meaningful.

If it is needed to comment if else statements, I prefer to describe the case what made the code reach that point. Especially in code with a high cyclomatic complexity

if (condition) {
// User is taking a course at college x:
i = 1;
} else {
// User is not taking any course at college x:
i = 2;
}

There is no single answer - different people will have different opinions about what is most readable. However, I think there is agreement that the comments should actually add value to the (otherwise self-explanatory) code, and that the commenting style should be consistent.

The way I handle comments for not immediately self-explanatory conditions is like this:

  // If the condition for a local tree imbalance is met,
// juggle the immediate nodes to re-establish the balance.
// Otherwise, execute a global balancing pass.
if ( somewhat muddled condition )
{
...code...
}
else // Tree is in local balance
{
... more code...


} // if/else (tree locally imbalanced)

The comment on the final '}' exists primarily to give the end of the condition more visual weight, to make reading through the source easier.

If the code is not already self-documenting, then I would structure it as follows:

if (someCondition) {
// If some condition, then do stuff 1.
doStuff1();
}
else {
// Else do stuff 2.
doStuff2();
}

But again, it doesn't make much sense if the code is already self-documenting. If you would like to add comments because of some complex condition like:

if (x == null || x.startsWith("foo") || x.endsWith("bar") || x.equals("baz")) {
doStuff1();
}
else {
doStuff2();
}

Then I would consider to refactor it as:

boolean someCondition = (x == null || x.startsWith("foo") || x.endsWith("baz") || x.equals("waa");


if (someCondition) {
doStuff1();
} else {
doStuff2();
}

Wherein the variable name someCondition actually summarizes the whole condition in a nutshell. E.g. usernameIsValid, userIsAllowedToLogin or so.

Comments are very much a personal thing, and (as can be seen by some of the earlier answers) generate as much debate as the code.

In simple cases, comments detract from the code. But assuming a more complex condition, I prefer:

/*
** Comment explaining what the condition
** is trying to determine
*/
if ( condition )
{
/*
** Comment explaining the implications
** of the condition being met
*/
do_something();
}
else
{
/*
** Comment explaining the implications
** of the condition not being met
*/
do_something_else();
}

In any case, the comments must not just repeat the code.