Saturday, July 16, 2011

Comments on code comments

Some easy topic for saturday evening!

Please do not comment your code!
Or do it less than you do now!

I know you have learned that comments are good, and yes, I was very happy to see lots of comments in an assembly code, but please, do not comment each line of your java code.

Consider the following snippet:

1  /**
2   * This method calculates some value.
3   * @param stockId stock identifier
4   * @return integer value
5   */
6   private int calculateSomeStockValue(int stockId) {
7       // the initial value of the algorithm
8       final int initialValue = 10;
9
10      EntityManager em = null;
11      try {
12          // create an entity manager to access the database
13          em = this.managerFactory.createEntityManager();
14          assert em != null;
15
16          // read the stock from the database
17          final Stock stock = em.readStockValue(stockId);
18
19          // if no stock found return the initial value
20          if ( stock == null )
21                return initialValue;
22
23         // retrieve the average price of the stock
24        final double stockPrice = stock.getCurrentPrice();
25
26         return stockPrice;
27      } finally {
28             // close the entity manager if not null
29             if ( em != null )
30                 em.close();
31      }
32 }


Just be honest, what additional information gives you those comments? I mean in spite of the fact that they make the code unreadable, and they are probably even false (see line 23,24 - is it a bug in the source, or just an old comment)!


Do not comment your code, or if you comment it consider writing useful information! Rather then use speaking variable and method names. Don't be afraid of long names. Your code will more readable through them.


Less comment is more!

No comments:

Post a Comment