5. Exceptions and Preconditions

An obvious design issue is whether to use a precondition, and if so, whether it should be checked.

A non-trivial precondition renders the method partial. This inconveniences clients, because they have to ensure that they don’t call the method in a bad state.

So users of methods don’t like preconditions, and for this reason the methods of a library will usually be total.

But sometimes though, a precondition allows you to write more efficient code and saves trouble.

The decision of whether to use a precondition is an engineering judgment. The key factors are:

Sometimes, it’s not feasible to check a condition without making a method unacceptably slow, and a precondition is often necessary in this case.

Example: In the Java standard library, for example, the binary search methods of the Arrays class require that the array given be sorted. To check that the array is sorted would defeat the entire purpose of the binary search: to obtain a result in logarithmic and not linear time.

Even if you decide to use a precondition, it may be possible to insert useful checks that may detect that the precondition was violated.

Example: For example, in balancing the binary tree, you might check when you visit a node that its children are appropriately ordered.

If a precondition is found to be violated, you should throw an unchecked exception, since the client will not be expected to handle it. The throwing of the exception will not be mentioned in the specification, although it can appear in implementation notes below it.