Cover of The Pragmatic Programmer by Andrew Hunt, David Thomas - Business and Economics Book

From "The Pragmatic Programmer"

Author: Andrew Hunt, David Thomas
Publisher: Addison-Wesley Professional
Year: 1999
Category: Computers

🎧 Free Preview Complete

You've listened to your free 10-minute preview.
Sign up free to continue listening to the full summary.

🎧 Listen to Summary

Free 10-min Preview
0:00
Speed:
10:00 free remaining
Chapter 4: Pragmatic Paranoia
Key Insight 2 from this chapter

Design by Contract (DBC)

Key Insight

Design by Contract (DBC) is a simple yet powerful technique for ensuring program correctness by documenting and agreeing upon the rights and responsibilities of software modules. A correct program performs precisely what it claims, no more and no less. The contract defines specific conditions: preconditions (what must be true before a routine is called, the caller's responsibility), postconditions (what the routine guarantees upon completion, implying no infinite loops), and class invariants (conditions always true from a caller's perspective when control returns from a routine).

The fundamental contract states: if all preconditions are met by the caller, the routine guarantees its postconditions and invariants will hold true upon completion. Failure by either party to uphold the contract constitutes a bug, leading to an agreed-upon remedy like an exception or program termination; preconditions should not be used for user-input validation, for example. Languages like Clojure offer direct support for pre- and post-conditions, exemplified by an `accept-deposit` function requiring `amount > 0.00` and an `account-open?` check as preconditions, and guaranteeing the new transaction's presence in postconditions.

Other languages, like Elixir, use guard clauses to achieve similar contractual behavior by dispatching function calls based on argument conditions. For instance, `accept_deposit` can have different implementations for amounts `> 100000`, `> 10000`, or `> 0`, with calls outside these ranges resulting in a `FunctionClauseError`. DBC compels developers to think rigorously about module interactions, offering advantages over traditional testing methods by defining success/failure parameters for all cases, being always active (design, development, deployment, maintenance), checking internal invariants, and being more efficient than redundant defensive programming.

📚 Continue Your Learning Journey — No Payment Required

Access the complete The Pragmatic Programmer summary with audio narration, key takeaways, and actionable insights from Andrew Hunt, David Thomas.