01 / 21

Method Contracts
& Invariants

Learn to state method contracts (inputs and outputs) and invariants: the promises every method makes and the truths that never change.

AP Computer Science A Java

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.

Preconditions
What must be true before the method runs: valid inputs, object state, and constraints.
Postconditions
What the method guarantees after it finishes: return values, side effects, and state changes.

Anatomy of a Contract

sqrt(double x) Method Body Computes square root Precondition
\( x \geq 0 \)
Postcondition
\( \text{result} \geq 0 \)
Invariant: object state unchanged

Why Contracts Matter

Without clear contracts, code becomes fragile. Contracts make your programs predictable, debuggable, and safe by making assumptions explicit.

Clarity
Other developers know exactly what inputs to provide and what output to expect.
Safety
Invalid inputs are caught early instead of causing mysterious bugs deep in the code.
Testability
Each precondition and postcondition becomes a concrete test case you can verify.

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
A property true for every instance at all times: "A BankAccount balance is never negative."
Loop Invariant
A property true before and after each iteration: "At step \( i \), the subarray is sorted."

Class Invariant: BankAccount

BankAccount
INVARIANT: \( \text{balance} \geq 0 \)
Constructor
\( \text{balance} = 0 \) ✓
deposit(amt)
\( \text{amt} > 0 \) ✓
withdraw(amt)
\( \text{amt} \leq \text{balance} \) ✓
INVARIANT HOLDS: \( \text{balance} \geq 0 \) ✓
Every method must preserve the invariant

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

1
Identify the inputs. List every parameter and any object state the method reads.
2
State preconditions. What must be true about each input? Think: null checks, range limits, valid states.
3
Identify the outputs. What does the method return? Does it modify any fields or parameters?
4
State postconditions. Describe the return value and all side effects precisely.
5
Check invariants. Does the method preserve all class-level truths?

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)
Precondition
\( 0 \leq \texttt{index} < \texttt{length()} \): the index must be within bounds.
Postconditions
Returns the correct character. The String object is not modified.

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

// Loop Invariant: \( \text{sum} = \text{arr}[0] + \text{arr}[1] + \dots + \text{arr}[i-1] \)
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] \) }
i=0
\( \text{sum}=0 \)
i=1
\( \text{sum}=\text{arr}[0] \)
i=2
\( \text{sum}=\text{arr}[0..1] \)
i=n
\( \text{sum}=\text{arr}[0..n\!-\!1] \)
Invariant holds at every checkpoint

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

Missing Null Check
Forgetting that parameters can be null. Always state whether null is allowed in the precondition.
Vague Postconditions
Writing "returns the result" instead of precisely specifying what the result is and how it relates to inputs.
Breaking Invariants
Adding a new method to a class that accidentally violates the class invariant (e.g., setting balance to a negative value).

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

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?