Sonntag, 11. November 2012

Describing Attributes of Classes

In many of the classes I saw over the last years were no comments to describe the attributes or member variables. The most frequently used style of commenting attributes from my experience is reformulating the variable-identifier in natural language. Consider the following Java-class as an example:


public class Invoice {

 /**
  * The order
  */
 private Order order;

 /**
  * The invoicing amount
  */
 private double invoicingAmount;

 /**
  * The id
  */
 private int id;

 /**
  * The due date
  */
 private Date dueDate;

 [...]
}

I believe that these comments will help nobody, because they are just redundant and contain no further information. But how to do it better? 

Well, in English one could describe the overall and general meaning in form of clauses. A clause is the simplest grammatical unit that can express a "meaning". There are several forms of clauses, e.g. relative ("I like the car, which is red.") or temporal ones ("After cleaning the house, please wash the car.").

I made the experience, that a simple patterns fits the problem of commenting attributes. You can use the main clause "This attribute represents ..." + CLAUSE. Since the main clause is always that same, you can omit it and just write the relative or temporal CLAUSE into your code. Look, how this pattern applies to the example from above:

public class Invoice {

 /**
  * What the customer has to pay for
  */
 private Order order;

 /**
  * What the customer has to pay including all discounts.
  */
 private double invoicingAmount;

 /**
  * What is used to find/identify this invoice.
  */
 private int id;

 /**
  * When this invoice has to be paid.
  */
 private Date dueDate;

 [...]
}

All of these clauses have the type of an content clause. They have the same role as an object. These clauses simply replace the object noun. I think, these comments express explicitly the general purpose the attributes. So we have an added value. When formulating it with clauses, this seem to come automatically. 

Please let me know if this patterns works for you :).