Robust Methods: Programs with Exceptions

  • Design robust methods with Exceptions.

Consider the specification of the IndexedList.get method:

/**
 * 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.
 */
T get(int index);

A client of get (any method that calls it) is responsible to ensure the pre-condition is met. The get method can check the validity of its input too. (It is not always the case that a method will be able to check and ensure its pre-conditions are met.)

A robust method is one that handles bad (invalid or absurd) inputs reasonably.

Java's exception handling mechanism supports the construction of robust methods.

Let's update the specification/declaration of IndexedList.get to make it robust.

/**
 * Retrieve the value stored at the given index.
 *
 * @param index representing a position in this list.
 * @return value at the given index.
 * @throws IndexOutOfBoundsException when index < 0 or index >= length.
 */
T get(int index) throws IndexOutOfBoundsException;

Notice we have removed the pre-condition. Instead, the method throws IndexOutOfBoundsException when index is out of range.

Resources

Here are some resources on robust coding:

Defensive programming is a closely related concept.