Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

Whenever I'm writing a typical if-else-construct in any language I wonder what would be the best way (in terms of readability and overview) to add comments to it. Especially when commenting the else clause the comments always feel out-of-place for me. Say we have a construct like this (examples are written down in PHP):

if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}

I could comment it like this:

// check, what kind of magic should happen
if ($big == true) {
    // do some big magic stuff
    bigMagic();
} else {
    // small magic is enough
    smallMagic()
}

or

// check, what kind of magic should happen
// do some big magic stuff
if ($big == true) {
    bigMagic();
}
// small magic is enough
else {
   smallMagic()
}

or

// check, what kind of magic should happen
// if:   do some big magic stuff
// else: small magic is enough
if ($big == true) {
    bigMagic();
} else {
    smallMagic()
}

What are your best-practice examples for commenting this?

share|improve this question

closed as not constructive by Mark Trapp, Walter, gnat, Steve Evers, Yannis Rizos Apr 5 '12 at 17:25

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.If this question can be reworded to fit the rules in the help center, please edit the question.

8  
else { // for future reader: sorry, at the moment of writing this I did not have time and skills to come up with a better way to express my logic –  gnat Apr 4 '12 at 11:27
1  
Why is Bigger better/preferable/different? See, I don't know. –  JeffO Apr 4 '12 at 13:31
    
Is this a subject for question or argue? Even if the question is well-meant, those are war-starters. –  Independent Apr 4 '12 at 16:12
1  
I find it interesting that so many people have have felt that this question was worth their answering, but not worth upvoting. While I'm interested in the answers (mine is the sole +1), the question does seem to be a quintessential example of a bike-shedding problem. –  canisrufus Apr 4 '12 at 16:19
1  
@canisrufus It only looks that way to you because the down votes offset the up votes. At this moment, there are 6 up and 4 down votes for a net +2. –  Caleb Apr 4 '12 at 16:24
show 4 more comments

9 Answers

up vote 33 down vote accepted

I prefer either:

if ($magic == big) {
    bigMagic();
}
else {
    smallMagic();
}

or:

if ($magic == big) {
    // big magic requires a big surprise, so I'm telling you about it here
    surprisingThing();
}
else {
    // give a magical feeling even if $magic is noMagicAtAll
    smallMagic();
}

It seems a little silly to write a comment explaining what your condition checks unless the code doesn't clearly state it. Even then, better to rewrite the code to make it as clear as possible. The same goes for the bodies of the conditional blocks -- if you can make the reason for doing something obvious, do that instead of commenting.

I don't subscribe to the "never write comments" philosophy, but I do believe in avoiding comments that say what the code should be saying. If you write a comment like "check what kind of magic should happen" when the code could say if ($magic == big) {..., readers will stop reading your comments very quickly. Using fewer, more meaningful comments gives each of your comments more value, and readers are much more likely to pay attention to those that you do write.

Choosing meaningful names for your variables and functions is important. A well-chosen name can eliminate the need for explanatory comments throughout your code. In your example, $magic or maybe $kindOfMagic seems like a better name than $big since according to your example, it's the "kind of magic" that's being tested, not the "bigness" of something.

Say as much as you can in code. Save prose for the cases that demand more explanation than you can reasonably write in code.

share|improve this answer
13  
+1 don't overdo comments, clear code requires no comments –  ratchet freak Apr 4 '12 at 10:40
3  
@ratchetfreak Seems like we're mostly in agreement, but comments are often necessary to make code clear. Providing historical context, explaining for surprising behavior, or resolving ambiguity are best done with comments. –  Caleb Apr 4 '12 at 10:50
1  
Good point, Caleb. It's true that code should some sort of auto-comment itself as long as it's possible. –  acme Apr 4 '12 at 11:44
7  
Good comments do not explain the what -- "check, what kind of magic should happen" -- they explain the why, i.e., "Users can select the kind of magic to run" or "The service will fill big magics if they are available, so we must check the type" or whatever. No matter how good your coding is, the whys are unknown to those who aren't familiar with the business rules. –  Bruno Brant Apr 4 '12 at 13:14
1  
The trouble is that it's easiest to write hard to read code and not comment. It's also easier to write hard to read code but comment it well than it is to consistently write code so good it doesn't need comments. –  asfallows Apr 4 '12 at 19:52
show 3 more comments

Try explanatory variable names

Comments can be great, but when possible, make the code self-documenting. One way of doing this is with explanatory variable names. For example, rather than this:

if (user.has_sideburns && user.can_gyrate) {
  // This user is a potential Elvis impersonator

}

I'd prefer a named variable:

is_potential_elvis_impersonator = user.has_sideburns && user.can_gyrate

if (is_potential_elvis_impersonator) {
  ...
}
share|improve this answer
2  
I go one step further and use: is_potential_elvis_impersonator. (Is/Has/etc. prefix for boolean variable..) –  jberger Apr 4 '12 at 18:48
    
@jberger - I like it. Editing answer accordingly. –  Nathan Long Apr 4 '12 at 19:28
add comment

Just to complete some comments:

The proper use of comments is to compensate for our failure to express ourself in code. Note that I used the word failure. I meant it. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration. (Clean Code by Robert C. Martin)

BTW: I do recommend this book.

share|improve this answer
add comment

Comments shouldn't paraphrase the code but explains things which aren't in the code (bigger picture, why, why an alternative hadn't been choosen...) And your example comments is just that: paraphrase of the code.

You may sometimes feel that a paraphrase is needed at the start of the else branch, but that is often a sign that your then branch is too big.

share|improve this answer
add comment

In your specific example, comments probably aren't necessary. As Caleb mentioned, if the code is clearly written and variables have semantic names, if statements are less likely to need commenting.

Compare your snippet with this:

if ($x) {
    func1();
} else {
    func2();
}

In this case, you would definitely want to use comments to describe what x, func1, and func2 represent (and slap the person who named things by that scheme, especially if it was you). You can't even tell whether $x is supposed to be a boolean. But this too is a case where you don't necessarily need comments, if you're able to refactor and rename.

In general, I like to write comments for logical blocks that describe things the code can't on its own. A one-liner every ~10-20 lines that describes what the following handful of lines accomplish at one higher level of abstraction (e.g. // Make the right amount of magic happen for your example) will help keep you oriented and give a new reviewer insight into what you're doing and when.

I actually often write these one-liners in before I start writing code, so that I don't lose track of the flow that the segment is supposed to have.

Finally, if you really do prefer (or there's a mandate that requires) commenting clauses in an if block regardless of the code's readability, I recommend:

// Broad description of block
if (something) {
    //Do this because something
    something();
} else {
    //Do this because !something
    somethingElse();
}

I feel it's the cleanest, because the comment lines up with the code to which it pertains. A comment describing what code does should be as close to the comment it describes as possible.

share|improve this answer
    
+1 for writing comments first –  Daenyth Apr 4 '12 at 19:35
add comment
if (IsWeekDay(day))
{// weekday -> alarm at 7am
   ...
}
else if(day == DayOfWeek.Saturday)
{// saturday -> alarm at 11am
   ...
}
else
{// (sunday) -> no alarm
   ...
}

I keep my brackets lined up and put it right after the bracket.

[Condition] -> [pseudo-code]

On an else, it technically means all other conditions failed, so I usually use parentheses.

([Condition]) -> [pseudo-code]

Note: this is for C#.

share|improve this answer
add comment

I try and use comments inside the block saying what that block does (your first sample).

Where this kinda' breaks down is when using elseif. I use Basic so there is no explicit end block and often have to comment what the condition is checking which goes on the line above (with a line break of course) if it's too long.

'Check XYZ
If Condition1 then
  'We need to do T and S
  DoCodeFor1();

'Check ABC
ElseIf Condition1 then
  'This requires something else to be done
  DoCodeFor2()

Else
  'We have no other option than to...
  DoCodeFor3()

End If
share|improve this answer
    
Yes, this is really working better when you are a using a language without parenthesis. –  acme Apr 4 '12 at 11:42
add comment
  • Keep your conditional blocks really short.
  • Call a method with a nice descriptive name if it looks like your conditional code is going to be more than a simple line or two.
  • Use nice descriptive names for your variables.
  • Make sure the conditional statement is clear in it's meaning, and not obfuscated or long. Use a method if it helps to keep things clean and readable.

If all of the above fails, add a very small descriptive comment before the if statement, to clarify your intent. Otherwise, there really shouldn't be a need to comment at all.

share|improve this answer
add comment

In C++ or C# I typically wouldn't comment simple cases (when its clear what's happening), and use this sort of style for commenting the final else ...

if (pattern == AAA)
{
  DoSomethingAAA();
}
else if (pattern == BBB)
{
  DoSomethingBBB();
}
else // if (pattern == CCC)
{
  DoSomethingCCC();
}
share|improve this answer
4  
Or better, "pattern.doSomething()" and let OO do its job. –  Paul Tomblin Apr 4 '12 at 13:38
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.