Title: Design Pattern Detection
1Design Pattern Detection
2Design Patterns
- A design pattern systematically names, explains
and evaluates an important and recurring design
problem and its solution - Good designers know not to solve every problem
from first principles - They reuse solutions
- This is very different from code reuse
- Software practitioners have not done a good job
of recording experience in software design for
others to use
3Design Patterns 2
- Definition
- We propose design patterns as a new mechanism
for expressing object oriented design experience.
Design patterns identify, name and abstract
common themes in object oriented design. They
capture the intent behind a design by identifying
objects, collaborations and distribution of
responsibilities. - Erich Gamma, Richard Helm, Ralph Johnson, John
Vlissides ,Design Patterns, Addison-Wesley,
1995. ISBN 0-201-63361-2
4Others On Design Patterns
- Christopher Alexander
- Each person describes a problem which occurs
over and over and over again in our environment
and then describes the core of the solution to
that problem, in such a way that you can use this
solution a million times over, without ever doing
it the same way twice. - Cunningham
- Patterns are the recurring solutions to the
problem of design. People learn patterns by
seeing them and recall them when need be without
a lot of effort
5Others On Design Patterns 2
- Booch
- A pattern is a solution to a problem in a
specific context. A pattern codifies specific
knowledge collected from experience in a domain.
6Patterns Frameworks
- Patterns support reuse of software architecture
and design - They capture static and dynamic structures of
successful solutions to problems. These problems
arise when building applications in a particular
domain - Frameworks support reuse of detailed design and
program source text - A framework is an integrated set of components
that collaborate to provide a reusable
architecture for a family of related applications
7Patterns Frameworks  2
- Frameworks tend to be less abstract than patterns
- Together, design patterns and frameworks help to
improve key quality factors like reusability,
extensibility and modularity
8Design Problems
- Finding appropriate classes
- Determine class granularity
- how abstract, how correct
- Specify interfaces
- Specify implementation
- Put reuse to work
- Client vs inheritance
- Relate run time and compile time structures
- program text may not reflect design
9Design Problems  2
- Design for change is difficult
- Common problems
- Explicit object creation
- Dependence of particular operations
- avoid hard coded operations
- Dependencies on hardware or software platforms
- Dependencies of object representation
- Dependencies on algorithms
- Tight coupling
10Claims of the Pattern Community
- Well defined design principles have a positive
impact on software engineering - Achievable reusability
- Provide common vocabulary for designers
- communicate, document, explore alternatives
- Patterns are like micro architectures
- Useful for building small parts of a system
- Reduce the learning time for understanding class
libraries - Avoid redesign stages by using encapsulated
experience
11When to Use Patterns
- Solutions to problems that recur with variations
- No need for pattern if the problem occurs in only
one context - Solutions that require several steps
- Not all problems need all steps
- Patterns can be overkill if solution is a simple
linear set of interactions - Solutions where the solver is more interested in
does there exist a solution? than in a
solutions complete derivation - Patterns often leave out lots of detail
12Pattern Benefits
- Enable large scale reuse of software
architectures - Explicitly capture expert knowledge and design
trade-offs - Help improve developer communication
- Help ease the transition to OO methods
13Pattern Drawbacks
- Patterns do not lead to direct code reuse
- Patterns are often deceptively simple
- You may suffer from pattern overload
- Patterns must be validated by experience and
debate rather than automated testing - Integrating patterns into a process is human
intensive rather than a technical activity
14General Template
- Name
- Intent
- What does the pattern do? What problems does it
address? - Motivation
- A scenario of pattern applicability
- Applicability
- In which situations can this pattern be applied
- Participants
- Describe participating classes/objects
15General Template  2
- Collaborations
- How do the participants carry out their
responsibilities? - Diagram
- Graphical representation of the pattern
- Consequences
- How does the pattern support its objectives?
- Implementation
- Pitfalls, language specific issues
- Examples
- From real systems
16Classification
- Structural
- Deal with decoupling interface and implementation
of classes and objects - Adapter, Facade, Decorator
- Behavioural
- Deal with dynamic interaction among collections
of classes and objects - Visitor, Iterator, Master-Slave
- Creational
- Deal with initializing and configuring
collections of classes and objects - Prototype, Abstract Factory, Builder
17Adapter Pattern
- Intent
- Convert the interface of a class into another
interface that the client expects. - Lets classes work together that couldn't
otherwise - Motivation Applicability
- Reuse of classes
- class is not reusable because its interface does
not match the domain-specific interface - If a class with a different, or incompatible,
interface is expected, we do not want to change
the reusable classes to suit the new application
18Adapter  Example
- EDITOR expects a SHAPE
- TEXT_VIEW is not a SHAPE
- TEXT is a SHAPE
- Features are mapped (body calls relevant method)
to TEXT_VIEW
SHAPE
EDITOR
TEXT
FIGURE
TEXT_VIEW
19Adapter Applicability
- Want to use an existing class but its interface
does not match the one you need - Want to create a reusable class that cooperates
with unrelated or unforeseen classes with
incompatible interfaces
20Facade Pattern
- Intent
- Provide a common interface to a set of interfaces
within a subsystem - Defines a higher level interface that should make
the subsystem easier to use - Motivation
- Structuring a system into subsystems reduces
complexity - A common design goal is to minimize communication
between subsystems
21Facade Diagram
Clients
Facade
Subsystem classes
22Facade  Applicability
- Want to provide a simple interface to a
collection of complex subsystems - Provide a simple default view
- As systems grow, classes become smaller more
refined - Better for reuse
- More difficult for clients to use
23Facade  Applicability  2
- Decouple subsystems from clients
- Reduce implementation dependencies
- Layer your subsystems
- Each layer has a single entry point
- Layers communicate only through Facade interface
24Facade Participants, Example
- Facade
- Compiler
- Knows which subsystem classes are responsible for
a request - Delegates client requests to appropriate
subsystem objects - Subsystems
- Scanner, Parser, Code Generator etc.
- Implement system functionality
- Handle work assigned by Facade object
- Have no knowledge of the facade
- Keep no references to it
25Facade Collaborations
- Clients communicate with the subsystem by sending
requests to Facade - Facade forwards requests to subsystem
- Facade may have to translate its interface to
subsystem interface (use Adapter) - Clients that use facade don't have direct access
to the subsystems
26Facade Consequences
- Benefits
- Shields clients from subsystem components
- Reducing number of objects clients deal with
- Promotes weak coupling between subsystems and
clients - Can vary components of subsystem without
affecting clients - Doesn't prevent expert clients from direct access
to subsystems - Choice between ease of use and generality
27Decorator Pattern
- Intent
- Attach additional responsibilities to an object
dynamically. - Provide a flexible alternative to subclassing for
extending functionality
28Decorator Motivation
- Motivation Applicability
- Want to add responsibility to individual objects
not to entire classes - Add properties like border, scrolling, etc to any
user interface component as needed - Enclose object within a decorator object for
flexibility - Nest recursively for unlimited customization
29Decorator Example
- Compose a border decorator with a scroll
decorator for text view.
a_border_decorator
component
a_scroll_decorator
component
a_text_view
30Decorator Example Diagram
VISUAL_COMPONENT
draw
DECORATOR
TEXT_VIEW
draw
component VISUAL_ COMPONENT
BORDER_DECORATOR
SCROLL_DECORATOR
draw border_width draw_border
draw scroll_position scroll_to
31Decorator Applicability
- Add responsibilities to individual objects
dynamically and transparently - Without affecting other objects
- For responsibilities that can be withdrawn
- When subclass extension is impractical
- Sometimes a large number of independent
extensions are possible - Avoid combinatorial explosion
- Class definition may be hidden or otherwise
unavailable for subclassing
32Decorator General Structure
COMPONENT
method
CONCRETE_COMPONENT
DECORATOR
component COMPONENT
method
CONCRETE_DECORATOR_B
CONCRETE_DECORATOR_ A
method another_feature
method other_feature
33Decorator Participants
- Component
- defines the interface for objects that can have
responsibilities added to them dynamically - Concrete component
- Defines an object to which additional
responsibilities can be attached - Decorator
- Maintains a reference to a component object and
defines an interface that conforms to COMPONENT - Concrete decorator
- Add responsibilities to the component
34Decorator Consequences
- Benefits
- More flexibility than static inheritance
- Can add and remove responsibilities dynamically
- Can handle combinatorial explosion of
possibilities - Avoids feature laden classes high up in the
hierarchy - Pay as you go when adding responsibilities
- Can support unforeseen features
- Decorators are independent of the classes they
decorate - Functionality is composed in simple pieces
35Decorator Consequences  2
- Liabilities
- From object identity point of view, a decorated
component is not identical - Decorator acts as a transparent enclosure
- Cannot rely on object identity when using
decorators - Lots of little objects
- Often result in systems composed of many look
alike objects - Differ in the way they are interconnected, not in
class or value of variables - Can be difficult to learn and debug
36Iterator Pattern
- Intent
- Access elements of a container sequentially
without exposing the underlying representation - Motivation
- Be able to process all the elements in a
container - Different iterators can give different sequential
ordering - Binary tree
- preorder, inorder, postorder
- Do not need to extend container interface
37Iterator Structure Diagram
ITERATOR
CONTAINER
next allDone item
size add remove
CONCRETE_ITERATOR
make_1 make_2 next allDone item
38Iterator  Applicability
- Access a containers contents without knowing
about or using its internal representation - Support multiple traversals
- Provide a uniform interface for traversing a
containers contents - Support polymorphic iteration
39Iterator  Participants
- Iterator
- Defines the interface for accessing and
traversing a containers contents - Concrete iterator
- Implements the iterator interface
- Keeps track of the current position in the
traversal - Container
- Could provide a method to create an instance of
an iterator
40Iterator  Consequences
- Supports variations in the traversal of a
container - Complex containers can be traversed in different
ways - Trees and graphs
- Easy to change traversal order
- Replace iterator instance with a different one
- Iterators simplify the container interface
- Do not need iterator interface in container
interface - Multiple simultaneous traversals
- Each iterator keeps track of its own state
41Visitor Pattern
- Intent
- Represent an operation to be performed on the
components of an object structure - Define new operations on the structure without
changing classes representing the components
42Prototype Pattern
- Intent
- Specify the kinds of objects to create using a
prototypical instance and create new objects by
copying this prototype
43Prototype  Motivation
- Build an editor for musical scores by customizing
a general framework for graphical editors - Add new objects for notes, rests, staves
- Have a palette of tools
- Click on eighth note tool and add it to the
document - Assume Framework provides
- Abstract_Graphic class
- Abstract_Tool class for defining tools
- Graphic_Tool subclass for creating instances of
graphical objects and adding them to the document
44Prototype  Motivation  2
- But Graphic_Tool doesn't know how to create
instances of music classes - Could subclass Graphic_Tool for each kind of
music object - But have lots of classes with insignificant
variations - Solution is to copy or clone an instance called a
prototype - Graphic_Tool is parameterized by the prototype to
clone
45Prototype  Example
46Prototype  Structure
PROTOTYPE
CLIENT
clone
operation
CONCRETE_2
CONCRETE_1
clone
clone
47Prototype Participants
- Prototype
- Declares an interface for cloning itself
- Concrete prototype
- Implements an operation for cloning itself
- Client
- Creates a new object by asking a prototype to
clone itself - Collaboration
- Client
- Asks a prototype to clone itself
48Detecting design patterns
- A difficult task
- Patterns are primarily a literary form
- No rigorous mathematical definitions
- Automatic detection beyond the state of the art
of Artificial Intelligence - Instead, detect the artifacts of implementing the
solution of the design pattern
49Detecting design patterns
- Purely structural patterns are easier to detect
- Purely behavioural patterns are much harder
- Most patterns are somewhere in the middle
50Template solution
- A template solution needs to be both
- Distinctive
- The design diagram is not likely to be
represented in a design that does not use the
pattern - Unambiguous
- Can only be done in one way (or in a small number
of variants)
51Analysis synergy
- Both static and dynamic analysis are necessary in
order to detect patterns - Static analysis
- The static structure of the pattern has to match
a subgraph of the static structure of the
software system - Dynamic analysis
- Message passing during run-time has to match the
message flow that implements the behaviour of the
pattern
52Kramer Prechelt 96
- Patterns detected Structural (Adapter, Bridge,
Composite, Decorator, Proxy) - Each pattern expressed as a set of Prolog rules
- No dynamic information used
- Reported precision 40
53Antoniol et al. 98
- Same patterns detected
- No handling of polymorphism
- Metrics were employed to help reduce false
positives - Precision 14 50
54SPOOL
- A Bell Canada / University of Montreal project
- Patterns detected Template Method, Factory
Method, Bridge - Design information stored in an OODBMS
- Querying the database was able to recover many
instances of patterns from three large C systems
55Niere et al. 01
- Semi-automatic approach
- Programs described in the form of Abstract Syntax
Graphs - Patterns described as graph transformations
- Limitation Each variant has to be described as a
separate transformation
56IDEA
- Detects patterns in UML diagrams
- May suggest improvements on the application of
the pattern (better naming, export status for
features etc). - Many patterns cannot be accurately detected from
diagrams
57Heuzeroth et al.