// blue cheese & brie


A comment on the Clearest Code Challenge inspires this post.  In particular the bit about how someone can figure out the code if it’s commented, “no matter how crap the code is”.


Perhaps.


Comments are smelly.  Really.  From Ward’s Wiki: “Refactor the code properly and you won’t need comments.”  My OO Jedi Master insisted I detail the implications while blindfolded & blancing an LCD panel on my nose.  There may be typos.



  • If a comment & a line of code both say the same thing, there’s duplication in your source code.  You now need to maintain both.  If you forget to update one of them, it’s now even more confusing.

  • What happens if you remove the comment and extract the line of code into its own method? 


    • Does the comment become the method name? 


      • Does the new method look useful elsewhere? 


        • Does that new method belong on a different class?


          • What if you create a new class?  What else goes on it?

  • Can you change the way you wrote the code so the comment isn’t necessary?  Do this now.

  • When you remove comments that duplicate teh code, you can now focus on commenting the whys.

  • See also CommentCostsAndBenefits

  • If you think code needs clarification, don’t leave it be.  If you can’t refactor now, add a comment so you remember that it needs refactoring later.  (To quote Kent Beck, “Never interrupt an interruption.“)

  • Comments don’t stink.  But they should catch the attention of your nose. 

Comments (5)

  1. Derek LaZard says:

    Comments are a higher level of abstraction from the details that help to manage complexity…

  2. Duncan Jones says:

    No matter how clear your code is it can only tell you what the code does – not what it is _intended_ to do.

  3. Jim Arnold says:

    "No matter how clear your code is it can only tell you what the code does – not what it is _intended_ to do"

    I disagree – code can absolutely tell you what was intended. Classes, methods, fields and variables have names for a reason. I have yet to see a comment which couldn’t be refactored away.

    Jim

  4. Guido Domenici says:

    Agree with Jim. Comments are certainly your friends, but only when they detail *what* a certain method does, not *how* it does it, or you’re in for a maintenance nightmare. The code should be self-documenting otherwise. If you find yourself adding book-length comments explaining how a piece of code accomplishes something, you’re probably in need of refactoring. (Exceptions exist — for example for certain performance-critical sections where you need to sacrifice some of the code clarity for speed of execution.)