3.2. Interface Contracts

A system is made up of interfaces that interact with each other. The interfaces can be implemented by object-oriented code or by procedural code. Yukihiro Matsumoto, the inventor of Ruby, suggests that the interface is everything to the user. I would add that the interface is everything to the developer.

FINDING YOUR WAY IN THE DARK

We arrived at a camping area in the darkness of a new moon. We were looking for the campsite we had been assigned. We had a flashlight, but it yielded only a narrow beam of light. Relating what we saw in that narrow beam to the written directions was difficult.

The next morning, the sunlight revealed the big picture of the camping area. How the campsites were positioned in the area was apparent instantly. It would have been much easier had we had that big picture the night before.

Bertrand Meyer introduced the concept of Design by Contract in Object-Oriented Software Construction (Prentice Hall PTR, 2000). An interface has a contract with the user of that interface. The contract consists of preconditions and postconditions for every method in the interface. Preconditions are assertions that must be true when the method is called so that the method can perform its operations. Postconditions are assertions that should be true when the method finishes.[*]

[*] Meyer also introduces the invariant condition, which must always be true for a valid object. An invariant condition typically involves the state of the attributes of an ...

Get Prefactoring now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.