Chapter 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 postconditions

Software reliability refers to the extent to which the system performs as expected, in a variety of operating conditions. In this chapter, we’ll explore the main coding techniques you can use to prevent or expose unexpected program behaviors. But first, let’s discuss how you can define the expected behavior of a piece of software, aka its specification. In line with the structure of this book, I’ll 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 in which each party accepts obligations in exchange for some benefits. In fact, what’s 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 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 precondition, a postcondition, and possibly a penalty.

5.2. Designing containers by contract

5.3. Containers that check their contracts    [Contracts]

5.4. Containers that check their invariants    [Invariants]

5.5. And now for something completely different

5.6. Real-world use cases

5.7. Applying what you learned

Summary

Answers to quizzes and exercises

Further reading

sitemap