Home > Store

Design by Contract, by Example

Register your product to gain access to bonus material or receive a coupon.

Design by Contract, by Example

Book

  • Sorry, this book is no longer in print.
Not for Sale

Description

  • Copyright 2002
  • Edition: 1st
  • Book
  • ISBN-10: 0-201-63460-0
  • ISBN-13: 978-0-201-63460-0

Design by Contract is a systematic approach to specifying and implementing object-oriented software elements based on precisely defined obligations between them. This is the first practical, example-centered guide to using Design by Contract. The authors introduce powerful design principles for writing good contracts and supporting guidelines -- and demonstrate those principles with real-world Java and Eiffel code examples. They review the fundamentals of Design by Contract -- preconditions, postconditions and invariants -- and presenting a real-world example. Next, drawing on their unparalleled experience with Design by Contract, they present six powerful design principles -- each with a clear statement of goals, rationale, examples in both Java and Eiffel, and supporting notes. Developers will learn how to strengthen their components' internal support for contracts; how to use contracts to specify subclasses whose objects can safely be substituted for superclass objects; how to extend contract to specify and check properties that remain unchanged; and how to use contracts in analysis-level models. The book concludes by summarizing key principles and presenting a realistic cost/benefit analysis of their use.

Sample Content

Online Sample Chapter

A First Taste of Design by Contract

Downloadable Sample Chapter

Click below for Sample Chapter related to this title:
mitchellch01.pdf

Table of Contents



Foreword.


Preface.


1. A First Taste of Design by Contract.

About This Chapter.

The Customer Manager Example.

Some Questions.

A Contract for CUSTOMER_MANAGER.

The Story So Far.

Runtime Checking.

Trustworthy Documentation.

Summary.

An Aide Memoire.

Things to Do.



2. Elementary Principles of Design by Contract.

About This Chapter.

Stacks.

Separate Commands and Queries.

Naming Conventions.

Separate Basic Queries and Derived Queries.

Specify How Commands Affect Basic Queries.

Capture Unchanging Properties in Invariants.

The Class and Its Contract.

The Basic Queries Are a Conceptual Model of Stacks.

The Six Principles.

Things to Do.



3. Applying the Six Principles.

About This Chapter.

Dictionaries.

Separating and Categorizing Features.

Postconditions.

Preconditions.

Invariant.

A Complete, Contract-Level View of DICTIONARY.

Summary.

Things to Do.



4. Building Support for Contracts—Immutable Lists.

About This Chapter.

Support for Linear Structures.

Contracts Involve Expressions.

Immutable Lists.

A Contract for Immutable Lists.

The Basic Queries.

The Creation Command.

The Derived Query Count.

The Derived Query Preceded_by.

The Derived Query Item.

The Derived Query is_equal.

The Derived Query Sublist.

Summary.

Things to Do.



5. Applying the Six Principles to QUEUE.

About This Chapter.

Queues.

A Contract for the Remove Feature.

Making Count a Derived Feature.

A Contract for the Initialize Feature.

A Contract for the Head Feature.

A Contract for the put Feature.

More Derived Queries.

Summary.

Things to Do.



6. Design by Contract and Inheritance.

About This Chapter.

Superclasses and Subclasses.

Redefining Contracts.

Eiffel Syntax.

Summary.

Invariants and Inheritance.

Designing Superclasses with Guarded Postconditions.

Two Kinds of Inheritance.

Summary.

Things to Do.



7. Frame Rules.

About This Chapter.

Change Specifications and Frame Rules.

Frame Rules for put Using Immutable Lists.

Frame Rules for put Using “Forall”.

Kinds of Frame Rules.

Things to Do.

Appendix: More About the Preprocessor.



8. Benefits of Design by Contract.

About This Chapter.

Kinds of Benefits.

Better Designs.

Improved Reliability.

Better Documentation.

Easier Debugging.

Support for Reuse.

Design by Contract and Defensive Programming.

Defending a Program Against Unwanted Input.

Bulletproofing a Routine.

Defensive Programming.

Some Costs and Limitations of Contracts.



9. Contracts for an Observer Framework.

About This Chapter.

The Observer Framework.

Immutable Sets.

Attaching and Detaching Observers.

Notification (For One Observer).

Notification (For All Observers).

A Performance Issue.

Frame Rules.

Privacy.

Things to Do.



10. Fulfilling a Precondition.

About This Chapter.

The Examples.

Fulfilling and Testing a Precondition.

Testing Versus Checking.

A Simple Counter Class.

The User's View of the Program.

The Internal Structure of the Program.

The Program's Behavior.

A Minor Detail.

Summary.

Things to Do.



11. Java Examples.

About This Chapter.

Why Java?

Queues.

The Basic Query size().

The Basic Query get().

The Derived Query head().

The Derived Query isEmpty().

The Derived Query shallowCopy().

The Constructor Queue.

The Command put.

The Command remove.

Summary.

Dictionaries.

Names.

The Invariant.

The Basic Queries.

A Derived Query.

The Commands.

The Constructor.

A Possible Set of Classes.

Java Without iContract.

Precondition Testing.

Things to Do.



12. Analysis by Contract.

About This Chapter.

A Use Case.

Contracts in Analysis Models.

A Contract for the withdrawCash Use Case.

From Analysis to Design.

Problem Domain and System Models.

The Object Constraint Language.

Summary.



Bibliography.


Index. 0201634600T10102001

Preface

WHAT THE BOOK COVERS

Design by contract is all about adding assertions to object-oriented programs, at the design and coding stages. Assertions are facts about a program that must be true for the program to be bug-free. The key assertions in design by contract define preconditions, postconditions, and invariants:

  • A precondition is a condition on a method specifying what must be true for it to be valid to call the method.
  • A postcondition is a condition on a method specifying what will become true when the method successfully completes.
  • An invariant is a condition on a whole class specifying what is true about any object of the class whenever you can call a method on that object.

The assertions are written in a programming language, so that

  • They make sense to programmers, providing good, helpful documentation.
  • They can be checked at runtime, providing support for testing and debugging.

This book concentrates on showing you how to write good contracts. The book presents six principles for writing good contracts, and some supporting guidelines. Through examples, the book motivates the principles and guidelines and shows them in use.

After studying the first three chapters, you will be in a position to write high-quality contracts. The rest of the book will help you do even better.

In addition to chapters that develop contracts for individual example classes, there are chapters on contracts in relation to inheritance and on the topic of frame rules (contracts that assert what does not change). Two larger examples towards the end of the book involve developing contracts across more than one class. Chapter 9 concerns the Observer pattern from Gamma et al. 1994, and Chapter 10 presents a small application in which an object in the user interface is shown to respect part of a contract in the heart of the application. Chapter 12 discusses the use of contracts in systems analysis. Chapter 8 reviews the benefits of using contracts and compares design by contract to defensive programming. Chapter 11 explores how to attach contracts to interfaces and explores briefly how you might implement contracts in a distributed environment.

PROGRAMMING LANGUAGES

The examples are presented first in the object-oriented programming language Eiffel. We chose Eiffel for three reasons:

  1. Eiffel has built-in support for contracts, so it is excellent for showing the concepts at work.
  2. Eiffel is easy to read, so it's a good pseudo-code from which you can implement the ideas in any object-oriented programming language.
  3. Commercial-strength compilers are available for Eiffel, so our contracts can play both their intended roles, as specifications and as checks. A contract is a specification of a class, describing precisely what services the class delivers. The assertions in a contract can be evaluated at runtime to check that the implementing code is consistent with its specification.

You don't have to be an Eiffel programmer to follow the examples. We are sure you'll be able to carry the principles over to your own programming environment. The issues we raise, and the advice we give, are not specific to Eiffel.

We do rework two of our examples in Java, using a preprocessor (called iContract) that provides support for contracts. This allows us to explore some issues that do not arise so directly in Eiffel and to show you contracts in another language.

WHO THE BOOK IS FOR

The book is written for anyone who wants to find out how to write good contracts. We intend it to be useful to practitioners, students (especially the early chapters), teachers, and researchers.

We don't believe the book is one you can curl up with by the fire (in winter) or the pool (in summer) and read your way through. We believe its material has to be studied and, most importantly, tried out. We hope you have access to a programming environment that supports contracts, such as a Java compiler and the iContract tool (see the bibliography for more information) or an Eiffel compiler (again, more information in the bibliography).

We do not teach object-oriented programming. We assume you know how to program in some object-oriented programming language. We have tried to give enough explanation of the Eiffel and Java code that those familiar with other OO languages can follow the examples.

STYLE

The book is based firmly on examples. Usually, a chapter is based on a single example. This means that there is quite a lot of code to wade through at times. However, most of the code is at the level of assertions, which define what a piece of program achieves. This level of code is generally easier to understand than the code that defines how a piece of program achieves its goal. In addition, we usually dissect the code a few lines at a time to make it easier to follow the discussion.

The examples are mostly simple ones. For example, instead of writing full contracts for the customer manager component introduced in Chapter 1, we write them for a look-up table (or dictionary), which is the data structure that underpins the customer manager component. That way, you won't get lost in too many details, and you won't lose sight of the basic principles. Once you see the principles, we are confident you'll be able to apply them to your own, more complicated examples.

We have been selective in what we put into this book. Other books have useful and insightful things to say on the subject of design by contract, but we have concentrated on what makes this book different--the advice it gives on how to write good contracts.

And, of course, this book is not the end of the story of design by contract. There is more work to be done on writing contracts, on developing the underlying technology and the underlying theory, on applying the ideas in broader contexts, and on assessing the benefits in practice.

WEB SITE

There is a Web site associated with the book. It contains the source code of the examples. Our hope is that you will download the code and play with it. Change the code. Add bugs, both in the implementation and in the contracts, and see what happens. Change the examples into new ones. Experiment. Use them on real projects. That's how we learned about contracts.



0201634600P12122001

Index

A
a_capacity argument, 91-92
Abstract classes, 158
ABSTRACT_SUBJECT class, 162
Account type, 219-220
add feature, 5-8, 10, 12
add_customer feature, 11
all_observers_up_to_date function, 158-159
Ampersands (&) in Java, 193
AN_INQUISITIVE_CLIENT class, 40-42
Analysis by contract, 215
design from, 220-221
models for, 217
object constraint language in, 224-225
problem domains and system models in, 221-224
summary, 225-226
use case, 215-216
withdrawCash case, 216-220
And operations
for assertions, 26
in Java, 193
and then operator, 59, 107, 112-113
Arguments in signatures, 7
Assertion-checking for documentation, 141
Assertions
as expressions, 70-71
multiple, 26
redundancy of, 36
Associations between components, 2
ATM example, 215-219
attached queries
in ABSTRACT_OBSERVER, 160-161
for observers, 156
Attaching observers, 151-152, 155-156
Attributes, 3
contracts on, 89
features as, 21
invariants for, 91
queries as, 20
types of, 4
B
Balances for Account, 219-220
BASIC_CUSTOMER_DETAILS type, 4-5
Basic queries
as conceptual models, 38-42
in DICTIONARY, 200-201
frame rules for, 131
for immutable lists, 72-73
separating from derived queries, 23-25
Benefits
in DIFFERENT_COURIER, 101
kinds of, 137-138
Black diamonds for associations, 2
Boolean queries, 23
Bulletproofing, 144-145
Buttons, grayed out, 175-176, 178, 183
C
Calling features, 6
Capacity
frame rule concerning, 122
of queues, 83-84, 92
Capital letters in Java, 200
change_customer feature, 13
Change specifications and frame rules, 119-121
Cheap-to-calculate queries, 160
Checking vs. testing of preconditions, 172-173
choice queries, 154
Clarity
of designs, 138-139
of documentation, 141
Class interfaces, 36, 198
Classes
abstract, 158
contracts for, 36-38
for frame rule constraints, 163
generic, 18
in Java, 198
short form of, 112, 198
superclasses and subclasses, 99-100
CLIENT class, 101
client_version_of_item_at feature, 40-42
clone queries, 154
Code reuse, 117
Commands
postconditions for, 26-34
preconditions for, 34
separating from queries, 19-22
for stacks, 18
Comments
for constraints, 146
for features, 7
in Java, 193, 202
tagged, 194
Components, 2
Conceptual models, basic queries as, 38-42
CONCRETE_SUBJECT class, 162
Concurrent programs, 147-148
Constraints, 58-59. See also Preconditions, Postconditions, and Invariants
for attributes, invariants for, 91
for frame rules, separate classes for, 163
on queries, 61-62
Constructors
for DICTIONARY, 202-203
in Java, 199
for Queue, 195
Contents in equal lists, 126
Contracts
analysis by. See Analysis by contract
on attributes, 89
for classes, 36-38
on functions, 89
redefining, 100-105
rights in, 14
Costs and limitations, 146-148
count method, 5, 7, 10
count_never_negative invariant, 35
count queries, 23
in IMMUTABLE_LIST, 74
in IMMUTABLE_SET, 154
in initialize, 27, 29-31, 62
invariants for, 34, 62-63
in NAME_LIST, 110
postconditions for, 11
preconditions for, 11, 57
in put, 26, 29, 34, 62
in QUEUE, 85, 87-91
for queues, 84
in RELAXED_NAME_LIST, 113
in remove, 28, 32, 34-35, 62-63
in SIMPLE_STACK, 24, 37
for stacks, 18
COUNTER class example, 173-174
behavior of, 178-184
internal structure, 176-177
user view, 174-176
COURIER class, 100-101, 106, 108
creation commands, 36
frame rules for, 130
for immutable lists, 74
Customer Manager example, 2-5
adding customers in, 6-8
contract for, 6-9
customer names in, 8-9
listing, 9-11
methods in, 5-6
runtime checking, 11-13
trustworthy documentation for, 13-14
CUSTOMER type, 2-3
CUSTOMER_MANAGER type, 2-3
D
Debugging support, 142
DECREMENT_BUTTON class, 176-180, 183
decrement command, 174-178, 181, 183
deep_clone feature, 126
deep_equal feature, 126
Defensive programming, 143
and bulletproofing, 144-145
example, 145-146
for unwanted input, 143-144
Deferred classes, 158
delete feature for STACK, 20
deliver service, 100-105
Derived queries
postconditions for, 25
separating from basic queries, 23-25
Design improvements as benefit, 138-139
Design patterns, 150
Detaching observers, 152, 155-156
Development, debugging support in, 142
Dictionaries, 2, 47-48
in Java, 199-200
separating features in, 48-49
DICTIONARY class, 48-49
contractual-level view of, 63-65
exercises, 66-67
invariants in, 62-63
in Java, 198-199
basic queries in, 200-201
commands in, 201-202
constructors for, 202-203
derived queries in, 201
invariants in, 200
for names, 199-200
set of, 203
postconditions for, 50-56
preconditions for, 56-62
summary, 65-66
DictionaryFactory class, 203-204
DictionaryUsingMap class, 203-204
DIFFERENT_COURIER subclass, 101-108
Directories, 2
Disabling buttons, 178-183
Distributed programs, 147-148
Documentation
as benefit, 140-141
for constraints, 146
for Customer Manager example, 13-14
E
Eiffel language
attribute types in, 4
contract syntax in, 11
libraries in, 22
names in, 5
short form of classes in, 198
subclass syntax in, 104-107
Void references in, 58-60
emptyQueue command, 211
Enabled state, 180-181
Enabling buttons, 178-183
end keyword, 104
ensure keyword
for postconditions, 7-8
in redefined contracts, 105
@ensure tag, 194
ensure then operation, 107, 112
Equal signs (=)
for equality tests, 7
in Java, 194
Equality
of lists, 123-126
of strings, 9
Exceptions
raised, 145-146
systematic use of, 139
Explicit conceptual models, 40
Expressions, 70-71
F
Factory class, 202
feature keyword, 36-37, 40
Features, 2
as attributes and routines, 21
contracts for, 6
mixed, 22
obligations of, 14
separating, 48-49
signatures for, 7
Flat-short form of classes, 112
forall operator
frame rules for, 128-129
preprocessor for, 132-135
in removing items, 197
in shallow copies, 195
Frame rules, 119
and change specifications, 119-121
constraints for, separate classes for, 163
exercises, 132, 166-167
for forall, 128-129
kinds of, 130-132
for observer framework, 161-163
for put, 121-127
from_position feature, 79-80
Fulfilling preconditions, 169-170
COUNTER class example, 173-174
behavior of, 178-184
internal structure, 176-177
user view, 1

Updates

Submit Errata

More Information

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.

Overview


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information


To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.

Surveys

Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.

Newsletters

If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information


Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.

Security


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.

Children


This site is not directed to children under the age of 13.

Marketing


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information


If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.

Choice/Opt-out


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information


Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents


California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure


Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.

Links


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact


Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice


We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020