This chapter covers:
- Writing method specifications in contract form
- Enforcing contracts at runtime
- Using assertions
- Checking class invariants as a lightweight alternative to post-conditions
Software reliability refers to the extent to which the system performs as expected, in a variety of operating conditions. In this chapter, we’re going to explore the main coding techniques you can use to prevent or expose unexpected program behaviors.
But first, let’s discuss how we can define the expected behavior of a piece of software, aka its specification. In line with the structure of this book, I’m going to focus on the behavior of a single class, such as Container.
A popular way to organize specifications of OO programs and classes therein is through the design-by-contract methodology.
In ordinary language, a contract is an agreement where each party accepts obligations in exchange for some benefits. In fact, what is an obligation for one party is the benefit of another. For example, a phone plan is a contract between a carrier and the phone owner. The carrier is obliged to render the phone service and the owner is obliged to pay for it, so that each party benefits from the other party’s obligations.
The design-by-contract methodology suggests attaching contracts to software artifacts, particularly individual methods.
A method contract comprises a pre-condition, a post-condition, and possibly a penalty.