views:

237

answers:

11

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.

+4  A: 

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.

sblom
+11  A: 

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 {
...
}
Preet Sangha
+1 I do my best to have my code understandable without comments
David Johnstone
Thanks, but it is not what question is about.
serg
@serg555: You may not explicitly ask this question, but this is the answer all the same. If you were using actual comments in your examples above, it would immediately be clear that it depends completely on what the specific comment related to. An actual comment at the outer level, for example, might explain that when you have a particular graphics card installed a bug arises that is otherwise not a problem, so you do things differently based on that condition. An inner comment might explain a particularly complex algorithm and how it's tied to that particular branch of the if statement.
Mike Burton
+1  A: 

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

HeavyWave
A: 

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.

Boris Pavlović
Lol, in such case isn't it better to do something like this? if (condition) conditionIsMet(); else conditionIsNotMet();
AOI Karasu
+6  A: 

Another option is:

if(condition) { //check for condition
    i = 1;
} else { //condition isn't met
    i = 2;
}
David Johnstone
this is the option I like... unless the comments are really long, then you're screwed...... i get frustrated and delete the comments because the look ugly.
Mark
+1 Best solution in my opinion.
Helper Method
This is what I do. If the comments are long then put a comment block above the conditional explaining the whole thing.
drawnonward
I like all comments start at the same position (at top level preferably). Having them all over the place is much harder to read to me.
serg
+1  A: 

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()
Ignacio Vazquez-Abrams
+2  A: 

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;
}
Justen
I like this method of doing things. It may take up more space but it makes it absolutely clear what is covered in a loop/if statement.
Faken
+4  A: 

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.

Chris Knight
+3  A: 

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) { 
//e.g user is taking a course at college x
    i = 1;
} else { 
//e.g user is not taking any course at college x
    i = 2;
}
MrBliss
+1  A: 

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.

Lars
+1  A: 

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

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

// Else do stuff 2.
else {
    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.

BalusC