chapter five

5 Self-conscious code: Reliability through monitoring

 

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.

5.1  Design by contract

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.

5.1.1  Pre- and post-conditions

5.1.2  Invariants

5.1.3  Correctness and robustness

5.1.4  Checking contracts

5.1.5  The broader picture

5.2  Designing containers by contract

5.3  Containers that check their contracts Contracts

5.3.1  Checking the contract of addWater

5.3.2  Checking the contract of connectTo

5.4  Containers that check their invariants Invariants

5.4.1  Checking the invariants in connectTo

5.4.2  Checking the invariants in addWater

5.5  And now for something completely different

5.5.1  The contracts