How to write comment (from Clean code book)
The proper use of comments is to compensate for our failure to express ourself in code. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration. Code changes and evolves. Chunks of it ...
- The proper use of comments is to compensate for our failure to express ourself in code. Comments are always failures. We must have them because we cannot always figure out how to express ourselves without them, but their use is not a cause for celebration.
- Code changes and evolves. Chunks of it move from here to there Inaccurate comments are far worse than no comments at all
- Truth can only be found in one place: the code. Only the code can truly tell you what it does
Comments Do Not Make Up for Bad Code
Clear and expressive code with few comments is far superior to cluttered and complex code with lots of comments. Rather than spend your time writing the comments that explain the mess you’ve made, spend it cleaning that mess.
Explain Yourself in Code
// Check to see if the employee is eligible for full benefits if ((employee.flags & HOURLY_FLAG) && (employee.age > 65))
should be
if (employee.isEligibleForFullBenefits())
Good Comments
Some comments are necessary or beneficial. We’ll look at a few that I consider worthy of the bits they consume. Keep in mind, however, that the only truly good comment is the comment you found a way not to write.
Legal Comments We should write some legal comment like this to help another person know where and when the code come from
// Copyright (C) 2003,2004,2005 by Object Mentor, Inc. All rights reserved. // Released under the terms of the GNU General Public License version 2 or later.
Explanation of Intent
In the example below, it would be better if we can change the return value more clear. but when its part of the standard library, or in code that you can not alter then a helpful clarifying ocmment can be useful
assertTrue(a.compareTo(a) == 0); // a == a assertTrue(a.compareTo(b) != 0); // a != b assertTrue(ab.compareTo(ab) == 0); // ab == ab
Warning of Consequence It is good if we use comment for explain some special reason
public static SimpleDateFormat makeStandardHttpDateFormat() { //SimpleDateFormat is not thread safe, //so we need to create each instance independently. SimpleDateFormat df = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss z"); df.setTimeZone(TimeZone.getTimeZone("GMT")); return df; }
TODO comments We should write TODO comment for note something that we will do in fuction
//TODO-MdM these are not needed // We expect this to go away when we do the checkout model protected VersionInfo makeVersion() throws Exception { return null; }