Describing instance variables and static variables
Figure 13.8 contains a class ItemSale whose instances contain information
of the sale of an item. For example, one instance might represent the sale of four
organic apples at a price of 3 for $1.19. We have shown only some the fields and
none of the methods in the class in order to make it easier to concentrate on the
issue at hand.
One might think that the names of these variables are self-explanatory and
that they might be made more explanatory by making them longer. Nevertheless,
the meaning of the variables will become much clearer with comments.
First, we describe name as the name of the item being sold. This distin-
guishes it, say, from the name of the salesperson.
Second, we describe groupCount and groupPrice together. This makes
sense because, together, they define the price of an item.
Third, we place the obvious comment on the declaration of numSold .
These comments clarify two points, which are not clear from the names of
the variables alone. They tell us precisely what name names, and they tell us that
the unit for groupPrice is cents, and not dollars or rubles or Euros or other mon-
etary units. This illustrates how comments can be more precise than names.
The term class invariant is generally used for the collection of descriptions
of all the instance and class variables. Together, these descriptions describe the
state of an object before and after each method of the class is called.
Cluster declarations by logical togetherness
We could have given these four declarations in some other order. However,
it is not a good idea to separate the declarations of groupCount and groupPrice
because, logically speaking, they belong together. Together, they describe the
price of the items. This illustrates an important principle:
Group logically related variables together and describe them with
We have aligned the comments that annotate these declarations. It is not nec-
essary to align them in this way, but it sure looks better and makes the comments
easier to read! So get in the habit of aligning comments suitably. The difficulty,
of course, is that if any change is made to the declarations, the alignment proba-
bly will not be proper. So some people will tell you, quite rightly, not to bother
with aligning the comments.
You can use an alternative form for the comments, as illustrated in Fig. 13.9:
Place the comments for a group of logically related variables
above the declarations and follow the last declaration by a blank
Separate declarations of static variables from declarations of instance vari-