Sub topic 14
Design Clear Method Contracts
A method is a named set of instructions. When you call a method, you ask it to run. A method contract is the agreement between the method and the code that calls it.
A clear contract answers four questions:
- What information does the method need?
- What result does it provide?
- What happens when the information is invalid?
- What, if anything, does the method change?
Contracts matter because callers should not have to read every line of a method to use it safely. They also help the person writing the method decide what the method must do.
Describe inputs and results
A parameter is a name for information a method receives. An argument is the actual value supplied in a call. For example, in a call such as sumPricesInCents(prices), prices is the argument.
A return value is the result a method gives back to its caller. A contract should describe both the accepted arguments and the return value.
Suppose a method adds prices. These details matter:
- Each price is in cents, not dollars.
- Prices must be zero or greater.
- An empty collection of prices has a total of zero.
- The result is also in cents.
Without units and limits, a caller might pass dollars or use a negative price without knowing whether that is allowed.
A precondition is a condition that must be met for a valid call. A postcondition is a promise about the result or state after a valid call completes. For our price method, nonnegative prices are a precondition. Returning their total is a postcondition.
Decide what the method may change
A side effect is a change a method makes beyond returning a value. For example, a method may change an item in a collection, print a message, or write to a file.
Side effects are not always bad. A method named printReceipt is expected to print. A method named sumPricesInCents, however, is easier to use if it only calculates and returns a total.
An array is a group of values stored in order. When a method receives an array, it can change the values in that array. The caller can then see those changes. If the method promises not to change the array, it must keep that promise even when the input is invalid.
Before writing a method, decide:
- Does it only read the input, or can it change it?
- Does it print or change anything else?
- If it fails, can it leave a partial change behind?
State important answers in the contract. A caller can then use the method without making a protective copy just to avoid an unexpected change.
Choose a clear response to invalid input
Input validation is checking whether supplied values meet the contract. For example, a price method can check that no price is negative.
In Java, null means that a reference does not point to an object. A reference is a value used to find an object, such as an array. A null array is not the same as an empty array: an empty array exists and contains zero items.
An exception is a signal that something prevented a method from completing normally. For invalid arguments, a method can throw an IllegalArgumentException. Throwing it stops the normal flow of the method unless calling code handles the exception.
For our example, we will make these choices:
- An empty array is valid and produces zero.
- A
nullarray is invalid. - An array with a negative price is invalid.
- Invalid input causes an
IllegalArgumentException. - The method does not change the array, even when it fails.
Other choices may be useful in other programs. The important point is to choose deliberately and tell callers what to expect.
Write and use a contract
The following program adds an array of prices. Save it as MethodContractsDemo.java.
public class MethodContractsDemo {
/**
* Returns the total of prices measured in cents.
*
* The array is not changed. An empty array has a total of zero.
*
* @param pricesInCents an array of nonnegative prices in cents
* @return the total in cents
* @throws IllegalArgumentException if the array is null or
* contains a negative price
*/
static long sumPricesInCents(int[] pricesInCents) {
if (pricesInCents == null) {
throw new IllegalArgumentException(
"pricesInCents must not be null"
);
}
long total = 0;
for (int priceInCents : pricesInCents) {
if (priceInCents < 0) {
throw new IllegalArgumentException(
"pricesInCents must not contain negative values"
);
}
total += priceInCents;
}
return total;
}
public static void main(String[] args) {
int[] prices = {250, 175, 0};
System.out.println(sumPricesInCents(prices));
System.out.println(prices[0]);
System.out.println(sumPricesInCents(new int[0]));
int[] largePrices = {2_000_000_000, 2_000_000_000};
System.out.println(sumPricesInCents(largePrices));
try {
sumPricesInCents(new int[] {100, -1});
} catch (IllegalArgumentException problem) {
System.out.println("Invalid prices: " + problem.getMessage());
}
}
}Compile and run the program with these commands:
javac MethodContractsDemo.java
java MethodContractsDemoThe output is:
425
250
0
4000000000
Invalid prices: pricesInCents must not contain negative valuesThe first total is 425 cents. The next line shows that the first price is still 250. The empty array produces zero. The large-price example shows why the result uses long: it can hold larger whole numbers than int. Each price is an int, but the total of several prices may be too large for an int.
The method is static, which means it belongs to the class rather than to an individual object. The main method can therefore call it without first creating an object. The try and catch part handles the invalid-input exception and prints its message.
The /** ... */ text is a Javadoc comment: a comment used to document Java code. Here, @param describes the input, @return describes the result, and @throws describes a possible exception.
Make names and responsibilities match
A good method name gives callers a useful first clue. sumPricesInCents says what is added and which unit is used. A name such as process would leave those details unclear.
A method is also easier to understand when it has one clear responsibility. Calculating a total and printing a receipt are different jobs. Keeping them separate lets a caller use the total without printing anything. Another caller can calculate the total and then choose how to display it.
Avoid adding unrelated behavior just because a method already has the needed data. For example, sumPricesInCents should not silently change prices or print warnings. If a method must make such changes, describe them in its name or contract, as well as in its documentation.
A clear contract does not need to describe every step inside the method. Callers need to know what the method promises, not whether it uses a particular loop.
Check boundaries and promises
A boundary is a value at or near the limit of what a method accepts. Boundaries are common places for mistakes. For the price method, zero is a boundary: it is valid, while a value below zero is not.
A test is a check that compares what a program does with what it should do. Use the contract to choose tests:
| Input | Expected behavior |
|---|---|
| An empty array | Return `0` |
| Prices `250`, `175`, and `0` | Return `425`; leave the array unchanged |
| Two prices of `2_000_000_000` | Return `4000000000` |
| An array containing `-1` | Throw `IllegalArgumentException`; leave the array unchanged |
| `null` | Throw `IllegalArgumentException` |
The sample program checks several of these cases. Printing prices[0] shows that one item stayed the same, but a fuller test would check every item in the array. It should also check that invalid calls do not change any items.
When reviewing a method, ask whether its behavior is predictable for ordinary inputs, boundaries, and invalid inputs. If an answer is unclear, improve the contract before callers have to guess.
Practice
Exercise
What happens when sumPricesInCents receives an array containing 100 and -1? What happens to the array?
Show answer
It throws IllegalArgumentException and returns no total. The array remains unchanged.
Exercise
A method named doublePriceInCents accepts a nonnegative int price and returns a long. What should its contract say?
Show answer
It should say that the input is a price in cents, the input must be nonnegative, and the returned value is twice that price in cents. It should also state what happens for a negative input and whether the method has any side effects.