Learn effective strategies for code commenting to enhance readability and maintainability. This guide covers best practices for commenting on code updates, handling debug statements, and documenting methods and properties.
There is almost always a better alternative to adding comments to your code.
What are the downsides of comments? What are the alternatives? What are bad and good types of comments?
Sometimes, you need to write code that deviates from the standard pattern. It might be a workaround for a library bug, an optimization for a critical performance path, or a temporary solution pending a larger refactor. Without context, a future developer, or even you, months later, might see this "weird" code and refactor it back to the standard pattern, unknowingly reintroducing a bug.
To prevent this, it's crucial to leave a clear, permanent note directly in the code. This ensures the "why" behind the decision is never lost.
When you create comments in your code, it is better to document why you've done something a certain way than to document how you did it. The code itself should tell the reader what is happening, there's no need to create "how" comments that merely restate the obvious unless you're using some technique that won't be apparent to most readers.
It's important that you have consistent commenting for your code, which can be used by other developers to quickly determine the workings of the application. The comments should always represent the rationale of the current behaviour.
It's common to add a
TODOcomment to some code you're working on, either because there's more work to be done here or because you've spotted a problem that will need to be fixed later. But how do you ensure these are tracked and followed up?First don’t do it and find the right fix. But if you have to, it should always be commented – as though your life depended on it.
If you have to use a workaround you should always comment your code.
In your code add comments with:
- Comments - Do you follow the code commenting standards?
- Do you leave explanatory notes for non-standard code?
- Comments - Do you know what to do with comments and Debug.Print statements?
- Do you know the best way to track comments when your code is updated?
- Do you document "TODO" tasks?
- Comments - Do you add a comment when you use Thread.Sleep?
- Do you know what to do with a work around?