A Diagram For Object-Oriented Programs

2y ago
41 Views
8 Downloads
568.14 KB
7 Pages
Last View : 1m ago
Last Download : 3m ago
Upload by : Axel Lin
Transcription

A Diagram for Object-Oriented ProgramsWard CunninghamKent BeckComputer Research LaboratoryTektronix, Inc.AbstractWe introduce a notation for diagramming themessage sending dialogue that lakes place betweenobjects participating in an object- orientedcomputation. Our representation takes a global pointof view which emphasizes the collaboration betweenobjects implementing the behavior of individuals.We illustrate the diagram's usage with examplesdrawn from the Smalltalk-80TM virtual image. Wealso describe a mechanism for automatic constructionof diagrams from Smalltalk code.1. IntroductionThe Smantalk-80 virtual image [Goldberg 83] hasmany examples of expertly organized programs,many of which play an important role in theSmalltalk-80 system. These are worthy objects ofstudy for at least two reasons. First, they oftenprovide exquisite examples of the style and idiomunique to object-oriented programming. As valuableas a concise definition of object-orientedprogramming might be, it could not replace thecorpus of code in the virtual image for illuminatingthe range of application of the object-oriented style.Students of object-oriented programming should begrateful that the implementors of SmaUtalk pushedthe object metaphor to the limit, building their systemout of nothing but objects. Their result offers a guideto the "objectification" of even the most elusivealgorithms. One learns by doing and one doesSmalltalk by browsing the work of otherprogrammers. Second, many Smalltalk objects aredirectly reusable--an even more compelling reasonto study their behavior. To the degree that one'sapplication mimics Smalltalk's own implementation,one will find useful objects in the image,preprogrammed, waiting to be used. Smalltalk'sreputation as a user-interface-prototypingenvironment stems from its wealth of reusableuser-interface components.We sought a way of presenting the computationsemployed in Smalltalk's modular user interface. Wedeveloped a representation, a diagram, thatemphasised the object nature of the interfacecomponents. The essence of an object-orientedcomputation is the dialog carried out by the objectsinvolved. With this in mind, we consciously omittedfrom the diagram indications of state or sequence. Soreduced, a single diagram shows the cascade ofmessages that result, for example, from a userinteraction. The diagrams are not unique touser-interface codes, though, they are unique toobject-oriented computations. We have since appliedthe diagramming technique to many of the moreesoteric examples from the Smalltalk-80 image. Theresult has solidified our own understanding ofobject-oriented programming, and enabled us toteach others more clearly about Smalltalk-80.the ACM copyright notice and the title of the publication and its date appear,and notice is given that copying is by permission of the Association forComputing Machinery. To copy otherwise, or to republish, requires a fee and/or specific ix.rmimion.In this paper we will introduce the notations of ourdiagramming technique and apply them to severalexamples from the Smalltalk-80 image. I aterexamples are drawn from behaviors in the image thatare often misunderstood. We hope in this way tomake a convincing demonstration of the diagrams'usefulness. Also, the reader can expect to seeglimpses of the unique suitability of objects inimplementing user-interfaces. We close with adiscussion of an automatic technique for theconstruction and formatting of publication qualitydiagrams. 1986 ACM 0-89791-204-7/86/0900-0361Smalltalk-80 is a n'ademark o f the Xerox Corp. PostScript isa trademark o f A d o b e S y s t e m s , Inc.Permission to copy without fee all or part of this material is granted providedthat the copies are not made or distributed for direct commercial advantage,S 198675 OOPSLA'86 Proceedings361

. :. .,. .i alp" hWe begin with objects. Objects accept responsibilityfor their own behavior. As a convenience, the codethat implements this behavior is collected into acommon place for all objects of the same class.Further, objects of one class might vary in behavioronly slightly from those of another class. A new classis said to refine another if it implements ouly thevariant behavior while relying on the other class forthe remainder.(lb)ii :i"Figure 1. a) An object receiving a message, b) Anobject sending a message to another object.An object will exhibit behavior appropriate for thespecific message it receives. The variouscomputations are implemented by distinct methods,each labeled with a method selector. We place theselector of methods invoked by messages at thereceiving end of a message arc (See figure 2a.) It isimportant to note that the method invoked by amessage will depend on the selector and the receivingobject. The same selector might select differentmethods when received by different objects. InFigure 2b, for example, we cannot tell whether thetwo methods labeled "gamma" are the same. We needto know more about the objects involved.362:'"betaWe represent an object as a box (See figure la.) Amessage sent to an object excites behavior specific tothat object. We draw a message-send as a directed arelanding within the receiving object. If more than oneobject participates in a computation then there will bemore than one box in the diagram (See figure lb.)When one object invokes a computation in anotherobject through a message send, we show that send asan arc originating in the sending object and landing inthe receiving object. With the message goes atransfer of control. That is, the computation of thesender is suspended until the computation of thereceiver is completed. Control returns backwardalong a message arc along with the answer to themessage, if any. So far this mimics the usualsemantics of procedure call. Note that we draw aparticular message are only once, even if the messageis sent repeatedly, in a loop or otherwise.(la)(2b)(2a)2. The Diagram!igain" m g ilnlll,'lFigure 2. a) One method for "alpha" invokes anotherfor "beta". b) One method for "gamma" invokesanother for "gamma".We identify an object in a diagram by its class. Recallthat all members of a class share the same methods.The methods of the objects in Figure 3 are all exactlydetermined because we know the selector and thereceiver's class for all of the messages. Recall alsothat objects of one class might inherit methods fromanother class. When methods are inherited fromother classes (when a class does not implement amethod, but one of its superclasses does) we dividethe receiver into layers representing the classesinvolved and locate the method selector in theappropriate layer. Figure 3b shows two objects oftwo different classes (Senator and Plebe) eachrefining a third class (Citizen). The method for"gamma" invoked by each is in fact the same method,the one both inherit from Citizen. Of course, thesame method won't necessarily execute in the sameway in both cases; it is being executed on behalf ofdistinctly different objects. Figure 3c shows arevised Plebe. This time Plebes provide their ownmethod for "gamma" which overrides the defaultimplementation inherited by all Citizens.We draw message arcs so that they always enter anobject from above. When an are travels across alayer of methods before finding its selector in adeeper layer, this suggests an opportunity to overridethat has not been exploited. The top layer will be thatof the object's own class. Deeper layers will besuperclasses. The bottom layer (if shown) will be theroot of the hierarchy- class Object.Note the contradictory use of the "elevation"methaphor by the terms "override" and "superclass".Which way is up? Some observers have complainedthat it is non-intuitive to place subclasses abovesuperclasses in our characterizations of objects. Wejudge overriding the more important concept and liketo think of method-lookup searching deeper for animplementation if none is provided by the surfaceclass. Besides, we tried drawing the diagramsupside-down. They looked lifeless with their arcslimply dangling between method selectors.OOPSLA '86 ProceedingsSeptember 1986

Oa)Senator(3b). iOc)Senator, . alpha,,.Ji!.7 f : --ICitizen t ISenator i .g ('J1g Citizen '. ." !: ":'{" ' ! . ,%.Plebe ' "" '" gamma.Figure 3. a) A Senator's method for "alpha" invokes a Plebe's method for "beta". b) ASenator's method for "gamma" invokes a Plebe's method for "gamma", in this case thesame method inherited by all Citizens. c) A variant of b) where a Plebe overrides theinherited implementation of "gamma".Consider an example drawn from the Smalltalk-80image. The class Collection includes refmements formany commonly used aggregate data structuresarrays, sets, linked lists and the like. AnOrderedCollection, for example, implements aflexibly sized array. An OrderedCollection respondsto the message "add: anElement" by addinganElement at the next available location within itself.A slightly simplified diagram of this operationappears in Figure 4a. We can see that the add methodmakes use of two more elementary methods, size andat:put:. The diagram doesn't exactly explain why, butone could guess that size is used to determine whereto put the new element and at:put: is used to put itthere. Contrast this to the implementation of add: forSets in figure 4b. This time the index is found byhashing the new element. Note that computing a hashfunction is the responsibility of the new element, notof the Set. All objects can hash themselves. Points,for example, compute their hash from their componentx and y coordinates as illustrated in figure 4c.We have now seen two examples of recursivebehavior. In figure 3b the "gamma" method for oneCitizen invoked itself for another. This style ofrecursion is common in Smalltalk especially when theobjects are organized into a tree or list. In figure 4awe see a distinctly different kind of self reference.One method (add:) invokes others (size and at:put:)on behalf of the same object. This is done byaddressing messages to "self'. This is an idiom inSmaUtalk since it is the mechanism by which complexmethods are decomposed into simpler ones. Figure 5illustrates some particularly interesting variations onthis theme. The method "addAll:" works by addingeach element of another Collection, one at a time.The algorithm works for all refinements thatimplement an appropriate method for "add:". Wedraw messages to self as arcs arching up and backdown through the refining layers of an object,emphasizing the ref'mement's opportunity tooverride.il.SeL a?d . . .,.,.i /Collectioni at:put: Collection1.;I:Put: [PointhashIhasInteger hash.3.:i.Figure 4. a) Adding to an OrderedCollection. b) Adding to a Set. c) Hashing a Point.Sep(ember 1986OOPSLA '86 Proceedin0s363

represent individual panes. Finally, an object calledthe model, accessible to all of the Views andControllers, represents the state and behavior of theapplication.Smalltalk-80 provides a mechanism for a refinementto directly address methods of its superclasses. Byaddressing a message to "super" an overridingmethod can employ the method it is overriding aspart of its implementation. We show a typicalapplication in figure 5b. Note the absence of arch inthis message arc. This visual distinction helps tomake clear the difference in the way the method isfound by the interpreter during a call to super, incontrast to the mechanism used in calls to self orother objects.A window displays itself by recursively traversing itsViews. Each View displays its border, its owncontents, and any Views it might contain (see Figure6a.) In practice, an application would employrefinements of View specialized for the needs of eachparticular pane. For example, a pane displaying a listmight use a ListView that overrides displayView withthe method for displaying lists. The actual contentsof the list would be accquired from the model asshown in figure 6b. Note that the task of displaying awindow has been decomposed using three separateprogramming techniques. First, several objectscollaborate in the task. Second, the task is brokeninto parts for each object. Third, specialized objectscan override any one of the parts. All of thesetechniques are visible in figure 6.o .("IsetI I.I.I.add:. I.,. S in''a'co,oo,ioo.ddA"."I Collection 7i initialize""., tI ,.- . Figure 5. a) Adding all of one Collection to another.b) A n initializationmethod invokes a similar methodin a superclass.As a user interacts with an application's window,changes made to the model from one pane mayrequire updates in others. The general mechanism forthis is outlined in figure 7. A Controller recognizesuser inputs as part of its controlActivity. When aninput activity is complete, the Controller notifies themodel that it has been changed. In response, themodel notifies all of its registered dependents (Viewsalways register themselves as a dependent of theirmodel) of the need to update. The process ofupdating is leR to the Views.3. AdvancedexamplesFor more challenging examples we turn to theSmalltalk-80 user-interface. Smalltalk applicationspresent themselves as windows on a bit-mappeddisplay. A windaw may be divided into a number ofpanes, each displaying a different aspeCt of theapplication. By convention, keystrokes and mousebuttons are interpreted in the context of the panetouched by the cursor. Objects of class View andController accept responsibility for displaying outputand interpreting input, respectively. A pair ofobjects, a View and a Controller, is allocated to eachpane and another pair to the window as a whole. Allof these are organized into a tree where the rootrepresents the whole window, and the leaves(6a),.View i,, . . pay].k(6b) - \I di.,,,.V,ew: 1displaySubViews ".1 'tViewAll Controllers cooperate to insure that the mostappropriate Controller interprets the user's input atany given time. A Controller that wants control(because its View contains the current cursor point)gets control with the message "staRUp". Figure 8shows how this message eventually invokes the, Controller's controlActivity. The controlLoop doesLi.,ViewJ I di.;,a,View Iit. &,,:J. . . ./I' Model cala r s tayFigure 6. a) A View displays itself and its subviews, b) A specialized View displays alist accquired from its model.364OOPSLA '66 ProceedingsSep mber 1986

(7)Controller gure7. Views are advised of a change by a model.the controlActivity repeatedly as long as theController remains active. In figure 8 we see thedefault implementation of convolActivity searchingamong its sub-Controllers for the appropriatecontroller for the moment. Refinements ofController differ primarily in their implementationof controlActivity. Like the example of figure 6, thisis simply a recursive traversal of the tree of panes.Both examples pass control to a critical method whichcan be overriden to implement specialized behaviors.Both will still inherit the behavior required toparticipate in the collaborative implementation of auser interface.Comparing these diagrams with the Smalltalk-80virtual image will reveal that we have bent the truthon many occasions. Yet, we argue, we have remainedfaithful to the style of the actual code. Our focus hasbeen on the relationship between objects participatingin a computation - a relationship that can be difficultto see when exploring objects one at a time. This is,in fact, the essence of object-oriented programming.4. Creating DiagramsOur notation emphasises the cooperation of objectsparticipating in a computation. We freely omitportions of the computation judged unimportant.Such judgement comes easily enough when drawing adiagram by hand or with a general purpose draftingprogram as in figures 1 through 8. Our strategy forautomating the drafting process had to admitintentional and asthetic considerations. Furthermore,we reasoned that only in the debugger [Goldberg 84],or more correctly, the simulation capability of thedebugger, do the raw materials of the diagrams cometogether in one place. That is, to collect theinformation required for constructing diagrams wemust do at least as much work as the debugger doeswhen it steps a computation. The observation wasfortuitous in that the debugger also had auser-interface that allowed one to step aroundcomputations judged uninteresting.The Smalltalk-80 debugger is shown in figure 9a. Itlists the activation records on the run-time stack,shows the source code of the selected activation, andprovides two inspectors, one on the current object,the other on arguments and temporary variables.The debugger's menu has two commands to advancethe computation, step and send. Step continuescomputing until the impending message returns avalue. Send retains control so the user can watch theexecution of the invoked method.Figure 8. Control leads to contmlActivity. The default controlActivity recursivelypasses control to a sub-Controller.September lee6OOPSLA '86 Proceedings365

(ga)Halt en ountered.J(9b)Hilt en ountima.IArray(SequenceableCollect;on)))do: k-r;ray(SequenceabiiCoilectl n))) doiOrderedCollect on))addAIILast:OrderedCollec rich)) a ddAll: ddAILlst: anOrderedlCollection"Add each element of anOrderedCollectl0nat the en(:l Of ;he receiver AnsweranOrderedCoFlection."anOrderedCollectiondo: [:each J self addLast: each].f anOrderedCo;lectionIself; firstln 1tasttnc " '" ' h I-OrderedCoUectlon))lddAIILallt:OrderedCollec tlon) addAIl:eddAIILut: e n O r t i m l"Add each element of enOrderedCollectlonat the end of the receiver. AnsweranOrderedCollectlen."anOrderedCollectlondo: [:each, ,elf .ddLast: each].tanOr4eredCollectlonI lastlncJl. . h lArrayI 8equenclable0ollectlon.Figure 9. a) The Smalltalk debugger, b) The debu zer with attached diagram editor.We chose an extension of the debugger as ourdrafting user interface. The modified debugger isshown in figure 9b. The additional pane on the rightis a special purpose diagram editor. The objects inthe diagram can be moved around by dragging themwith the mouse. Information is added to the diagramby menu commands step and send, which duplicatethe ordinary debugger commands except that theyrecord the message in the diagram. Objects andselectors are added to the diagram on demand.Objects require an initial placement by the user;selectors are positioned automatically.To create a diagram one uses the step and send menucommands from the diagram pane to record themessages judged important. The original debugger(;ca)commands can be used to locate the desired contextwithout modifying the diagream. Other mouseoperations are used to adjust the objects in thediagram until it is visually balanced and clearlyconveys the computation.A prepared diagram can be saved as a bitmap or as ahigh-resolution image encoded as PostScript [Adobe 85] function calls. The PostScript pagedescription language provides a flexible way ofspecifying the contents of a typeset page. We wrotePostScript functions for each graphical element: arc,box, selector and class. A diagram is compactlyencoded as a sequence of calls on these functions.Figures 10a and 10b contrast the bimlap andPostScript output.U0b)OrderedGollectlonIaddlill: addAlll./as ddLast: IArraySequenceableC )lle onFigure 10. a) The bitmap output of the diagram editor, b) The same diagram withPostscript output.I I

We were struck by the dynamics of the diagrams asthey developed on-screen, in the debugger. Theobjects in the diagram provided a helpful spatialreference to the objects involved in the computation.In this regard our work is similar to Brad Meyersvisualizations in Incense [Meyers 85]. We found thatby highlighting the currently executing object wewere able to trace much

unique to object-oriented programming. As valuable as a concise definition of object-oriented programming might be, it could not replace the corpus of code in the virtual image for illuminating the range of application of the object-oriented style. Students of object

Related Documents:

WIRING DIAGRAM DIRECTORY WARNING: Wiring direct to battery not recommended. Install actuator after ignition switch, or master power switch. Diagram 1 Diagram 2 Diagram 3 Diagram 4 Diagram 5 Diagram 6 Diagram 7 Diagram 8 Diagram 9 Diagram 10 Diagram 11 Diagram 12 Diagram 13 Diagram 14 Diagram 15 On/Off, 12VDC, 3-wire/3-pin, SPST On/Off, 12VDC, 3 .

Bruksanvisning för bilstereo . Bruksanvisning for bilstereo . Instrukcja obsługi samochodowego odtwarzacza stereo . Operating Instructions for Car Stereo . 610-104 . SV . Bruksanvisning i original

Structured analysis Object-oriented analysis System boundary Context diagram Use case diagram Functionality Data flow diagram Activity diagram Interaction diagrams Data Entity-relationship diagram Class diagram Object diagram Control State diagram State diagram Structured methods System as a set of nested processes accessing system data.

Object Class: Independent Protection Layer Object: Safety Instrumented Function SIF-101 Compressor S/D Object: SIF-129 Tower feed S/D Event Data Diagnostics Bypasses Failures Incidences Activations Object Oriented - Functional Safety Object: PSV-134 Tower Object: LT-101 Object Class: Device Object: XS-145 Object: XV-137 Object: PSV-134 Object .

method dispatch in different object-oriented programming languages. We also include an appendix on object-oriented programming languages, in which we consider the distinction between object-based and object-oriented programming languages and the evolution and notation and process of object-oriented analysis and design, start with Chapters 5 and 6;

object-oriented programming language is based on a kind of old object-oriented programming language. For example, though C language is an object-oriented programming language, it still retains the pointer which is complex but has strong function. But C# improved this problem. C# is a kind of pure object-oriented language.

Reusability, CK Metric, Object - Oriented. 1. INTRODUCTION Object oriented systems continue to share a major portion of software development and customer base for these systems is on the rise. This is because there are many advantages in taking the object oriented concept. The weakness though is that most object oriented systems tend to be .

Object built-in type, 9 Object constructor, 32 Object.create() method, 70 Object.defineProperties() method, 43–44 Object.defineProperty() method, 39–41, 52 Object.freeze() method, 47, 61 Object.getOwnPropertyDescriptor() method, 44 Object.getPrototypeOf() method, 55 Object.isExtensible() method, 45, 46 Object.isFrozen() method, 47 Object.isSealed() method, 46