Design by contract
Programming by contract, also called design by contract, is an approach to designing software components. Every component or object, whichever you prefer to call it, has a contract. The contract describes the inputs, outputs, and invariants (conditions that stay fixed) of that component. Any client working with the component accepts the contract simply by using it.
public class Auto {
private int maxHmotnost; //maximalni hmotnost auta
private int hmotnost; //aktualni hmotnost
public class Auto(int maxHmotnost) {
this.maxHmotnost = maxHmotnost;
}
public int nalozit(int hmotnostNaklad) {
if(hmotnostNaklad maxHmotnost) {
throw new IllegalArgumentException();
}
int novaHmotnost = hmotnost + hmotnostNaklad;
if(novaHmotnost > maxHmotnost) {
throw new IllegalArgumentException();
}
this.hmotnost = novaHmotnost;
return this.hmotnost;
}
}The contract for the Auto class is defined as follows. The maximum weight of the car is invariant. It never changes. The contract also defines the range of the input argument to nalozit. It must be greater than zero and no greater than the maximum weight. Under those conditions the method guarantees that the returned new weight won’t exceed the car’s maximum weight.
Our class defines its contract explicitly. It contains the checks needed to enforce it. This prevents erroneous behavior if the client breaks the contract, for instance by trying to lighten the car with a negative weight or, conversely, overloading it.
Design by contract is based on all components defining their contracts explicitly. That ensures a violation interrupts processing or prevents the operation from running. From a development perspective, that’s appropriate. Breaking a contract by using the component incorrectly leads to an exception and an interruption, signaling incorrect use or another problem.
There are several ways to check the contract in Java. You can use a test like the one in nalozit, for example, or use the assert keyword (Java 1.4). Another option is to use annotations, as frameworks like Contract4J or Spring contracts do.
If design by contract hasn’t caught your interest, or you think you missed something, I highly recommend giving it one last chance with the interview
Design by Contract: A Conversation with Bertrand Meyer, Part II.
Related articles
Related CZ Podcast episodes
- #261 · Leadership
On leading people and teams. · Czech audio
- #3 · Java 6 SE, Vývoj webových aplikací
Dagi and Filemon discuss Java 6 and web application frameworks. · Czech audio
- #1 · Vývojová prostředí v Javě
The first CZ Podcast episode looks at Java development environments. · Czech audio