Applying 'Design by Contract'
Total Page:16
File Type:pdf, Size:1020Kb
I Applying “Design by Contract ” Bertrand Meyer Interactive Software Engineering s object-oriented techniques steadily gain ground in the world of software development. users and prospective users of these techniques are clam- oring more and more loudly for a “methodology” of object-oriented software construction - or at least for some methodological guidelines. This article presents such guidelines, whose main goal is to help improve the reliability of software systems. Reliability is here defined as the combination of correctness and robustness or. more prosaically, as the absence of bugs. Everyone developing software systems. or just using them, knows how pressing this question of reliability is in the current state of software engineering. Yet the rapidly growing literature on object-oriented analysis. design. and programming includes remarkably few contributions on how to make object-oriented software more reliable. This is surprising and regrettable, since at least three reasons justify devoting particular attention to reliability in the context of object-oriented devel- opment: The cornerstone of object-oriented technology is reuse. For reusable compo- nents, which may be used in thousands of different applications, the potential consequences of incorrect behavior are even more serious than for application- specific developments. Proponents of object-oriented methods make strong claims about their bene- .. Thc object-oriented approach, based on~thetheory of abstract data types, Reliability iS even mOre provides a particularly appropriate framework for discussing and enforcing important in object- reliability. oriented programming The pragmatic techniques presented in this article, while certainly not providing infallible ways to guarantee reliability, may help considerably toward this goal. than elsewhere*This They rely on the theory of design by contruct. which underlies the design of the article shows how to Eiffel analysis, design, and programming language’ and of the supporting libraries, from which a number of examples will be drawn. reduce bugs by building The contributions of the work reported below include ’Oftware components a coherent set of nrrthocfological pri/?ciples helping to produce correct and on the basis of carefully robust software; a systematic approach to the delicate problem of how to deal with abnormal designed contracts. cases. leading to a simple and powerful exception-handling mechanism; and a better understanding of inherit- plexity and unwieldiness that often char- letter or package delivered to another anceandof the associated techniques acterizes software. Paris address, you may decide to deliver (redeclaration, polymorphism, and Obtaining and guaranteeing reliabil- it yourself, or you may contract out the dynamic binding) through the no- ity requires a more systematic approach. task to a courier service. tion of subcontract, allowing a sys- In particular, software elements should Two major properties characterize tematic approach to using these pow- be considered as implementations meant human contracts involving two parties: erful but sometimes dangerous to satisfy well-understood specifications, mechanisms. not as arbitrary executable texts. This is Each party expects some benefits where the contract theory comes in. from the contract and is prepared to Most of the concepts presented here incur some obligations to obtain them. have appeared elsewhere. They were These benefits and obligations are previewed in the book Object-Oriented The notion of contract documented in a contract document. Software Construction’; and a more com- plete exposition was presented in a re- Assume you are writing some pro- Table 1 shows an imaginary roster of cent book chapter,’ from which this ar- gram unit implementing a task to be obligations and benefits for the courier ticle has been adapted. More profoundly, performed at runtime. Unless the task service of the example. this work finds its root in earlier work is trivial, it involves a number of sub- A contract document protects both on systematic program tasks. For example, it might appear as sides: and abstract data types. h-X This article focuses on the central ideas, introduc- my-task is It protects the client by specifying ing them concisely for direct applica- do how much should be done: The client is tion by developers. subtask, ; entitled to receive a certain result. subtask2 ; It protects the contractor by speci- ... fying how little is acceptable: The con- Defensive programming subtask,, ; tractor must not be liable for failing to revisite d end carry out tasks outside of the specified scope. a form that suffices for this discussion. Software engineering and program- although in many cases the control struc- As evidenced by this example, what is ming methodology textbooks that dis- ture linking the various subtasks is less an obligation for one party is usually a cuss reliability often emphasize the tech- simple than the mere sequencing shown benefit for the other. nique known as defensive programming, here. This example also suggests a some- which directs developers to protect ev- For each of these subtasks, you may what more subtle observation, which is ery software module against the slings either write the corresponding solution important in the following discussion and arrows of outrageous fortune. In in line as part of the body of my-task, or (and in studying the application of these particular, this encourages programmers rely on a call to another unit. The deci- ideas to concurrent computation). If the to include as many checks as possible, sion is a typical design trade-off: Too contract is exhaustive, every “obliga- even if they are redundant with checks much calling causes fragmentation of tion” entry also in a certain sense de- made by callers. Include them anyway, the software text: too little results in scribes a “benefit” by stating that the the advice goes; if they do not help. at overcomplex individual units. constraints given are the only relevant least they will not harm. Assume you decide to use a routine ones. For example, the obligation entry This approach suggests that routines call for one of the subtasks. This is sim- for the client indicates that a client who should be as general as possible. A par- ilar to the situation encountered in ev- satisfies all the constraints listed is enti- tial routine (one that works only if the eryday life when you decide to contract tled to the benefits shown in the next caller ensures certain restrictive condi- out for a certain (human) task rather entry. This is the No Hidden Clauses tions at the time of the call) is consid- than doing it yourself. For example. if rule: With a fully spelled out contract ered dangerous because it might pro- you are in Paris and want an urgent between honest parties, no requirement duce unwanted consequences if a caller does not abide by the rules. This technique, however, often de- Table 1. Example contract. feats its own purposes. Adding possibly redundant code “just in case” only con- Party Obligations Benefits tributes to the software’s complexity - the single worst obstacle to software Client Provide letter or package of no Get package delivered to quality in general. and to reliability in more than 5 kgs. each dimension recipient in four hours or particular. The result of such blind check- no more than 2 meters. less. ing is simply to introduce more soft- Pay 100 francs. ware. hence more sources of things that could go wrong at execution time, hence Supplier Deliver package to recipient No need to deal with the need for more checks, and so on ad in four hours or less. deliveries too big, too infinitum. Such blind and often redun- heavy, or unpaid. dant checking causes much of the com- October 1992 41 I other than the contract’s offi- This is the contract en- cial obligations may be im- routine-name (argument declarations) is forced by put-child on any posed on the client as a condi- -- Header comment potential caller. It contains tion for obtaining the require the most important informa- contract’s official benefits. Precondition tion that can be given about do the routine: what each party The No Hidden Clauses Routine body, Le. instructions principle does not prevent us ensolte in the contract must guaran- from including references. Postcondition tee for a correct call, and what implicit or explicit, to rules end each party is entitled to in not physically part of the con- return. Because this informa- tract. For example, general Figure 1. A routine equipped with assertions. tion is so crucial to the con- rules such as the relevant laws struction of reliable systems and common business prac- using such routines, it should tices are implicitly considered put-child (new: NODE) is be a formal part of the rou- to be part of every contract of -- Add new to the children of current node tine’s text (see Figure 2). a certain kind. even if not ex- require A few more details about plicitly repeated in the text of new /= Void the rules of object-oriented each contract. They apply to do programming as embodied in both client and supplier and ... Insertion algorithm ... Eiffel should help make this will lead below to the notion ensure example completely clear: of class invariant. new.parent = Current; child-count = old child-count + 1 A reference such as new end -- put-child is either void (not attached Assertions: to any object) or attached to Contracting for Figure 2. Assertions for child insertion routine. an object. In the first case, it equals the value Void. Here software the precondition expresses assertion is a list of Boolean expres- that the reference new must not be void, It is not difficult to see how the pre- sions, separated by semicolons; here a as stated informally by the correspond- ceding ideas apply to software construc- semicolon is equivalent to a Boolean ing entry in Table 2.