Java Reference
In-Depth Information
Consider, for example, the get method. It is a fairly simple method that allows the
client to access individual elements of the list:
public int get(int index) {
return elementData[index];
}
This method makes sense only if the value of index is in the range of occupied
cells. In other words, it has to be greater than or equal to 0 and it has to be less than
the size of the list. We can describe these constraints in a precondition comment:
// pre : 0 <= index < size()
public int get(int index) {
return elementData[index];
}
The postcondition should describe what the method accomplishes, assuming that
the precondition is met. You can do that with a short description of the method's
behavior:
// pre : 0 <= index < size()
// post: returns the integer at the given index in the list
public int get(int index) {
return elementData[index];
}
There are quite a few preconditions for the methods you have written. All of the
methods that take an index as a parameter assume that it is a legal index. The construc-
tor that takes a capacity can't work with a negative value. And there is another impor-
tant precondition lurking out there. Remember that your list has a fixed capacity. What
happens if the client calls the add method so many times that the capacity is
exceeded? You should warn the client about that scenario to make the contract clear.
In the next section we'll examine how to handle bad values more directly, but for
now we'll settle for documenting the various preconditions.
It is worth noting that the method comments for this class do not contain com-
ments about implementation. For example, we wouldn't mention that the remove
method shifts values in the array. That's a detail of the implementation that won't
generally interest the client. If you think that the implementation is complicated
enough to deserve comments, then include those comments with the code itself inside
the method. The comment on the method itself should be written from the client per-
spective, not from the perspective of the implementer.
Professional Java programmers write their comments in Javadoc format so that they
can be extracted from the actual program files and published as html files. If you've been
referring to Sun's API documentation, then you've been reading such comments. We
don't use Javadoc format for our comments, but you can read about it in Appendix C.
Search WWH ::




Custom Search