Recall that the purpose of code is to instruct a computing device what to do in a form that is easy for the code’s intended audience to understand and maintain. Therefore, good code not only makes the device do what is wanted but also communicates three things:
- what the device was instructed to do,
- what the code’s authors intended the device to do, and
- why the code was written in the way that it was.
This last part—the “why”—is crucial. It includes domain knowledge, design and coding choices, and the rationale for those choices. Without this “why” knowledge, code becomes harder for its audience to understand and maintain, especially in organizations with many programmers and large code repositories.
Because logic is an unwieldy and sometimes unreliable vehicle for communicating anything but device instruction, good code usually communicates intent and “why” information at least partially via commentary.
Discussion
Let me defend some of the nuances and implications of my claims above.
Why should good code communicate both (1) “what the device was instructed to do” and (2) “what the code’s authors intended the device to do”? In good code, shouldn’t they be the same?
The reason that good code must communicate both (1) and (2) is that its audience must understand the authors’ intent for the code, but the code’s logic can only express what the device was actually instructed to do. Ideally, the logic would align with the intent, but there are many cases when it cannot or does not, for instance when the logic is buggy or when the logic by choice expresses an approximation of the intent (e.g., fast math logic in game engines). For this reason, good code communicates the authors’ intent directly to the intended audience, usually via commentary.
Why are comments necessary in good code?
The reason that comments are necessary in good code is twofold. First, the code’s logic cannot be trusted to express what the code’s authors intended the code to do. Logic can only express what the computing device was actually instructed to do. Without comments to communicate intent to the audience directly, bugs and approximations can be mistaken for the author’s ultimate intent.
Second, natural languages such as English are vastly more expressive than what you can shoehorn into a programming language’s logic. When you need to communicate a requirement, design decision, or other domain knowledge to your code’s audience, what is the most effective means? There is a reason that the very sources of this knowledge—requirements documents, design documents, standards, textbooks, and so on—are written in natural language. For the same reason, you probably ought to use natural language when you communicate these things in your code. And since you can’t use natural language except in comments, good code usually has comments.