17
Understanding Design Patterns Density with Aspects: A Case Study in JHotDraw using AspectJ Simon Denier, Pierre Cointe To cite this version: Simon Denier, Pierre Cointe. Understanding Design Patterns Density with Aspects: A Case Study in JHotDraw using AspectJ. Welf L¨ owe and Mario S¨ udholt. Proceedings of the Inter- national Workshop on Software Composition (SC’06), Mar 2006, Vienne, Austria. Springer- Verlag, 4089, pp.243-258, 2006, Lecture Notes in Computer Science. <10.1007/11821946 16>. <inria-00458193> HAL Id: inria-00458193 https://hal.inria.fr/inria-00458193 Submitted on 19 Feb 2010 HAL is a multi-disciplinary open access archive for the deposit and dissemination of sci- entific research documents, whether they are pub- lished or not. The documents may come from teaching and research institutions in France or abroad, or from public or private research centers. L’archive ouverte pluridisciplinaire HAL, est destin´ ee au d´ epˆ ot et ` a la diffusion de documents scientifiques de niveau recherche, publi´ es ou non, ´ emanant des ´ etablissements d’enseignement et de recherche fran¸cais ou ´ etrangers, des laboratoires publics ou priv´ es.

Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

  • Upload
    others

  • View
    1

  • Download
    0

Embed Size (px)

Citation preview

Page 1: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

Understanding Design Patterns Density with Aspects:

A Case Study in JHotDraw using AspectJ

Simon Denier, Pierre Cointe

To cite this version:

Simon Denier, Pierre Cointe. Understanding Design Patterns Density with Aspects: A CaseStudy in JHotDraw using AspectJ. Welf Lowe and Mario Sudholt. Proceedings of the Inter-national Workshop on Software Composition (SC’06), Mar 2006, Vienne, Austria. Springer-Verlag, 4089, pp.243-258, 2006, Lecture Notes in Computer Science. <10.1007/11821946 16>.<inria-00458193>

HAL Id: inria-00458193

https://hal.inria.fr/inria-00458193

Submitted on 19 Feb 2010

HAL is a multi-disciplinary open accessarchive for the deposit and dissemination of sci-entific research documents, whether they are pub-lished or not. The documents may come fromteaching and research institutions in France orabroad, or from public or private research centers.

L’archive ouverte pluridisciplinaire HAL, estdestinee au depot et a la diffusion de documentsscientifiques de niveau recherche, publies ou non,emanant des etablissements d’enseignement et derecherche francais ou etrangers, des laboratoirespublics ou prives.

Page 2: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

Understanding Design Patterns Density

with Aspects

a Case Study in JHotDraw using AspectJ

Simon Denier and Pierre Cointe

OBASCO

Ecole des Mines de Nantes, INRIA, LINA,4, rue Alfred Kastler, Nantes, France

{sdenier, cointe}@emn.fr

Abstract. Design patterns offer solutions to common engineering prob-lems in programs [1]. In particular, they shape the evolution of programelements. However, their implementations tend to vanish in the code:thus it is hard to spot them and to understand their impact. The prob-lem becomes even more difficult with a “high density of pattern”: thenthe program becomes easy to evolve in the direction allowed by patternsbut hard to change [2]. Aspect languages offer new means to modular-ize elements. Implementations of object-oriented design patterns withAspectJ have been proposed [3]. We aim at testing the scalability ofsuch solutions in the JHotDraw framework. We first explore the impactof density on pattern implementation. We show how AspectJ helps toreduce this impact. This unveils the principles of aspects and AspectJ tocontrol pattern density.

1 Introduction

Design patterns [1] are well-known couples of problem-solution for program engi-neering. They shape the structure and the interface of their targets, and redefinesome behaviors. Most design patterns aim at decoupling concerns, in particularto allow separate evolution. However, the shape they impose disallows evolutionin other directions. Also, the programmer must often make a tradeoff betweenthe impact of the pattern and the properties he wants from it, which results indistortions from the standard pattern. Then implementations of design patternssuffer from lack of traceability: some elements tend to be lost and pattern iden-tity itself is hard to trace back to the model — such that the pattern is said to“vanish” in the code [4].

The impact of design patterns on implementation, their tendency to shapeevolution, and the difficulty to trace them in the code raise questions when soft-ware grows in complexity. But the implications of design patterns in complexsoftware is not well understood. Most prominent work includes the study of rela-tionships between design patterns, such as [1] (section “Design pattern relation-ships”) and [5], who proposes a classification of different kind of relationships.

Page 3: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

This includes patterns making use of other patterns in their implementation aswell as interactions between two patterns. [2] shows in the context of JUnit thatmature frameworks tend to have a high density of patterns: then they are “easyto use, but hard to change”. Implementations become so entangled that it isnearly impossible to think of a pattern alone and that they can lose some oftheir flexibility.

Aspect-oriented languages a la AspectJ [6, 7] offer new means to modular-ize software elements. [3] shows some general aspectizations of the GoF designpatterns [1]. Aspect-oriented languages allow:

– modularization of crosscutting pattern elements;– better separation between a generic (reusable) part and a specific part;– language-level detection and visualization tools for interactions;– pluggability of modules to replace a pattern implementation by another.

Our aim is to test the scalability of such aspectizations of design patterns ina real application. We experiment with the JHotDraw framework1 as it is a welldocumented “design exercise” involving many design patterns.

Our guideline is to look for an incremental and reversible development ofJHotDraw. We start with a basic yet functional framework (called the base there-after). We then “compose” new modules into the base, incrementally enhancingthe framework, but still with the option to come back to earlier versions. Bydoing so we underline design choices which happen through the whole programwhen more functions are composed together, but get lost because there is nomean to trace such choices to the module they support. Such a guideline allowsfor a deeper separation of concerns highlighting the development process andproduct versions.

Section 2 presents JHotDraw base (internals and design patterns), as wellas the specific example of the “invalidation” concern. Section 3 examines theinvasive impact of two additional concerns on the base, related to the Observer,Composite and Decorator patterns. Section 4 shows how such impact canbe modularized with AspectJ constructs. We follow with some discussions inSect. 5, related work in Sect. 6 and conclude in Sect. 7.

2 An Overview of the JHotDraw framework

2.1 General Architecture

Figure 1 shows main interfaces and relationships involved in the JHotDrawframework base. It gives a feeling of how a JHotDraw application works andwhat can be extended. We now explain the responsibilities and collaborations ofeach interface, in particular with regard to framework extension:

– DrawingEditor is the base interface for the application. It maintains a linkto the active DrawingView and to the current tool. Extensions usually definethe GUI, instantiate tools and drawing views.

1 We use JHotDraw 5.3 – available at http://www.jhotdraw.org/

Page 4: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

– DrawingView displays one drawing. It holds interactions between the userand the drawing, as well as graphics with Swing. This is apparent as it islinked to JPanel, maintains a link to the list of currently selected figures,and has access to the current tool via the editor. The default implementationclass fulfills all these roles.

– Drawing acts as a container and a uniform layer to manage a set of figures.

– Figure is a central entity to the user. Depending on the application, it canspawn a large tree of derived figures, such as rectangle, circle, line, or morestructured figures.

– Tool & Handle allow to create or manipulate Figures, either as a whole(select, move) or focusing on a specific property (size, radius). Tools andhandles are notified of user interactions by the drawing view. They too canspawn a large tree of derived classes depending on the application.

JFrame

DrawingEditor

JPanel

DrawingView

Tool Drawing

FigureHandle

Link created

’on the fly’

Method call

Specific Legend

JHotDraw

Framework

Interfaces

owner

selection

figures

handles

notification

notificationcurrent tool

Swing

Fig. 1. A synthetic diagram of main interfaces and relationships in JHotDraw.The inheritance relationship between Swing class JFrame and JHotDraw inter-face DrawingEditor is a shortcut to the real relationship between JFrame and aDrawApplication class implementing DrawingEditor. The same is true for JPanel

and DrawingView

2.2 Design Patterns Involvement

We now quickly sketch how design patterns are involved in this general architec-ture (Fig. 1) and in the underlying implementation. The design patterns exposed

Page 5: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

here are documented in the code. The list below shows the importance of pat-terns to define relationships (Mediator, Observer) as well as to extend theframework (State, Prototype, Strategy, Adapter, Factory Method).These patterns build up the JHotDraw framework base.

– Mediator: DrawingEditor is a mediator between the current tool and thedrawing view.

– Strategy: some DrawingView activities such as painting the drawing or gridconstraining are configured with strategies.

– Observer: there are two occurrences of the Observer pattern. One is lyingbetween figures and the drawing, the other between a drawing and a drawingview. They basically serve to update the drawing and the view in responseto figure modifications. One such concern is detailed in Sect. 2.3.

– State & Prototype: by switching between tools for the current tool state,the user changes the behavior he wants to apply in the drawing view context.Creation tools create figures by copying a prototype figure.

– Adapter & Factory Method: Handler adapts the Figure interface to re-spond to mouse events. The strong link between a figure and its specifichandles is enforced by a factory method in Figure.

Finally two other patterns are worth mentioning for the purpose of this arti-cle: an occurrence of the Composite pattern with CompositeFigure, to manipu-late a group of Figures as a single entity; and an occurrence of the Decorator

pattern with DecoratorFigure, which adds singularities on the target figure(a border for example).

We now focus on the relationship between DrawingView, Drawing and Figure.We will survey how design patterns are involved in a particular concern.

2.3 Updating a View: the Invalidation Concern

Whenever a figure changes, the display view has to be updated to reflect thosechanges. Following a classic optimization, the area to be redrawn is clipped inorder to speed up refreshing and avoid screen flashing. The process of updating aview takes two steps: first compute the clipping area and announce it to Swing,then draw on the graphics context when required by Swing. We call the firststep the invalidation concern: its purpose is to collect damaged area from figuresbefore sending a repaint request to Swing.

The obvious way to do that is to let figures announce their own clipping areawhenever they change. They should notify their Drawing. The clipping area ofa figure can be simply defined by its bounding rectangle. The clipping area forthe drawing can be defined by the union of all clipping areas notified betweentwo updates.

Obviously, this concern can be implemented with an Observer occurrencebetween Figure and Drawing:

– when a figure is added to a drawing (after its creation for example), thedrawing is registered as an observer for the figure;

Page 6: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

– when performing some actions (such as move, change color), the figure no-tifies its drawing with its bounding box;

– when notified, the drawing adds the bounding box to its clipping area;– when a figure is deleted, it deregisters the drawing as observer.

Another occurrence of Observer stands between Drawing and DrawingView:

– a drawing registers its drawing view as observer;– on request the drawing sends its clipping area to the drawing view (which

forwards to Swing); after this point the clipping area can be reset.

Notice how the invalidation concern is itself decomposed in two steps: collectingthe clipping area in Drawing and notifying Swing in DrawingView. This rela-tionship is summarized in Fig. 1 by the two arrow lines for notification.

3 Study of Pattern Density in JHotDraw

The functionalities described in Sect. 2 define the JHotDraw framework base.We examine two additions to this base, both related to design patterns andthe invalidation concern. Our goal is to understand how the current framework(which already contains these additions) differs from the basic one and to exam-ine the impact in term of implementation. We do this in the spirit of incrementalevolution exposed in the introduction.

3.1 Impact of Composite and Decorator on Invalidation

In the base framework all figures are direct children of the drawing and re-fer to it for the invalidation process. When the Composite pattern is usedto manipulate a group of figures as a single entity, figures trees can be con-structed (GroupFigure, Fig. 2). The same is true for the Decorator patternwith BorderDecorator. Then, since we can have any number of levels betweenthe drawing and figures, does it affect the invalidation concern?

We first consider GroupFigure. It just merges clipping areas of figures un-derneath. There is no difference in merging at the group level or at the drawinglevel. So invalidation concern is not affected: figures can directly notify the draw-ing, and GroupFigure is not involved in this Observer pattern. This solutionis labelled A in Fig. 2.

On the contrary, BorderDecorator has the property to redefine the clippingarea of the figure underneath. It enhances the bounding box by the size of itsborder. How do we notify the drawing that the clipping area of a figure shouldbe enhanced? Obviously, solution A does not work since BorderDecorator doesnot have a chance to notify its change. We can think of other solutions:

– B: all Figures notify the Drawing each time a command is transmitted;– C: base Figures notify their direct parent Figure of the change; parent can

change the notification; recursively, the notification traverses the hierarchyto the Drawing;

Page 7: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

Command (dispatched)

B (all figures)

C (path)

D (top most)

A (leaves only)

Notification :

BorderDecoratorGroupFigure

RectangleFigure RectangleFigure RectangleFigure

StandardDrawing

C

B

A

D

Screen

Fig. 2. Figures organized in a tree with Composite and Decorator patterns. In theupper left corner is a sample of figures display. The object diagram shows differentstrategies to deal with notification of invalidation (Sect. 3.1)

– D: in some cases, a parent Figure can directly notify the Drawing.

Solution B is very easy to implement, since all figures classes can inheritfrom an abstract class with the link to drawing. However, GroupFigure andBorderDecorator will trigger notifications every time: they can trigger false no-tifications since they do not know when their children really change. Notificationsof children are redundant with those of GroupFigure and BorderDecorator yetit is impractical to inhibit them for temporary time.

Solution C is much more elegant with respect to false notification:GroupFigure and BorderDecorator will notify only if they receive notifica-tions from children. This is the time for BorderDecorator to grow the clippingarea. However, this has a cost in term of implementation: GroupFigure andBorderDecorator are subjects but also observers. This deeply changes the de-sign as we now have many observers which are linked together in a chain, upto the drawing. In fact, the design for the invalidation concern is now that of aChain of Responsibility pattern [1].

Solution D aims at reducing redundancy. A command such as “move figures”will automatically trigger changes in target figures. Then a GroupFigure cantrigger the notification at the top level, computing the clipping area, and avoidnotifications in levels underneath. The difficulty is to temporarily disable suchnotifications: however, the benefits seem too low for the cost of implementationin object-oriented languages.

The current JHotDraw framework chooses solution C. Figure 3 gives some de-tails on the implementation of this solution. It allows to easily redefine for eachFigure observer how it handles notifications (CompositeFigure, lines 17–18)and, in particular, if it changes them (BorderDecorator, lines 26–29). However,code complexity is increased. First, we notice that the change is only needed forthe purpose of invalidation with BorderDecorator; but the change also affects

Page 8: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

the composite class, due to the chaining solution. Second, as said above, theimpact of the Composite and Decorator patterns is to transform the Ob-

server pattern into a Chain of Responsibility pattern, where each handlercan be seen as an observer of its children.

1 abstract class AbstractFigure implements Figure { // Subject ro l eprivate FigureChangeListener obse rver ;

3 ( . . . )public void moveBy( int dx , int dy){ i n v a l i d a t e ( ) ; ( . . . ) }

5 public void i n v a l i d a t e ( ){Rectangle r = displayBox ( ) ; // c l i pp ing area

7 obse rver . f i g u r e I n v a l i d a t e d (new FigureChangeEvent ( this , r ) ) ;}

9 public abstract Rectangle displayBox ( ) ;}

11 interface FigureChangeListener { // Observer ro l epublic void f i g u r e I n v a l i d a t e d ( FigureChangeEvent e ) ; }

13class CompositeFigure extends AbstractFigure // Composite ro l e

15 implements FigureChangeListener {( . . . )

17 public void f i g u r e I n v a l i d a t e d ( FigureChangeEvent e ){obse rver . f i g u r e I n v a l i d a t e d ( e ) ; } // simple forward

19 }class GroupFigure extends CompositeFigure { . . . } // Composite extension

21class DecoratorFigure extends AbstractFigure // Decorator ro l e

23 implements FigureChangeListener { . . . }class BorderDecorator extends DecoratorFigure {// Decorator extension

25 ( . . . )public void f i g u r e I n v a l i d a t e d ( FigureChangeEvent e ){

27 Rectangle r = e . ge t Inva l ida t edRec tang l e ( ) ;r . grow ( fac torx , f a c t o ry ) ; // grow by s i z e of border

29 obse rver . f i g u r e I n v a l i d a t e d (new FigureChangeEvent ( this , r ) ) ; }}

Fig. 3. Implementation of the Observer pattern impacted by Composite and Decorator patternsin the current JHotDraw framework. AbstractFigure defines main parts of the Subject role, in-cluding the reference (line 2) to the Observer role, which is reified by the FigureChangeListener

interface. figureInvalidated (line 12) is the notification method for the invalidation concern. BothCompositeFigure and DecoratorFigure inherit from AbstractFigure to be subjects and implementFigureChangeListener to be observers. While the default behavior for figureInvalidated is to for-ward the event (see CompositeFigure, lines 17–18), BorderDecorator must redefine this method totake account of its specifity (lines 26–29)

3.2 Evolving to Multiple Drawing Views

The base JHotDraw framework allows to build single-window applications (Fig. 6,left). There is only one drawing view, which can be managed by a Singleton

pattern. This considerably simplifies the implementation of the Observer pat-tern between a drawing and its drawing view (Fig. 4).

An extension of JHotDraw allows to build MDI (Multiple Document Inter-face) applications, allowing multiple drawing views on the same drawing (Fig. 6,right). The implementation is primarily supported by Swing and internal frames.

Page 9: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

class StandardDrawing ( . . . ) implements Drawing {2 ( . . . )

public void f i g u r e I n v a l i d a t e d ( FigureChangeEvent e ){4 StandardDrawingView . in s tance ( ) . drawingInva l idated (

new DrawingChangeEvent ( this ,6 e . g e t Inva l i da t edRec tang l e ( ) ) ) ; }

}

Fig. 4. Simple implementation of the Subject role for the Drawing–DrawingView Observer pattern,with DrawingView as a Singleton pattern

The extension is almost modular since the base framework for single windows isnot modified – except for the Observer pattern in Fig. 4 which does not allowmultiple observers per drawing. We need to change its implementation accordingto Fig. 5. This new implementation works in both singleton and multiple cases,but we have lost the simple choice of the single window framework.

1 class StandardDrawing ( . . . ) implements Drawing {( . . . )

3 private Vector<DrawingView> obse rve r s= new Vector<DrawingView >() ;

5 // when a view i s l inked to a drawing , i t must c a l l t h i s method// to r e g i s t e r i t s e l f as an observer

7 public void addObserver (DrawingView view ) { . . . }public void removeObserver (DrawingView view ) { . . . }

9 public void f i g u r e I n v a l i d a t e d ( FigureChangeEvent e ){for ( DrawingView view : obse rve r s )

11 view . drawingInva l idated (new DrawingChangeEvent ( this ,

13 e . g e t Inva l i da t edRec tang l e ( ) ) ) ; }}

Fig. 5. Implementation of the Subject role for the Drawing–DrawingView Observer pattern, modifiedto handle multiple DrawingViews. For brevity, the original code has been rewritten using Java 5generics and the new for loop

3.3 Impact of Pattern Density

Pattern density is a sign that the program design becomes complex, but it doesnot mean that patterns themselves are complex: the combination of the Com-

posite, Decorator and Observer patterns which form a Chain of Re-

sponsibility pattern is fairly easy to configure. The Observer pattern is evensimpler with a Singleton pattern. However, our short study shows that such acombination can have deep impact on implementation.

Page 10: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

Fig. 6. Two JHotDraw applications: on the left, single view per drawing; on the right,multiple views on the same drawing.

4 Pattern Density with Aspects

We now investigate the invalidation concern and the above additions with AspectJ.We want those additions to be both incremental and reversible. The process isthree-fold and can be summed up as:

1. a “classic” aspectization of Observer patterns for the invalidation concern;2. configuration of Observer pointcuts to deal with Composite and Deco-

rator patterns;3. use of modularity and pluggability of aspects to deal with the presence or

absence of the Singleton pattern.

4.1 Aspectization of the Invalidation Concern

We extract the whole invalidation concern from the base classes (resp. inter-faces): AbstractFigure (resp. Figure), StandardDrawing (resp. Drawing), andStandardDrawingView (resp. DrawingView). This also includes many call pointsto the invalidate method (see AbstractFigure.moveBy in Fig. 3), scatteredthrough the Figure hierarchy2.

The DrawingDamage aspect (Fig. 7) structurally modifies Drawing classes tointroduce a field called damageArea (line 2) and its control logic. The introducedaddDamage method saves and merges clipping areas in this field (lines 3–5).The introduced getAndResetDamage method retrieves the clipping area of thedrawing and resets it on purpose of the refresh process (lines 6–8).

2 We count up to forty-one invalidating calls scattered across seventeen classes, withstandard extension such as GroupFigure and BorderDecorator included.

Page 11: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

aspect DrawingDamage {2 private Rectangle Drawing . damageArea ;

void Drawing . addDamage( Rectangle newDamage){4 i f ( damageArea == null ) damageArea = newDamage ;

else damageArea . add (newDamage ) ; }6 Rectangle Drawing . getAndResetDamage ( ){

Rectangle r = damageArea ; damageArea = null ;8 return r ; }

}

Fig. 7. The DrawingDamage aspect, which introduces new field and methods in Drawing subclasses forthe invalidation concern

The GetFigureDamage aspect (Fig. 8) supports observation between a figureand its drawing. Similar to the reference to a FigureChangeListener (see Fig. 3,line 2), it introduces in each figure a reference to a drawing (myListeningDrawing,line 3). Registration is directly performed via pointcut and advice (lines 4–8).Notification pointcuts extract all previous method calls to invalidate whichwhere scattered in Figures methods (lines 12–20). The description by pointcutsis not especially shorter but is localized in the aspect. Finally the invalidate ac-tion triggered by advice makes use of the damage interface introduced in Drawing

by DrawingDamage (lines 24–27).The RepairSingleView aspect (Fig. 9) supports the second observer and

the refresh logic (refresh logic was not shown in Sect. 3.2 but follows the sameprinciple). We consider the singleton case for the drawing view: there is no needfor an observer reference. Pointcuts extract requests for screen update (usuallyafter an user operation — line 3). The advice notifies the singleton observer(lines 8–10) which then performs the Swing request (lines 15–16).

The code above shows no more than common benefits we expect from as-pects: scattered code for notifications, structure and methods relevant to theinvalidation concern are localized in aspects. We should note that the invali-dation concern and the Observer pattern are typical examples of crosscuttingconcerns. We now examine issues from Sects. 3.1 & 3.2 with the help of AspectJ.

4.2 Revisiting Composite and Decorator Interactions

We consider the four strategies envisionned in Sect. 3.1 for invalidation of figures.Code from Fig. 8 implements solution B by default. Indeed GroupFigure andBorderDecorator are Figure via their respective superclass. TheGetFigureDamage aspect is oblivious to the dynamic type of Figure instances.

It follows that solution A requires more effort. We must explicitly excludeCompositeFigure and DecoratorFigure from invalidate pointcuts. For examplethe changed pointcut must be rewritten as:

pointcut changed(Figure f):

this(f) && execution(void Figure+.setAttribute(..))

&& !this(CompositeFigure) && !this(DecoratorFigure);

Page 12: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

1 aspect GetFigureDamage {// Reg is t ra t ion of drawing ( observer ) in f i gu r e

3 private Drawing Figure . myListeningDrawing ;po intcut r e g i s t e rF i g u r e (Drawing d , Figure f ) :

5 execut ion ( Figure CompositeFigure . add ( Figure ) )&& this (d) && args ( f ) ;

7 a f t e r (Drawing d , Figure f ) : r e g i s t e rF i g u r e (d , f ) {f . myListeningDrawing = d ; }

9 ( . . . )

11 // Not i f i ca t i on of changespo intcut wil lChange ( Figure f ) :

13 ( execut ion (void Figure+. displayBox ( Point , Point ) )| | execut ion (void Figure+.moveBy ( . . ) ) ) && this ( f ) ;

15 be f o r e ( Figure f ) : wi l lChange ( f ){ i n v a l i d a t e ( f ) ; }a f t e r ( Figure f ) : wi l lChange ( f ){ i n v a l i d a t e ( f ) ; }

17po intcut changed ( Figure f ) :

19 this ( f ) && execut ion (void Figure+. s e tAt t r i bu t e ( . . ) ) ;a f t e r ( Figure f ) : changed ( f ){ i n v a l i d a t e ( f ) ; }

21 ( . . . )

23 // Action on no t i f i c a t i onvoid i n v a l i d a t e ( Figure f ){

25 i f ( f . myListeningDrawing !=null ){f . myListeningDrawing . addDamage( f . displayBox ( ) ) ;

27 } ( . . . ) }}

Fig. 8. Sample from GetFigureDamage aspect, which supports the observer relationship from figures totheir drawing. Pointcuts and advice are used both for registration and notification of the observer.Pointcut willChange (lines 12–15) stands for actions which invalidate both the old bounding box(where the figure used to be) and the new bounding box: such actions (move, resize) are advisedbefore and after their execution (lines 15–16). Pointcut changed (lines 18–19) is used solely for actionswhich modify the inner appearance of the figure but not its bounding box: then notification occursonly after action (line 20)

aspect RepairSingleView {2 // Not i f i c a t i on s ( reques t for update )

a f t e r ( ) : execut ion (void StandardDrawingView . mousePressed ( . . ) ) {4 repairDamage ( StandardDrawingView . in s t ance ( ) . drawing ( ) ) ; }

( . . . )6

// Action on no t i f i c a t i on8 private void repairDamage (Drawing d){

Rectangle r = d . getAndResetDamage ( ) ;10 StandardDrawingView . in s t ance ( ) . repairDamage ( r ) ; }

}12

class StandardDrawingView extends JPanel implements DrawingView {14 ( . . . )

public void repairDamage ( Rectangle r ) { // Swing reques t16 i f ( r != null ) { r epa in t ( r . x , r . y , r . width , r . he ight ) ; }}

}

Fig. 9. Sample from RepairSingleView aspect with singleton view configuration

Page 13: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

This strategy is initially not interesting and loses even more appeal followingsuch constraints. The this(Type) predicate can be translated as a dynamicthis instanceof Type test in some cases.

Solution C is interesting: we do not need to transform the Observer pat-tern into the Chain of Responsibility pattern to get the same effect. Thecase involves solely BorderDecorator: we only target figures which have aBorderDecorator in the chain of parents. If there is to be a change down in thechain, necessarily the clipping area will be that of the top most decorator. Theprocess of detecting the top most decorator and passing it down to the triggeringfigure can be managed by pointcuts:

pointcut targetaction():

execution(void BorderDecorator.setAttribute(..));

pointcut topmostdecorator(BorderDecorator bd):

this(bd) && targetaction()

&& !cflowbelow(targetaction());

pointcut changed(Figure f):

execution(void Figure+.setAttribute(..))

&& cflowbelow(topmostdecorator(f));

after(Figure f): changed(f) { invalidate(f); }

The topmostdecorator pointcut captures any execution of methodsetAttribute which are not in the control flow of another BorderDecorator:the decorator is then the top most. The changed pointcut will capture any ex-ecution of setAttribute which are under a BorderDecorator. But, insteadof notifying invalidate with the current figure, it will use the parameter oftopmostdecorator. The clipping area retrieved by invalidate (Fig. 8, line 26)will be that of the decorator.

The changed pointcut captures all executions below the top most decora-tor, including other decorators. This is not intended: only “leaves” (such asRectangleFigure) will trigger real modifications. Currently there is no mean inthe AspectJ language to capture leaves in the control flow. An extension to thelanguage is proposed in [8]. We could also use !this(DecoratorFigure) suchas in solution A.

Solution D is more simple. We do not want all figures to trigger notifications,when we are sure that they will change. We simply trigger notifications for topmost calls. For example move command can be notified at the top most level, bya figure, a composite or a decorator. The willChange pointcut can be rewritten:

pointcut action(): execution(void Figure+.moveBy(..));

pointcut willChange(Figure f):

this(f) && action() && !cflowbelow( action() );

Preliminary conclusion shows that the AspectJ pointcut language is expres-sive enough to implement the four notification strategies. Contrary to the objectsolution, there is no need to change Figure subclasses, CompositeFigure andDecoratorfigure. However, there is the hidden cost of using AspectJ dynamic

Page 14: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

construct such as cflow. Currently we lack quantitative benchmarks on the per-formance of cflow with respect to the Chain of Responsibility solution,although this is not perceptible in the context of JHotDraw.

4.3 Pluggability of Aspects: Revisiting Multiple Views

Same as the observer in Fig. 4, RepairSingleView does not work with multi-ple views. Yet, we simply build a new RepairMultipleViews aspect (Fig. 10).Contrary to Fig. 5, StandardDrawing is not changed. The framework user canchoose at weaving time which configuration (singleton or multiple views) heneeds. A drawback is that there is no reuse between RepairSingleView andRepairMultipleViews, so that some change in base code could impact bothaspects. However, it is possible to share some definitions (such as pointcuts fornotification) using AspectJ abstract aspect and extension mechanism.

1 aspect RepairMult ip leViews {// (De) r e g i s t r a t i on of drawing views in drawing

3 private List<DrawingView> Drawing . l i s t en i ngV i ews= new LinkedList<DrawingView >() ;

5 po intcut linkViewToDrawing (DrawingView view , Drawing drawing ) :execut ion (void DrawingView+. setDrawing (Drawing ) )

7 && this ( view ) && args ( drawing ) ;b e f o r e (DrawingView v , Drawing d ) : linkViewToDrawing (v , d ){

9 ( . . . )v . drawing ( ) . l i s t en i ngV i ews . remove (v ) ;

11 d . l i s t en i ngV i ews . add (v ) ; }

13 // Not i f i c a t i on s ( reques t for update )a f t e r (DrawingView v ) : this ( v )

15 && execut ion (void StandardDrawingView . mousePressed ( . . ) ) {repairDamage (v . drawing ( ) ) ; }

17 ( . . . )

19 // Action on no t i f i c a t i onprivate void repairDamage (Drawing d){

21 Rectangle r = d . getAndResetDamage ( ) ;for (DrawingView view : d . l i s t en i ngV i ews ) {

23 view . repairDamage ( r ) ; }}}

Fig. 10. Sample from RepairMultipleViews aspect for multiple views (MDI) configuration. Drawing

manages a list of drawing views which are its observers (lines 3–11). Since a view displays one drawingat a time, its registration on a new drawing involves its deregistration from the previous drawing(lines 10–11). Another change from Fig. 9 is the capture of the contextual view during notification(line 14)

5 Discussions

Before concluding, we present two subjects of discussion inspired by this work.They are complementary to this study but, to this day, rely much on subjectiveopinion.

Page 15: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

5.1 Specificity of the AspectJ Solution

The specificity of the cflow-based AspectJ solution in Sect. 4.2 can be comparedto a language where inspection of the execution stack is possible. Of course, acflow construct can be easily emulated in such a language. However, the cflowconstruct combined with aspects allows to easily “compose” modules and pat-terns without modifying the base code. The fact that such a modification canbe modularized simply with a stack inspector remains to be evaluated.

Intertype declaration (previously introduction) is another feature of AspectJwhich is frequently used in pattern implementation (see Figs. 7, 8 or 10). Thisfeature can partially emulate mixin or trait-like reuse [9].

5.2 Avoiding Implementation Overhead in a Field of Patterns

Without a reusable pattern library, programmers need to implement design pat-terns over and over: this leads to “implementation overhead” [10] when it comesto patterns with heavy, repetitive elements. When pattern density rises and thesame pattern is being used over the same classes, there is a natural tendencyin object-oriented languages to fuse concerns together in order to reuse patternimplementation and reduce the overhead. Thus reusability is enhanced at thedepends of separation of concerns. We expose two such cases:

– the Observer pattern in Figure is reused in a “figure connection” concern.Such connections are transversal to the invalidation concern. Typically ob-servers in connection concern implement void methods for the invalidationnotification and vice-versa;

– StandardDrawing implements the Composite pattern to manipulate Figure.In fact, it extends the CompositeFigure to reuse its structure and behav-ior, redefining some methods to accomodate for its nature of Drawing. Thisleads Drawing to copy the interface of CompositeFigure in a brittle relation.StandardDrawing also inherits from Figure a nonsensical subject role.

6 Related Work

The Observer pattern serves as an exercise of choice for aspect languages fea-tures. The instantiation model of Caesar [11] follows more closely the objectmodel of design patterns. Reflex [12] offers a metaphor of metaobjects as ob-servers of hooksets. Many works, such as [13] and [14], deal with modularity andreusability of aspects in the context of design patterns: they contain valuableideas on the way to configure generic aspects for use.

Few other patterns have been studied. One interesting case is the Memento

pattern, for which different attempts with AspectJ have been made [15]. To datethe sole extensive study of single design patterns implementation with aspectsis in [3]. It also contains some evaluation on “composition transparency” forthose new implementations, that is the property to define multiple occurrences

Page 16: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

of the same pattern while keeping them separate. However, it does not explorethe issues of density and composition with other patterns.

[16] revisits the case of pattern density in JUnit [2]. It follows a differentguideline than ours by not aspectizing the pattern but the supported concern.It remains to be shown whether such solutions can be generalized as designpatterns.

7 Conclusion

Summary of problems we review about pattern implementation includes cross-cutting of implementation, invasive modification of a pattern by application ofanother pattern, and tangling of concerns when reuse occurs to reduce overhead.One could argue that such problems are not specific to the implementation ofdesign patterns. However, these are symptoms following the density of designpatterns. These problems must be studied at the level of patterns and softwaredesign to promote their reusability. Software designers should be aware of suchimpacts:

– composition of patterns mean you have to reconsider forces so that you selectanother pattern, with the same concern (see Sect. 3.1);

– lack of reusable patterns itself could lead to tangling concerns in order toreduce implementation overhead.

Overall, there is a feeling that the difficulty in a dense field of patterns does notlie within pattern themselves (which remain what they are) but between them.

We notice AspectJ provides a sum of technologies, some of which (cflow, in-troduction) are not specific to aspects and exist in other languages. Nonetheless,this sum allows to cleanly modularize new concerns and compose them back andforth. It allows to avoid transformations of patterns described above, so that wewere able to retain the basic JHotDraw framework and configure it by selectingaspects. We believe such an approach is valuable in software engineering to tracedesign choices during the development process.

The case of implementation overhead (Sect. 5.2) links to a reusable patternlibrary. We have implemented a composition of Composite, Iterator, andVisitor patterns which remains to be evaluated in the context of JHotDraw(StandardDrawing and CompositeFigure). The approach is to build reusablecompositions based on the reusable single patterns.

Aspectization of patterns opens a new perspective: traceability is enhancedand, in particular, we could benefit from interaction detection [17] and visual-ization tool3. Detection of interactions can lead to automation:

– presence of the Singleton pattern links to a simple implementation of theObserver pattern;

– automatic configuration of pointcuts with cflow-like construct whenever Com-

posite or Decorator patterns are detected;

3 See AspectJ plugin for Eclipse – http://www.eclipse.org/ajdt/

Page 17: Understanding Design Patterns Density with Aspects: A Case … · 2017-01-06 · Understanding Design Patterns Density with Aspects a Case Study in JHotDraw using AspectJ Simon Denier

– automatic registration of the Observer pattern based on registration in theComposite pattern.

Acknowledgements. We would like to thank the anonymous reviewers for theircomments, which help to improve the quality of this article.

References

1. Gamma, E., Helm, R., Johnson, R., Vlissides, J.: Design Patterns: Elements ofReusable Object-Oriented Software. Addison Wesley, Massachusetts (1994)

2. Gamma, E., Beck, K.: JUnit: A Cook’s Tour (2002)http://junit.sourceforge.net/doc/cookstour/cookstour.htm.

3. Hannemann, J., Kiczales, G.: Design pattern implementation in Java and AspectJ.In: Proc. of OOPSLA 2002, ACM Press (2002) 161–173

4. Soukup, J.: Implementing patterns. In: Pattern languages of program design. ACMPress/Addison-Wesley Publishing Co., USA (1995) 395–412

5. Zimmer, W.: Relationships between design patterns. In Coplien, J.O., Shmidt,D.C., eds.: Pattern Languages of Program Design. Addison-Wesley (1994)

6. Kiczales, G., Hilsdale, E., Hugunin, J., Kersten, M., Palm, J., Griswold, W.G.: Anoverview of AspectJ. In Knudsen, J.L., ed.: Proc. of ECOOP 2001, LNCS 2072,Springer-Verlag (2001) 327–353

7. Colyer, A., Clement, A., Harley, G., Webster, M.: eclipse AspectJ. the eclipseseries. Addison-Wesley (2005)

8. Douence, R., Teboul, L.: A crosscut language for control-flow. In: Proc. of GPCE2004, LNCS, Springer-Verlag (2004)

9. Denier, S.: Traits programming with AspectJ. RSTI - L’objet 11(3) (2005) 69–8610. Bosch, J.: Design patterns as language constructs. Journal of Object-Oriented

Programming 11(2) (1998) 18–3211. Ostermann, K., Mezini, M.: Conquering aspects with Caesar. In Aksit, M., ed.:

Proc. of AOSD 2003, ACM Press (2003) 90–9912. Tanter, E., Noye, J., Caromel, D., Cointe, P.: Partial behavioral reflection: Spatial

and temporal selection of reification. In Crocker, R., Steele, Jr., G.L., eds.: Proc.of OOPSLA 2003, ACM Press (2003) 27–46

13. Clarke, S., Walker, R.J.: Composition patterns: An approach to designing reusableaspects. In: Proc. of ICSE 2001. IEEE Computer Society (2001) 5–14

14. Lieberherr, K., Lorenz, D.H., Ovlinger, J.: Aspectual collaborations: Combiningmodules and aspects. Computer Journal of the British Computer Society 46(5)(2003) 542–565

15. Marin, M.: Refactoring JHotDraw’s undo concern to AspectJ. In: Proceedings ofthe 1st Workshop on Aspect Reverse Engineering (WARE 2004). (2004)

16. Isberg, W.: Aop pointcut patterns in the JUnit Cook’s Tour (2005)http://junit.sourceforge.net/doc/cookstour/cookstour.htm.

17. Douence, R., Fradet, P., Sudholt, M.: A framework for the detection and resolutionof aspect interactions. In Batory, D., Consel, C., Taha, W., eds.: Proc. of GPCE2002. LNCS 2487, Springer-Verlag (2002) 173–188