Docsity

design patterns for object oriented programming, Essays (university) of Object Oriented Programming

Toggle sidebar
bg1
Automatic Design Pattern Detection
Dirk Heuzeroth Thomas Holl Gustav Högström Welf Löwe
University of Karlsruhe,Germany
IPD, Program Structures Group
University of VÀxjö, Sweden
MSI, Software Technology Group
{heuzer|holl}@ipd.info.uni-karlsruhe.de [email protected]
Abstract
We detect design patterns in legacy code combining
static and dynamic analyses. The analyses do not depend
on coding or naming conventions. We classify potential
pattern instances according to the evidence our analyses
provide. We discuss our approach for the Observer,
Composite, Mediator, Chain of Responsibility and Visitor
Patterns. Our Java analysis tool analyzes Java programs.
We evaluate our approach by applying the tool on itself
and on the Java SwingSetExample using the Swing
library.
1. Introduction
A major task in software comprehension is the
understanding of its design and architecture. As software
can get large, this task should be supported by tools
performing automatic analyses.
Design, however, is hard to detect automatically, as it
is not tangible. Fortunately, standard solutions to solve
certain design problems have been established. These
design patterns are described together with the design
problem(s) they intend to solve [1]. Many of them have
been formalized, for example to introduce them automa-
tically into software [2]. If it were possible to detect these
patterns in software systems, one would be able to deduce
the intended design.
Components and their ports, connectors between ports,
and the containment relation of components in larger
components define a systemSs architecture [3]. Compo-
nents are coherent classes or coherent smaller compo-
nents (our notion of components is recursive). Connectors
and ports are implemented using basic communication
constructs like calls, RPCs, RMIs, input output routines
etc. provided by the implementation language or the
component system. In contrast to such an implementation,
the ports and connectors themselves abstract from details.
A port defines points in a component that provide data to
its environment and require data from its environment,
respectively. A connector defines out-port and in-port to
be connected and specifies whether data is transported
synchronously or asynchronously [4].
In order to understand architecture, we would prefer to
view a system consisting of components, abstract ports
and connectors. However, legacy (source) code only con-
tains classes, with port and connector implementations
scattered throughout their code.
Fortunately, connectors are often implemented with
design patterns, e.g. the Observer Pattern. Other patterns
indicate a high coherence of classes, e.g., the Composite
Pattern. If it were possible to detect these special patterns
in software systems, it would be easier to deduce the
systemSs architecture.
Design patterns usually have static and dynamic
aspects. A pattern specifies structural connections among
the classes via call, delegation or inheritance relations
(static information). Additionally, it requires some
specific sequences of actions and interactions of the
objects of these classes (dynamic information).
Hence, we propose to analyze the structure and the
behavior of the system with respect to the patterns
indicating the instance of a certain design pattern. This is
necessary, since there are situations, where neither static
nor dynamic analyses alone are sufficient (or not with
acceptable expenses). For example it is statically not
computable, which method or attribute is actually called
or accessed at run time and how often. Even data flow
analyses cannot predict all branches and loops, especially
when the program to be analyzed requires user inter-
actions. As objects are created at run time, relations
among objects are dynamic by nature.
We organize the paper in the following way: Section 2
describes our approach in general. Section 3 describes the
design pattern detection with the Observer Patterns as a
running example in detail. Section 4 discusses similar
approaches for the other patterns. Section 5 evaluates our
results in practical experiments. Section 6 sketches an
approach of a general generator of pattern analyses based
on our experiences with the patterns discussed so far.
pf3
pf4
pf5
pf8
pf9
pfa

Partial preview of the text

Download design patterns for object oriented programming and more Essays (university) Object Oriented Programming in PDF only on Docsity!

Automatic Design Pattern Detection

Dirk Heuzeroth Thomas Holl Gustav Högström Welf Löwe

University of Karlsruhe,Germany

IPD, Program Structures Group

University of VÀxjö, Sweden

MSI, Software Technology Group

{ heuzer | holl } @ipd.info.uni-karlsruhe.de [email protected]

Abstract

We detect design patterns in legacy code combining static and dynamic analyses. The analyses do not depend on coding or naming conventions. We classify potential pattern instances according to the evidence our analyses provide. We discuss our approach for the Observer, Composite, Mediator, Chain of Responsibility and Visitor Patterns. Our Java analysis tool analyzes Java programs. We evaluate our approach by applying the tool on itself and on the Java SwingSetExample using the Swing library.

1. Introduction

A major task in software comprehension is the understanding of its design and architecture. As software can get large, this task should be supported by tools performing automatic analyses. Design , however, is hard to detect automatically, as it is not tangible. Fortunately, standard solutions to solve certain design problems have been established. These design patterns are described together with the design problem(s) they intend to solve [1]. Many of them have been formalized, for example to introduce them automa- tically into software [2]. If it were possible to detect these patterns in software systems, one would be able to deduce the intended design. Components and their ports, connectors between ports, and the containment relation of components in larger components define a system’’s architecture [3]. Compo- nents are coherent classes or coherent smaller compo- nents (our notion of components is recursive). Connectors and ports are implemented using basic communication constructs like calls, RPCs, RMIs, input output routines etc. provided by the implementation language or the component system. In contrast to such an implementation, the ports and connectors themselves abstract from details. A port defines points in a component that provide data to

its environment and require data from its environment, respectively. A connector defines out-port and in-port to be connected and specifies whether data is transported synchronously or asynchronously [4]. In order to understand architecture, we would prefer to view a system consisting of components, abstract ports and connectors. However, legacy (source) code only con- tains classes, with port and connector implementations scattered throughout their code. Fortunately, connectors are often implemented with design patterns, e.g. the Observer Pattern. Other patterns indicate a high coherence of classes, e.g., the Composite Pattern. If it were possible to detect these special patterns in software systems, it would be easier to deduce the system’’s architecture. Design patterns usually have static and dynamic aspects. A pattern specifies structural connections among the classes via call, delegation or inheritance relations (static information). Additionally, it requires some specific sequences of actions and interactions of the objects of these classes (dynamic information). Hence, we propose to analyze the structure and the behavior of the system with respect to the patterns indicating the instance of a certain design pattern. This is necessary, since there are situations, where neither static nor dynamic analyses alone are sufficient (or not with acceptable expenses). For example it is statically not computable, which method or attribute is actually called or accessed at run time and how often. Even data flow analyses cannot predict all branches and loops, especially when the program to be analyzed requires user inter- actions. As objects are created at run time, relations among objects are dynamic by nature. We organize the paper in the following way: Section 2 describes our approach in general. Section 3 describes the design pattern detection with the Observer Patterns as a running example in detail. Section 4 discusses similar approaches for the other patterns. Section 5 evaluates our results in practical experiments. Section 6 sketches an approach of a general generator of pattern analyses based on our experiences with the patterns discussed so far.

Section 7 compares our result to related works. Finally, Section 8 concludes the results and points to directions of future work.

2. General Approach

A design pattern instance is defined by a tuple of program elements such as classes, methods or attributes conforming to the restrictions or rules of a certain design pattern. An example of such a tuple for an instance of an Observer Pattern is: (Subject.addListener, Subject.removeListener, Subject.notify, Listener.update) We distinguish the role of a class in a pattern from the program element itself. Observer and Observable, e.g., are roles of classes in the Observer Pattern. SomeObserverClass and^ AnObservableClass can be two concrete classes in the two roles. Moreover, we even distinguish an object instance from a design pattern instance, if the latter contains class program elements. As an example consider, that we could have different object instances of SomeObserverClass each with several object instances of AnObservableClass, or, e.g. AnotherObservable attached to it. Our analyses distinguish between static and dynamic pattern restrictions or rules. The former restrict the code structure the latter the runtime behavior. Analyzing with the static restrictions results in a set of candidate occur- rences in the code. In practice this set is large and pro- grammers hardly want to screen all of them to detect the actual instances. Therefore, we execute the program under investigation and monitor the executions of the candidate instances found by the static analysis with respect to the dynamic restrictions. Figure 1 illustrates our approach.

Figure 1. Static and Dynamic Analyses of Patterns.

The results of dynamic analyses depend on an exe- cution of the candidate instances. Methods not executed at run time cannot be evaluated with respect to the dynamic pattern thus providing no information. However, testing techniques and environments could guarantee that each reachable program part is executed while testing (of course not every program sequence). Using these tech- niques, we may consider dynamic information available for each candidate occurrence. Moreover, we argue that

parts that are less frequently executed are also less critical for understanding. For the understanding of a system's architecture, intra- component communications patterns are less important. We thus have the option to perform component pattern analysis first and filter the candidates for communication patterns inside components, leading to a tremendous reduction of communication pattern candidates. However, as our analyses are fast enough, we do not do so. Instead, we use the information on high-level connectors in the code as an additional indication for the correct partitio- ning of the legacy system into its components. The hypothesis behind this is that components have an elaborated interaction interface to other components while intra-component interactions are often implemented ad hoc. Hence, we expect many sources and targets of com- munication patterns to reside in different components when choosing the right partitioning into components while many of the essential communications become intra-component for a partitioning not intended. Unfortunately, the analyses are not unique. Hence, the process of pattern and architecture detection is an iterative, interactive process where analyses and visuali- zations complement on another. However, visualizations are not focused in this paper, we have discussed them in more detail in another paper [5]. The static analyses are done with Recoder [6], a tool to read, analyze and manipulate Java programs. In principle, Recoder is a compiler front end. It reads the source code and constructs the abstract syntax tree (AST). Then it performs the static semantic analyses where it resolves names and types. In addition to the semantic analyses required by the programming language, it can compute additional relations over the syntactical and semantic elements, e.g. define-use-relations. It has a programmer interface to add new, user-defined analyses for the computation of arbitrary relations. In contrast to standard compilers, Recoder provides all these entities and relations as an API. In order to analyze the structure of a program, we simply write a program accessing this interface. The elements of candidates of pattern instances retrieved by the static analysis are nodes in the AST accessible via Recoder. Examples of such elements are classes and methods that potentially play different roles in a pattern. These program parts are then instrumented using the code manipulation interface of Recoder. We simply add appropriate event generators tracing the dynamic execu- tion of the candidates and providing runtime information. Dynamic analyses are the corresponding event handlers, checking that the protocol of the candidate execution conforms to the expected dynamic pattern restrictions. Although, currently Recoder investigates Java sour- ces only, the approach and the architecture can be applied to sources written in any typed language.

This results in the following static analysis algorithm that computes the static candidates C :

C := ∅ for each class c do Y := ∅ // intermediate result for each method m in c do for each parameter type p in m where p ⊄ c ∧ c ⊄ p ∧ c ≠ p do for each call from c.n to p.u do if isNotifyListener (c.n,^ p.u) Y := Y âˆȘ {(c.m, c.n, p.u)}

for each (c.a1,c.n1,p1.u1) ∈ Y do for each (c.a2,c.n2,p2.u2) ∈ Y , where c.n1 = c.n2 ∧ p1.u1 = p2.u2) do if ( isAddListener (c.a1)) if (c.a1 = c.a2) C := C âˆȘ (c.a1, null, c.n1, p1.u1) else C := C âˆȘ (c.a1, c.a2, c.n1, p1.u1)

Although the candidate set is computed quite efficiently by the directed search algorithm, we still face the problem of being too conservative with our approxi- mation: the candidate set is large compared to the set of actual pattern instances and not appropriate for providing it to the system designer as it is. There are three possible solutions: expert knowledge like coding and naming conventions, dynamic analysis, or static data flow analysis. We choose dynamic analyses.

3.2. Dynamic Analysis

The static analysis provided tuples of AST nodes in the candidate set C. The dynamic analysis takes this set C as its input. It monitors the execution of the nodes of every tuple. It further tracks the effects of the executed nodes to check whether the candidate satisfies the dynamic pattern rules. In case of a rule violation, the candidate is rejected. Each element of a candidate tuple is contained in a class definition or is a class definition itself. At runtime we might have many object instances of these classes and each should conform to the dynamic pattern. Additionally, patterns require n:m , 1:n , or 1:1 relations among objects of the implementing classes. For each individual candidate tuple, the number of instance objects of their classes could be restricted. The Observer Pattern, e.g., requires a 1:n relation of the subject instances and their listener instances. Moreover, we might have more than one instance of the Observer Pattern defined by the different subject and listener classes. Altogether, we trace a set of instances for each candidate tuple of a pattern. Each may contain several

objects per position in the tuple. Considering our Observer Pattern, we thus assign to every candidate tuple (S.addListener, S.removeListener, S.notify, L.update), cf. Section 3.1, a set of instance tuples (s.addListener, s.removeListener, s.notify, {l 1 .update 
 ln .update}) where s is an instance (object) of class S and l 1 
 ln are instances of L. It is not necessary to store the subject s three times. Further- more, the addListener , removeListener, notify, and update methods are always the same and already captured in the candidate tuple. To avoid redundancies, we only associate a set of tuples (s, { l 1 
 ln } ). We monitor each node in a tuple of the candidates. Whenever we dynamically execute such a monitored node, we retrieve the entire candidate tuples in which the node is contained. Depending on the node's unique role in each single tuple, we execute dynamic test actions on the object sets associated to the corresponding candidate tuples. In the Observer Pattern, we use the subject object as a key to retrieve the affected object set of each candidate tuple. To determine the proper object set, we distinguish two cases: If the method complies with the addListener, removeListener or notify roles, then the key subject object is the object the method is called on. If the method complies with the update role, then the key subject object is the object the corresponding notify method is called on. The dynamic test actions for the Observer Pattern depend on the role of the method: addListener: We add the passed argument to the subject's list of listener objects. No protocol mismatch can be detected here. removeListener : We remove the passed argument from the subject's list of listener objects. A protocol mismatch occurs, if the listener to be removed has not been added before. This can also be caused by a programming error. We therefore allow turning off this criterion. notify : We do not change the set of subject or listener objects. A correct protocol updates all or no listener objects (atomic update). To check this protocol, we have to distinguish between the method entry and the method exit. At the method entry, we mark all attached listener objects as not updated. At the method exit we check whether all or no listener objects have been marked as updated. In this case, the protocol is satisfied. The other case indicates a protocol violation. To accept the case of not updating any listener objects as a protocol match makes sense, because notify may be called, although the subject's state did not change. Then there is no need to notify the attached listeners. update : We do not change the set of subject or listener objects. If the update method has been called by the notify method of the same candidate tuple, we mark the listener object as updated. To recognize this, we need to

detect the source of the method call, a functionality to be provided by the dynamic framework. A call of update by the corresponding notify method is a protocol mismatch if the listener object has not been attached previously.

4. Further Patterns

So far, we only discussed the detection of just one pattern, the Observer Pattern. In the same way, as we detected this pattern, we also implemented static and dynamic analyses to detect the Composite, Mediator, Chain of Responsibility and Visitor Patterns [1].

4.1. Composite Pattern

4.1.1 The Static Analysis algorithm is given below:

C := ∅ for each class c do Y := ∅ // intermediate result for each method m in c do for each parameter type p in m where c ⊂ p do for each call from c.o to p.o do if isCompositeOperation (c.o, p.o) Y := Y âˆȘ {(c.m, c.o, p.o)}

for each (c1.a,c1.o,p1.o) ∈ Y do for each (c2.a,c.o,p2.o) ∈ Y do if ( isAddComponent (c1.a)) if (c1.o = c2.o ∧ p1.o = p2.o) if (c.a1 = c.a2) C := C âˆȘ (c.a1,null,c.n1,p1.u1) else C := C âˆȘ (c.a1,c.a2,c.n1,p1.u1)

The predicate isAddComponent exactly corresponds to the isAddListener predicate and the isComposite- Operation predicate exactly corresponds to the isNotify- Listeners predicate. The main difference between the two patterns is the intended decoupling of classes: The Observer Pattern requires the Observers and Observable to be unrelated; the Composite Pattern requires Component and Composite to satify a subtype relation. It is obvious, that this algorithm is similar to the static analysis for the Observer Pattern and was therefore easy to encode.

4.1.2 The Dynamic Analysis was even easier to port, since both patterns do not differ in their protocol. Hence, we applied the dynamic analysis algorithm of the Observer Pattern detection unmodified.

4.2. Mediator Pattern

A Mediator pattern consists of at least two classes both with a reference to each other. In general, a central Mediator has arbitrary many users. The Mediator refers to every User. Users in turn are connected back to their Mediator. Usually, the User is attached to the Mediator at construction. Later attachment by a method call is possible, as well.

4.2.1 The Static Analysis checks for every class (potential Mediator) if it has variables pointing to a User knowing that Users have a variable of the Mediator’’s class or its superclass. The User must have the Mediator class as an argument in its constructor or in at least one other method. It is not possible that the Mediator and its Users are of same type. As it does not make sense to implement a Mediator pattern with only one User, we reject candidates with only one possible user variable in the Mediator:

C := ∅ for each class c do Y := ∅ // intermediate result for each variable v in c do for each class u := class(v) do for each variable v’ in u do if c=class(v’) √ c ⊂ class(v’) Y := Y âˆȘ {(c,v,u,v’)}

for each (c,v,u,v’) ∈ Y do for each method m in u do if “v’:= 
” in body(m) for each parameter p in m do if c=class(p) √ c ⊂ class(p) C := C âˆȘ {(c,v,u,v’,m)}

To avoid redundant storing, {(c,v 1 ,u 1 ,v’ 1 ,m 1 ), (c,v 2 ,u 2 ,v’ 2 ,m 2 ), 
} is reduced to {(c, {v 1 ,v 2 ,
}, {u 1 ,u 2 ,
}, {v’ 1 ,v’ 2 ,
}, {m 1 ,m 2 ,
} ), 
 }.

4.2.2 The Dynamic Analysis distinguishes different Mediator objects for a Mediator candidate class (^) M and different objects for all its User classes U 1 
 Un. Again, the variables pointing to the User and the method receiving the Mediator reference are stored in the candidate and need not to be captured in the dynamic tuple of objects (mObject, { u 1 
 u (^) n } ). Whenever the method m handing over the Mediator object to the User object is invoked, it is checked whether it send a self-reference to the mediator object. Whenever, the body of that method is executed, it is checked whether this object reference is actually stored in the Mediator typed variable (^) v’ in the User.

To continue the verifying process, we applied our tool to the source code of our tool itself including the Recoder packages. In this code the Observers were well documented. Hence we were able to count false positives and true negatives. Then we applied it to the SwingSet2 example of the JDK 1.3.1 including the javax.swing.* packages. In order to determine the number of Observers in this unkown software, we trusted the strict naming conventions of SUN's library programmers. We firstly issued a

grep"add\wListener\w{"

and checked the hits manually for correctness. To catch Observer Pattern instances violating the naming conventions, as well, we also screened the output of our tool and added the remaining occurrences. An example of an Observer Pattern instance violating the naming conventions is the DefaultTableColumnModel in the javax.swing.table package with methods addColumn in the^ addListener -role,^ removeColumn in the removeListener-role and recalcWidthCache in the notify -role. This procedure yields a fairly good approximation of the number of Observer Patterns really contained in the code. Finally, we analyzed the other patterns. Unfortunately, these patterns have not been documented that well and no naming conventions applied. Hence, we only excluded the detection of false positives by screening the analysis results. An estimation of true negatives was not possible.

5.1. Observers in our Analyzer Tool

Statistics about our analysis tool including the Recoder package are given in Table 1.

Table 1. Statistics on our tool including the Recoder. Classes Methods Observers 1 Recoder 555 6734 2 VizzAnalyzer 43 214 3 Sum 598 6948 5

The main task of the static algorithm is to reduce the amount of candidates. In case of the Observer Pattern detection, the amount of possible candidates is equal to 9.7× 1013 calculated by the formula:

žž^ +

(^1) Subjects used neither delegation nor sub-classes of subjects.

The former term accounts for the 6948 methods in the 4 possible roles, the latter term models tuples with empty removeListener role. Our static analysis applies the isAddListener and isNotifyListeners predicates as main criteria to reduce this amount of candidates to 28030 tuples containing all 5 Observer Pattern occurrences. The corresponding analysis phase needs about 70 seconds on a Pentium III, 500Mhz, 256MB RAM, running Windows NT 4 with JDK 1.3.1. Table 2 shows the results of the dynamic analysis. The ““Detected”” row lists the numbers of tuples of the corres- ponding category detected by our tool, whereas the ““Real”” row lists the number of tuples of the correspon- ding category that represent real Observer occurrences.

Table 2. Results of dynamic analysis of our analysis tool. Full 1:n match

Full 1: match

May match

No decision

Mis- match

Detected 4 5 67 18638 9316 Real 4 0 0 1 0

The Full 1:n match category shows that our tool classified all Observer Pattern occurrences used in that program run correctly. The Full 1:1 match column reveals that delegation confuses our analyses. The reason is, that delegation shows the same static and dynamic properties as the Observer Pattern. The only difference is that delegation always constitutes a 1:1 relation. This is one of the reasons the static algorithm produces a lot of false positives. The following code fragment illustrates this effect:

class Delegate { X delegate;

//is detected as addListener void set(X x) { delegate =x;}

//is detected as notify void internalAction(){delegate. ();} }

A 1:1 relation is suspicious, but need not be a mismatch, since this may be a valid configuration of the Observer Pattern. In case the (^) set method of (^) Delegate objects is called many times followed by a call of doSomething, our algorithm detects doSomething 's violations of the notify role. In our case, all 5 tuples in the Full 1:1 match class were actually delegations. The May match class contains no Observer occurrence. In over 70% of the tuples, either only the addListener or only the notify method was called, but these methods cannot provoke a protocol mismatch. The Observer Pattern tuple in category No decision has not been executed, and therefore not been classified.

If we ensured by employing testing technology that every candidate method gets executed, we could classify all tuples and thus achieve an empty No decision set. All detected mismatches were correct, i.e., these tuples did not represent an implementation of the Observer Pattern.

5.2. Observer in the SwingSet2 Example

To evaluate the quality of our analyses in this case study, we first need to determine the number of Observer Pattern occurrences in the example code. Since SUN's developers obey naming conventions, we found quite a few pattern occurrences. To catch also Observer pattern occurrences violating the naming conventions, we screened the output of our tool and added the remaining occurrences. This procedure yields a fairly good approximation of the number of Observer patterns actually contained in the code and results in the statistics presented in Table 3.

Table 3. Statistics about the SwingSet2 example including javax.swing.* packages. Classes Methods Observers 2 Swing 1357 11478 59 SwingSet2 124 403 0 Sum 1481 11881 59

The high number of 59 Observer Pattern occurrences in Table 3 results from our way of counting: Since we identify the particular method roles, a subject class containing several notify methods contributes to multiple Observer Pattern occurrences. We count every such combination as one separate occurrence. In the same way as in the previous case study, the static analysis reduces the number of 8.3× 10 14 possible candidates to 200 738 tuples containing all 59 Observer Pattern occurrences. The corresponding analysis phase needs about 190 seconds on a Pentium III, 500Mhz, 256MB RAM, running Windows NT 4 with JDK 1.3.1.

Table 4. Results of dynamic analysis for the SwingSet example. Full 1:n match

Full 1: match

May match

No decision

Mis- match

Detected 13 805 36 85620 114264 Real 13 20 2 24 0

Table 4 shows the results of the dynamic analysis. The ““Detected”” row lists the numbers of tuples of the corres- ponding category detected by our tool, whereas the

(^2) Subjects using neither delegation nor sub-classes of subjects.

““Real”” row lists the number of tuples of the correspon- ding category that represent real Observer occurrences. The results show that all 13 Observer Pattern occurrences in the full 1:n match category have been classified correctly by our analyses. Besides the 20 real Observer Pattern occurrences the Full 1:1 match category again contains a lot of Delegation Pattern occurrences as in the Recoder example. The same holds for the May match category. Note that the Mismatch category again does not contain a real Observer Pattern occurrence, i.e., all detected mismatches were correct.

5.3. Further Patterns

To validate our analyses algorithms for the Mediator, Chain of Responsibility and Visitor Patterns, we applied them to our tool itself. We first discuss the results of the static analyses and then those of the dynamic analyses. The results from the static analyses are each presented as a table of the detected candidate tuples. The static analysis of the Mediator Pattern detected 298 possible tuples. The high number of candidates can be misleading, but one pattern instance may lead to a set of candidate tuples, because we consider all possible combinations of roles. The static analysis of the Chain of Responsibility Pattern provided 349 tuples. The tuples represent elements of the chain linked together and not a whole chain because a static analysis cannot conclude how the instances of the classes are connected together. Only a bunch of different elements probably linked together somehow are detected statically. In some cases, there were just only one possible class that the chain is constituted from. However, at runtime a long chain of objects of that instance are observed. The high number of tuples is somewhat misleading: The highest number of different classes that potentially constitute a Chain of Responsibility was seventeen; all classes issued a call to the same method of a common super class. The analysis has not included a detection of these superclass calls. This is not a restriction, as they will be detected anyway during the analysis of the superclass. When used in visualizations, the analyzed Recoder application visits all AST nodes and presents them in some way. In this setting, we detected the PrettyPrinter class as a Visitor. The program has implemented a subclass of the PrettyPrinter and the analysis detected 1701 different pairs of instances that can constitute the whole Visitor pattern. That also included some possible subclasses. The high number of detected elements can be seen as very misleading, most of the detected pairs were connected to the same visitor and they had the same Accept methods. This fact can also be

part of a pattern requires defining the data structure for the simulator and the actions to perform. It thus corres- ponds exactly to giving an implementation for the dyna- mic analysis, i.e., to the event handlers. However, events are generated automatically. The code is instrumented automatically at the statically recognized candidates, usu- ally method entries and exits and hands over parameters. These predefined hooks for the event listeners checking the dynamic pattern simplify the task significantly. At the moment, we are already able to generate the presented analyses to detect the Observer Pattern. To validate that our specification language and the generator are general enough, we currently try to detect the Media- tor Pattern as well. The problem is to keep the language small and simple enough so that pattern specifications are at the right level of abstraction and more appropriate than directly coding the analysis algorithms.

7. Related Work

Quite a bit of work has already been done in the field of automatic pattern detection. Keller et al. [8] describe a static analysis to discover design patterns (Template Method, Factory Method and Bridge) from C++ systems. The authors identify the necessity for human insight into the problem domain of the software at hand, at least for detecting the Bridge pattern due to the large number of false positives. The Pat system [9] detects structural design patterns by extracting design information from C++ header files and storing them as Prolog facts. Patterns are expressed as rules and searching is done by executing Prolog queries. Brown [10] uses dynamic information, analyzing the flow of messages. His approach is restricted to detecting design patterns in Smalltalk, since he only regards flows in VisualWorks for Smalltalk. He therefore annotates the Smalltalk runtime environment. Another drawback is, that he only gathers type information at periodic events. Carriere et al. [11] also employ code instrumentation to extract dynamic information to analyze and transform architectures. The presented approach only identifies communication primitives, but no complex protocols. The present paper extends our previous results [7] in two ways. Firstly, it implements more than the Observer Pattern analyzer and extends the experiments to unknown code. These extensions show that the results (and shortcomings in the dynamic analysis) can be generalized. Secondly, it sketches our approach to and first results of automatic generation of analyses.

8. Conclusion

We presented an approach to support the understanding of software systems by detecting design

patterns automatically. We use static and dynamic analyses. More specifically, we filtered information gained by static pattern detection on the code using the observations of dynamic code execution. This approach improves the quality of the results tremendously as protocol conformance of a pattern can be checked. We argued that neither static nor dynamic analyses by themselves provide an adequate approach to find patterns in software systems. The number of false positives is small, in most experiments even zero. However, if pattern candidates are not executed during the dynamic analyses we cannot provide any evidence for its conformance to or its violation of the protocol. Hence the number of true negatives could be large. Currently, we try to apply results from test theory to ensure that every (reachable) candidate gets eventually executed. To further reduce the true negatives, we plan to integrate data flow analyses and checking of naming conventions into our static analyses.

9. References

[1] Gamma, E; R. Helm, R. Johnson, and J. Vlissides (1995), ““Design Patterns: Elements of Reusable Object-Oriented Software””, Addison-Wesley Professional Computing Series, Addison-Wesley Publishing Company, New York, NY. [2] Genssler, T.; B. Mohr, B. Schulz and W. Zimmer (1998), ““On the Computer Aided Introduction of Design Patterns into Object-Oriented Systems””. In Proc. 27th TOOLS. [3] D. Garlan, M. Shaw (1993), ““An Introduction to Software Architecture””, In Advances in Software Engineering and Knowledge Engineering, vol. 1, World Scientific Publishing Company, Singapore, pp. 1-40. [4] Heuzeroth, D., W. Löwe, A. Ludwig, and U. Aßmann (2001), ““Aspect-Oriented Configuration and Adaptation of Component Communication””, In 3rd Int. Conf. GCSE, Springer, LNCS 2186, p. 58 ff. [5] Heuzeroth, D. and W. Löwe (2003), ““Understanding Architecture Through Structure and Behavior Visualization”” In: Kang Zhang (Ed.). ““Software Visualization - From Theory to Practice””, Kluwer Academic Publishers. [6] Ludwig, A., R. Neumann, U. Aßmann, and D. Heuzeroth (2001), ““RECODER Homepage””, http://recoder.sf.net. [7] Heuzeroth, D., T. Holl, and W. Löwe (2002), ““Combining Static and Dynamic Analyses to Detect Interaction Patterns””, In Proc. 6th Int. Conf. IDPT. [8] Keller, R. K., R. Schauer, S. Robitaille, and P. Page (1999), ““Pattern-Based Reverse-Engineering of Design Components””, In Proc. ISCE, pp. 226-235. [9] Prechelt, L. and C. KrĂ€mer (1998), ““Functionality versus Practicality: Employing Existing Tools for Recovering Structural Design Patterns””, J.UCS: 4, 12, 866ff. [10] Brown, K. (1997), ““Design Reverse-Engineering and Automated Design Pattern Detection in Smalltalk””, Master Thesis, Univserity of Illinois at Urbana-Champaign [11] Carriere, S. J., S. G. Woods, and R. Kazman (1999), ““Software Architectural Transformation””, In Proc. 6th WCRE.