On comments

I mentioned that keeping comments up-to-date with modifications in source code helps me with task-switching in a busy workplace.

Of course, that doesn't make a difference if you're not commenting your code well.

Therein lies the rub. I spent weeks on learning various sorting algorithms in my data structures and algorithms class, but I never really learned anything on the whys and wherefores of commenting.

I've been taught that

// This is an inline comment.

and that

/* This is a block comment, which makes
 * longer comments a little bit more
 * readable.
 */

and also how to use comments to temporarily disable portions of your source code to try something out.

And that's fine.

But what should you put in your comments?

Visual Studio has a neat feature where if you type three slashes in a row (///) before a method definition, it'll expand a comment snippet that includes, as appropriate, sections for a summary, what method argument parameters are, and what the method returns. Whatever you enter there shows up in a tool tip when you hover over the method call later.

Similarly, three slashes (///) in Xcode will allow you to enter comments that show up when you hover over method calls.1

Handy, for sure.

But, really, when I'm heads down and trying to push code out before, say, I leave for the day, I've noticed that all I write in these comments is a re-iteration of the method signature—and given that I try to use very descriptive method and variable names in the first place, these extra lines of typing are pretty redundant. I'm just giving myself work for zero added benefit.

Samantha's tweet inspired me to think a bit more about how I comment my code. Intent is key, I agree. If the source code is the documentation2, then the comments should probably play the role of both the chapter summaries, and the sidebars that warn of the gotchas, the perils, and the pitfalls. The bigger-picture stuff. Why is this structured this way? What might I have to look out for when testing this particular method?

All the best practices we learn—design patterns, unit testing, &cet.—are meant to make our code more maintainable. Comments should be an integral part of that, not just as a repetition of what's obvious from the source, but as a reflection of the intent of the thing.

  1. You definitely should pick up Erica Sadun's Swift Documentation Markup to really make the most of this feature, by the way.

  2. I'm not 100% convinced of this particular mantra. Of course, code is the canonical source of ground truth, and that's the intent, but as far as it being documentation—well, that's a post for another day.

Discuss...