Clear, concise comments can make the difference between software that’s mildly confusing and completely impenetrable. But despite our best intentions, comments often wind up less obvious than they seem. Even ones that are crystal clear still must be maintained; if the system evolves (but its comments don’t) we’ll soon be back to scratching our collective head.
There’s a time and a place for thoroughly-commented software, but the next time you’re struggling to explain the code in front of you, consider these five alternatives.
- Help the code explain itself. Before trying to comment your way out of convoluted logic, try fixing it. Complexity breeds bugs. While a comment may later help you ascribe blame, your future self won’t appreciate you any more for it.
- Explain the code in a test. Tests are the best sort of supplemental documentation, specifying the system’s purpose and providing confirmation that it’s working as intended.
- Explain the code in the logs. Log entries can still be ambiguous or outdated, but their visibility improves the odds that they’ll actually be maintained. And if a comment contains an important warning, why not make sure it’s exposed in production?
- Explain the code to a compiler. Dragoon your language’s type system, database schema, serializer definitions, and input validation into helping explain and enforce your design decisions. If they aren’t clear, make them clear.
- Explain the code in source-control. Writing small, focused commits and clearly explaining their motivation can help convey your intentions. And unlike inline comments, commit messages will grow harder to find as the offending code evolves and disappears.
Comments just sit there—why not put them to work instead? Make the logic clearer, expand the spec, increase visibility, improve the types, or exercise those source control muscles. Do the things you ought to be doing anyway, and get as much value from those comments as you can!