Method Contracts
& Invariants
Learn to state method contracts (inputs and outputs) and invariants: the promises every method makes and the truths that never change.
What Is a Method Contract?
A method contract is an agreement between a method and the code that calls it. It specifies exactly two things: what the method requires from the caller, and what the method guarantees in return.
Anatomy of a Contract
Why Contracts Matter
Without clear contracts, code becomes fragile. Contracts make your programs predictable, debuggable, and safe by making assumptions explicit.
Preconditions: The Caller's Promise
A precondition is a condition that must be true before a method executes. If the precondition is violated, the method is not required to behave correctly.
* @pre \( \text{divisor} \neq 0 \)
* @post returns dividend / divisor
*/
public static double divide(double dividend, double divisor) {
if (divisor == 0) {
throw new IllegalArgumentException("Divisor cannot be 0");
}
return dividend / divisor;
}
Postconditions: The Method's Promise
A postcondition is a condition guaranteed to be true after the method completes, assuming preconditions were met. It describes the result and any side effects.
* @pre arr is not null and \( \text{arr.length} > 0 \)
* @post returns the largest element in arr
* @post arr is unchanged
*/
public static int findMax(int[] arr) {
int max = arr[0];
for (int val : arr) {
if (val > max) max = val;
}
return max;
}
What Is an Invariant?
An invariant is a condition that remains always true throughout the life of an object or during a method's execution. It describes a property that no operation is allowed to break.
Class Invariant: BankAccount
Key Distinction: Three Contract Parts
| Property | Precondition | Postcondition | Invariant |
|---|---|---|---|
| When checked | Before execution | After execution | Always |
| Whose job? | Caller | Method | All methods |
| Example | \( \text{index} \geq 0 \) | \( \text{size()} = \text{old size()} + 1 \) | \( \text{size} \geq 0 \) |
| Violation means | Caller's bug | Method's bug | Design flaw |
How to Write a Contract
Example 1: charAt
* Returns the character at position index in this String.
*
* @pre \( 0 \leq \text{index} < \text{this.length()} \)
* @post returns the char at position index
* @post this String is unchanged
*/
public char charAt(int index)
Example 2: ArrayList.add
* Inserts element at specified position.
*
* @pre \( 0 \leq \text{index} \leq \text{size()} \)
* @pre element is not null (if nulls disallowed)
* @post element is at position index
* @post \( \text{size()} = \text{old size()} + 1 \)
* @post all elements at index..\( \text{old size}()-1 \) shifted right by 1
*/
public void add(int index, E element)
Example 3: Loop Invariant
int sum = 0;
for (int i = 0; i < arr.length; i++) {
// Invariant holds here: sum is the total of \( \text{arr}[0..i-1] \)
sum += arr[i];
// Invariant restored: sum is the total of \( \text{arr}[0..i] \)
}
Documenting with Javadoc
In Java, method contracts are documented using Javadoc comments. While Java doesn't have built-in @pre / @post tags, the convention is widely used.
* Computes the average of a non-empty array.
*
* @param values the array of numbers
* @pre \( \text{values} \neq \text{null} \) && \( \text{values.length} > 0 \)
* @post returns the arithmetic mean of all elements
* @throws IllegalArgumentException if precondition violated
*/
public static double average(double[] values) {
if (values == null || values.length == 0)
throw new IllegalArgumentException();
double sum = 0;
for (double v : values) sum += v;
return sum / values.length;
}
Common Mistakes
Summary: Contracts at a Glance
| Concept | What It Is | Example |
|---|---|---|
| Precondition | Input requirement | \( \text{index} \geq 0 \) |
| Postcondition | Output guarantee | \( \text{result} = \text{max element} \) |
| Class Invariant | Always-true property | \( \text{balance} \geq 0 \) |
| Loop Invariant | True each iteration | \( \text{sum} = \text{arr}[0..i\!-\!1] \) |
| Guard Clause | Enforces precondition | if (x == null) throw ... |
Question 1 of 5
A method's precondition is violated when the caller passes an out-of-range index. Whose responsibility is the resulting error?
Question 2 of 5
Which of the following is a postcondition for a method that sorts an array in ascending order?
Question 3 of 5
A BankAccount class has the invariant: \( \text{balance} \geq 0 \). A programmer adds a transfer method that can set the sender's balance to \(-50\). What happened?
Question 4 of 5
Consider this method contract:
@pre \( \text{list} \neq \text{null} \) and \( \text{list.size()} > 0 \)
@post returns the element removed from index 0
@post \( \text{list.size()} = \text{old list.size()} - 1 \)
@post all remaining elements shift left by 1
What happens if the caller passes an empty list to this method?
Question 5 of 5
In a summation loop, the loop invariant states: "sum equals the total of \( \text{arr}[0] \) through \( \text{arr}[i-1] \)." When does this invariant need to hold?