Responsibilities and Rewards: Specifying

Neelam Soundarajan and Jason O. Hallstrom Computer and Information Science

Ohio State University, Columbus, OH 43210  e-mail: neelam, hallstro @cis.ohio-state.edu

Abstract Second, when a new designer joins the design team, he or she will be able, given prior knowledge and understanding Design patterns provide guidance to system designers on of the specific patterns involved, to get a quicker and more how to structure individual classes or groups of classes, as thorough grasp of how the system is structured, why it be- well as constraints on the interactions among these classes, haves in particular ways, etc. to enable them to implement flexible and reliable systems. But if we are to fully realize these benefits, we must have Patterns are usually described informally. While such in- precise ways to reason about these design patterns that we formal descriptions are useful and even essential, if we want can apply to understand and predict the behavior of systems to be sure that designers precisely and unambiguously un- built using them. Our goal in this paper is to investigate such derstand the requirements that must be met when applying reasoning techniques. In our approach, the specification of a given pattern, and be able to reliably predict the behav- a pattern will consist of two components. The responsibili- iors the resulting system will exhibit, we also need formal ties component will consist of the conditions that a designer characterizations of the patterns. must ensure are satisfied with regards to the structures of the In this paper, we develop an approach to formalizing de- classes, the behaviors of particular methods of the classes, sign patterns. The requirements that a designer must meet and the interactions among various classes. The rewards with respect to the structures of the classes, as well as with component will specify the particular patterns of behavior respect to the behaviors exhibited by the relevant methods, that the resulting system will be guaranteed to exhibit if all are captured in the responsibilities component of the pat- the requirements contained in the responsibilities compo- tern’s specification; the benefits that will result by applying nent are satisfied. the pattern, in terms of specific behaviors that the result- In specifying a pattern, we will start by listing the roles ing system will be guaranteed to exhibit, are captured in the that make up the pattern. For example, in the case of the rewards component. One important aspect of many design [5], which we will use as the running ex- patterns is their flexibility; our approach is designed to en- ample throughout the paper, there are two roles, Subject sure that this flexibility is retained in the formalization of and Observer. This information is already clear from the the pattern. We illustrate the approach by applying it to a standard UML representation of the pattern (Fig. 1). Also standard design pattern. clear from the diagram is the fact that the Notify() method of Subject will invoke the Update() method on each of the observers1. What is not clear is when Notify() will be 1 Introduction called and by whom. This question is addressed in the com- mentary (under “Collaborations”) in the description of the Design patterns [1, 2, 5, 8, 15] are widely regarded as Observer pattern in [5], “. . . subject notifies its observers one of the most powerful tools in designing OO systems. whenever a change occurs that could make its observers’ Specific patterns provide precise guidance on how to struc- state inconsistent with its own.” But it is not clear how the ture individual classes or groups of classes, as well as the 1We use names starting with uppercase letters such as Subject for interactions among these classes, to implement flexible and roles; and the corresponding lowercase names such as subject to refer reliable solutions in specific contexts. Using design patterns to the individual objects that play these roles. We also use names starting helps system designers in two ways: First, design patterns with uppercase letters for patterns, classes, and methods; member variables represent the collective wisdom and experience of the com- will have names starting with lowercase letters. In some cases the name of a pattern is also used for one of the roles in that pattern, as in the case of munity, so the application of the relevant patterns should the Observer role of the Observer pattern. In such cases, the context will lead to higher quality systems with predictable behavior. make clear whether we are talking about the role or the pattern.

Proceedings of the 26th International Conference on Software Engineering (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE subject will know when its state has become inconsistent Most previous work on patterns has focused on identify- with that of one or more observers. Indeed, what does it ing patterns and specifying them informally, usually in the mean to say that the subject state has become inconsistent style introduced by [5]. There has been some work related with that of an observer? How is this to be determined? to formal aspects of patterns; these have dealt with such Perhaps more to the point from the point of view of a de- things as modeling patterns using temporal action systems, signer, what exactly are the requirements that the designer categories, etc. To our knowledge, there has not been much must ensure are met in order to apply the pattern as in- work that has tried to specify patterns by formally defin- tended? And what exactly can the designer expect in re- ing the exact program properties that the use of the pattern turn for meeting these requirements? For the Observer pat- will ensure, or the requirements that a system adopting a tern, the return is that if the pattern is applied as intended, given pattern should meet. We will briefly address indi- the view of each observer will remain consistent with the vidual items of related work later in the paper but one im- subject’s state – again consistent in what sense? As we will portant notion that we should mention here is Reenskaug’s see, the kind of formal specifications that we develop in this [13] role models. Role models allow us to focus on the in- paper will provide precise answers to these questions. teractions among the various objects participating in what area of concern There is an inherent risk in formalizing design patterns he calls an . For example, an area of con- [14] in that flexibility, which is the hallmark of many de- cern for a system could be the question of how a group of observer subject sign patterns, may be lost. For example, in the case of objects keep track of the changes in a . Observer, if we adopt one definition for the notion of in- An important point here is that a given object playing the Observer consistency, the pattern may not be usable in systems that role of an may have many other aspects to it that have a different notion of this concept. As we will see, our are not relevant to this area of concern. Although Reen- approach, while requiring us to provide a precise character- skaug’s work is not concerned with formal specifications, ization of the pattern, also enables us to retain the flexibility his ideas on role models have heavily influenced our ap- contained in the pattern. proach to specifying patterns formally. As we will see, the major part of the pattern’s specification is the precise speci- There is a similarity between our approach to specifying fication of the various roles in that pattern. design patterns and the standard design-by-contract (DBC) In the next section, we develop the basic ideas of our ap- approach [9, 10, 11] using pre/post-conditions and invari- proach. We analyze the different components that must be ants to specify classes and methods. In DBC, the meth- included in the specification of a pattern and some possi- ods of each class have a precisely defined pre-condition and ble variations. In Section 3, we apply our approach to the post-condition, and the class as a whole has an invariant as- Observer pattern and develop a specification for this pat- sociated with it. Whenever invoking a method of a class, tern. In Section 4 we consider related work. In the final it is the caller’s responsibility to make sure that the corre- section, we summarize our approach, reiterate the advan- sponding pre-condition is satisfied. In return, the caller is tages of having formal specifications of patterns, and con- assured that when control returns, the post-condition will sider pointers for future work. be satisfied (assuming that the method is implemented cor- rectly). In our formalization of patterns, the specification will specify a set of requirements that the system designer 2 An Approach to Specifying Patterns wishing to use this pattern must meet; in return, the designer is assured that the invariant associated with the pattern will Consider the Observer pattern [5] in Fig. 1. This pat- be satisfied (as long as the ‘pattern instance’ –a notion to tern is intended to be used when one or more (“observer”) be defined shortly– continues to exist). In a sense, pat- objects are interested in the state of a (“subject”) ob- terns are a natural extension of classes; while classes fo- ject. When an object wishes to become an observer of a cus on how individual objects should behave, patterns are subject,itinvokestheAttach() method of that object; and concerned with interactions among a group of objects and when it is no longer interested in that subject, it invokes its relations between their respective states. Note that it may Detach() method. (One might also ask if a third party ob- well be possible to encapsulate this entire group of objects ject can enroll a given object to play the role of a subject or into a class and focus on the interactions of this class with observer; the formal specification in the next section will external objects. If we did that, we would again be in the answer this question.) domain of standard DBC. But here we want to think of the When a subject’s state changes, it executes the Notify() objects in this group as individual entities and consider the operation; this results in the Update() operation of interactions among them. DBC allows us to deal with indi- each observer being invoked. What the Update() vidual classes in a precise manner; our work is an attempt operation does depends on how it is defined in the to extend that to deal with the group of objects that a given ConcreteObserver class(es). The goal of the Update() pattern is concerned with. operation should be to update the observer’s view of the

Proceedings of the 26th International Conference on Software Engineering2 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE Subject Observer is not a permanent notion. If, for example, S2 were to cease observers to exist, then of course O3 and O4 cannot observe it any +Update() +Attach(in Observer) 1 * +Notify() longer, and the corresponding pattern instance will cease to +Detach(in Observer) exist. But, on the other hand, even if both O3 and O4 were destroyed, this pattern instance might continue to exist, with for all o in observers S2 waiting for other observer objects to become interested o.Update() in it in the future.

ConcreteSubject ConcreteObserver Second, apart from the differences in the details of what −subjectState * 1 −observerState the two roles in the Observer pattern are responsible for, subject +Update() there is one other important distinction between them which is already implicit in our discussion so far. This is that while any number of objects may play the Observer role Figure 1. Observer Pattern in a given instance of this pattern, we must have exactly one object playing the Subject role. Indeed, in order to create a new instance of this pattern, what we need is an object state of the subject so that it is consistent with the actual deciding to play the Subject role. Even if no other objects current state of the subject. have expressed an interest in observing this subject object, How do we formalize the Observer pattern? Note first we will create a new instance of the pattern. This instance that the pattern does not really tell us anything much about will wait for objects to enroll in the role observer, but no the ConcreteSubject or the ConcreteObserver2.Thefo- new object can enroll in the Subject role of this instance. cus is on the Subject and the Observer, and the interac- Each role will be specified by a requires clause and an tions between them. Correspondingly, in our specification ensures clause for each method. In addition, we will also of the pattern, we will say that it has two roles, subject and use a preserves clause which will just say that the state observer. It is worth stressing that a role is neither a class components specified in that clause are not changed by nor an object. Instead, objects that wish to interact accord- that method. However, we are dealing with roles here, not ing to this pattern will enroll in the pattern to play different classes. This means that we do not know what the com- roles. They will then have to obey the constraints imposed plete state of the actual class (of the object that will enroll on the respective roles by the pattern’s specification. to play this particular role) will consist of. All we can be Before we turn to those constraints, two other points sure of is that there must be certain components that will should be noted. First, in a given system, at a given time be used to maintain the information dictated by the pattern, during execution, it is possible that we have two observer and to achieve the interactions required by the pattern be- objects O1 and O2 ‘observing’ the subject object S1 while tween its various roles. We will handle this problem as fol- two other objects O3 and O4 are observing a different ob- lows. The pattern specification will include a portion la- ject S2. In this situation, S1, O1,andO2 form one group beled state. This will list all the components needed from of interacting objects interacting (if the system has been the point of view of the pattern. These components will be built correctly) according to the Observer pattern, while partitioned into states corresponding to the individual roles. S2, O3,andO4 is a second group, independent of the first, The requires, preserves,andensures clauses will be writ- also interacting according to the same pattern. What we ten in terms of these components. In addition, it may also have at this point are two instances of the Observer pat- be appropriate to have a component corresponding to the tern. Thus at any given time, we may have many different pattern as whole, i.e., that cannot be logically thought of as instances of any given pattern. Moreover, a pattern instance being part of one or the other of the roles, but that is not the case with the Observer pattern. Interestingly, when we 2In fact, in the original diagram in [5] for Observer,some asked ourselves this question, it occurred to us that there additional information is included about the ConcreteSubject and might indeed be a more general version of this pattern that ConcreteObserver. This information says that ConcreteSubject has a method GetState() and that the ConcreteObserver’s Update() invokes does have such a component. We will briefly mention this that method to get the current state of the subject. But this seems too generalization in the next section. restrictive. The diagram in [5] further says that every observer will set But the state portion of the pattern specification is not by its state (observerState) to the value returned by the GetState() method of subject. Does that mean all observers have the same kind of state? itself adequate to allow us to specify the various methods That is clearly not the intention since the whole point of having different of the various roles. Consider, for example, the require- observers is to have different views of the state of the subject;butade- ment that Notify() should be invoked when the state of the signer studying that diagram could well get such an impression although subject object changes since the views that the observers the accompanying discussion in [5] should clarify this. In any case, we believe having formal specifications of the kind we propose in this paper have of the subject may no longer be consistent with its for patterns can help in eliminating or reducing such misunderstandings. new state. But what does it mean to say that the state of the

Proceedings of the 26th International Conference on Software Engineering3 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE subject has changed? It surely should not mean that every invoke the Update() method of each observer. To specify time any bit in that object changes, we need to update all the such requirements, we will use the call sequence or trace observers. We need to be able to allow the answer to this that records the calls a method makes during its execution question to be provided when the object in question enrolls and allow conditions to be imposed on this trace, as part of to play the Subject role rather than assuming one particu- the ensures clause of the method. lar answer when defining the pattern. To allow for this, in So far we have focused on the requirements that objects our specification we use the notion of auxiliary concepts. enrolling to play specific roles must meet, in other words Essentially, we parameterize our specification in terms of on the responsibilities component of the pattern. There are these concepts. In the case of the Observer pattern, we will some additional aspects to this which we will see in Sec- use two such concepts. One will correspond to the notion tion 3, but let us now turn to the rewards component. In of how to determine if the state of the subject has changed. many patterns, the main reward of consistently abiding by The second will answer the question, corresponding to the the guidelines of the pattern is that an invariant relation be- given subject and each observer object, what does it mean tween the states of the various objects playing roles in that for the observer’s state to be consistent with that of the pattern instance will be satisfied. Thus, for example, in the subject. At the point that the pattern instance is created or case of the Observer, this invariant is that whenever con- at the point that an object enrolls to play a particular role in a trol is not inside one of the methods of these objects, the currently existing pattern instance, the system designer will state of each observer will be consistent with that of the have to provide suitable definitions for these concepts. For subject where consistency is as defined in the correspond- that pattern instance, the specification will use these partic- ing auxiliary concept when this observer object enrolled ular definitions. to play its role. For other patterns, there are other rewards The notion of consistency should in fact be on a per- that the designer can expect to reap by applying the pattern observer basis since the whole point of having multiple correctly. One of the rewards to be expected when using observers is that each may adopt a different view of the the , for example, is an information hid- state of the subject, hence what it means for a given view ing guarantee. In future work, we aim to characterize other to be consistent with the state of the subject will clearly rewards and to investigate the techniques to specify them. depend on the view in question. That the notion of con- We conclude this section with a comment about the re- sistency to be used varies from one observer to the next lation between the code of the system and the pattern(s) it will become evident in our specification where, as part of uses. According to our discussion, when an object enrolls, an object’s enrollment in the Observer role, we will have to sayintheSubject role of a new instance of Observer,the provide the definition of the corresponding notion of consis- designer must provide definitions for the auxiliary concepts, tency. This also raises the possibility that perhaps the notion check that the methods of the class that this object is an in- of what it means for the subject state to be modified should stance of meet the requirements of the corresponding role also depend in some way on the state of the observer.For specifications, etc. But there is nothing in the code of the example, if a given observer is not interested in a partic- system where this object declares its intention of playing ular part of the subject’s state then, from the point of that theroleofSubject in an instance of Observer. Unlike, observer, changes in that portion of the state should not be for example, a class and its methods, the patterns are not counted as “modifying the state of the subject”; but a dif- explicit in the code; they are, so to speak, in the eyes of ferent observer interested in this part of the subject’s state the design team. To handle this, we will have to introduce will want to count such a change as modifying the subject’s pattern-code (which will essentially be written to fit the for- state. We will return to this when we develop the formal mat of comments in the underlying programming language specification in the next section. so that normal compilers can ignore it) at suitable points, in Let us now consider an important issue related to the particular at points where a new pattern instance is created, ensures clauses of the individual methods in the different as well as at points where an object enrolls in or dis-enrolls roles. While many of these will be expressible in terms of from an existing pattern instance. Verification responsibil- the corresponding state components, for some we need a ities will materialize, so to speak, at the points wherever more elaborate mechanism. This has to do with the fact this pattern-code exists, requiring a conscientious designer that in some situations, the pattern dictates not that a par- to verify that the appropriate responsibilities had been met ticular method change the state to meet some specified con- at these points. This verification may be fully formal, or dition, but that during its execution it make a specific se- semi-formal, or informal depending on the tastes of the de- quence of calls to other methods (either other methods of signer. Alternately, or in addition, automated tools can be the same role, or methods of other roles). A good exam- built that can mechanize part of this verification task, or pos- ple of this is the Notify() method of the subject role of sibly test at run-time whether the appropriate assertions are Observer; this method is required, during its execution, to satisfied at the appropriate points (in the pattern-code).

Proceedings of the 26th International Conference on Software Engineering4 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE 3 Case Study cated, one corresponding to each such observer ob- ject. In this pattern, there is no component correspond- In this section, we develop the formal specification of the ing to the pattern as a whole, hence this part is speci- Observer pattern. For convenience, we have split the spec- fiedtobenull. One possible generalization would be ification into three separate figures. The first one, Fig. 2, is to have a pattern in which there is a limit on the num- concerned with the pattern-level portion of the specification. ber of observers in any given instance of the pattern. The second one, Fig. 3, is concerned with the specification In that case, we could keep a count of the number of of the Subject role; and Fig. 4 with the specification of the objects currently enrolled to play this role, and one of Observer role. the conditions for enrolling as an Observer would be that the value of count be less than the limit.

pattern Observer These are not the ‘complete’ states of the actual roles: Subject, Observer*; // see note 1 below subject or observer objects. Those objects will state: have additional components (defined in their respec- Subject: set[Observer] observers; // note 2 tive classes), and we will have to refer them in our Observer: Subject subject; pattern specification. For example, we will have to pattern: null; specify that when the state of the subject changes, the observers will be notified. But what do we mean by auxiliaryConcepts: // note 3

the state of the subject? This is not the part of the state « relation: Consistent(Subject. « , Observer. );

that is listed here as belonging to the subject role. This

« « ¾ relation: Modified(Subject. ½ , Subject. ); part has to do with the state needed by the pattern.The constraint:

actual object that plays this role will have additional

 ´ «  « µ ¾ Modified su ½ su

state. Indeed, if it didn’t, there would be nothing for

´ «  « µ µ 

Consistent su ½ ob

the observers to observe! We will use the notation

´ «  « µ

Consistent su ¾ ob

« (for additional “application-level” state) to refer to

invariant: // note 4 this non-pattern portion of the object’s state.

¾ « «  ob observers: Consistent(subject. ,ob. ) pattern instantiation: //note 5 3. The notion of what it means for the state of an

observer to be Consistent with the state of the

  Subject:player Modified

subject depends on the pattern instance and the  enrolling as Subject: false subject and observer in question, hence it is listed

enrolling as Observer: as an auxiliaryConcept. Similarly, given two subject

´  µ

 player Subject.player states (which, at the point where we use it in Fig. 3,

¾ µ ´

 player observers will be the state at the start and end of a method in the

´ µ Consistent  Subject.player.Attach self subject’s class), the Modified concept lets us decide whether the second state is modified or unmodified Figure 2. Observer Specification: Pattern from the first. These concepts will be defined when an object enrolls as an Observer and an object enrolls Notes: as a Subject at pattern instantiation time respectively (note (5) below). 1. There are two roles, Subject and Observer.The‘*’

at the end of the Observer says that any number of But there is an additional condition we need to im- ×Ù «

objects may enroll to play this role in a given instance pose. Suppose we have two subject states, ½ ×Ù « of this pattern; by contrast, only one object may play and ¾ that, according to the definition of the Subject role. Modified are the ‘same’; suppose also that there is an

observer state Ó « that, according to the definition ×Ù «

2. The state is partitioned into a component correspond- of Consistent is consistent with ½ but not with ×Ù «

ing to each role. The part corresponding to the Subject ¾ . Then we will have a problem because if the

×Ù « ×Ù « ¾ role consists of a variable, observers,whichisaset subject state were to change from ½ to , of references to observer objects, these of course be- the subject would not call the Update() methods of ing the objects that have enrolled to play that role. The the observers since its state has ‘not changed’ accord- part corresponding to the Observer role is subject ing to the given Modified; but if the state of one of the

which will hold a reference to the object playing that observersisÓ « , this would no longer be consis- role; note that since multiple objects may enroll to play tent with the new state of the subject! The specified the Observer role, this state component will be dupli- constraint ensures that this problem will not arise. It

Proceedings of the 26th International Conference on Software Engineering5 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE may be worth pointing out that since the Consistent enrolling to play the particular role to the correspond- concept depends on the particular observer ob in ing role state. question, it may be more accurate to use the notation Some points are worth noting. The potential incompatibil- Consistentob; we omit the subscript in the interest of presentation. ity between the definitions of Modified and Consistent that we discuss in point (3) above and the solution we have pro- 4. The pattern invariant is the reward for using this pat- posed, in the form of the corresponding constraint seems tern. This asserts that for each observer in the set to be new. We have not seen this potential problem men- observers, its state will be consistent with that of tioned before and indeed, it was only as we were designing the state of the object playing the Subject role, where the formal specification in Fig. 2 that we realized the prob- ‘consistency’ is as per the definition supplied at the lem. A less significant point has to do with the conditions point of observer enrollment. to be met when an object wishes to enroll in an existing in- stance of the Observer pattern. This condition too seems to 5. Next we specify what is needed for creating a pat- have been overlooked in much of the literature, the one ex- tern instance and for enrolling in the Subject and ception we are aware of being [12] which gives a temporal Observer roles. To create a new pattern instance, we characterization of this condition. The point is that formal are required, according to this specification, to provide specifications while they are certainly challenging to write an object that will play the Subject role, which means down, allow us to identify potential problems that can be that the class of that object must meet the constraints overlooked in the informal documentations, and to resolve (in Fig. 3) for that role; and to provide the definition them. The goal, of course, is to build systems that are more for Modified, one of the two auxiliary concepts. (Note reliable. that player is a keyword that represents the object that Next we turn to the specification of the Subject role in wishes to play the role of Subject in the pattern in- Figure 3. stance about to be created.) 6. We first specify the initial condition that must be sat- For enrolling as a Subject after the pattern instance isfied when an object enrolls into this role (possibly has been created, we are required to satisfy the impos- at the time of the instance creation). Here the condi- sible condition false. This simply means that another tion states that the observers component of the ob- object cannot decide to enroll into this role once the ject must be empty (since no objects should have been pattern instance has been created. enrolled to play the role of observer at this point). There is no invariant for this role, so this is defined The conditions for enrolling as an Observer are of to be true. course more liberal. The requirements are that the ob- ject (player) that wants to play this role must not al- 7. Next we have specifications for the individual methods ready be enrolled (in this instance) as an Observer or of this role. Attach(), as we saw above, is the method Subject. It may be worth noting that some systems do an object wishing to become an observer should call. use a version of the pattern where an object playing the Its pre-condition requires that this object not already Subject role enrolls also as an Observer in the same be an observer; that this object not be the subject; instance, for example the ‘private’ events in the .NET and finally that the object calling Attach() be the same framework; if we want to allow this, this clause should as the one that wishes to become an observer.Again be omitted. Further, when an object enrolls to play these clauses may have to be generalized depending this role, we must provide a definition for the auxil- on whether we want to allow third-party enrollment of iary concept Consistent; this definition is the one we observers. In other words, this clause prevents enroll- referred to as Consistentob above, and will be used ment of a given object as an observer of our subject only for this observer object. The final component by a third object. If we want to allow for such third- states that to enroll as an Observer, the object needs party enrollments, this clause should be omitted. to invoke the Attach() method on the object playing We should note that in this pattern, enrollment into the Subject role, and pass itself as argument; here one roles is a simple matter. But in more complex patterns could ask if a third-party object could enroll this object it may be that enrollment of an object into a particu- as an Observer; if we want to allow that, we must use lar role takes place only when a number of specified player rather than self as the argument of Attach(). actions, perhaps by a number of specified objects (not In addition, when creating a pattern instance or en- just the object enrolling), are completed. Specifying rolling into an existing pattern, we are also required to such enrollment requirements will of course be more provide mappings from the (class of the) actual object complex than that in Fig. 2.

Proceedings of the 26th International Conference on Software Engineering6 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE roleSpec Subject need for such a call does not seem to have been noted

initCondition observers = ¨; // note 6 elsewhere in the literature. Detach() is similar with- invariant true; out the requirement for a call to Update() (but note that such a call is not forbidden, just not required). methods: //note 7 void Attach(Observer ob): 10. The Notify() method has a more complex call sequence

requirement. Essentially, its ensures clause requires

¾ µ  ´  µ requires: ´ob observers ob this

that the Update() method of each observer is called.

 ´ µ ob  caller

preserves: « ; //note 8 11. The actual class of the object playing this role may

ensures: observers = have not only additional state, but also additional  observers@pre ob ; //note 9 methods. The “others” part of the specification is a ensures (call sequence): call ob.Update() condition that must be met by all such methods (i.e., void Detach(Observer ob): methods other than Attach(), Detach(),andNotify()).

requires: ob ¾ observers; ob = caller The preserves clause requires them not to make any

preserves: ob; « ; changes in observers (else the protocol implemented  ensures: observers = observers@pre ob ; by Attach() and Detach() will be clearly compro- void Notify(): //note 10 mised). Further, the ensures clause requires that if the requires: true additional state is modified (as per the definition of the concept Modified which was provided at the time of preserves: observers; « ; ensures (call sequence): pattern instantiation), then there must be an appropri- ate call to Notify(). In order to specify this, we as- calls to ob.Update() for each ob ¾ observers sume that the call sequence cs automatically records

others: //note 11

  all calls; each call is recorded as an element, cs ,that

requires: true

 Ñ specifies the name of the method (cs ), and in-

preserves: observers

 « cludes the state (cs ) at the time of the call. Thus ensures (call sequence: cs):

this clause states that there must be a call to Notify,

´« «  [Modified @pre, )]

that the final state must be unmodified (as per the defi-

 Ñ  µ  ´ cs Notify

nition of Modified) from the one recorded in this call;

´  ««µµ  ´ Modified cs

and there must be no later calls to Notify (else such a

¼ ¼

 Ñ  µ    ´ cs Notify ] later call might provide incorrect information about the  final state). This will ensure that the observer’s views Figure 3. Observer Specification: Subject are updated if the subject state changes. Gamma et al. [5] do point out the importance of ensuring this last requirement. We feel, however, that even if we had

8. The preserves clause tells us that « , the additional been unaware of it at the start, we would have discovered state of the subject object will also be unchanged. In the need for it when writing this part of the specification. general, all methods explicitly listed in the specifica- We now turn to the spec of the Observer role in Fig. 4. tion of any role of the pattern are likely to have a simi- lar clause since these methods are only concerned with 12. The initialization condition requires that the subject performing the activities required by the pattern, hence field be set appropriately to refer to the object that is there is no reason for them to modify any component playing the role of subject. of the additional state. 13. The specification of Update() says that it should not modify the value of subject, and that it should up- 9. The first part of the ensures clause simply requires the date the state of the current object to be consistent (as new observer object to be added to observers.The per the definition of the Consistent relation provided second part is a condition on the call sequence of the when this object enrolled to play this role) with the Attach() method. This part requires that the call se- state of the object referred to by subject. quence should consist of a call to ob.Update().The reason for this is to ensure that once an object becomes 14. For the other methods that might be defined in the an observer, its view is consistent with the state of the ConcreteObserver, the requirement is that they not subject, as indeed required by the pattern invariant. change the value of subject and that they leave the This was another requirement whose need we discov- state of the current object consistent with the state of ered only as we were designing this specification. The the subject.

Proceedings of the 26th International Conference on Software Engineering7 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE roleSpec Observer role, we would include a line of code such as,

initCondition subject = subject.player; // note 12 /*@ Observer pI = new Observer ¼

invariant true; ( Subject: xx, Modified: (xx.u  xx.u) ) */ methods: pI is a “pattern instance variable” that will allow us to re- void Update(): // note 13 fer to this pattern instance later in the program. We need to requires: true; be able to do this, for example, when another object wishes preserves: subject; to enroll as an observer in this particular pattern instance.

xx refers to the object that is being enrolled to play the role

« « µ ensures: Consistent ´ subject this of Subject in the new instance of Observer being created; others: //note 14 the Modified predicate is defined to be the relation speci- requires: true; fied, where u is an integer member variable of the class of

preserves: subject; xx. Recall that Modified is a relation between two states of

« « µ ensures: Consistent ´ subject this a given object, here the one that xx refers to; when a method  operates on this object, it may change the values of one or

more member variables of that object; the “ ¼ ” refers to the Figure 4. Observer Specification: Observer value of the variable in question when the operation started, and the unprimed variable, its value when the operation fin- ishes. Thus here we are saying that, for the purposes of this With respect to this last point, it is worth noting that it per- instance of Observer, we will treat the state of the object to mits the state of the observer to be modified so long as have been modified if the value of xx.u has increased; if the the new state is also consistent with the current state of the value of xx.u has decreased or not changed, the object will subject. Thus if the observer object in question was one be considered unmodified, independent of what might have that could be displayed on the screen, we might iconify it, so happened to the values of the other member variables. In clearly its state would change; but this would be permitted practice, we would probably have more involved notions of by this specification so long as the definition of Consistent Modified(). More importantly, we would not want to refer that has been provided is such that the iconified state is con- to the states of objects in terms of concrete member vari- sistent with the state of the subject. While, as we noted ables, but rather in terms of their abstract states. above, the need to call Notify() on the subject when its state Each piece of pattern code will have an associated proof is modified has been explicitly noted in the literature, we obligation. Thus, for the line of code corresponding to cre- have not see any discussion of what changes we can make ating the new instance pI, we would have to show that the in the observer object independently of the subject.The initialization requirements of Fig. 2 are satisfied. In each auxiliary concept Consistent allows us to give a precise line that corresponds to an object enrolling as an Observer, characterization of what changes are permitted. we would have to show that the definition of Consistent In terms of sheer size, our formal specification is shorter given at that point, and of Modified given above, together than typical informal descriptions of the pattern, although satisfy the constraint specified in the pattern specification in of course, even with some practice it is harder to read than Fig. 2. It is by meeting these proof obligations (formally informal descriptions. More important is the precision our or informally depending on our tastes and the needs of the specification ensures; it was this precision that allowed us to system), that we would show that we have applied the pat- pinpoint various omissions and gaps in the informal descrip- tern correctly. And, in return, we can assert that as long as tions, and allowed us, indeed forced us, to consider ways to pI exists, the invariant specified in Fig. 2 will be satisfied fill them. (whenever control is outside all the methods that modify We have only developed the formal specification of the any of the objects enrolled in that pattern instance). pattern. In a system that uses one or more instances of the pattern, how do we show that the requirements of the pat- tern have indeed been met, and how do we make use of the 4 Related Work reward, i.e., the pattern invariant specified in Fig. 2? The approach we plan to adopt for addressing these questions is As we noted earlier, much of the patterns literature is as follows: The designer will be required to include in the concerned with informally documenting specific patterns. body of the system in question, pattern code that will rep- Dong [3] considers the question of how the use of a design resent such actions as a new pattern instance being created, pattern in a particular application can be made clear in a an object enrolling in a given role, etc. Thus, for exam- UML diagram. The idea is to annotate the UML diagram so ple, at the point that we decide to create an instance of the that for any given class, we can specify if it is part of a pat- Observer pattern with a given object playing the Subject tern instance. The name of the pattern as well as the ”role”

Proceedings of the 26th International Conference on Software Engineering8 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE (in the pattern) that this class plays are shown in the dia- from smaller patterns, where the larger pattern gains its gram. The individual operations of the class can similarly importance as a result of synergy between its components, carry annotations specifying the roles they play in the ap- and indeed without such synergy Riehle does not consider plication of the pattern. Dong accounts for the fact that the the result a . His focus is on trying to same class might participate in the use of several patterns. identify the key roles in the composite pattern and relate But [3] does not directly address the question of specifying them to the roles in the component patterns. While the precisely the pattern in question or the responsibilities that identification of roles is done semi-formally, Riehle does a designer using the pattern must meet. not consider the possibility of specifying their behaviors Eden et al. [4] propose a higher order logic formalism in formally which, of course, has been our focus. which a design pattern is a formula. The primitives of the logic are things like classes, methods, etc. The key point 5 Discussion is that the logic is rich enough to specify the relations that are common between patterns. It is not clear whether this The goal of our work was to develop a technique for rea- formalism will be of use in specifying individual patterns soning about design patterns and the applications in which and identifying, to the designer, the specific responsibilities they are used. To that end, we presented a formalism and and rewards that the use of the patterns entail. associated notation similar to that of standard design-by- Mikkonen [12] specifies a pattern by specifying the contract that allows us to precisely specify pattern behavior. classes involved, including an abstract model and a list The specification approach consists of two parts. The first of the relations among the various items. Thus for the deals with the pattern as a whole, and the second, with the Observer pattern, he specifies that Attached is a relation individual roles that participate in the pattern. between a subject and an observer. He uses an action- At the pattern level, we identify the constituent roles, system type specification in a guarded-command language, the state required of each role, the pattern instantiation con- to specify the sequences of actions. For specifications that straints, the object enrollment constraints, and the rewards do not require the call sequence, using action-system speci- a designer can expect to reap by fulfilling the specified re- fications provide no advantage over simple assertion-based sponsibilities. We also identify the auxiliary concepts re- specifications; but it may be possible to express complex quired in specifying the pattern and constraints that the con- conditions on the call sequence as action-system type spec- cepts are required to meet. These auxiliary concepts, typ- ifications, and we plan to investigate this in future work. ically relations or predicates on the objects that enroll to There are some similarities between our pattern specifi- play a part in the pattern, allow for precision without com- cations and contracts of Helm et al. [7]. The participants promising flexibility. These auxiliary concepts are also used that appear in contracts are analogous to our roles, and the at the role level, where we identify the state and behaviors invariant that appears in a contract is similar to our reward that must be provided by objects enrolling to play each role. invariant in that it describes a condition relating the states For each role we identify the initial conditions, method con- of the different participants. But there are also important tracts, role-level invariants, and the restrictions imposed on differences. For example, although [7] uses a notion sim- non-pattern methods. ilar to our auxiliary concepts, there is nothing analogous As a case study, we applied our approach to the clas- to the constraints we impose on our relations. Also, noth- sic Observer pattern. Although the resulting specification ing similar to our others clause is used in contracts; hence, is relatively involved, it does highlight a number of issues additional methods in the classes of the objects that act as that seem to have been overlooked in previous discussions. the actual participants may invalidate the invariant in the Some of the points worth recapitulating include: contract. Further, although contracts do allow us to require 1. In providing definitions of Modified and Consistent, that a certain method (such as Notify()) is invoked at a cer- a potential incompatibility arises. Namely, it is pos- tain point to achieve a certain condition, there is nothing sible to provide definitions which allow for a subject that forbids additional actions that then nullify that condi- to become inconsistent with one or more observers tion; the use of call sequences in our specifications enable without ever notifying the inconsistent observers. As us to preclude this possibility. One important idea that [7] a consequence, the whole point of applying the pattern introduces is that of composing contracts to obtain “higher- is undermined. The potential incompatibility, as well level” contracts; a similar idea should be applicable to our as the proposed solution, appears to be new. specifications and we plan to investigate that in future work. We have already mentioned the role models of 2. When an object enrolls to play the role of Observer, Reenskaug[13]. Riehle [14] explores an idea of pattern it is required to invoke the Attach method of the cor- composition, somewhat similar to [7]’s higher-level con- responding subject. In writing the specification of tracts. The idea is that larger patterns can be composed Attach, we realized that the new observer need not be

Proceedings of the 26th International Conference on Software Engineering9 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE consistent with the corresponding subject before the Second, we plan to develop the pattern-code notation call to Attach. To ensure the pattern rewards, namely that will be used to specify, at appropriate points in the code, consistency between the subject and each observer, pattern instance creation, object enrollment, and object dis- the Attatch method must bring the new observer into enrollment. As the verification responsibilities materialize a consistent state by invoking the observer’s Update at these points, we then plan to focus on the proof rules that method. The potential problem, as well as the pro- can be used to formally verify the correct use of a pattern. posed solution, appears to be new. These rules will form the basis of a formal proof system for verifying the correct application of a pattern, as well as pre- 3. In specifying the constraints on non-pattern meth- dicting the behavior that a system will exhibit when devel- ods in the Observer role specification, one’s first in- oped using it. An alternative is to explore the use of a moni- stinct is to prevent these methods from modifying toring system, similar to the assertion monitoring system of the application-level state of the observer,assuch Eiffel, that checks whether the related constraints and asser- changes could bring the observer into a state that is tions are being satisfied at runtime. Exploring such a tool is inconsistent with the corresponding subject.Thisis also work for the future. too restrictive, however, as not every modification need Acknowledgments: We thank the referees for detailed bring the observer into an inconsistent state. Our comments on the first draft of the paper. specification permits the state of the observer to be modified so long as the new state is consistent with the References current state of the subject. While the importance of invoking Notify after modifying the subject’s state is [1] K. Beck and R. Johnson. Patterns generate architectures. In noted elsewhere, we have not seen any discussion of Proceedings of the Eighth ECOOP, pages 139–149, 1994. what changes can be made to an observer indepen- [2] F. Buschmann, R. Meunier, H. Rohnert, P. Sommerlad, and dent of its corresponding subject. M. Stal. A system of patterns. Wiley, 1996. [3] J. Dong. UML extenstions for design pattern compositions. Thus, even for a relatively simple pattern such as In C. Mingins, editor, Proc. of TOOLS, in Special Issue of J. Observer, the kind of specification we have proposed can of Object Technology, vol. 1, no. 3, pages 149–161, 2002. prove helpful in identifying and resolving problems in the [4] A. Eden, J. Gil, Y. Hirshfeld, and A. Yehudai. Toward a informal descriptions. Indeed, it was only as we were devel- mathematical foundation for design patterns. Technical Re- oping the specification that these issues became evident. As port 004, Tel Aviv University, 1999. [5] E. Gamma, R. Helm, R. Johnson, and J. Vlissides. Design one of the benefits of using design patterns is to facilitate the Patterns: Elements of Reusable OO Software. Addison- understanding of complex architectures, the mechanisms Wesley, 1995. used to describe them should be unambiguous. We believe [6] J. Hallstrom and N. Soundarajan. Reasoning about design we have achieved this precision while avoiding the pitfall patterns – a case study. submitted to Int. Conf. on Software of compromised flexibility by parameterizing our specifi- Reuse, 2004. cations with auxiliary concepts, definitions of which can [7] R. Helm, I. Holland, and D. Gangopadhyay. Contracts: be tailored to each pattern instance. Thus, our specifica- Specifying behavioral compositions in object-oriented sys- tions enable common-case reasoning, while allowing for tems. In OOPSLA-ECOOP, pages 169–180, 1990. [8] R. Johnson. Components, frameworks, patterns. In ACM per-instance specialization. SIGSOFT Symposium on Software Reusability, pages 10– We conclude with pointers to future work. First, we plan 17, 1997. to apply our approach to several additional patterns. We [9] G. Leavens and W. Weihl. Specification and verification of have already carried out another case-study [6] in which object-oriented programs using supertype abstraction. Acta we specified the Memento pattern. As in the case of Ob- Informatica, 32:705–778, 1995. server, as we developed the specification, we discovered [10] B. Liskov and J. Wing. A behavioral notion of subtyping. numerous ways to make the pattern more flexible than is ACM Trans. on Prog. Lang. and Sys., 16:1811–1841, 1994. [11] B. Meyer. Object-Oriented Software Construction. Prentice allowed by the standard informal description of Memento. Hall, 1997. No new primitives or mechanisms beyond the ones we used [12] T. Mikkonen. Formalizing design patterns. In Proceed- in the specification of Observer were needed to handle Me- ings of 20th ICSE, pages 115–124. IEEE Computer Society mento.ButMemento, like Observer, is a behavioral pat- Press, 1998. tern; we plan to use our approach on structural and cre- [13] T. Reenskaug. Working with objects. Prentice-Hall, 1996. ational patterns, as well as on patterns for concurrent and [14] D. Riehle. Composite design patterns. In Proc. of OOPSLA, . Some of these may require new pages 218–228. ACM, 1997. [15] D. Riehle and H. Zullighoven. Understanding and using pat- mechanisms to be used in their specifications. For example, terns in software development. Theory and Practice of Ob- as a referee noted, invariants may not always be sufficient ject Systems, 2(1):3–13, 1996. to specify rewards.

Proceedings of the 26th International Conference on Software Engineering10 (ICSE’04) 0270-5257/04 $20.00 © 2004 IEEE