As a senior software engineer with over a decade of experience, I’ve seen how comments in code can evolve from helpful documentation to misleading traps. Today, I want to share some insights about writing cleaner, self-documenting code.
The Problem with Comments
Why Im so down on comments? Because they lie. Not always, not intentionally but too often. The older the comment is the more likely it is to be wrong. The reason is software engineers maintain the code but not the comments. Code will not lie to you but comment will; Code evolves but comments not. Thus comments sometimes will be misleading.
Therefore although comments are sometimes necessary, we need to try to minumise them.
One of the common motivation for comments is bad code. We wrote a piece of code and we know it is complex, confusing and hard to understand. So we say to ourselves, “It is good for readers, I need to write down my thoughts here”. But we have another choice, we can spend time in cleaning it.
Have a look at the below piece of code:
//does the module from the list depend on the subsystem?
if(module.getDependSubsystems().contain(othermodule.getSubSystem()))
At first glance, the comment seems helpful. But let’s break down why this isn’t ideal:
- - The comment is explaining what the code does (which should be obvious from the code itself)
- - There’s a typo in the method name (contain vs. contains)
- - The variable names aren’t as descriptive as they could be ###The Better Approach Here’s how we can refactor this code to be self-documenting:
List<String> dependentSubsystems = module.getDependentSubsystems();
String targetSubSystem = otherModule.getSubSystem();
boolean isModuleDependentOnSubSystem = dependentSubsystems.contains(targetSubSystem);
if (isModuleDependentOnSubSystem) {
// handle dependency case
}
Let’s analyze the improvements:
- Meaningful Variable Names: dependentSubsystems and targetSubSystem clearly describe their purpose
- Extracted Boolean Logic: The condition is now stored in a well-named boolean variable
- Proper Method Names: Fixed the typo in contains
- No Comments Needed: The code is now self-explanatory
When Are Comments Appropriate?
Comments aren’t always bad. They’re useful for:
- Legal requirements
- API documentation
- Complex algorithms that can’t be simplified further
- Explaining why something is done, not what is being done
Conclusion
Remember: The best code is code that tells its own story. Before adding a comment, ask yourself: “Could I make this clearer through better code structure?”
Top comments (0)
Some comments may only be visible to logged-in visitors. Sign in to view all comments.