How should one comment an if-else structure?

Coding StyleComments

Coding Style Problem Overview


Lets say you have:

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

and you need to put comments explaining if and else blocks. What's the most readable way of doing it so someone can easily pick them up at first glance?

I usually do it like this:

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

which I find not good enough as comments are located at different levels, so at quick glance you would just pick up if comment and else comment would look like it belongs to some inner structure.

Putting them like this:

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

doesn't look good to me either as it would seem like the whole structure is not commented (condition might be big and take multiple lines).

Something like that:

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

would be probably the best style from comments point of view but confusing as a code structure.

How do you comment such blocks?

PS. I am not asking about refactoring this two lines of code, only about code style and comment formatting.

Coding Style Solutions


Solution 1 - Coding Style

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

Solution 2 - Coding Style

Another option is:

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

Solution 3 - Coding Style

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 {
...
}

Solution 4 - Coding Style

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.

Solution 5 - Coding Style

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.

Solution 6 - Coding Style

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.

Solution 7 - Coding Style

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.

Solution 8 - Coding Style

//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 :)

Solution 9 - Coding Style

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

Solution 10 - Coding Style

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.

Solution 11 - Coding Style

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()

Solution 12 - Coding Style

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsergView Question on Stackoverflow
Solution 1 - Coding StyleMrBlissView Answer on Stackoverflow
Solution 2 - Coding StyleDavid JohnstoneView Answer on Stackoverflow
Solution 3 - Coding StylePreet SanghaView Answer on Stackoverflow
Solution 4 - Coding StyleBalusCView Answer on Stackoverflow
Solution 5 - Coding StyleChris KnightView Answer on Stackoverflow
Solution 6 - Coding StyleAndrewView Answer on Stackoverflow
Solution 7 - Coding StylesblomView Answer on Stackoverflow
Solution 8 - Coding StyleEgor PavlikhinView Answer on Stackoverflow
Solution 9 - Coding StyleJustenView Answer on Stackoverflow
Solution 10 - Coding StyleLarsView Answer on Stackoverflow
Solution 11 - Coding StyleIgnacio Vazquez-AbramsView Answer on Stackoverflow
Solution 12 - Coding StyleBoris PavlovićView Answer on Stackoverflow