Explain Your Work

There are lots of reasons why maintaining a large and/or old codebase is difficult, especially as different people work on that codebase over time.

One of the big reasons is _intent_—what did the author intend when they wrote this piece of code? Engineers that aren’t intimately familiar with an area of code (a.k.a. most engineers) won’t immediately understand more nuanced snippets or decisions.

There are many Good Ways that we try to combat this. We can encapsulate things to make them self-contained. We can extract shared or repeated functionality. These things aim to reduce what engineers have to hold in working memory.

There’s also the good, old-fashioned approach: explain your work. Don’t just tell me the answer, tell me why this is an appropriate answer.

In other words, leave some comments explaining what your code does.

Objections

Let’s quickly address some natural objections.

Explaining your code isn’t a replacement for making good design decisions.

They complement each other—good decisions keep the code structured well and good explanations help ensure others understand that structure.

Self-explanatory code doesn’t eliminate the need for explanation.

There are many people who believe that good code should explain itself, via its structure and how it’s named. I agree, although I don’t think that this is enough.

In particular, comments can explain different perspectives. They can explain why an approach was taken. They can also connect different concepts or abstraction levels that aren’t immediately obvious.

Useful Comments

A comment is useful when it makes it easier for someone else to understand your code in the future. This has a few different flavors.

Complex Code

Sometimes we write convoluted, ugly code—often when we’re dealing with lower levels of abstraction or taking a hacky approach. A comment explaining the intent is helpful.

Algorithms

An algorithm isn’t always intuitive—enumerating the steps or critical pieces allows a reader to get an idea of what the algorithm is. Otherwise, we’re forcing them to reconstruct and understand the algorithm before they can understand the code.

Hacks and Band-Aids

There are times we don’t know what’s going on—we’ve all been there. You might be copying a Stack Overflow answer, using a hack you don’t understand, or trying to apply a quick band-aid so you can focus your attention somewhere else.

It helps to explain what you’re trying to do, the constraints you have, and what you’re uncertain about. If you’re copying an answer from somewhere else, link back to it so future readers can retrace your steps.

Business Logic

Sometimes it’s critical that our code hits on the requirements in a spec. Comments can tag which snippets are responsible for which requirements, and even aid with future grepping.