Adjust Comments To Fit Coding Style

"Should software be commented?" is a bit too general a question for my taste. I prefer to ask the questions "What comments are appropriate for a particular coding style?" and "What coding style should be used?"

Re comments:

  1. In my opinion, a good comment almost always adds some value to a method.

  2. However, adding a comment and keeping it up to date also costs time and effort.

  3. A comment is only worth adding if its value outweighs its cost. This will happen in some fraction of your methods. If you write long functions in assembly, this fraction is probably close or equal to one. If you write small methods in Smalltalk, KentBeck claims this fraction can be less than 1%.

  4. I think it is time-efficient to comment large, non-intention-revealing methods (putting aside the question of changing the method itself).

  5. I don't think it is time-efficient to comment small, intention-revealing methods, even if you think, like me, that a comment might still add some additional value (e.g. the "why" of the method, or who calls it).

Re coding style:

  1. Writing small, composed (all one level), intention-revealing methods (averaging 2 to 5 lines) is a trade-off.

  2. You gain ease of change, micro-understandability (no need for comments), and long term efficiency.

  3. You lose macro-understandability (harder to trace code - see RavioliCode), it takes longer in the short term, your classes become cluttered with more methods in the short term, and to do it right you have to change methods in classes you are not focusing on at the moment.

  4. If long-term efficiency is your goal, the trade-off is a good one.

  5. However, even if you try to write small methods, it is hard to get "over the hump" and learn to ignore the nagging voice in your head that keeps pointing out the drawbacks mentioned in point #3.

  6. If you are not yet over the hump, or have no reason or desire to get over the hump, your methods may average 6 to 10 or even more lines, and mix high and low level stuff. You may find comments are still often time-efficient.

  7. If and as you move over the hump and start to shrink and un-mix your methods, you will hopefully code fewer and fewer methods in which comments are time-efficient.

  8. One way to tell if you are "over the hump" is if adding base-class methods becomes a normal occurrence.


I can add methods to any class in the system. I don't, not usually. The cost of maintenance is just too high. So I don't quite see point 8 above. -- KentBeck

One benefit of small methods that isn't mentioned above is that you encounter many more opportunities for reuse. With larger methods, the temptation to cut-n-paste (instead of refactor) is greater. I personally haven't experienced any drawbacks from RavioliCode, but I've never had to maintain unfamiliar Ravioli. -- JimLittle


EditText of this page (last edited October 21, 2004) or FindPage with title or text search