Commenting your code

My philosophy on comments is pretty simple.

They’re for explaining outlier situations, not handholding. You don’t write comments to point out the obvious — e.g., “Open the file and parse it as JSON…” And if you are, STOP!

Sure there’s badly written code out there. But in general anymore, if you’re reading through code and believe you need comments to understand what’s going on, you don’t understand 1. the language, 2. the framework (React, .NET, MFC, etc.), or 3. the application and concepts involved. Comments shouldn’t be written so just anyone can jump into the codebase.

And if you’re writing a large comment to explain a block of code, you very likely need to rewrite the block of code. Functionality should be obvious from looking at it. And exceptions to that should be extremely rare.

Instead the aim should be writing code that is self-documenting. We’re long past the limitations of the… past that made meaningful abstraction impossible. All names should be descriptive. And given the comprehensive functionality in most any IDE today, there really isn’t any excuse to NOT make these names descriptive. Again, we’re long past the memory and storage limitations that made meaningful abstraction impossible.

I’ll give an example from my recent experience. As of this writing, I’m finishing up an enhancement for the Ghost CMS stemming from a theme I’m writing. The code base is JavaScript. Themes are a combination of HTML, CSS, JavaScript, and Handlebars.js. I don’t have much experience with JavaScript, and the file I’m modifying has zero comments beyond the comment block at the top, except for one line explaining why an index variable needs to be decremented by 1 – because the why isn’t obvious.

Yet.. I didn’t need comments on every code block or, worse, line of code to understand what’s going on. It was fairly easy to figure out. Comments would likely have just been more… stating the obvious.