26

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?

9
  • 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, 2012 at 11:27
  • 1
    Why is Bigger better/preferable/different? See, I don't know.
    – JeffO
    Apr 4, 2012 at 13:31
  • Is this a subject for question or argue? Even if the question is well-meant, those are war-starters. Apr 4, 2012 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, 2012 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, 2012 at 16:24

9 Answers 9

37

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.

9
  • 14
    +1 don't overdo comments, clear code requires no comments Apr 4, 2012 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, 2012 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, 2012 at 11:44
  • 9
    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. Apr 4, 2012 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, 2012 at 19:52
13

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) {
  ...
}
1
  • I think this kind of has a weakness. If you do this with an else-if and a condition that takes a long time to compute, then you have to compute it regardless of condition. Aug 25, 2022 at 19:53
4

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.

4

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.

2

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.

0
2
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#.

1

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
1
  • Yes, this is really working better when you are a using a language without parenthesis.
    – acme
    Apr 4, 2012 at 11:42
1
  • 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.

0

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();
}
1
  • 4
    Or better, "pattern.doSomething()" and let OO do its job. Apr 4, 2012 at 13:38

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