Code Contracts Using Documentation Comments
- Declare an ADT using a Java interface, with complete JavaDoc comments.
- Understand the importance and use of pre- and post-conditions for methods documentation.
Here is the IndexedList
documented using Java Documentation Comments (or simply Javadoc):
/**
* IndexedList ADT.
*/
public interface IndexedList {
/**
* Change the value at the given index.
*
* @param index representing a position in this list.
* Pre: 0 <= index < length
* @param value to be written at the given index.
* Post: this.get(index) == value
*/
void put(int index, int value);
/**
* Retrieve the value stored at the given index.
*
* @param index representing a position in this list.
* Pre: 0 <= index < length
* @return value at the given index.
*/
int get(int index);
/**
* Get the declared capacity of this list.
*
* @return the length
* Inv: length() >= 0
*/
int length();
}
Documentation comments are considered part of the specification of an ADT, as well as a general good programming practice.You are expected to follow this practice in this course.
Documentation comments provide code contract: a way to specify the behavior of your ADT as well as preconditions, post-conditions, invariants, etc.
-
Preconditions are requirements that must be met when entering a method. For example, the
get
method specifiesPre: 0 <= index < length()
, which means the value for theindex
parameter must be non-negative and smaller than the length of the list. If a client violates this condition, they cannot expect theget
method to behave as specified. -
Postconditions describe expectations at the time the method exits. For example, the
put
method specifiesPost: this.get(index) == value
which means once the method is successfully executed, you can callget(index)
and expect it to return thevalue
. -
Invariants describe the expected state for all objects of a class. For example, the
length
method specifiesInv: length() >= 0
which means the length is always a non-negative value.
Resources
Here are two articles to help you get up to speed with Java Documentation Comments:
You can add a Javadoc using automatic comments in IntelliJ. See this guideline for more details.