In the words of Uncle Bob1:
“The proper use of comments is to compensate for our failure to express ourselves in code.”Here are some things to remember:
- Code is Leading.
- If comments and code do not match up, the comments are wrong.
- Code is always current, comments age.
- add comments, if the source code is unclear
- refactor the code, if the source code is unclear, until the code is clear
However, if the code is abstract, but the implementation refers to a (potentially complicated) knowledge domain, comments are a requirement.
However, sometimes the code should follow the knowledge domain. You try to implement the Knowledge Domain as faithfully as possible, to sort of map it one-on-one, if possible. If that succeeds, what you end up with is a Domain Specific Language (DSL).
Example
For example, in my job I work with valuation of houses. There are several characteristics that account for the value of a house.- location
- quality
- maintenance
- appearance
- purpose
- facilities
Here is roughly my iterative software development written out:
- I added comments on each of these (on the getters and setters) to indicate that it was a value characteristic. (instead of, for example, an address, price, year of construction, etc.).
- I thought about it, and decided that this was a group of related data.
- I made a class ValueCharacteristics, that contained all these.
- I removed the comments.
Conclusion
The steps you take can be generified as follows:- If the code is unclear, try and add comments.
- Then try and think how you can change the code to better reflect the comments.
- Change the code.
- Remove the comments.
Always keep in mind, if you have to add lots of comments to a piece of code, perhaps it is time to refactor instead.
I think that comments can still provide insight in "why" we do things, whereas the code only tells us "how" we do things.
References
- [1] Clean Code - Chapter 4 - Comments
- Robert C. Martin (Uncle Bob)
There are companies where you only get 5 minutes to digest what a method is doing. otherwise, the whole team will review and refactor it
ReplyDeleteThat is awesome! It sounds like a very good metric on how insightful the source code is!
Delete