Monday, 12 January 2015

Are Comments Necessary?

There are a lot of opinions on Comments in code.

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.
There are two ways we can deal with unclear source code:
  1. add comments, if the source code is unclear
  2. refactor the code, if the source code is unclear, until the code is clear
The second option seems the best.

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
Now, these individual items were stored in the record for a House.

Here is roughly my iterative software development written out:
  1. 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.).
  2. I thought about it, and decided that this was a group of related data.
  3. I made a class ValueCharacteristics, that contained all these.
  4. I removed the comments.
Added bonus: once a value characteristic is added or removed, the different places where this will impact my code are much more clearly visible.

Conclusion

The steps you take can be generified as follows:
  1. If the code is unclear, try and add comments.
  2. Then try and think how you can change the code to better reflect the comments.
  3. Change the code.
  4. Remove the comments.
Comments can cause us to think about the code we produce.

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)

2 comments:

  1. 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

    ReplyDelete
    Replies
    1. That is awesome! It sounds like a very good metric on how insightful the source code is!

      Delete