SlideShare une entreprise Scribd logo
1  sur  213
Télécharger pour lire hors ligne
Some Theory and Practice on
Patterns – In Practice
Yann-Gaël Guéhéneuc
NII, Tokyo, Japan
12/02/14

This work is licensed under a Creative
Commons Attribution-NonCommercialShareAlike 3.0 Unported License
Patterns
 Patterns

document reusable solutions to
recurring problems
– Architecture
• Architectural styles

– Design
• Design patterns
• Design anti-patterns

– Implementation
• Idioms
2/213
Examples
 Do

you know

– C++?
– Java?
– Lisp?
– Prolog?
– Smalltalk?

3/213
C++
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

4/213
C++
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

?

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

5/213
C++
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Overriding of
operator =

?

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

6/213
Java
final Object oldListOfEntities =
this.listOfEntities();
this.fireVetoableChange(
"RemoveEntity",
oldListOfEntities,
anEntity);
this.removeEntity(anEntity);
this.firePropertyChange(
"RemoveEntity",
oldListOfEntities,
anEntity);

7/213
Java
final Object oldListOfEntities =
this.listOfEntities();
this.fireVetoableChange(
"RemoveEntity",
oldListOfEntities,
anEntity);
this.removeEntity(anEntity);
this.firePropertyChange(
"RemoveEntity",
oldListOfEntities,
anEntity);

?
8/213
Java
final Object oldListOfEntities =
this.listOfEntities();
this.fireVetoableChange(
"RemoveEntity",
oldListOfEntities,
anEntity);
this.removeEntity(anEntity);
this.firePropertyChange(
"RemoveEntity",
oldListOfEntities,
anEntity);

Veto protocol
of JavaBeans

?

9/213
Lisp
(define (square ls)
(if (null? ls)
'()
(cons ((lambda(x) (* x x))
(car ls))
(square (cdr ls)))))

10/213
Lisp
(define (square ls)
(if (null? ls)
'()
(cons ((lambda(x) (* x x))
(car ls))
(square (cdr ls)))))

?
11/213
Lisp
(define (square ls)
(if (null? ls)
'()
(cons ((lambda(x) (* x x))
(car ls))
(square (cdr ls)))))

?

Map

12/213
Prolog
checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent(
[],
E),
interpretEvent(E, IE),
checkLt1(IE, LA, LT, LD, NLA, NLT, NLD),
!,
(
(IE = programEnd,
NNLA = NLA,
NNLT = NLT,
NNLD = NLD)
;
checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD)
).

13/213
Prolog
checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent(
[],
E),
interpretEvent(E, IE),
checkLt1(IE, LA, LT, LD, NLA, NLT, NLD),
!,
(
(IE = programEnd,
NNLA = NLA,
NNLT = NLT,
NNLD = NLD)
;
checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD)
).

?

14/213
Prolog
checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent(
[],
E),
interpretEvent(E, IE),
checkLt1(IE, LA, LT, LD, NLA, NLT, NLD),
!,
(
(IE = programEnd,
NNLA = NLA,
NNLT = NLT,
NNLD = NLD)
;
checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD)
).

?

Conditional

15/213
Smalltalk
Integer>>+ aNumber
^aNumber addInteger: self
Float>>+ aNumber
^aNumber addFloat: self
Integer>>addInteger: anInteger
<primitive: 1>
Float>>addFloat: aFloat
<primitive: 2>
Integer>>addFloat: aFloat
^self asFloat addFloat: aFloat
Float>>addInteger: anInteger
^self addFloat: anInteger asFloat

Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X.

16/213
Smalltalk
Integer>>+ aNumber
^aNumber addInteger: self
Float>>+ aNumber
^aNumber addFloat: self
Integer>>addInteger: anInteger
<primitive: 1>
Float>>addFloat: aFloat
<primitive: 2>
Integer>>addFloat: aFloat
^self asFloat addFloat: aFloat
Float>>addInteger: anInteger
^self addFloat: anInteger asFloat

?

Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X.

17/213
Smalltalk
Integer>>+ aNumber
^aNumber addInteger: self
Float>>+ aNumber
^aNumber addFloat: self
Integer>>addInteger: anInteger
<primitive: 1>
Float>>addFloat: aFloat
<primitive: 2>
Integer>>addFloat: aFloat
^self asFloat addFloat: aFloat
Float>>addInteger: anInteger
^self addFloat: anInteger asFloat

Double
dispatch

?

Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X.

18/213
Conclusion on the Examples
 The

examples showed idioms in the given
pieces of source code
– These idioms are recurring motifs in a program
source code
– These motifs connote a recognized,
acknowledge style of programming

19/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
20/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
21/213
Definition


Context
– 1977 et 1979: architecture
• Christopher Alexander
• A Pattern Language: Towns, Buildings,
Construction and the idea of generative patterns
• The Timeless Way of Building and the idea of
perfection in architecture

– 1990: object-oriented design
• Erich Gamma, Richard Helm, Ralph Johnson,
and John Vlissides†
• Design Patterns drawn from experience
22/213
Definition
A

Pattern Language:
Towns, Buildings, Construction
– 253 patterns
– Generative grammar
– “At the core... is the idea that people should
design for themselves their own houses, streets
and communities. This idea... comes simply
from the observation that most of the wonderful
places of the world were not made by architects
but by the people.”

23/213
Definition
“Each pattern describes a problem which occurs over and
over again in our environment, and then describes the core
of the solution to that problem, in such way that you can
use this solution a million times over, without ever doing it
the same way twice.”
—Christopher Alexander, 1977
“Each pattern is a three part rule, which express a relation
between a context, a problem, and a solution.”
—Christopher Alexander, 1977

24/213
盈進学園 東野高等学校
http://eishin.ac/
25/213
Definition
 Design

Patterns:
Elements of Reusable OO Software
– 23 patterns
– Not a language?
– “Dynamic, highly parameterized software is
harder to understand and build than more static
software.”

26/213
Definition
“The strict modeling of the real world leads
to reflect today’s realities but not necessarily
tomorrow’s. The abstractions that emerge
during design are key to making a design
flexible.”
—Erich Gamma, 1994

27/213
JHotDraw
http://www.jhotdraw.org/
http://www.javaworld.com/article/2074997/swing-gui-programming/
become-a-programming-picasso-with-jhotdraw.html
28/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance

29/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development,
operation, and maintenance
– Patterns have been identified for
•
•
•
•

Different phases of software development
Different levels of abstraction
Different technologies
…
30/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a
given context in software development,
operation, and maintenance

31/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a
given context in software development,
operation, and maintenance
– Problem faced by three people at three different
times in a similar context
– Particular problems are not included, except if
they occur more than three times…

32/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance

33/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance
– Essentially, a solution must describe steps to
solve the problem
• Architecture
• Design
• Implementation
34/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance

35/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance
– The solution must not be particular
– The solution can be adapted
– The solution must be adapted

36/213
Definition
A

pattern is a general reusable solution to a
commonly occurring problem within a given
context in software development, operation,
and maintenance
– The solution must not be particular
– The solution can be adapted
– The solution must be adapted
• Forces
• Variants
37/213
Recall the C++ Example
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

38/213
Recall the C++ Example
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

39/213
Recall the C++ Example
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Development, operation, and
maintenance

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

40/213
Recall the C++ Example
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Development, operation, and
maintenance
Commonly occurring problem
within a given context

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

41/213
Recall the C++ Example
class Dog {
string name;
Dog(const Dog* dog) : name(dogname) {}}
class Kennel { Dog* dog; string name; }

if (&kennel != this) {
thisdog =
new Dog(kennel.dog);
thisname = kennel.name;
}
return *this;

Development, operation, and
maintenance
Commonly occurring problem
within a given context
General reusable solution

Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000.

42/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
43/213
Quality
A

means to enhance the reusability

– Of the code written using the pattern
+ Its flexibility
– Of the problem and its solution




44/213
Quality
A

means to enhance the reusability

– Of the code written using the pattern
+ Its flexibility
– Of the problem and its solution
A

means to encapsulate design experience




45/213
Quality
A

means to enhance the reusability

– Of the code written using the pattern
+ Its flexibility
– Of the problem and its solution
A

means to encapsulate design experience
 A common vocabulary among designers


46/213
Quality
A

means to enhance the reusability

– Of the code written using the pattern
+ Its flexibility
– Of the problem and its solution
A

means to encapsulate design experience
 A common vocabulary among designers
A

means to have that
“quality without a name”
47/213
Quality Without a Name







48/213
Quality Without a Name
“There is a point you reach in tightening a nut, where you
know that to tighten just a little more might strip the thread,
but to leave it slightly looser would risk having the hut
coming off from vibration. If you've worked with your hands
a lot, you know what this means, but the advice itself is
meaningless.”
—Robert Pirsig, circa. 1972



49/213
Quality Without a Name
“There is a point you reach in tightening a nut, where you
know that to tighten just a little more might strip the thread,
but to leave it slightly looser would risk having the hut
coming off from vibration. If you've worked with your hands
a lot, you know what this means, but the advice itself is
meaningless.”
—Robert Pirsig, circa. 1972
“[T]oo often software developers spend their days grinding
away for pay at programs they neither need nor love. But
not in the Linux world - which may explain why the
average quality of software originated in the Linux
community is so high.”
—Eric Raymond, 1998
50/213
Quality Without a Name

51/213
Quality Without a Name
ニワトリのヒナの雌雄鑑別
(chick sexing)




http://discovermagazine.com/2011/sep/18-your-brain-knows-lot-more-than-you-realize

52/213
Quality Without a Name
ニワトリのヒナの雌雄鑑別
(chick sexing)
“The master would stand over the
apprentice and watch. The student
would pick up a chick, examine its
rear, and toss it into one bin or the
other. The master would give
feedback: yes or no.”
—Eagleman, 2011
http://discovermagazine.com/2011/sep/18-your-brain-knows-lot-more-than-you-realize

53/213
54/213
Practice, practice
and practice more

55/213
56/213
Quality
 Rationale

– “Software design is widely recognised as being
a “wicked” or “ill-structured” problem,
characterised by ambiguous specifications, no
true/false solutions (only ones that are “better” or
“worse” from a particular perspective), the lack
of any “stopping rule” to determine when a
solution has been reached, and no ultimate test
of whether a solution meets the requirements.”

—Zhang and Budgen, 2012
57/213
Quality
“Important assumptions
– That patterns can be codified in such a way that
they can be shared between different designers
– That reuse will lead to “better” designs. There is
an obvious question here of what constitutes
“better”, but a key measure is maintainability”

—Zhang and Budgen, 2012
(With minor adaptations)

58/213
Quality
“Advantages:
– Using patterns improves programmer productivity and
program quality
– Novices can increase their design skills significantly by
studying and applying patterns
– Patterns encourage best practices, even for experiences
designers
– Design patterns improve communication, both among
developers and from developers to maintainers”

—Zhang and Budgen, 2012
(With minor adaptations)
59/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
60/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

61/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

62/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

63/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

64/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

65/213
Form
 Several

books, articles

– “Theoretical”
– With examples
– Among others…

66/213
Form
 Several

books, articles

– Amazon.com
• Books › Computers & Technology › Programming ›
Software Design, Testing & Engineering › ObjectOriented Design › "patterns"
• 224 results on May 31, 2013

67/213
Form
 Several

books, articles

– Amazon.com
• Exclusion
– Unreleased books
– Specific to a technology or frameworks
» e.g., MVVM Unleashed by Michael Brown
– Process oriented, user-interface, programming languages
» e.g., Process Patterns: Building Large-Scale Systems
Using Object Technology by Scott W. Ambler and
Barbara Hanscome
– Proceedings of conferences
– Unrelated to software engineering
68/213
Form
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
16.
17.
18.
19.
20.
21.
22.
23.
24.
25.
26.
27.
28.
29.
30.
31.
32.
33.
34.
35.

Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects: Volume 2 (Wiley Software...
by Douglas C. Schmidt, Michael Stal, Hans Rohnert and Frank Buschmann
Pattern-Oriented Software Architecture, Patterns for Resource Management: Volume 3 (Wiley Software Patterns
Series... by Michael Kircher and Prashant Jain
Pattern-Oriented Software Architecture, A System of Patterns: Volume 1 (Wiley Software Patterns Series) by Frank
Buschmann, Regine Meunier, Hans Rohnert and Peter Sommerlad
Pattern-Oriented Software Architecture For Dummies (For Dummies (Computers)) by Robert Hanmer
Web Security Patterns by Ramesh Nagappan and Christopher Steel
Safe C++ by Vladimir Kushnir
Programming in the Large with Design Patterns by Eddie Burris
Elemental Design Patterns by Jason McC. Smith
Java Application Architecture: Modularity Patterns with Examples Using OSGi (Robert C. Martin Series) by Kirk
Knoernschild
Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions (Addison-Wesley
Signature... by Gregor Hohpe and Bobby Woolf
Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series (Fowler)) by Martin Fowler
Cognitive Patterns: Problem-Solving Frameworks for Object Technology by Robert K Konitzer, Bobbin Teegarden,
Alexander Rush and Karen M Gardner
Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services by Robert
Daigneau
The ACE Programmer's Guide: Practical Design Patterns for Network and Systems Programming by Stephen D.
Huston, James CE Johnson and Umar Syyid
Patterns for Parallel Software Design (Wiley Software Patterns Series) by Jorge Luis Ortega-Arjona
Design Patterns in Object-oriented ABAP by Igor Barbaric
Object-Oriented Reengineering Patterns by Oscar Nierstrasz, Stéphane Ducasse and Serge Demeyer
Dependency Injection by Dhanji R. Prasanna
Object-Oriented Software Engineering Using UML, Patterns, and Java (3rd Edition) by Bernd Bruegge and Allen H.
Dutoit
J2EE Design Patterns by William Crawford and Jonathan Kaplan
Applying UML and Patterns: An Introduction to Object-oriented Analysis and Design and Iterative Development by
Craig Larman
Object-oriented Analysis and Design Using Umlan Introduction to Unified Process and Design Patterns by Mahesh P.
Matha
C++ Design Patterns and Derivatives Pricing (Mathematics, Finance and Risk) by M. S. Joshi
Effective Java (2nd Edition) by Joshua Bloch
Patterns for Fault Tolerant Software (Wiley Software Patterns Series) by Robert Hanmer
Implementation Patterns by Kent Beck
Patterns for Computer-Mediated Interaction (Wiley Software Patterns Series) by Till Schummer and Stephan Lukosch
Pattern Oriented Software Architecture Volume 5: On Patterns and Pattern Languages by Frank Buschmann, Kevlin
Henney and Douglas C. Schmidt
Object-Oriented Analysis and Design with Applications (3rd Edition) by Grady Booch, Robert A. Maksimchuk, Michael
W. Engle and Bobbi J. Young
Head First Object-Oriented Analysis and Design by Brett D. McLaughlin, Gary Pollice and Dave West
Agile Principles, Patterns, and Practices in C# by Robert C. Martin and Micah Martin
Design Patterns For Dummies by Steve Holzner
Pattern Languages of Program Design 5 by Dragos Manolescu, Markus Voelter and James Noble
Design Patterns in Java(TM) (Software Patterns Series) by Steven John Metsker and William C. Wake
Object-Oriented Design and Patterns by Cay S. Horstmann

37.
38.
39.
40.
41.
42.
43.
44.
45.
46.
47.
48.
49.
50.
51.
52.
53.
54.
55.
56.
57.
58.
59.
60.
61.
62.
63.
64.
65.
66.
67.
68.
69.
70.
71.
72.

Object-Oriented Modeling and Design with UML (2nd Edition) by Michael R. Blaha and James R Rumbaugh
Remoting Patterns: Foundations of Enterprise, Internet and Realtime Distributed Object Middleware (Wiley
Software... by Markus Völter, Michael Kircher and Uwe Zdun
Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools (Wiley Application
Development... by Jack Greenfield, Keith Short, Steve Cook and Stuart Kent
Refactoring to Patterns by Joshua Kerievsky
Architecting Enterprise Solutions: Patterns for High-Capability Internet-based Systems (Wiley Software Patterns...
by Paul Dyson and Andrew Longshaw
Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML by Jim Arlow and Ila
Neustadt
Data Access Patterns: Database Interactions in Object-Oriented Applications by Clifton Nock
Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans
Pattern-Oriented Analysis and Design: Composing Patterns to Design Software Systems by Sherif M. Yacoub,
Hany H. Ammar, Sherif Yacoub and Hany Ammar
Java Extreme Programming Cookbook by Eric M. Burke and Brian M. Coyner
J2EE Best Practices: Java Design Patterns, Automation, and Performance (Wiley Application Development
Series) by Darren Broemmer
Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems by Bruce Powel Douglass
Design Patterns Java¿ Workbook by Steven John Metsker
EJB Design Patterns: Advanced Patterns, Processes, and Idioms by Floyd Marinescu
Streamlined Object Modeling: Patterns, Rules, and Implementation by Jill Nicola, Mark Mayfield and Mike Abney
Design Patterns Explained: A New Perspective on Object-Oriented Design by Alan Shalloway and James Trott
Small Memory Software: Patterns for systems with limited memory (Software Patterns Series) by James Noble
and Charles Weir
AntiPatterns in Project Management by William J. Brown, Hays W. "Skip" McCormick III and Scott W. Thomas
Pattern Languages of Program Design 4 (Software Patterns Series) by Brian Foote, Neil Harrison and Hans
Rohnert
Testing Object-Oriented Systems: Models, Patterns, and Tools by Robert V. Binder
Design Patterns and Contracts by Jean-Marc Jezequel, Michel Train and Christine Mingins
Object-Oriented Software Development Using Java: Principles, Patterns, and Frameworks (1/e) by Xiaoping Jia
Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant and William Opdyke
More Process Patterns: Delivering Large-Scale Systems Using Object Technology (SIGS: Managing Object
Technology... by Scott W. Ambler
Pattern Hatching: Design Patterns Applied by John Vlissides
AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis by William J. Brown, Raphael C. Malveau,
Hays W. "Skip" McCormick and Thomas J. Mowbray
A Little Java, A Few Patterns (Language, Speech, & Communication) by Matthias Felleisen, Daniel P. Friedman
and Ralph E. Johnson
Pattern Languages of Program Design 3 (v. 3) by Robert C. Martin, Dirk Riehle and Frank Buschmann
Object Models: Strategies, Patterns, and Applications (2nd Edition) by Peter Coad, David North and Mark Mayfield
Analysis Patterns: Reusable Object Models by Martin Fowler
Patterns of Software: Tales from the Software Community by Richard P. Gabriel
Pattern Languages of Program Design 2 (v. 2) by John Vlissides, James O. Coplien and Norman L. Kerth
Software Patterns by James Coplien
Software Architecture: Perspectives on an Emerging Discipline by Mary Shaw and David Garlan
Adaptive Object-Oriented Software: The Demeter Method with Propagation Patterns: The Demeter Method with
Propagation... by Karl Lieberherr
Pattern Languages of Program Design by James O. Coplien and Douglas C. Schmidt

69/213
Form
“Each pattern is a three part rule, which
express a relation between a context, a
problem, and a solution.”
—Christopher Alexander, 1977

70/213
Form
 General

form as for the GoF
also inspired by Coplien’s form
– Name
– Problem(s)
– Solution
– Consequences

71/213
Form (Extended)
 General

form as for the GoF
also inspired by Coplien’s form
– Name
– Problem(s)
– Example(s)
– Solution
– Example(s)
– Consequences
– (Follow-up)
72/213
Form
 General

form as for the GoF
also inspired by Coplien’s form
– Not formal
– Room for interpretation
– But…
• UML-like class diagrams
• UML-like sequence diagrams
• Smalltalk / C++ example code
73/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
74/213
Example
 Simplified

(1/5)
compiler

– Parse files to build an AST
– Iterate over the AST
• Build DefaultMutableTreeNodes
javax.swing.tree.DefaultMutableTreeNode
for a graphical representation of the AST

• Bind types
• Generate code
• …
75/213
Example
 Simplified

(1/5)
compiler

– Parse files to build an AST
– Iterate over the AST
• Build DefaultMutableTreeNodes
javax.swing.tree.DefaultMutableTreeNode
for a graphical representation of the AST

• Bind types
• Generate code
• …
76/213
Example


(2/5)

AST

CompilationUnit

Main

generateCode()

Class
generateCode()

Field

Method

generateCode()

generateCode()

Statement
generateCode()

77/213
Example

(3/5)

package compiler;
import java.util.Set;
public class Method {
private Set statements;
public void addStatement(final Statement aStatement) {
this.statements.add(aStatement);
}
public void removeStatement(final Statement aStatement) {
this.statements.remove(aStatement);
}
}
package compiler;

package compiler;

public class Field {
/* To be implemented. */
}

public class Statement {
/* To be implemented. */
}

78/213
Example

(4/5)

package compiler;
import java.util.Set;
public class Class {
private String name;
private Set methods;
private Set fields;
public String getName() {
return this.name;
}
public void addMethod(final Method aMethod) {
this.methods.add(aMethod);
}
public void removeMethod(final Method aMethod) {
this.methods.remove(aMethod);
}
public void addField(final Method aField) {
this.fields.add(aField);
}
public void removeField(final Field aField) {
this.fields.remove(aField);
}
}

79/213
Example

(5/5)

package compiler;
import java.util.Iterator;
import java.util.Set;
public class CompilationUnit {
private Set classes;
public void addClass(final Class aClass) {
this.classes.add(aClass);
}
public void removeClass(final Class aClass) {
this.classes.remove(aClass);
}
public Class getClass(final String aName) {
final Iterator iterator = this.classes.iterator();
while (iterator.hasNext()) {
final Class aClass = (Class) iterator.next();
if (aClass.getName().equals(aName)) {
return aClass;
}
}
return null;
}
}

80/213
Naïve Implementation
 How

(1/7)

to generate microcode for

– Microsoft Windows operating system
– Intel Pentium processor

81/213
Naïve Implementation
 How

(1/7)

to generate microcode for

– Microsoft Windows operating system
– Intel Pentium processor

Add a generateCode()
method in each class

82/213
Naïve Implementation

(2/7)

public class Method {
…
public String generateCode() {
String generatedCode = "";
/* Do something at the beginning. */
final Iterator iterator = this.statements.iterator();
while (iterator.hasNext()) {
final Statement aStatement = (Statement) iterator.next();
generatedCode += aStatement.generateCode();
}
/* Do something at the end. */
return generatedCode;
}
}
public class Field {
…
public String generateCode() {
String generatedCode = "";
/* Do something. */
return generatedCode;
}
}

public class Statement {
…
public String generateCode() {
String generatedCode = "";
/* Do something. */
return generatedCode;
}
}

83/213
Naïve Implementation

(3/7)

public class Class {
…
public String generateCode() {
String generatedCode = "";
/* Do something at the beginning. */
final Iterator iteratorOnFields = this.fields.iterator();
while (iteratorOnFields.hasNext()) {
final Field aField = (Field) iteratorOnFields.next();
generatedCode += aField.generateCode();
}
final Iterator iteratorOnMethods = this.methods.iterator();
while (iteratorOnMethods.hasNext()) {
final Method aMethod = (Method) iteratorOnMethods.next();
generatedCode += aMethod.generateCode();
}
/* Do something at the end. */
return generatedCode;
}
}

84/213
Naïve Implementation

(4/7)

public class CompilationUnit {
…
public String generateCode() {
String generatedCode = "";
/* Do something at the beginning. */
final Iterator iterator = this.classes.iterator();
while (iterator.hasNext()) {
final Class aClass = (Class) iterator.next();
generatedCode += aClass.generateCode();
}
/* Do something at the end. */
return generatedCode;
}
}

85/213
Naïve Implementation
m : Main

cu :
CompilationUnit

c : Class

(5/7)

m : Method

s : Statement

generateCode( )
generateCode( )
generateCode( )
generateCode( )

86/213
Naïve Implementation
 Limitations

(6/7)

of the naïve implementation

– What about generating code for
• Linux on PowerPC?
• Linux on Motorola 68060?
• OS/400 on AS/400?

87/213
Naïve Implementation
 Limitations

(6/7)

of the naïve implementation

– What about generating code for
• Linux on PowerPC?
• Linux on Motorola 68060?
• OS/400 on AS/400?

Combinatorial explosion of
generateCodeForXXX()
methods in each class
88/213
Naïve Implementation

(7/7)

 Requirements

– Decouple the data structure
• The AST

– From algorithms on the data structure
• The generateCodeForXXX() method
• And others, including type binding!

89/213
Naïve Implementation

(7/7)

 Requirements

– Decouple the data structure
• The AST

– From algorithms on the data structure
• The generateCodeForXXX() method
• And others, including type binding!

The Visitor design pattern
guides you to do that!
90/213
Visitor
 Name:

(2/13)
Visitor

 Intent:

“Represent an operation to be
performed on the elements of an object
structure. Visitor lets you define a new
operation without changing the classes of
the elements on which it operates.”

91/213
Visitor

(3/13)

 Motivation:

“Consider a compiler that
represents programs as abstract syntax
trees. It will need to perform operations on
abstract syntax trees for "static semantic"
analyses like checking that all variables are
defined. It will also need to generate code.”

92/213
Visitor

(4/13)

 Motivation

(cont’d): “[…] It will be confusing
to have type-checking code mixed with
pretty-printing code or flow analysis code.
[…] It would be better if each new operation
could be added separately, and the node
classes were independent of the operations
that apply to them.”

93/213
Visitor

(5/13)

 Motivation

(cont’d): “We can have both by
packaging related operations from each
class in a separate object, called a visitor,
and passing it to elements of the abstract
syntax tree as it's traversed.”

94/213
Visitor

(6/13)

 Motivation

(cont’d): “When an element
accepts the visitor, it sends a request to the
visitor that encodes the element's class. It
also includes the element as an argument.
The visitor will then execute the operation for
that element—the operation that used to be
in the class of the element.”

95/213
Visitor

(8/13)

 Applicability

– An object structure contains many classes of
objects with differing interfaces…
– Many distinct and unrelated operations need to
be performed on objects in an object structure…
– The classes defining the object structure rarely
change, but you often want to define new
operations over the structure…

96/213
Visitor

(9/13)

 Structure

97/213
Visitor


(10/13)

Participants
– Visitor (NodeVisitor)
• Declares a Visit operation for
each class…

– ConcreteVisitor
(TypeCheckingVisitor)
• Implements each Visit…

– Element (Node)
• Defines an Accept operation…

– ConcreteElement
(AssignmentNode)
• Implements Accept …

– ObjectStructure (Program)
• Can enumerate its elements
• May provide a high-level
interface to allow the visitor
to visit its elements
• May either be a composite
(see Composite) or a
collection

98/213
Visitor

(11/13)

 Collaborations

99/213
Visitor

(13/13)

 Consequences:

…
 Implementation: …
 Sample code: …
 Known uses
– ASTs
– Meta-models
–…
 Related

patterns: Composite
100/213
Better Implementation

(1/6)

package compiler.visitor;
import
import
import
import
import

compiler.Class;
compiler.CompilationUnit;
compiler.Field;
compiler.Method;
compiler.Statement;

public interface Visitor {
void open(final Class aClass);
void open(final CompilationUnit aCompilationUnit);
void open(final Method aMethod);
void close(final Class aClass);
void close(final CompilationUnit aCompilationUnit);
void close(final Method aMethod);
void visit(final Field aField);
void visit(final Statement aStatement);
}

101/213
Better Implementation

(2/6)

public class Method {
…
public void accept(final Visitor aVisitor) {
aVisitor.open(this);
final Iterator iterator = this.statements.iterator();
while (iterator.hasNext()) {
final Statement aStatement = (Statement) iterator.next();
aStatement.accept(aVisitor);
}
aVisitor.close(this);
}
}
public class Field {
…
public void accept(final Visitor aVisitor) {
aVisitor.visit(this);
}
}
public class Statement {
…
public void accept(final Visitor aVisitor) {
aVisitor.visit(this);
}
}

102/213
Better Implementation

(3/6)

public class Class {
…
public void accept(final Visitor aVisitor) {
aVisitor.open(this);
final Iterator iteratorOnFields = this.fields.iterator();
while (iteratorOnFields.hasNext()) {
final Field aField = (Field) iteratorOnFields.next();
aField.accept(aVisitor);
}
final Iterator iteratorOnMethods = this.methods.iterator();
while (iteratorOnMethods.hasNext()) {
final Method aMethod = (Method) iteratorOnMethods.next();
aMethod.accept(aVisitor);
}
aVisitor.close(this);
}
}

103/213
Better Implementation

(4/6)

public class CompilationUnit {
…
public void accept(final Visitor aVisitor) {
aVisitor.open(this);
final Iterator iterator = this.classes.iterator();
while (iterator.hasNext()) {
final Class aClass = (Class) iterator.next();
aClass.accept(aVisitor);
}
aVisitor.close(this);
}
}

104/213
105/213

Better implementation

(5/6)
(5/6)

m : Main

cu :
CompilationUnit

c : Class

m : Method

s : Statement

Better implementation

generateCode( )
generateCode( )
generateCode( )
generateCode( )

106/213
(5/6)

m : Mai n

cu :
CompilationUnit

c : Class

m : Method

s : Statem ent

v : IVisitor

accept(IVisitor)
open(Com pilationUnit)

a ccept(IVisitor)
o pen(Cl as s)

accept(IVisitor)

Better implementation

open(Method)

a ccept(IVis itor)
visit(Statement)

clos e(Method)

close(C lass)

clos e(Compil ationUn it)

107/213
m : Mai n

cu :
CompilationUnit

c : Class

m : Method

s : Statem ent

v : IVisitor

accept(IVisitor)
open(Com pilationUnit)

a ccept(IVisitor)

m : Main

cu :
CompilationUnit

c : Class

m : Method

s : Statement

o pen(Cl as s)

accept(IVisitor)

generateCode( )

open(Method)

generateCode( )
a ccept(IVis itor)
visit(Statement)

generateCode( )
generateCode( )

clos e(Method)

close(C lass)

clos e(Compil ationUn it)

108/213
Better Implementation
 By

(6/6)

using the visitor design pattern

– Decouple data structure and algorithms
– Put the traversal in only one place, in the AST
– Allow the addition of new algorithms without
changing the data structure

109/213
Better Implementation
 By

(6/6)

using the visitor design pattern

– Decouple data structure and algorithms
– Put the traversal in only one place, in the AST
– Allow the addition of new algorithms without
changing the data structure

Much better, clearer
implementation!
110/213
Conclusion on the Example
 The

Visitor design pattern is useful
anywhere you have
– A data (stable) structure
– Algorithms (infinite) on that data structure

 Design

patterns provided good solution to
recurrent problems!

111/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
112/213
Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides ;
Design Patterns: Elements of Reusable Object-Oriented Software ;
Addison-Wesley, 1995

113/213
Catalogue
 Design

patterns

– Development and maintenance
– Design/implementation levels
– Examples in C++ and Smalltalk
 Divided

in three categories

– Behavioural
– Creational
– Structural
114/213
Catalogue

115/213
Catalogue

116/213
Catalogue
 Abstract

Factory (87)

– Provide an interface for creating families of
related or dependent objects without specifying
their concrete classes
 Adapter

(139)

– Convert the interface of a class into another
interface clients expect. Adapter lets classes
work together that couldn't otherwise because of
incompatible interfaces
117/213
Catalogue
 Bridge

(151)

– Decouple an abstraction from its implementation
so that the two can vary independently
 Builder

(97)

– Separate the construction of a complex object
from its representation so that the same
construction process can create different
representations

118/213
Catalogue
 Chain

of Responsibility (223)

– Avoid coupling the sender of a request to its
receiver by giving more than one object a
chance to handle the request. Chain the
receiving objects and pass the request along the
chain until an object handles it

119/213
Catalogue
 Command

(233)

– Encapsulate a request as an object, thereby
letting you parameterize clients with different
requests, queue or log requests, and support
undoable operations
 Composite

(163)

– Compose objects into tree structures to
represent part-whole hierarchies. Composite lets
clients treat individual objects and compositions
of objects uniformly
120/213
Catalogue
 Decorator

(175)

– Attach additional responsibilities to an object
dynamically. Decorators provide a flexible
alternative to subclassing for extending
functionality
 Facade

(185)

– Provide a unified interface to a set of interfaces
in a subsystem. Facade defines a higher-level
interface that makes the subsystem easier to use
121/213
Catalogue
 Factory

Method (107)

– Define an interface for creating an object, but let
subclasses decide which class to instantiate.
Factory Method lets a class defer instantiation to
subclasses
 Flyweight

(195)

– Use sharing to support large numbers of finegrained objects efficiently

122/213
Catalogue
 Interpreter

(243)

– Given a language, define a representation for its
grammar along with an interpreter that uses the
representation to interpret sentences in the
language
 Iterator

(257)

– Provide a way to access the elements of an
aggregate object sequentially without exposing
its underlying representation
123/213
Catalogue
 Mediator

(273)

– Define an object that encapsulates how a set of
objects interacts. Mediator promotes loose
coupling by keeping objects from referring to
each other explicitly, and it lets you vary their
interaction independently
 Memento

(283)

– Without violating encapsulation, capture and
externalize an object's internal state so that the
object can be restored to this state later
124/213
Catalogue
 Observer

(293)

– Define a one-to-many dependency between
objects so that when one object changes state,
all its dependents are notified and updated
automatically
 Prototype

(117)

– Specify the kinds of objects to create using a
prototypical instance, and create new objects by
copying this prototype
125/213
Catalogue
 Proxy

(207)

– Provide a surrogate or placeholder for another
object to control access to it.
 Singleton

(127)

– Ensure a class only has one instance, and
provide a global point of access to it

126/213
Catalogue
 State

(305)

– Allow an object to alter its behaviour when its
internal state changes. The object will appear to
change its class
 Strategy

(315)

– Define a family of algorithms, encapsulate each
one, and make them interchangeable. Strategy
lets the algorithm vary independently from
clients that use it
127/213
Catalogue
 Template

Method (325)

– Define the skeleton of an algorithm in an
operation, deferring some steps to subclasses.
Template Method lets subclasses redefine
certain steps of an algorithm without changing
the algorithm's structure

128/213
Catalogue
 Visitor

(331)

– Represent an operation to be performed on the
elements of an object structure. Visitor lets you
define a new operation without changing the
classes of the elements on which it operates

129/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
130/213
Practice
“The strict modeling of the real world leads
to reflect today’s realities but not necessarily
tomorrow’s. The abstractions that emerge
during design are key to making a design
flexible.”
—Erich Gamma, 1994

131/213
Practice
“The description of communicating objects
and classes customized to solve general
design problem in a particular context.”
—Erich Gamma, 1994

132/213
Practice
“Each design pattern lets some aspect of
system structure vary independently of other
aspects, thereby making a system more
robust to a particular kind of change.”
—Erich Gamma, 1994

133/213
The following is only complementary
to reading books and practicing
134/213
Practice
 Scattered

information

– Informal text
A

suggested example rather than a
general rule

Interpreting them all...
135/213
Practice
 When

encountering complex problems?

– Numerous design patterns (is there any
complete list out there?)
– Granularity
•
•
•
•

Requirements, analysis, architecture
Design, implementation (idioms)
Refactoring, testing
…

Knowing them all...
136/213
Practice
 Iterative

induction process

– From an example to an abstraction to an
application to the abstraction to an application…
– Validation process?

Applying them all...
137/213
Practice
 Use

known categories

– Behavioural
– Creational
– Structural
 Use

the Internet

 Read

and discuss others’ code
138/213
Practice
 Use

known categories

– Behavioural
– Creational
– Structural
 Use

the Internet

 Read

and discuss others’ code
139/213



 Read

and discuss others’ code
140/213
Practice
 Assess

the trade-offs

– Flexibility
– Complexity

141/213
Practice
 Assess

the trade-offs

– Flexibility
– Complexity

142/213
Practice
 Assess

the trade-offs

– Flexibility
– Complexity

 Sometimes

it is necessary to remove the
solution of a DP used in the code
143/213
Practice
 Sometimes

it is necessary to remove the
solution of a DP used in the code

144/213
Practice
“There is a natural relation between patterns
and refactorings. “Patterns are where you
want to be; refactorings are ways to get
there from somewhere else”
—Josuha Kerievsky citing
Martin Fowler, 2004

145/213
146/213
Practice
 Refactoring

to a Visitor

– Previous example of code generation from a
common AST
 Implementing

a variant of the Visitor

– padl.kernel.impl.Constituent.accept(IVisitor)
– padl.kernel.impl.Constituent.accept(IVisitor, String)
– padl.kernel.impl.Constituent.accept(Class, IVisitor,
String, boolean)

 Refactoring

away from the Visitor

– ptidej.statement.creator.classfiles.loc.BCELLOCFinder

147/213
Practice
 Refactoring

to a Visitor

– Previous example of code generation from a
common AST
 Implementing

a variant of the Visitor

– padl.kernel.impl.Constituent.accept(IVisitor)
– padl.kernel.impl.Constituent.accept(IVisitor, String)
– padl.kernel.impl.Constituent.accept(Class, IVisitor,
String, boolean)

 Refactoring

away from the Visitor

– ptidej.statement.creator.classfiles.loc.BCELLOCFinder

148/213
Practice
 Refactoring

to a Visitor

– Previous example of code generation from a
common AST
 Implementing

a variant of the Visitor

– padl.kernel.impl.Constituent.accept(IVisitor)
– padl.kernel.impl.Constituent.accept(IVisitor, String)
– padl.kernel.impl.Constituent.accept(Class, IVisitor,
String, boolean)

 Refactoring

away from the Visitor

– ptidej.statement.creator.classfiles.loc.BCELLOCFinder

149/213
Practice
 Implementing

a variant of the Visitor

– Problem when implementing the solution of the
Visitor design pattern
• Too many duplicated accept(…) methods
• Two cases for visit(…) and open(…)+close(…)

150/213
Practice
 Implementing

a variant of the Visitor

– Problem when implementing the solution of the
Visitor design pattern
• Too many duplicated accept(…) methods
• Two cases for visit(…) and open(…)+close(…)
• What if the data structure changes?

151/213
Practice
 Implementing

a variant of the Visitor

– Problem when implementing the solution of the
Visitor design pattern
• Too many duplicated accept(…) methods
• Two cases for visit(…) and open(…)+close(…)
• What if the data structure changes?

152/213
Practice
 Implementing

a variant of the Visitor

– Problem when implementing the solution of the
Visitor design pattern
• Too many duplicated accept(…) methods
• Two cases for visit(…) and open(…)+close(…)
• What if the data structure changes?

– Solution
• Use the introspection mechanism of Java
153/213
Practice
 Implementing

a variant of the Visitor

– Problem when implementing the solution of the
Visitor design pattern
• Too many duplicated accept(…) methods
• Two cases for visit(…) and open(…)+close(…)
• What if the data structure changes?

– Solution
• Use the introspection mechanism of Java
154/213
private boolean accept(
final java.lang.Class currentReceiver,
final IVisitor visitor,
final String methodName,
final boolean shouldRecurse) {

acceptClassName = currentReceiver.getName();
java.lang.Class argument = null;
try {

}

the introspection
mechanism of Java
 Use

Practice

argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);

catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(
methodName,
new java.lang.Class[] { argument });
method.invoke(visitor, new Object[] { this });
return true;
}
catch (final Exception e) {
if (e instanceof NoSuchMethodException) {
visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}
else {
throw new RuntimeException(e);
}
}
return false;
}

155/213
private boolean accept(
final java.lang.Class currentReceiver,
final
final MethodIVisitor visitor, visitor.getClass().getMethod(
method =
final String methodName,
final boolean
methodName,

shouldRecurse) {

new java.lang.Class[] { argument });
acceptClassName = currentReceiver.getName();
java.lang.Class argument
null;
method.invoke(visitor, =new Object[] { this });
try {

}

the introspection
mechanism of Java
 Use

Practice

argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);

catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(
methodName,
new java.lang.Class[] { argument });
method.invoke(visitor, new Object[] { this });
return true;
}
catch (final Exception e) {
if (e instanceof NoSuchMethodException) {
visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}
else {
throw new RuntimeException(e);
}
}
return false;
}

156/213
private boolean accept(
final java.lang.Class currentReceiver,
final IVisitor visitor,
final String methodName,
final boolean shouldRecurse) {

acceptClassName = currentReceiver.getName();
java.lang.Class argument = null;
try {

}

the introspection
mechanism of Java
 Use

Practice

argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);

catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(
methodName,
new java.lang.Class[] { argument });
method.invoke(visitor, new Object[] { this });
return true;
}
catch (final Exception e) {
if (e instanceof NoSuchMethodException) {
visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}
else {
throw new RuntimeException(e);
}
}
return false;
}

157/213
private boolean accept(
final java.lang.Class currentReceiver,
final IVisitor visitor,
final String methodName,
final boolean shouldRecurse) {

acceptClassName = currentReceiver.getName();
java.lang.Class argument = null;
try {
argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);

the introspection
mechanism of Java

}
catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(

methodName,
acceptClassName = currentReceiver.getName();
new java.lang.Class[] { argument });

java.lang.Class argumentmethod.invoke(visitor,
= null;

Practice

try {

new Object[] { this });

return true;
}
catch (final Exception e) {

argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);
if (e instanceof NoSuchMethodException) {

}

visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}

 Use

catch (final ClassNotFoundException e) {
else {
throw new RuntimeException(e);

visitor.unknownConstituentHandler(methodName, this);
}
}

return false;

}

return false;
}

158/213
private boolean accept(
final java.lang.Class currentReceiver,
final IVisitor visitor,
final String methodName,
final boolean shouldRecurse) {

acceptClassName = currentReceiver.getName();
java.lang.Class argument = null;
try {

}

the introspection
mechanism of Java
 Use

Practice

argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);

catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(
methodName,
new java.lang.Class[] { argument });
method.invoke(visitor, new Object[] { this });
return true;
}
catch (final Exception e) {
if (e instanceof NoSuchMethodException) {
visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}
else {
throw new RuntimeException(e);
}
}
return false;
}

159/213
private e) {
catch (final Exception boolean accept(
final java.lang.Class currentReceiver,

if (e instanceof NoSuchMethodException) {
final IVisitor visitor,
final String methodName,

visitor.unknownConstituentHandler(methodName + '(‘ + argument.get...;
final boolean shouldRecurse) {
}
acceptClassName = currentReceiver.getName();

else {

java.lang.Class argument = null;
try {

throw new RuntimeException(e);
argument = visitor.getClass().getClassLoader().loadClass(acceptClassName);
}

the introspection
mechanism of Java

Practice

}

 Use

}

catch (final ClassNotFoundException e) {
visitor.unknownConstituentHandler(methodName, this);
return false;
}

try {
final Method method = visitor.getClass().getMethod(
methodName,
new java.lang.Class[] { argument });
method.invoke(visitor, new Object[] { this });
return true;
}
catch (final Exception e) {
if (e instanceof NoSuchMethodException) {
visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this);
}
else {
throw new RuntimeException(e);
}
}
return false;
}

160/213
Practice
 Use

the introspection mechanism of Java

– No more duplicated accept(…) methods
– Handles cases for visit(…) and
open(…)+close(…)
– Plus, allows extensions to the data structure
without changing all existing Visitors

161/213
Practice
 Use

the introspection mechanism of Java

– No more duplicated accept(…) methods
– Handles cases for visit(…) and
open(…)+close(…)
– Plus, allows extensions to the data structure
without changing all existing Visitors

162/213
Practice
 Refactoring

to a Visitor

– Previous example of code generation from a
common AST
 Implementing

a variant of the Visitor

– padl.kernel.impl.Constituent.accept(IVisitor)
– padl.kernel.impl.Constituent.accept(IVisitor, String)
– padl.kernel.impl.Constituent.accept(Class, IVisitor,
String, boolean)

 Refactoring

away from the Visitor

– ptidej.statement.creator.classfiles.loc.BCELLOCFinder

163/213
away from the Visitor
 Refactoring

Practice

final FileInputStream fis = new FileInputStream(path);
final ClassParser parser = new ClassParser(fis, path);
final JavaClass clazz = parser.parse();
clazz.accept(this.instFinder);
fis.close();

public class BCELLOCFinder implements Visitor {
private JavaClass currentClass;

public void visitCode(final Code aCode) {
}
public void visitCodeException(final CodeException aCodeException) {
}
// 18 other empty “visit” methods
public void visitJavaClass(final JavaClass aClass) {
this.currentClass = aClass;
final Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
this.visitMethod(methods[i]);
}
}
// 4 more empty “visit” methods
public void visitMethod(final Method aMethod) {
Integer count = null;
final String ckey = this.adaptor.adapt(this.currentClass);
final String mkey = this.adaptor.adapt(this.currentClass, aMethod);
final Map methodMap = this.methodMap(ckey);
count = this.getLOC(code);
methodMap.put(mkey, count);
}
// 6 more empty “visit” methods
}

164/213
away from the Visitor
 Refactoring

Practice

final FileInputStream fis = new FileInputStream(path);
final ClassParser parser = new ClassParser(fis, path);
final JavaClass clazz = parser.parse();
clazz.accept(this.instFinder);
fis.close();

public class BCELLOCFinder implements Visitor {
private JavaClass currentClass;

public void visitCode(final Code aCode) {
}
public void visitCodeException(final CodeException aCodeException) {

final FileInputStream fis = new FileInputStream(path);
}
// 18 other
final ClassParserempty “visit” methods ClassParser(fis, path);
parser = new
public void visitJavaClass(final JavaClass aClass) {
this.currentClass = parser.parse();
final JavaClass clazz = aClass;
final Method[] methods = aClass.getMethods();

clazz.accept(this.instFinder);
for (int i = 0; i < methods.length;
fis.close(); }

i++) {

this.visitMethod(methods[i]);

}
// 4 more empty “visit” methods
public void visitMethod(final Method aMethod) {
Integer count = null;
final String ckey = this.adaptor.adapt(this.currentClass);
final String mkey = this.adaptor.adapt(this.currentClass, aMethod);
final Map methodMap = this.methodMap(ckey);
count = this.getLOC(code);
methodMap.put(mkey, count);
}
// 6 more empty “visit” methods
}

165/213
away from the Visitor
 Refactoring

Practice

final FileInputStream fis = new FileInputStream(path);
final ClassParser parser = new ClassParser(fis, path);
final JavaClass clazz = parser.parse();
clazz.accept(this.instFinder);
fis.close();

public class BCELLOCFinder implements Visitor {
private JavaClass currentClass;

public void visitCode(final Code aCode) {
}
public void visitCodeException(final CodeException aCodeException) {
}
// 18 other empty “visit” methods
public void visitJavaClass(final JavaClass aClass) {
this.currentClass = aClass;
final Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
this.visitMethod(methods[i]);
}
}
// 4 more empty “visit” methods
public void visitMethod(final Method aMethod) {
Integer count = null;
final String ckey = this.adaptor.adapt(this.currentClass);
final String mkey = this.adaptor.adapt(this.currentClass, aMethod);
final Map methodMap = this.methodMap(ckey);
count = this.getLOC(code);
methodMap.put(mkey, count);
}
// 6 more empty “visit” methods
}

166/213
away from the Visitor
 Refactoring

Practice

public final FileInputStream fis = new FileInputStream(path);
void visitJavaClass(final JavaClass aClass) {
final ClassParser parser = new ClassParser(fis, path);

this.currentClassparser.parse();
= aClass;
final JavaClass clazz =
clazz.accept(this.instFinder);
final Method[] methods = aClass.getMethods();
fis.close();

for (int i = 0; i < methods.length; i++) {
this.visitMethod(methods[i]);

public class BCELLOCFinder implements Visitor {
private JavaClass currentClass;

}

public void visitCode(final Code aCode) {

}

}
public void visitCodeException(final CodeException aCodeException) {
}
// 18 other empty “visit” methods
public void visitJavaClass(final JavaClass aClass) {
this.currentClass = aClass;
final Method[] methods = aClass.getMethods();
for (int i = 0; i < methods.length; i++) {
this.visitMethod(methods[i]);
}
}
// 4 more empty “visit” methods
public void visitMethod(final Method aMethod) {
Integer count = null;
final String ckey = this.adaptor.adapt(this.currentClass);
final String mkey = this.adaptor.adapt(this.currentClass, aMethod);
final Map methodMap = this.methodMap(ckey);
count = this.getLOC(code);
methodMap.put(mkey, count);
}
// 6 more empty “visit” methods
}

167/213
Practice
 Refactoring

away from the Visitor

– 28 empty methods
– Hard-coded call the visitMethod(…)
• See this.visitMethod(methods[i]);

– JavaClasses do not contain other similar
objects, they are not a Composite object
– Unnecessary code, complexity
168/213
Practice
 Refactoring

away from the Visitor

– 28 empty methods
– Hard-coded call the visitMethod(…)
• See this.visitMethod(methods[i]);

– JavaClasses do not contain other similar
objects, they are not a Composite object
– Unnecessary code, complexity
169/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

170/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

Flexibility

171/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

Flexibility

Complexity

172/213
Practice
 Trade-offs

of (most of) design patterns

– Flexibility
• Favouring composition over inheritance

– Complexity
• More objects interacting
• More messages exchanged

173/213
Practice
 Trade-offs

of (most of) design patterns

– Flexibility
• Favouring composition over inheritance

– Complexity
• More objects interacting
• More messages exchanged

174/213
m : Mai n

cu :
CompilationUnit

c : Class

m : Method

s : Statem ent

v : IVisitor

accept(IVisitor)
open(Com pilationUnit)

a ccept(IVisitor)

m : Main

cu :
CompilationUnit

c : Class

m : Method

s : Statement

o pen(Cl as s)

accept(IVisitor)

generateCode( )

open(Method)

generateCode( )
a ccept(IVis itor)
visit(Statement)

generateCode( )
generateCode( )

clos e(Method)

close(C lass)

clos e(Compil ationUn it)

175/213
m : Mai n

cu :
CompilationUnit

c : Class

m : Method

s : Statem ent

v : IVisitor

accept(IVisitor)
open(Com pilationUnit)

a ccept(IVisitor)

m : Main

cu :
CompilationUnit

c : Class

m : Method

s : Statement

o pen(Cl as s)

accept(IVisitor)

generateCode( )

open(Method)

generateCode( )
a ccept(IVis itor)
visit(Statement)

generateCode( )
generateCode( )

Plus the use of reflection!

clos e(Method)

close(C lass)

clos e(Compil ationUn it)

176/213
Practice
 Trade-offs

of (most of) design patterns

– Flexibility
• Favouring composition over inheritance

– Complexity
• More objects interacting
• More messages exchanged

177/213
Practice
 Trade-offs

of (most of) design patterns

– Flexibility
• Favouring composition over inheritance

– Complexity
• More objects interacting
• More messages exchanged

178/213
Practice
 Flexibility

– Favour composition over inheritance
• Allow changing implementation
• Allow safe inheritance

179/213
Practice
 Flexibility

– Favour composition over inheritance
• Allow changing implementation
• Allow safe inheritance

Add one level of indirection

180/213
Practice
 Flexibility

– Favour composition over inheritance
• Allow changing implementation
• Allow safe inheritance

Add one level of indirection
and (possibly)

Use double-dispatch
181/213
Practice
 Add

one level of indirection

“Rather than giving you a lengthy explanation,
let me just point you to the Strategy pattern. It is
my prototypical example for the flexibility of
composition over inheritance.”
Erich Gamma, 2005

182/213
Practice
 Add

one level of indirection

http://itewbm.tistory.com/29

183/213
Practice
 Add

one level of indirection

http://itewbm.tistory.com/29

184/213
Practice
 Add

one level of indirection

http://itewbm.tistory.com/29

185/213
Practice
 Add

one level of indirection

http://programmers.stackexchange.com/questions/203210/
is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir

186/213
187/213
Practice
 Add

one level of indirection

http://programmers.stackexchange.com/questions/203210/
is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir

188/213
No
spe
Practice with th cial co
eN
de
ullO for
bje “no
beh
 Add one level of indirection ct d
esi
avi
gn
our
pat
”
tern

http://programmers.stackexchange.com/questions/203210/
is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir

189/213
Practice
 Add

Enc
aps
u

late

one level of indirection

http://programmers.stackexchange.com/questions/203210/
is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir

wh
at v

arie
s

190/213
Practice
 Add

one level of indirection

“You have a container, and you plug in some
smaller objects. These smaller objects
configure the container and customize the
behaviour of the container. This is possible
since the container delegates some behaviour
to the smaller thing. In the end you get
customization by configuration. ”
Erich Gamma, 2005
(With minor adaptations)

191/213
Practice
 Add

one level of indirection

“You have a container, and you plug in some
smaller objects. These smaller objects
configure the container and customize the
behaviour of the container. This is possible
since the container delegates some behaviour
to the smaller thing. In the end you get
customization by configuration. ”
Erich Gamma, 2005
(With minor adaptations)

192/213
Practice
 Use

double-dispatch

– Object receives a message
– Object sends a message back
with itself as parameter

193/213
Practice
 Use

double-dispatch

– Object receives a message
– Object sends a message back
with itself as parameter

194/213
Practice


print(CtxWriter aCTXWriter, Rect aRectangle) { ... }
...
print(StringWriter aStringWriter, Triangle aTriangle) { ... }
...

PrinterWriter printer = new SystemWriter();
IShape shape = new Square();
print(printer, shape);
195/213
Practice


print(CtxWriter aCTXWriter, Rect aRectangle) { ... }
...
print(StringWriter aStringWriter, Triangle aTriangle) { ... }
...

PrinterWriter printer = new SystemWriter();
IShape shape = new Square();
print(printer, shape);
196/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

197/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

198/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

199/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

200/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

201/213
public class Main {
public static void main(final String[] args) {
final PrinterWriter writer = new SystemWriter();
IShape shape;
shape = new Rect();
shape.printOn(writer);
shape = new Square();
shape.printOn(writer);

public class SystemWriter implements PrinterWriter {
@Override
public void print(final Rect rect) {
System.out.print("Printed the rectangle: ");
System.out.println(this);
}
@Override
public void print(final Square aSquare) {
System.out.print("Printed the square: ");
System.out.println(this);
}
}

}
}

public interface PrinterWriter {
void print(final Rect aRect);
void print(final Square aSquare);
...
}

public interface IShape {
void printOn(final PrinterWriter aWriter);
}

http://c2.com/cgi-bin/wiki?DoubleDispatchExample
http://www.patentstorm.us/patents/6721807/description.html

public class Rect implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

public class Square implements IShape {
@Override
public void printOn(final PrinterWriter aWriter) {
aWriter.print(this);
}
}

202/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

203/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

Flexibility

204/213
Practice
 Unnecessary

code, complexity

– Trade-offs of (most of) design patterns

Flexibility

Complexity

205/213
Practice
 Beware

also of “bad” solutions to recurring
design problems

http://www.jot.fm/issues/issue_2006_07/column4/

206/213
Practice
 Anti-patterns

(also antipatterns)

– A common response to a
recurring problem that is usually
ineffective and may be
counterproductive
– Code smells are symptoms of
“bad” programming

207/213
Practice
 Two

examples of anti-patterns

– Visitor design and JavaClasses
ptidej.statement.creator.classfiles.loc.BCELLOCFinder

– Blob (aka God Class)

208/213
Outline
 Definition
 Quality
 Form
 Example
 Catalogue
 Practice
 Conclusion
209/213
Conclusion
 Patterns

ease communication

 Patterns

improve regularity

and quality… even without a name…
 Patterns

avoid surprises

i.e., reinventing the wheel differently each time
 Patterns

generate architectures
210/213
Conclusion
 Identify

a recurring design problem

 Identify

a design pattern that potentially
solve the problem

 Assess

the costs and benefits of
implementing the proposed solution
– Quality and quality without a name
211/213
Conclusion
 Identify

a recurring design problem

 Identify

that the solution brings

– Unneeded flexibility
– Unnecessary complexity
 Assess

the costs and benefits of removing
the proposed solution
212/213
Conclusion
 Tools

supporting design patterns

– “GoF” book
• Lists, classifications, relationships [Gamma et al., 1996]

– CASE Tools
• Fragments [Florijn et al., 1997]
• PatternsBox and Ptidej [Albin et al., 2001]
• Refactoring tools…

– Navigation
• Tutor [Motelet, 2000]
213/213

Contenu connexe

Tendances (20)

Ch03lect1 ud
Ch03lect1 udCh03lect1 ud
Ch03lect1 ud
 
Design pattern
Design patternDesign pattern
Design pattern
 
Ch04lect1 ud
Ch04lect1 udCh04lect1 ud
Ch04lect1 ud
 
Design Patterns - General Introduction
Design Patterns - General IntroductionDesign Patterns - General Introduction
Design Patterns - General Introduction
 
Ch08lect3 ud
Ch08lect3 udCh08lect3 ud
Ch08lect3 ud
 
Complexity
ComplexityComplexity
Complexity
 
Ch06lect1 ud
Ch06lect1 udCh06lect1 ud
Ch06lect1 ud
 
Ch08lect2 ud
Ch08lect2 udCh08lect2 ud
Ch08lect2 ud
 
Ch10lect1 ud
Ch10lect1 udCh10lect1 ud
Ch10lect1 ud
 
Context-Oriented Programming
Context-Oriented ProgrammingContext-Oriented Programming
Context-Oriented Programming
 
Ch07lect1 ud
Ch07lect1 udCh07lect1 ud
Ch07lect1 ud
 
Circuit design presentation
Circuit design presentationCircuit design presentation
Circuit design presentation
 
Ch09lect2 ud
Ch09lect2 udCh09lect2 ud
Ch09lect2 ud
 
Ch11lect1 ud
Ch11lect1 udCh11lect1 ud
Ch11lect1 ud
 
Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)Design Patterns (Examples in .NET)
Design Patterns (Examples in .NET)
 
Ch10lect2 ud
Ch10lect2 udCh10lect2 ud
Ch10lect2 ud
 
Thesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.pptThesis+of+laleh+eshkevari.ppt
Thesis+of+laleh+eshkevari.ppt
 
Gof design patterns
Gof design patternsGof design patterns
Gof design patterns
 
Icsme16.ppt
Icsme16.pptIcsme16.ppt
Icsme16.ppt
 
Design Principles of Advanced Task Elicitation Systems
Design Principles of Advanced Task Elicitation SystemsDesign Principles of Advanced Task Elicitation Systems
Design Principles of Advanced Task Elicitation Systems
 

En vedette

Software Design Patterns in Theory
Software Design Patterns in TheorySoftware Design Patterns in Theory
Software Design Patterns in TheoryPtidej Team
 
Quality and Software Design Patterns
Quality and Software Design PatternsQuality and Software Design Patterns
Quality and Software Design PatternsPtidej Team
 
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future Challenges
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future ChallengesAsianPLoP'14: How and Why Design Patterns Impact Quality and Future Challenges
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future ChallengesPtidej Team
 
Icsm07 tooldemo.pdf
Icsm07 tooldemo.pdfIcsm07 tooldemo.pdf
Icsm07 tooldemo.pdfPtidej Team
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns pptmkruthika
 
Recommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentRecommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentFrancis Palma
 
PRDCW-advanced-design-patterns
PRDCW-advanced-design-patternsPRDCW-advanced-design-patterns
PRDCW-advanced-design-patternsAmir Barylko
 
PRDC12 advanced design patterns
PRDC12 advanced design patternsPRDC12 advanced design patterns
PRDC12 advanced design patternsAmir Barylko
 
Unity - Software Design Patterns
Unity - Software Design PatternsUnity - Software Design Patterns
Unity - Software Design PatternsDavid Baron
 
Icsoc12 tooldemo.ppt
Icsoc12 tooldemo.pptIcsoc12 tooldemo.ppt
Icsoc12 tooldemo.pptPtidej Team
 

En vedette (20)

Software Design Patterns in Theory
Software Design Patterns in TheorySoftware Design Patterns in Theory
Software Design Patterns in Theory
 
Quality and Software Design Patterns
Quality and Software Design PatternsQuality and Software Design Patterns
Quality and Software Design Patterns
 
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future Challenges
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future ChallengesAsianPLoP'14: How and Why Design Patterns Impact Quality and Future Challenges
AsianPLoP'14: How and Why Design Patterns Impact Quality and Future Challenges
 
Icsm07 tooldemo.pdf
Icsm07 tooldemo.pdfIcsm07 tooldemo.pdf
Icsm07 tooldemo.pdf
 
Mribp13.ppt
Mribp13.pptMribp13.ppt
Mribp13.ppt
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
Software design patterns ppt
Software design patterns pptSoftware design patterns ppt
Software design patterns ppt
 
Recommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software DevelopmentRecommendation System for Design Patterns in Software Development
Recommendation System for Design Patterns in Software Development
 
Software Design Patterns
Software Design PatternsSoftware Design Patterns
Software Design Patterns
 
PRDCW-advanced-design-patterns
PRDCW-advanced-design-patternsPRDCW-advanced-design-patterns
PRDCW-advanced-design-patterns
 
PRDC12 advanced design patterns
PRDC12 advanced design patternsPRDC12 advanced design patterns
PRDC12 advanced design patterns
 
Unity - Software Design Patterns
Unity - Software Design PatternsUnity - Software Design Patterns
Unity - Software Design Patterns
 
Wcre12b.ppt
Wcre12b.pptWcre12b.ppt
Wcre12b.ppt
 
See12.ppt
See12.pptSee12.ppt
See12.ppt
 
Icsoc12 tooldemo.ppt
Icsoc12 tooldemo.pptIcsoc12 tooldemo.ppt
Icsoc12 tooldemo.ppt
 
Wcre13b.ppt
Wcre13b.pptWcre13b.ppt
Wcre13b.ppt
 
Ppap13b.ppt
Ppap13b.pptPpap13b.ppt
Ppap13b.ppt
 
Ppap13a.ppt
Ppap13a.pptPpap13a.ppt
Ppap13a.ppt
 
Wcre12c.ppt
Wcre12c.pptWcre12c.ppt
Wcre12c.ppt
 
Wcre13a.ppt
Wcre13a.pptWcre13a.ppt
Wcre13a.ppt
 

Similaire à Software Design Patterns in Practice

Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoJoel Falcou
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing ScenarioTara Hardin
 
Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#CodeOps Technologies LLP
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already KnowKevlin Henney
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311Andreas Pauley
 
Deep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowDeep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowOswald Campesato
 
Feature-Oriented Software Evolution
Feature-Oriented Software EvolutionFeature-Oriented Software Evolution
Feature-Oriented Software EvolutionLeonardo Passos
 
Generic Programming Galore Using D
Generic Programming Galore Using DGeneric Programming Galore Using D
Generic Programming Galore Using DAndrei Alexandrescu
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Codemotion
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingEelco Visser
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingEelco Visser
 
F# Ignite - DNAD2010
F# Ignite - DNAD2010F# Ignite - DNAD2010
F# Ignite - DNAD2010Rodrigo Vidal
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia岳華 杜
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesGanesh Samarthyam
 

Similaire à Software Design Patterns in Practice (20)

Designing Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.ProtoDesigning Architecture-aware Library using Boost.Proto
Designing Architecture-aware Library using Boost.Proto
 
Addressing Scenario
Addressing ScenarioAddressing Scenario
Addressing Scenario
 
Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#Compiler Case Study - Design Patterns in C#
Compiler Case Study - Design Patterns in C#
 
Functional Programming You Already Know
Functional Programming You Already KnowFunctional Programming You Already Know
Functional Programming You Already Know
 
An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311An Introduction to Functional Programming - DeveloperUG - 20140311
An Introduction to Functional Programming - DeveloperUG - 20140311
 
030325+seminar+scg+iam.ppt
030325+seminar+scg+iam.ppt030325+seminar+scg+iam.ppt
030325+seminar+scg+iam.ppt
 
Deep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlowDeep Learning: R with Keras and TensorFlow
Deep Learning: R with Keras and TensorFlow
 
Feature-Oriented Software Evolution
Feature-Oriented Software EvolutionFeature-Oriented Software Evolution
Feature-Oriented Software Evolution
 
Generic Programming Galore Using D
Generic Programming Galore Using DGeneric Programming Galore Using D
Generic Programming Galore Using D
 
Introduction to Domain-Driven Design
Introduction to Domain-Driven DesignIntroduction to Domain-Driven Design
Introduction to Domain-Driven Design
 
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
Functional Programming You Already Know - Kevlin Henney - Codemotion Rome 2015
 
Experimental dtrace
Experimental dtraceExperimental dtrace
Experimental dtrace
 
Declare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term RewritingDeclare Your Language: Transformation by Strategic Term Rewriting
Declare Your Language: Transformation by Strategic Term Rewriting
 
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term RewritingCS4200 2019 | Lecture 5 | Transformation by Term Rewriting
CS4200 2019 | Lecture 5 | Transformation by Term Rewriting
 
Introduction to Prolog
Introduction to PrologIntroduction to Prolog
Introduction to Prolog
 
F# Ignite - DNAD2010
F# Ignite - DNAD2010F# Ignite - DNAD2010
F# Ignite - DNAD2010
 
Scala and Deep Learning
Scala and Deep LearningScala and Deep Learning
Scala and Deep Learning
 
Introduction to Julia
Introduction to JuliaIntroduction to Julia
Introduction to Julia
 
Design Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on ExamplesDesign Patterns - Compiler Case Study - Hands-on Examples
Design Patterns - Compiler Case Study - Hands-on Examples
 
Dafunctor
DafunctorDafunctor
Dafunctor
 

Plus de Ptidej Team

From IoT to Software Miniaturisation
From IoT to Software MiniaturisationFrom IoT to Software Miniaturisation
From IoT to Software MiniaturisationPtidej Team
 
Presentation by Lionel Briand
Presentation by Lionel BriandPresentation by Lionel Briand
Presentation by Lionel BriandPtidej Team
 
Manel Abdellatif
Manel AbdellatifManel Abdellatif
Manel AbdellatifPtidej Team
 
Azadeh Kermansaravi
Azadeh KermansaraviAzadeh Kermansaravi
Azadeh KermansaraviPtidej Team
 
CSED - Manel Grichi
CSED - Manel GrichiCSED - Manel Grichi
CSED - Manel GrichiPtidej Team
 
Cristiano Politowski
Cristiano PolitowskiCristiano Politowski
Cristiano PolitowskiPtidej Team
 
Will io t trigger the next software crisis
Will io t trigger the next software crisisWill io t trigger the next software crisis
Will io t trigger the next software crisisPtidej Team
 
Thesis+of+nesrine+abdelkafi.ppt
Thesis+of+nesrine+abdelkafi.pptThesis+of+nesrine+abdelkafi.ppt
Thesis+of+nesrine+abdelkafi.pptPtidej Team
 
Thesis+of+étienne+duclos.ppt
Thesis+of+étienne+duclos.pptThesis+of+étienne+duclos.ppt
Thesis+of+étienne+duclos.pptPtidej Team
 

Plus de Ptidej Team (20)

From IoT to Software Miniaturisation
From IoT to Software MiniaturisationFrom IoT to Software Miniaturisation
From IoT to Software Miniaturisation
 
Presentation
PresentationPresentation
Presentation
 
Presentation
PresentationPresentation
Presentation
 
Presentation
PresentationPresentation
Presentation
 
Presentation by Lionel Briand
Presentation by Lionel BriandPresentation by Lionel Briand
Presentation by Lionel Briand
 
Manel Abdellatif
Manel AbdellatifManel Abdellatif
Manel Abdellatif
 
Azadeh Kermansaravi
Azadeh KermansaraviAzadeh Kermansaravi
Azadeh Kermansaravi
 
Mouna Abidi
Mouna AbidiMouna Abidi
Mouna Abidi
 
CSED - Manel Grichi
CSED - Manel GrichiCSED - Manel Grichi
CSED - Manel Grichi
 
Cristiano Politowski
Cristiano PolitowskiCristiano Politowski
Cristiano Politowski
 
Will io t trigger the next software crisis
Will io t trigger the next software crisisWill io t trigger the next software crisis
Will io t trigger the next software crisis
 
MIPA
MIPAMIPA
MIPA
 
Thesis+of+nesrine+abdelkafi.ppt
Thesis+of+nesrine+abdelkafi.pptThesis+of+nesrine+abdelkafi.ppt
Thesis+of+nesrine+abdelkafi.ppt
 
Medicine15.ppt
Medicine15.pptMedicine15.ppt
Medicine15.ppt
 
Qrs17b.ppt
Qrs17b.pptQrs17b.ppt
Qrs17b.ppt
 
Icpc11c.ppt
Icpc11c.pptIcpc11c.ppt
Icpc11c.ppt
 
Icsme16.ppt
Icsme16.pptIcsme16.ppt
Icsme16.ppt
 
Msr17a.ppt
Msr17a.pptMsr17a.ppt
Msr17a.ppt
 
Icsoc15.ppt
Icsoc15.pptIcsoc15.ppt
Icsoc15.ppt
 
Thesis+of+étienne+duclos.ppt
Thesis+of+étienne+duclos.pptThesis+of+étienne+duclos.ppt
Thesis+of+étienne+duclos.ppt
 

Dernier

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyAlfredo García Lavilla
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piececharlottematthew16
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024BookNet Canada
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Patryk Bandurski
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLScyllaDB
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Mattias Andersson
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024Stephanie Beckett
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsSergiu Bodiu
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsMark Billinghurst
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 3652toLead Limited
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsMemoori
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr BaganFwdays
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024Lorenzo Miniero
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxNavinnSomaal
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Commit University
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr LapshynFwdays
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxhariprasad279825
 

Dernier (20)

Commit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easyCommit 2024 - Secret Management made easy
Commit 2024 - Secret Management made easy
 
Story boards and shot lists for my a level piece
Story boards and shot lists for my a level pieceStory boards and shot lists for my a level piece
Story boards and shot lists for my a level piece
 
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
Transcript: New from BookNet Canada for 2024: BNC CataList - Tech Forum 2024
 
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
Integration and Automation in Practice: CI/CD in Mule Integration and Automat...
 
Developer Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQLDeveloper Data Modeling Mistakes: From Postgres to NoSQL
Developer Data Modeling Mistakes: From Postgres to NoSQL
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?Are Multi-Cloud and Serverless Good or Bad?
Are Multi-Cloud and Serverless Good or Bad?
 
What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024What's New in Teams Calling, Meetings and Devices March 2024
What's New in Teams Calling, Meetings and Devices March 2024
 
DevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platformsDevEX - reference for building teams, processes, and platforms
DevEX - reference for building teams, processes, and platforms
 
Human Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR SystemsHuman Factors of XR: Using Human Factors to Design XR Systems
Human Factors of XR: Using Human Factors to Design XR Systems
 
Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365Ensuring Technical Readiness For Copilot in Microsoft 365
Ensuring Technical Readiness For Copilot in Microsoft 365
 
AI as an Interface for Commercial Buildings
AI as an Interface for Commercial BuildingsAI as an Interface for Commercial Buildings
AI as an Interface for Commercial Buildings
 
"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan"ML in Production",Oleksandr Bagan
"ML in Production",Oleksandr Bagan
 
SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024SIP trunking in Janus @ Kamailio World 2024
SIP trunking in Janus @ Kamailio World 2024
 
SAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptxSAP Build Work Zone - Overview L2-L3.pptx
SAP Build Work Zone - Overview L2-L3.pptx
 
Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!Nell’iperspazio con Rocket: il Framework Web di Rust!
Nell’iperspazio con Rocket: il Framework Web di Rust!
 
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
"Federated learning: out of reach no matter how close",Oleksandr Lapshyn
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Artificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptxArtificial intelligence in cctv survelliance.pptx
Artificial intelligence in cctv survelliance.pptx
 

Software Design Patterns in Practice

  • 1. Some Theory and Practice on Patterns – In Practice Yann-Gaël Guéhéneuc NII, Tokyo, Japan 12/02/14 This work is licensed under a Creative Commons Attribution-NonCommercialShareAlike 3.0 Unported License
  • 2. Patterns  Patterns document reusable solutions to recurring problems – Architecture • Architectural styles – Design • Design patterns • Design anti-patterns – Implementation • Idioms 2/213
  • 3. Examples  Do you know – C++? – Java? – Lisp? – Prolog? – Smalltalk? 3/213
  • 4. C++ class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 4/213
  • 5. C++ class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; ? Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 5/213
  • 6. C++ class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Overriding of operator = ? Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 6/213
  • 7. Java final Object oldListOfEntities = this.listOfEntities(); this.fireVetoableChange( "RemoveEntity", oldListOfEntities, anEntity); this.removeEntity(anEntity); this.firePropertyChange( "RemoveEntity", oldListOfEntities, anEntity); 7/213
  • 8. Java final Object oldListOfEntities = this.listOfEntities(); this.fireVetoableChange( "RemoveEntity", oldListOfEntities, anEntity); this.removeEntity(anEntity); this.firePropertyChange( "RemoveEntity", oldListOfEntities, anEntity); ? 8/213
  • 9. Java final Object oldListOfEntities = this.listOfEntities(); this.fireVetoableChange( "RemoveEntity", oldListOfEntities, anEntity); this.removeEntity(anEntity); this.firePropertyChange( "RemoveEntity", oldListOfEntities, anEntity); Veto protocol of JavaBeans ? 9/213
  • 10. Lisp (define (square ls) (if (null? ls) '() (cons ((lambda(x) (* x x)) (car ls)) (square (cdr ls))))) 10/213
  • 11. Lisp (define (square ls) (if (null? ls) '() (cons ((lambda(x) (* x x)) (car ls)) (square (cdr ls))))) ? 11/213
  • 12. Lisp (define (square ls) (if (null? ls) '() (cons ((lambda(x) (* x x)) (car ls)) (square (cdr ls))))) ? Map 12/213
  • 13. Prolog checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent( [], E), interpretEvent(E, IE), checkLt1(IE, LA, LT, LD, NLA, NLT, NLD), !, ( (IE = programEnd, NNLA = NLA, NNLT = NLT, NNLD = NLD) ; checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD) ). 13/213
  • 14. Prolog checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent( [], E), interpretEvent(E, IE), checkLt1(IE, LA, LT, LD, NLA, NLT, NLD), !, ( (IE = programEnd, NNLA = NLA, NNLT = NLT, NNLD = NLD) ; checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD) ). ? 14/213
  • 15. Prolog checkLt0(LA, LT, LD, NNLA, NNLT, NNLD) :nextEvent( [], E), interpretEvent(E, IE), checkLt1(IE, LA, LT, LD, NLA, NLT, NLD), !, ( (IE = programEnd, NNLA = NLA, NNLT = NLT, NNLD = NLD) ; checkLt0(NLA, NLT, NLD, NNLA, NNLT, NNLD) ). ? Conditional 15/213
  • 16. Smalltalk Integer>>+ aNumber ^aNumber addInteger: self Float>>+ aNumber ^aNumber addFloat: self Integer>>addInteger: anInteger <primitive: 1> Float>>addFloat: aFloat <primitive: 2> Integer>>addFloat: aFloat ^self asFloat addFloat: aFloat Float>>addInteger: anInteger ^self addFloat: anInteger asFloat Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X. 16/213
  • 17. Smalltalk Integer>>+ aNumber ^aNumber addInteger: self Float>>+ aNumber ^aNumber addFloat: self Integer>>addInteger: anInteger <primitive: 1> Float>>addFloat: aFloat <primitive: 2> Integer>>addFloat: aFloat ^self asFloat addFloat: aFloat Float>>addInteger: anInteger ^self addFloat: anInteger asFloat ? Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X. 17/213
  • 18. Smalltalk Integer>>+ aNumber ^aNumber addInteger: self Float>>+ aNumber ^aNumber addFloat: self Integer>>addInteger: anInteger <primitive: 1> Float>>addFloat: aFloat <primitive: 2> Integer>>addFloat: aFloat ^self asFloat addFloat: aFloat Float>>addInteger: anInteger ^self addFloat: anInteger asFloat Double dispatch ? Kent Beck ; Smalltalk – Best practice patterns ; Pages 55–57, Prentice Hall, 1997, ISBN 0-13-476904-X. 18/213
  • 19. Conclusion on the Examples  The examples showed idioms in the given pieces of source code – These idioms are recurring motifs in a program source code – These motifs connote a recognized, acknowledge style of programming 19/213
  • 20. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 20/213
  • 21. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 21/213
  • 22. Definition  Context – 1977 et 1979: architecture • Christopher Alexander • A Pattern Language: Towns, Buildings, Construction and the idea of generative patterns • The Timeless Way of Building and the idea of perfection in architecture – 1990: object-oriented design • Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides† • Design Patterns drawn from experience 22/213
  • 23. Definition A Pattern Language: Towns, Buildings, Construction – 253 patterns – Generative grammar – “At the core... is the idea that people should design for themselves their own houses, streets and communities. This idea... comes simply from the observation that most of the wonderful places of the world were not made by architects but by the people.” 23/213
  • 24. Definition “Each pattern describes a problem which occurs over and over again in our environment, and then describes the core of the solution to that problem, in such way that you can use this solution a million times over, without ever doing it the same way twice.” —Christopher Alexander, 1977 “Each pattern is a three part rule, which express a relation between a context, a problem, and a solution.” —Christopher Alexander, 1977 24/213
  • 26. Definition  Design Patterns: Elements of Reusable OO Software – 23 patterns – Not a language? – “Dynamic, highly parameterized software is harder to understand and build than more static software.” 26/213
  • 27. Definition “The strict modeling of the real world leads to reflect today’s realities but not necessarily tomorrow’s. The abstractions that emerge during design are key to making a design flexible.” —Erich Gamma, 1994 27/213
  • 29. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance 29/213
  • 30. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance – Patterns have been identified for • • • • Different phases of software development Different levels of abstraction Different technologies … 30/213
  • 31. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance 31/213
  • 32. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance – Problem faced by three people at three different times in a similar context – Particular problems are not included, except if they occur more than three times… 32/213
  • 33. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance 33/213
  • 34. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance – Essentially, a solution must describe steps to solve the problem • Architecture • Design • Implementation 34/213
  • 35. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance 35/213
  • 36. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance – The solution must not be particular – The solution can be adapted – The solution must be adapted 36/213
  • 37. Definition A pattern is a general reusable solution to a commonly occurring problem within a given context in software development, operation, and maintenance – The solution must not be particular – The solution can be adapted – The solution must be adapted • Forces • Variants 37/213
  • 38. Recall the C++ Example class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 38/213
  • 39. Recall the C++ Example class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 39/213
  • 40. Recall the C++ Example class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Development, operation, and maintenance Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 40/213
  • 41. Recall the C++ Example class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Development, operation, and maintenance Commonly occurring problem within a given context Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 41/213
  • 42. Recall the C++ Example class Dog { string name; Dog(const Dog* dog) : name(dogname) {}} class Kennel { Dog* dog; string name; } if (&kennel != this) { thisdog = new Dog(kennel.dog); thisname = kennel.name; } return *this; Development, operation, and maintenance Commonly occurring problem within a given context General reusable solution Bruce Eckel ; Thinking in C++ ; Volume 2, pages 551–553, Planet PDF, 2nd Edition, 2000. 42/213
  • 43. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 43/213
  • 44. Quality A means to enhance the reusability – Of the code written using the pattern + Its flexibility – Of the problem and its solution     44/213
  • 45. Quality A means to enhance the reusability – Of the code written using the pattern + Its flexibility – Of the problem and its solution A means to encapsulate design experience    45/213
  • 46. Quality A means to enhance the reusability – Of the code written using the pattern + Its flexibility – Of the problem and its solution A means to encapsulate design experience  A common vocabulary among designers   46/213
  • 47. Quality A means to enhance the reusability – Of the code written using the pattern + Its flexibility – Of the problem and its solution A means to encapsulate design experience  A common vocabulary among designers A means to have that “quality without a name” 47/213
  • 48. Quality Without a Name     48/213
  • 49. Quality Without a Name “There is a point you reach in tightening a nut, where you know that to tighten just a little more might strip the thread, but to leave it slightly looser would risk having the hut coming off from vibration. If you've worked with your hands a lot, you know what this means, but the advice itself is meaningless.” —Robert Pirsig, circa. 1972   49/213
  • 50. Quality Without a Name “There is a point you reach in tightening a nut, where you know that to tighten just a little more might strip the thread, but to leave it slightly looser would risk having the hut coming off from vibration. If you've worked with your hands a lot, you know what this means, but the advice itself is meaningless.” —Robert Pirsig, circa. 1972 “[T]oo often software developers spend their days grinding away for pay at programs they neither need nor love. But not in the Linux world - which may explain why the average quality of software originated in the Linux community is so high.” —Eric Raymond, 1998 50/213
  • 51. Quality Without a Name 51/213
  • 52. Quality Without a Name ニワトリのヒナの雌雄鑑別 (chick sexing)   http://discovermagazine.com/2011/sep/18-your-brain-knows-lot-more-than-you-realize 52/213
  • 53. Quality Without a Name ニワトリのヒナの雌雄鑑別 (chick sexing) “The master would stand over the apprentice and watch. The student would pick up a chick, examine its rear, and toss it into one bin or the other. The master would give feedback: yes or no.” —Eagleman, 2011 http://discovermagazine.com/2011/sep/18-your-brain-knows-lot-more-than-you-realize 53/213
  • 57. Quality  Rationale – “Software design is widely recognised as being a “wicked” or “ill-structured” problem, characterised by ambiguous specifications, no true/false solutions (only ones that are “better” or “worse” from a particular perspective), the lack of any “stopping rule” to determine when a solution has been reached, and no ultimate test of whether a solution meets the requirements.” —Zhang and Budgen, 2012 57/213
  • 58. Quality “Important assumptions – That patterns can be codified in such a way that they can be shared between different designers – That reuse will lead to “better” designs. There is an obvious question here of what constitutes “better”, but a key measure is maintainability” —Zhang and Budgen, 2012 (With minor adaptations) 58/213
  • 59. Quality “Advantages: – Using patterns improves programmer productivity and program quality – Novices can increase their design skills significantly by studying and applying patterns – Patterns encourage best practices, even for experiences designers – Design patterns improve communication, both among developers and from developers to maintainers” —Zhang and Budgen, 2012 (With minor adaptations) 59/213
  • 60. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 60/213
  • 61. Form  Several books, articles – “Theoretical” – With examples – Among others… 61/213
  • 62. Form  Several books, articles – “Theoretical” – With examples – Among others… 62/213
  • 63. Form  Several books, articles – “Theoretical” – With examples – Among others… 63/213
  • 64. Form  Several books, articles – “Theoretical” – With examples – Among others… 64/213
  • 65. Form  Several books, articles – “Theoretical” – With examples – Among others… 65/213
  • 66. Form  Several books, articles – “Theoretical” – With examples – Among others… 66/213
  • 67. Form  Several books, articles – Amazon.com • Books › Computers & Technology › Programming › Software Design, Testing & Engineering › ObjectOriented Design › "patterns" • 224 results on May 31, 2013 67/213
  • 68. Form  Several books, articles – Amazon.com • Exclusion – Unreleased books – Specific to a technology or frameworks » e.g., MVVM Unleashed by Michael Brown – Process oriented, user-interface, programming languages » e.g., Process Patterns: Building Large-Scale Systems Using Object Technology by Scott W. Ambler and Barbara Hanscome – Proceedings of conferences – Unrelated to software engineering 68/213
  • 69. Form 1. 2. 3. 4. 5. 6. 7. 8. 9. 10. 11. 12. 13. 14. 15. 16. 17. 18. 19. 20. 21. 22. 23. 24. 25. 26. 27. 28. 29. 30. 31. 32. 33. 34. 35. Pattern-Oriented Software Architecture, Patterns for Concurrent and Networked Objects: Volume 2 (Wiley Software... by Douglas C. Schmidt, Michael Stal, Hans Rohnert and Frank Buschmann Pattern-Oriented Software Architecture, Patterns for Resource Management: Volume 3 (Wiley Software Patterns Series... by Michael Kircher and Prashant Jain Pattern-Oriented Software Architecture, A System of Patterns: Volume 1 (Wiley Software Patterns Series) by Frank Buschmann, Regine Meunier, Hans Rohnert and Peter Sommerlad Pattern-Oriented Software Architecture For Dummies (For Dummies (Computers)) by Robert Hanmer Web Security Patterns by Ramesh Nagappan and Christopher Steel Safe C++ by Vladimir Kushnir Programming in the Large with Design Patterns by Eddie Burris Elemental Design Patterns by Jason McC. Smith Java Application Architecture: Modularity Patterns with Examples Using OSGi (Robert C. Martin Series) by Kirk Knoernschild Enterprise Integration Patterns: Designing, Building, and Deploying Messaging Solutions (Addison-Wesley Signature... by Gregor Hohpe and Bobby Woolf Patterns of Enterprise Application Architecture (Addison-Wesley Signature Series (Fowler)) by Martin Fowler Cognitive Patterns: Problem-Solving Frameworks for Object Technology by Robert K Konitzer, Bobbin Teegarden, Alexander Rush and Karen M Gardner Service Design Patterns: Fundamental Design Solutions for SOAP/WSDL and RESTful Web Services by Robert Daigneau The ACE Programmer's Guide: Practical Design Patterns for Network and Systems Programming by Stephen D. Huston, James CE Johnson and Umar Syyid Patterns for Parallel Software Design (Wiley Software Patterns Series) by Jorge Luis Ortega-Arjona Design Patterns in Object-oriented ABAP by Igor Barbaric Object-Oriented Reengineering Patterns by Oscar Nierstrasz, Stéphane Ducasse and Serge Demeyer Dependency Injection by Dhanji R. Prasanna Object-Oriented Software Engineering Using UML, Patterns, and Java (3rd Edition) by Bernd Bruegge and Allen H. Dutoit J2EE Design Patterns by William Crawford and Jonathan Kaplan Applying UML and Patterns: An Introduction to Object-oriented Analysis and Design and Iterative Development by Craig Larman Object-oriented Analysis and Design Using Umlan Introduction to Unified Process and Design Patterns by Mahesh P. Matha C++ Design Patterns and Derivatives Pricing (Mathematics, Finance and Risk) by M. S. Joshi Effective Java (2nd Edition) by Joshua Bloch Patterns for Fault Tolerant Software (Wiley Software Patterns Series) by Robert Hanmer Implementation Patterns by Kent Beck Patterns for Computer-Mediated Interaction (Wiley Software Patterns Series) by Till Schummer and Stephan Lukosch Pattern Oriented Software Architecture Volume 5: On Patterns and Pattern Languages by Frank Buschmann, Kevlin Henney and Douglas C. Schmidt Object-Oriented Analysis and Design with Applications (3rd Edition) by Grady Booch, Robert A. Maksimchuk, Michael W. Engle and Bobbi J. Young Head First Object-Oriented Analysis and Design by Brett D. McLaughlin, Gary Pollice and Dave West Agile Principles, Patterns, and Practices in C# by Robert C. Martin and Micah Martin Design Patterns For Dummies by Steve Holzner Pattern Languages of Program Design 5 by Dragos Manolescu, Markus Voelter and James Noble Design Patterns in Java(TM) (Software Patterns Series) by Steven John Metsker and William C. Wake Object-Oriented Design and Patterns by Cay S. Horstmann 37. 38. 39. 40. 41. 42. 43. 44. 45. 46. 47. 48. 49. 50. 51. 52. 53. 54. 55. 56. 57. 58. 59. 60. 61. 62. 63. 64. 65. 66. 67. 68. 69. 70. 71. 72. Object-Oriented Modeling and Design with UML (2nd Edition) by Michael R. Blaha and James R Rumbaugh Remoting Patterns: Foundations of Enterprise, Internet and Realtime Distributed Object Middleware (Wiley Software... by Markus Völter, Michael Kircher and Uwe Zdun Software Factories: Assembling Applications with Patterns, Models, Frameworks, and Tools (Wiley Application Development... by Jack Greenfield, Keith Short, Steve Cook and Stuart Kent Refactoring to Patterns by Joshua Kerievsky Architecting Enterprise Solutions: Patterns for High-Capability Internet-based Systems (Wiley Software Patterns... by Paul Dyson and Andrew Longshaw Enterprise Patterns and MDA: Building Better Software with Archetype Patterns and UML by Jim Arlow and Ila Neustadt Data Access Patterns: Database Interactions in Object-Oriented Applications by Clifton Nock Domain-Driven Design: Tackling Complexity in the Heart of Software by Eric Evans Pattern-Oriented Analysis and Design: Composing Patterns to Design Software Systems by Sherif M. Yacoub, Hany H. Ammar, Sherif Yacoub and Hany Ammar Java Extreme Programming Cookbook by Eric M. Burke and Brian M. Coyner J2EE Best Practices: Java Design Patterns, Automation, and Performance (Wiley Application Development Series) by Darren Broemmer Real-Time Design Patterns: Robust Scalable Architecture for Real-Time Systems by Bruce Powel Douglass Design Patterns Java¿ Workbook by Steven John Metsker EJB Design Patterns: Advanced Patterns, Processes, and Idioms by Floyd Marinescu Streamlined Object Modeling: Patterns, Rules, and Implementation by Jill Nicola, Mark Mayfield and Mike Abney Design Patterns Explained: A New Perspective on Object-Oriented Design by Alan Shalloway and James Trott Small Memory Software: Patterns for systems with limited memory (Software Patterns Series) by James Noble and Charles Weir AntiPatterns in Project Management by William J. Brown, Hays W. "Skip" McCormick III and Scott W. Thomas Pattern Languages of Program Design 4 (Software Patterns Series) by Brian Foote, Neil Harrison and Hans Rohnert Testing Object-Oriented Systems: Models, Patterns, and Tools by Robert V. Binder Design Patterns and Contracts by Jean-Marc Jezequel, Michel Train and Christine Mingins Object-Oriented Software Development Using Java: Principles, Patterns, and Frameworks (1/e) by Xiaoping Jia Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, John Brant and William Opdyke More Process Patterns: Delivering Large-Scale Systems Using Object Technology (SIGS: Managing Object Technology... by Scott W. Ambler Pattern Hatching: Design Patterns Applied by John Vlissides AntiPatterns: Refactoring Software, Architectures, and Projects in Crisis by William J. Brown, Raphael C. Malveau, Hays W. "Skip" McCormick and Thomas J. Mowbray A Little Java, A Few Patterns (Language, Speech, & Communication) by Matthias Felleisen, Daniel P. Friedman and Ralph E. Johnson Pattern Languages of Program Design 3 (v. 3) by Robert C. Martin, Dirk Riehle and Frank Buschmann Object Models: Strategies, Patterns, and Applications (2nd Edition) by Peter Coad, David North and Mark Mayfield Analysis Patterns: Reusable Object Models by Martin Fowler Patterns of Software: Tales from the Software Community by Richard P. Gabriel Pattern Languages of Program Design 2 (v. 2) by John Vlissides, James O. Coplien and Norman L. Kerth Software Patterns by James Coplien Software Architecture: Perspectives on an Emerging Discipline by Mary Shaw and David Garlan Adaptive Object-Oriented Software: The Demeter Method with Propagation Patterns: The Demeter Method with Propagation... by Karl Lieberherr Pattern Languages of Program Design by James O. Coplien and Douglas C. Schmidt 69/213
  • 70. Form “Each pattern is a three part rule, which express a relation between a context, a problem, and a solution.” —Christopher Alexander, 1977 70/213
  • 71. Form  General form as for the GoF also inspired by Coplien’s form – Name – Problem(s) – Solution – Consequences 71/213
  • 72. Form (Extended)  General form as for the GoF also inspired by Coplien’s form – Name – Problem(s) – Example(s) – Solution – Example(s) – Consequences – (Follow-up) 72/213
  • 73. Form  General form as for the GoF also inspired by Coplien’s form – Not formal – Room for interpretation – But… • UML-like class diagrams • UML-like sequence diagrams • Smalltalk / C++ example code 73/213
  • 74. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 74/213
  • 75. Example  Simplified (1/5) compiler – Parse files to build an AST – Iterate over the AST • Build DefaultMutableTreeNodes javax.swing.tree.DefaultMutableTreeNode for a graphical representation of the AST • Bind types • Generate code • … 75/213
  • 76. Example  Simplified (1/5) compiler – Parse files to build an AST – Iterate over the AST • Build DefaultMutableTreeNodes javax.swing.tree.DefaultMutableTreeNode for a graphical representation of the AST • Bind types • Generate code • … 76/213
  • 78. Example (3/5) package compiler; import java.util.Set; public class Method { private Set statements; public void addStatement(final Statement aStatement) { this.statements.add(aStatement); } public void removeStatement(final Statement aStatement) { this.statements.remove(aStatement); } } package compiler; package compiler; public class Field { /* To be implemented. */ } public class Statement { /* To be implemented. */ } 78/213
  • 79. Example (4/5) package compiler; import java.util.Set; public class Class { private String name; private Set methods; private Set fields; public String getName() { return this.name; } public void addMethod(final Method aMethod) { this.methods.add(aMethod); } public void removeMethod(final Method aMethod) { this.methods.remove(aMethod); } public void addField(final Method aField) { this.fields.add(aField); } public void removeField(final Field aField) { this.fields.remove(aField); } } 79/213
  • 80. Example (5/5) package compiler; import java.util.Iterator; import java.util.Set; public class CompilationUnit { private Set classes; public void addClass(final Class aClass) { this.classes.add(aClass); } public void removeClass(final Class aClass) { this.classes.remove(aClass); } public Class getClass(final String aName) { final Iterator iterator = this.classes.iterator(); while (iterator.hasNext()) { final Class aClass = (Class) iterator.next(); if (aClass.getName().equals(aName)) { return aClass; } } return null; } } 80/213
  • 81. Naïve Implementation  How (1/7) to generate microcode for – Microsoft Windows operating system – Intel Pentium processor 81/213
  • 82. Naïve Implementation  How (1/7) to generate microcode for – Microsoft Windows operating system – Intel Pentium processor Add a generateCode() method in each class 82/213
  • 83. Naïve Implementation (2/7) public class Method { … public String generateCode() { String generatedCode = ""; /* Do something at the beginning. */ final Iterator iterator = this.statements.iterator(); while (iterator.hasNext()) { final Statement aStatement = (Statement) iterator.next(); generatedCode += aStatement.generateCode(); } /* Do something at the end. */ return generatedCode; } } public class Field { … public String generateCode() { String generatedCode = ""; /* Do something. */ return generatedCode; } } public class Statement { … public String generateCode() { String generatedCode = ""; /* Do something. */ return generatedCode; } } 83/213
  • 84. Naïve Implementation (3/7) public class Class { … public String generateCode() { String generatedCode = ""; /* Do something at the beginning. */ final Iterator iteratorOnFields = this.fields.iterator(); while (iteratorOnFields.hasNext()) { final Field aField = (Field) iteratorOnFields.next(); generatedCode += aField.generateCode(); } final Iterator iteratorOnMethods = this.methods.iterator(); while (iteratorOnMethods.hasNext()) { final Method aMethod = (Method) iteratorOnMethods.next(); generatedCode += aMethod.generateCode(); } /* Do something at the end. */ return generatedCode; } } 84/213
  • 85. Naïve Implementation (4/7) public class CompilationUnit { … public String generateCode() { String generatedCode = ""; /* Do something at the beginning. */ final Iterator iterator = this.classes.iterator(); while (iterator.hasNext()) { final Class aClass = (Class) iterator.next(); generatedCode += aClass.generateCode(); } /* Do something at the end. */ return generatedCode; } } 85/213
  • 86. Naïve Implementation m : Main cu : CompilationUnit c : Class (5/7) m : Method s : Statement generateCode( ) generateCode( ) generateCode( ) generateCode( ) 86/213
  • 87. Naïve Implementation  Limitations (6/7) of the naïve implementation – What about generating code for • Linux on PowerPC? • Linux on Motorola 68060? • OS/400 on AS/400? 87/213
  • 88. Naïve Implementation  Limitations (6/7) of the naïve implementation – What about generating code for • Linux on PowerPC? • Linux on Motorola 68060? • OS/400 on AS/400? Combinatorial explosion of generateCodeForXXX() methods in each class 88/213
  • 89. Naïve Implementation (7/7)  Requirements – Decouple the data structure • The AST – From algorithms on the data structure • The generateCodeForXXX() method • And others, including type binding! 89/213
  • 90. Naïve Implementation (7/7)  Requirements – Decouple the data structure • The AST – From algorithms on the data structure • The generateCodeForXXX() method • And others, including type binding! The Visitor design pattern guides you to do that! 90/213
  • 91. Visitor  Name: (2/13) Visitor  Intent: “Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates.” 91/213
  • 92. Visitor (3/13)  Motivation: “Consider a compiler that represents programs as abstract syntax trees. It will need to perform operations on abstract syntax trees for "static semantic" analyses like checking that all variables are defined. It will also need to generate code.” 92/213
  • 93. Visitor (4/13)  Motivation (cont’d): “[…] It will be confusing to have type-checking code mixed with pretty-printing code or flow analysis code. […] It would be better if each new operation could be added separately, and the node classes were independent of the operations that apply to them.” 93/213
  • 94. Visitor (5/13)  Motivation (cont’d): “We can have both by packaging related operations from each class in a separate object, called a visitor, and passing it to elements of the abstract syntax tree as it's traversed.” 94/213
  • 95. Visitor (6/13)  Motivation (cont’d): “When an element accepts the visitor, it sends a request to the visitor that encodes the element's class. It also includes the element as an argument. The visitor will then execute the operation for that element—the operation that used to be in the class of the element.” 95/213
  • 96. Visitor (8/13)  Applicability – An object structure contains many classes of objects with differing interfaces… – Many distinct and unrelated operations need to be performed on objects in an object structure… – The classes defining the object structure rarely change, but you often want to define new operations over the structure… 96/213
  • 98. Visitor  (10/13) Participants – Visitor (NodeVisitor) • Declares a Visit operation for each class… – ConcreteVisitor (TypeCheckingVisitor) • Implements each Visit… – Element (Node) • Defines an Accept operation… – ConcreteElement (AssignmentNode) • Implements Accept … – ObjectStructure (Program) • Can enumerate its elements • May provide a high-level interface to allow the visitor to visit its elements • May either be a composite (see Composite) or a collection 98/213
  • 100. Visitor (13/13)  Consequences: …  Implementation: …  Sample code: …  Known uses – ASTs – Meta-models –…  Related patterns: Composite 100/213
  • 101. Better Implementation (1/6) package compiler.visitor; import import import import import compiler.Class; compiler.CompilationUnit; compiler.Field; compiler.Method; compiler.Statement; public interface Visitor { void open(final Class aClass); void open(final CompilationUnit aCompilationUnit); void open(final Method aMethod); void close(final Class aClass); void close(final CompilationUnit aCompilationUnit); void close(final Method aMethod); void visit(final Field aField); void visit(final Statement aStatement); } 101/213
  • 102. Better Implementation (2/6) public class Method { … public void accept(final Visitor aVisitor) { aVisitor.open(this); final Iterator iterator = this.statements.iterator(); while (iterator.hasNext()) { final Statement aStatement = (Statement) iterator.next(); aStatement.accept(aVisitor); } aVisitor.close(this); } } public class Field { … public void accept(final Visitor aVisitor) { aVisitor.visit(this); } } public class Statement { … public void accept(final Visitor aVisitor) { aVisitor.visit(this); } } 102/213
  • 103. Better Implementation (3/6) public class Class { … public void accept(final Visitor aVisitor) { aVisitor.open(this); final Iterator iteratorOnFields = this.fields.iterator(); while (iteratorOnFields.hasNext()) { final Field aField = (Field) iteratorOnFields.next(); aField.accept(aVisitor); } final Iterator iteratorOnMethods = this.methods.iterator(); while (iteratorOnMethods.hasNext()) { final Method aMethod = (Method) iteratorOnMethods.next(); aMethod.accept(aVisitor); } aVisitor.close(this); } } 103/213
  • 104. Better Implementation (4/6) public class CompilationUnit { … public void accept(final Visitor aVisitor) { aVisitor.open(this); final Iterator iterator = this.classes.iterator(); while (iterator.hasNext()) { final Class aClass = (Class) iterator.next(); aClass.accept(aVisitor); } aVisitor.close(this); } } 104/213
  • 106. (5/6) m : Main cu : CompilationUnit c : Class m : Method s : Statement Better implementation generateCode( ) generateCode( ) generateCode( ) generateCode( ) 106/213
  • 107. (5/6) m : Mai n cu : CompilationUnit c : Class m : Method s : Statem ent v : IVisitor accept(IVisitor) open(Com pilationUnit) a ccept(IVisitor) o pen(Cl as s) accept(IVisitor) Better implementation open(Method) a ccept(IVis itor) visit(Statement) clos e(Method) close(C lass) clos e(Compil ationUn it) 107/213
  • 108. m : Mai n cu : CompilationUnit c : Class m : Method s : Statem ent v : IVisitor accept(IVisitor) open(Com pilationUnit) a ccept(IVisitor) m : Main cu : CompilationUnit c : Class m : Method s : Statement o pen(Cl as s) accept(IVisitor) generateCode( ) open(Method) generateCode( ) a ccept(IVis itor) visit(Statement) generateCode( ) generateCode( ) clos e(Method) close(C lass) clos e(Compil ationUn it) 108/213
  • 109. Better Implementation  By (6/6) using the visitor design pattern – Decouple data structure and algorithms – Put the traversal in only one place, in the AST – Allow the addition of new algorithms without changing the data structure 109/213
  • 110. Better Implementation  By (6/6) using the visitor design pattern – Decouple data structure and algorithms – Put the traversal in only one place, in the AST – Allow the addition of new algorithms without changing the data structure Much better, clearer implementation! 110/213
  • 111. Conclusion on the Example  The Visitor design pattern is useful anywhere you have – A data (stable) structure – Algorithms (infinite) on that data structure  Design patterns provided good solution to recurrent problems! 111/213
  • 112. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 112/213
  • 113. Erich Gamma, Richard Helm, Ralph Johnson, and John Vlissides ; Design Patterns: Elements of Reusable Object-Oriented Software ; Addison-Wesley, 1995 113/213
  • 114. Catalogue  Design patterns – Development and maintenance – Design/implementation levels – Examples in C++ and Smalltalk  Divided in three categories – Behavioural – Creational – Structural 114/213
  • 117. Catalogue  Abstract Factory (87) – Provide an interface for creating families of related or dependent objects without specifying their concrete classes  Adapter (139) – Convert the interface of a class into another interface clients expect. Adapter lets classes work together that couldn't otherwise because of incompatible interfaces 117/213
  • 118. Catalogue  Bridge (151) – Decouple an abstraction from its implementation so that the two can vary independently  Builder (97) – Separate the construction of a complex object from its representation so that the same construction process can create different representations 118/213
  • 119. Catalogue  Chain of Responsibility (223) – Avoid coupling the sender of a request to its receiver by giving more than one object a chance to handle the request. Chain the receiving objects and pass the request along the chain until an object handles it 119/213
  • 120. Catalogue  Command (233) – Encapsulate a request as an object, thereby letting you parameterize clients with different requests, queue or log requests, and support undoable operations  Composite (163) – Compose objects into tree structures to represent part-whole hierarchies. Composite lets clients treat individual objects and compositions of objects uniformly 120/213
  • 121. Catalogue  Decorator (175) – Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending functionality  Facade (185) – Provide a unified interface to a set of interfaces in a subsystem. Facade defines a higher-level interface that makes the subsystem easier to use 121/213
  • 122. Catalogue  Factory Method (107) – Define an interface for creating an object, but let subclasses decide which class to instantiate. Factory Method lets a class defer instantiation to subclasses  Flyweight (195) – Use sharing to support large numbers of finegrained objects efficiently 122/213
  • 123. Catalogue  Interpreter (243) – Given a language, define a representation for its grammar along with an interpreter that uses the representation to interpret sentences in the language  Iterator (257) – Provide a way to access the elements of an aggregate object sequentially without exposing its underlying representation 123/213
  • 124. Catalogue  Mediator (273) – Define an object that encapsulates how a set of objects interacts. Mediator promotes loose coupling by keeping objects from referring to each other explicitly, and it lets you vary their interaction independently  Memento (283) – Without violating encapsulation, capture and externalize an object's internal state so that the object can be restored to this state later 124/213
  • 125. Catalogue  Observer (293) – Define a one-to-many dependency between objects so that when one object changes state, all its dependents are notified and updated automatically  Prototype (117) – Specify the kinds of objects to create using a prototypical instance, and create new objects by copying this prototype 125/213
  • 126. Catalogue  Proxy (207) – Provide a surrogate or placeholder for another object to control access to it.  Singleton (127) – Ensure a class only has one instance, and provide a global point of access to it 126/213
  • 127. Catalogue  State (305) – Allow an object to alter its behaviour when its internal state changes. The object will appear to change its class  Strategy (315) – Define a family of algorithms, encapsulate each one, and make them interchangeable. Strategy lets the algorithm vary independently from clients that use it 127/213
  • 128. Catalogue  Template Method (325) – Define the skeleton of an algorithm in an operation, deferring some steps to subclasses. Template Method lets subclasses redefine certain steps of an algorithm without changing the algorithm's structure 128/213
  • 129. Catalogue  Visitor (331) – Represent an operation to be performed on the elements of an object structure. Visitor lets you define a new operation without changing the classes of the elements on which it operates 129/213
  • 130. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 130/213
  • 131. Practice “The strict modeling of the real world leads to reflect today’s realities but not necessarily tomorrow’s. The abstractions that emerge during design are key to making a design flexible.” —Erich Gamma, 1994 131/213
  • 132. Practice “The description of communicating objects and classes customized to solve general design problem in a particular context.” —Erich Gamma, 1994 132/213
  • 133. Practice “Each design pattern lets some aspect of system structure vary independently of other aspects, thereby making a system more robust to a particular kind of change.” —Erich Gamma, 1994 133/213
  • 134. The following is only complementary to reading books and practicing 134/213
  • 135. Practice  Scattered information – Informal text A suggested example rather than a general rule Interpreting them all... 135/213
  • 136. Practice  When encountering complex problems? – Numerous design patterns (is there any complete list out there?) – Granularity • • • • Requirements, analysis, architecture Design, implementation (idioms) Refactoring, testing … Knowing them all... 136/213
  • 137. Practice  Iterative induction process – From an example to an abstraction to an application to the abstraction to an application… – Validation process? Applying them all... 137/213
  • 138. Practice  Use known categories – Behavioural – Creational – Structural  Use the Internet  Read and discuss others’ code 138/213
  • 139. Practice  Use known categories – Behavioural – Creational – Structural  Use the Internet  Read and discuss others’ code 139/213
  • 140.    Read and discuss others’ code 140/213
  • 141. Practice  Assess the trade-offs – Flexibility – Complexity 141/213
  • 142. Practice  Assess the trade-offs – Flexibility – Complexity 142/213
  • 143. Practice  Assess the trade-offs – Flexibility – Complexity  Sometimes it is necessary to remove the solution of a DP used in the code 143/213
  • 144. Practice  Sometimes it is necessary to remove the solution of a DP used in the code 144/213
  • 145. Practice “There is a natural relation between patterns and refactorings. “Patterns are where you want to be; refactorings are ways to get there from somewhere else” —Josuha Kerievsky citing Martin Fowler, 2004 145/213
  • 147. Practice  Refactoring to a Visitor – Previous example of code generation from a common AST  Implementing a variant of the Visitor – padl.kernel.impl.Constituent.accept(IVisitor) – padl.kernel.impl.Constituent.accept(IVisitor, String) – padl.kernel.impl.Constituent.accept(Class, IVisitor, String, boolean)  Refactoring away from the Visitor – ptidej.statement.creator.classfiles.loc.BCELLOCFinder 147/213
  • 148. Practice  Refactoring to a Visitor – Previous example of code generation from a common AST  Implementing a variant of the Visitor – padl.kernel.impl.Constituent.accept(IVisitor) – padl.kernel.impl.Constituent.accept(IVisitor, String) – padl.kernel.impl.Constituent.accept(Class, IVisitor, String, boolean)  Refactoring away from the Visitor – ptidej.statement.creator.classfiles.loc.BCELLOCFinder 148/213
  • 149. Practice  Refactoring to a Visitor – Previous example of code generation from a common AST  Implementing a variant of the Visitor – padl.kernel.impl.Constituent.accept(IVisitor) – padl.kernel.impl.Constituent.accept(IVisitor, String) – padl.kernel.impl.Constituent.accept(Class, IVisitor, String, boolean)  Refactoring away from the Visitor – ptidej.statement.creator.classfiles.loc.BCELLOCFinder 149/213
  • 150. Practice  Implementing a variant of the Visitor – Problem when implementing the solution of the Visitor design pattern • Too many duplicated accept(…) methods • Two cases for visit(…) and open(…)+close(…) 150/213
  • 151. Practice  Implementing a variant of the Visitor – Problem when implementing the solution of the Visitor design pattern • Too many duplicated accept(…) methods • Two cases for visit(…) and open(…)+close(…) • What if the data structure changes? 151/213
  • 152. Practice  Implementing a variant of the Visitor – Problem when implementing the solution of the Visitor design pattern • Too many duplicated accept(…) methods • Two cases for visit(…) and open(…)+close(…) • What if the data structure changes? 152/213
  • 153. Practice  Implementing a variant of the Visitor – Problem when implementing the solution of the Visitor design pattern • Too many duplicated accept(…) methods • Two cases for visit(…) and open(…)+close(…) • What if the data structure changes? – Solution • Use the introspection mechanism of Java 153/213
  • 154. Practice  Implementing a variant of the Visitor – Problem when implementing the solution of the Visitor design pattern • Too many duplicated accept(…) methods • Two cases for visit(…) and open(…)+close(…) • What if the data structure changes? – Solution • Use the introspection mechanism of Java 154/213
  • 155. private boolean accept( final java.lang.Class currentReceiver, final IVisitor visitor, final String methodName, final boolean shouldRecurse) { acceptClassName = currentReceiver.getName(); java.lang.Class argument = null; try { } the introspection mechanism of Java  Use Practice argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, new java.lang.Class[] { argument }); method.invoke(visitor, new Object[] { this }); return true; } catch (final Exception e) { if (e instanceof NoSuchMethodException) { visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); } else { throw new RuntimeException(e); } } return false; } 155/213
  • 156. private boolean accept( final java.lang.Class currentReceiver, final final MethodIVisitor visitor, visitor.getClass().getMethod( method = final String methodName, final boolean methodName, shouldRecurse) { new java.lang.Class[] { argument }); acceptClassName = currentReceiver.getName(); java.lang.Class argument null; method.invoke(visitor, =new Object[] { this }); try { } the introspection mechanism of Java  Use Practice argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, new java.lang.Class[] { argument }); method.invoke(visitor, new Object[] { this }); return true; } catch (final Exception e) { if (e instanceof NoSuchMethodException) { visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); } else { throw new RuntimeException(e); } } return false; } 156/213
  • 157. private boolean accept( final java.lang.Class currentReceiver, final IVisitor visitor, final String methodName, final boolean shouldRecurse) { acceptClassName = currentReceiver.getName(); java.lang.Class argument = null; try { } the introspection mechanism of Java  Use Practice argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, new java.lang.Class[] { argument }); method.invoke(visitor, new Object[] { this }); return true; } catch (final Exception e) { if (e instanceof NoSuchMethodException) { visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); } else { throw new RuntimeException(e); } } return false; } 157/213
  • 158. private boolean accept( final java.lang.Class currentReceiver, final IVisitor visitor, final String methodName, final boolean shouldRecurse) { acceptClassName = currentReceiver.getName(); java.lang.Class argument = null; try { argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); the introspection mechanism of Java } catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, acceptClassName = currentReceiver.getName(); new java.lang.Class[] { argument }); java.lang.Class argumentmethod.invoke(visitor, = null; Practice try { new Object[] { this }); return true; } catch (final Exception e) { argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); if (e instanceof NoSuchMethodException) { } visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); }  Use catch (final ClassNotFoundException e) { else { throw new RuntimeException(e); visitor.unknownConstituentHandler(methodName, this); } } return false; } return false; } 158/213
  • 159. private boolean accept( final java.lang.Class currentReceiver, final IVisitor visitor, final String methodName, final boolean shouldRecurse) { acceptClassName = currentReceiver.getName(); java.lang.Class argument = null; try { } the introspection mechanism of Java  Use Practice argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, new java.lang.Class[] { argument }); method.invoke(visitor, new Object[] { this }); return true; } catch (final Exception e) { if (e instanceof NoSuchMethodException) { visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); } else { throw new RuntimeException(e); } } return false; } 159/213
  • 160. private e) { catch (final Exception boolean accept( final java.lang.Class currentReceiver, if (e instanceof NoSuchMethodException) { final IVisitor visitor, final String methodName, visitor.unknownConstituentHandler(methodName + '(‘ + argument.get...; final boolean shouldRecurse) { } acceptClassName = currentReceiver.getName(); else { java.lang.Class argument = null; try { throw new RuntimeException(e); argument = visitor.getClass().getClassLoader().loadClass(acceptClassName); } the introspection mechanism of Java Practice }  Use } catch (final ClassNotFoundException e) { visitor.unknownConstituentHandler(methodName, this); return false; } try { final Method method = visitor.getClass().getMethod( methodName, new java.lang.Class[] { argument }); method.invoke(visitor, new Object[] { this }); return true; } catch (final Exception e) { if (e instanceof NoSuchMethodException) { visitor.unknownConstituentHandler(methodName + '(‘ + argument.getName() + ')', this); } else { throw new RuntimeException(e); } } return false; } 160/213
  • 161. Practice  Use the introspection mechanism of Java – No more duplicated accept(…) methods – Handles cases for visit(…) and open(…)+close(…) – Plus, allows extensions to the data structure without changing all existing Visitors 161/213
  • 162. Practice  Use the introspection mechanism of Java – No more duplicated accept(…) methods – Handles cases for visit(…) and open(…)+close(…) – Plus, allows extensions to the data structure without changing all existing Visitors 162/213
  • 163. Practice  Refactoring to a Visitor – Previous example of code generation from a common AST  Implementing a variant of the Visitor – padl.kernel.impl.Constituent.accept(IVisitor) – padl.kernel.impl.Constituent.accept(IVisitor, String) – padl.kernel.impl.Constituent.accept(Class, IVisitor, String, boolean)  Refactoring away from the Visitor – ptidej.statement.creator.classfiles.loc.BCELLOCFinder 163/213
  • 164. away from the Visitor  Refactoring Practice final FileInputStream fis = new FileInputStream(path); final ClassParser parser = new ClassParser(fis, path); final JavaClass clazz = parser.parse(); clazz.accept(this.instFinder); fis.close(); public class BCELLOCFinder implements Visitor { private JavaClass currentClass; public void visitCode(final Code aCode) { } public void visitCodeException(final CodeException aCodeException) { } // 18 other empty “visit” methods public void visitJavaClass(final JavaClass aClass) { this.currentClass = aClass; final Method[] methods = aClass.getMethods(); for (int i = 0; i < methods.length; i++) { this.visitMethod(methods[i]); } } // 4 more empty “visit” methods public void visitMethod(final Method aMethod) { Integer count = null; final String ckey = this.adaptor.adapt(this.currentClass); final String mkey = this.adaptor.adapt(this.currentClass, aMethod); final Map methodMap = this.methodMap(ckey); count = this.getLOC(code); methodMap.put(mkey, count); } // 6 more empty “visit” methods } 164/213
  • 165. away from the Visitor  Refactoring Practice final FileInputStream fis = new FileInputStream(path); final ClassParser parser = new ClassParser(fis, path); final JavaClass clazz = parser.parse(); clazz.accept(this.instFinder); fis.close(); public class BCELLOCFinder implements Visitor { private JavaClass currentClass; public void visitCode(final Code aCode) { } public void visitCodeException(final CodeException aCodeException) { final FileInputStream fis = new FileInputStream(path); } // 18 other final ClassParserempty “visit” methods ClassParser(fis, path); parser = new public void visitJavaClass(final JavaClass aClass) { this.currentClass = parser.parse(); final JavaClass clazz = aClass; final Method[] methods = aClass.getMethods(); clazz.accept(this.instFinder); for (int i = 0; i < methods.length; fis.close(); } i++) { this.visitMethod(methods[i]); } // 4 more empty “visit” methods public void visitMethod(final Method aMethod) { Integer count = null; final String ckey = this.adaptor.adapt(this.currentClass); final String mkey = this.adaptor.adapt(this.currentClass, aMethod); final Map methodMap = this.methodMap(ckey); count = this.getLOC(code); methodMap.put(mkey, count); } // 6 more empty “visit” methods } 165/213
  • 166. away from the Visitor  Refactoring Practice final FileInputStream fis = new FileInputStream(path); final ClassParser parser = new ClassParser(fis, path); final JavaClass clazz = parser.parse(); clazz.accept(this.instFinder); fis.close(); public class BCELLOCFinder implements Visitor { private JavaClass currentClass; public void visitCode(final Code aCode) { } public void visitCodeException(final CodeException aCodeException) { } // 18 other empty “visit” methods public void visitJavaClass(final JavaClass aClass) { this.currentClass = aClass; final Method[] methods = aClass.getMethods(); for (int i = 0; i < methods.length; i++) { this.visitMethod(methods[i]); } } // 4 more empty “visit” methods public void visitMethod(final Method aMethod) { Integer count = null; final String ckey = this.adaptor.adapt(this.currentClass); final String mkey = this.adaptor.adapt(this.currentClass, aMethod); final Map methodMap = this.methodMap(ckey); count = this.getLOC(code); methodMap.put(mkey, count); } // 6 more empty “visit” methods } 166/213
  • 167. away from the Visitor  Refactoring Practice public final FileInputStream fis = new FileInputStream(path); void visitJavaClass(final JavaClass aClass) { final ClassParser parser = new ClassParser(fis, path); this.currentClassparser.parse(); = aClass; final JavaClass clazz = clazz.accept(this.instFinder); final Method[] methods = aClass.getMethods(); fis.close(); for (int i = 0; i < methods.length; i++) { this.visitMethod(methods[i]); public class BCELLOCFinder implements Visitor { private JavaClass currentClass; } public void visitCode(final Code aCode) { } } public void visitCodeException(final CodeException aCodeException) { } // 18 other empty “visit” methods public void visitJavaClass(final JavaClass aClass) { this.currentClass = aClass; final Method[] methods = aClass.getMethods(); for (int i = 0; i < methods.length; i++) { this.visitMethod(methods[i]); } } // 4 more empty “visit” methods public void visitMethod(final Method aMethod) { Integer count = null; final String ckey = this.adaptor.adapt(this.currentClass); final String mkey = this.adaptor.adapt(this.currentClass, aMethod); final Map methodMap = this.methodMap(ckey); count = this.getLOC(code); methodMap.put(mkey, count); } // 6 more empty “visit” methods } 167/213
  • 168. Practice  Refactoring away from the Visitor – 28 empty methods – Hard-coded call the visitMethod(…) • See this.visitMethod(methods[i]); – JavaClasses do not contain other similar objects, they are not a Composite object – Unnecessary code, complexity 168/213
  • 169. Practice  Refactoring away from the Visitor – 28 empty methods – Hard-coded call the visitMethod(…) • See this.visitMethod(methods[i]); – JavaClasses do not contain other similar objects, they are not a Composite object – Unnecessary code, complexity 169/213
  • 170. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns 170/213
  • 171. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns Flexibility 171/213
  • 172. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns Flexibility Complexity 172/213
  • 173. Practice  Trade-offs of (most of) design patterns – Flexibility • Favouring composition over inheritance – Complexity • More objects interacting • More messages exchanged 173/213
  • 174. Practice  Trade-offs of (most of) design patterns – Flexibility • Favouring composition over inheritance – Complexity • More objects interacting • More messages exchanged 174/213
  • 175. m : Mai n cu : CompilationUnit c : Class m : Method s : Statem ent v : IVisitor accept(IVisitor) open(Com pilationUnit) a ccept(IVisitor) m : Main cu : CompilationUnit c : Class m : Method s : Statement o pen(Cl as s) accept(IVisitor) generateCode( ) open(Method) generateCode( ) a ccept(IVis itor) visit(Statement) generateCode( ) generateCode( ) clos e(Method) close(C lass) clos e(Compil ationUn it) 175/213
  • 176. m : Mai n cu : CompilationUnit c : Class m : Method s : Statem ent v : IVisitor accept(IVisitor) open(Com pilationUnit) a ccept(IVisitor) m : Main cu : CompilationUnit c : Class m : Method s : Statement o pen(Cl as s) accept(IVisitor) generateCode( ) open(Method) generateCode( ) a ccept(IVis itor) visit(Statement) generateCode( ) generateCode( ) Plus the use of reflection! clos e(Method) close(C lass) clos e(Compil ationUn it) 176/213
  • 177. Practice  Trade-offs of (most of) design patterns – Flexibility • Favouring composition over inheritance – Complexity • More objects interacting • More messages exchanged 177/213
  • 178. Practice  Trade-offs of (most of) design patterns – Flexibility • Favouring composition over inheritance – Complexity • More objects interacting • More messages exchanged 178/213
  • 179. Practice  Flexibility – Favour composition over inheritance • Allow changing implementation • Allow safe inheritance 179/213
  • 180. Practice  Flexibility – Favour composition over inheritance • Allow changing implementation • Allow safe inheritance Add one level of indirection 180/213
  • 181. Practice  Flexibility – Favour composition over inheritance • Allow changing implementation • Allow safe inheritance Add one level of indirection and (possibly) Use double-dispatch 181/213
  • 182. Practice  Add one level of indirection “Rather than giving you a lengthy explanation, let me just point you to the Strategy pattern. It is my prototypical example for the flexibility of composition over inheritance.” Erich Gamma, 2005 182/213
  • 183. Practice  Add one level of indirection http://itewbm.tistory.com/29 183/213
  • 184. Practice  Add one level of indirection http://itewbm.tistory.com/29 184/213
  • 185. Practice  Add one level of indirection http://itewbm.tistory.com/29 185/213
  • 186. Practice  Add one level of indirection http://programmers.stackexchange.com/questions/203210/ is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir 186/213
  • 188. Practice  Add one level of indirection http://programmers.stackexchange.com/questions/203210/ is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir 188/213
  • 189. No spe Practice with th cial co eN de ullO for bje “no beh  Add one level of indirection ct d esi avi gn our pat ” tern http://programmers.stackexchange.com/questions/203210/ is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir 189/213
  • 190. Practice  Add Enc aps u late one level of indirection http://programmers.stackexchange.com/questions/203210/ is-context-inheritance-as-shown-by-head-first-design-patterns-duck-example-ir wh at v arie s 190/213
  • 191. Practice  Add one level of indirection “You have a container, and you plug in some smaller objects. These smaller objects configure the container and customize the behaviour of the container. This is possible since the container delegates some behaviour to the smaller thing. In the end you get customization by configuration. ” Erich Gamma, 2005 (With minor adaptations) 191/213
  • 192. Practice  Add one level of indirection “You have a container, and you plug in some smaller objects. These smaller objects configure the container and customize the behaviour of the container. This is possible since the container delegates some behaviour to the smaller thing. In the end you get customization by configuration. ” Erich Gamma, 2005 (With minor adaptations) 192/213
  • 193. Practice  Use double-dispatch – Object receives a message – Object sends a message back with itself as parameter 193/213
  • 194. Practice  Use double-dispatch – Object receives a message – Object sends a message back with itself as parameter 194/213
  • 195. Practice  print(CtxWriter aCTXWriter, Rect aRectangle) { ... } ... print(StringWriter aStringWriter, Triangle aTriangle) { ... } ... PrinterWriter printer = new SystemWriter(); IShape shape = new Square(); print(printer, shape); 195/213
  • 196. Practice  print(CtxWriter aCTXWriter, Rect aRectangle) { ... } ... print(StringWriter aStringWriter, Triangle aTriangle) { ... } ... PrinterWriter printer = new SystemWriter(); IShape shape = new Square(); print(printer, shape); 196/213
  • 197. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 197/213
  • 198. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 198/213
  • 199. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 199/213
  • 200. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 200/213
  • 201. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 201/213
  • 202. public class Main { public static void main(final String[] args) { final PrinterWriter writer = new SystemWriter(); IShape shape; shape = new Rect(); shape.printOn(writer); shape = new Square(); shape.printOn(writer); public class SystemWriter implements PrinterWriter { @Override public void print(final Rect rect) { System.out.print("Printed the rectangle: "); System.out.println(this); } @Override public void print(final Square aSquare) { System.out.print("Printed the square: "); System.out.println(this); } } } } public interface PrinterWriter { void print(final Rect aRect); void print(final Square aSquare); ... } public interface IShape { void printOn(final PrinterWriter aWriter); } http://c2.com/cgi-bin/wiki?DoubleDispatchExample http://www.patentstorm.us/patents/6721807/description.html public class Rect implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } public class Square implements IShape { @Override public void printOn(final PrinterWriter aWriter) { aWriter.print(this); } } 202/213
  • 203. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns 203/213
  • 204. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns Flexibility 204/213
  • 205. Practice  Unnecessary code, complexity – Trade-offs of (most of) design patterns Flexibility Complexity 205/213
  • 206. Practice  Beware also of “bad” solutions to recurring design problems http://www.jot.fm/issues/issue_2006_07/column4/ 206/213
  • 207. Practice  Anti-patterns (also antipatterns) – A common response to a recurring problem that is usually ineffective and may be counterproductive – Code smells are symptoms of “bad” programming 207/213
  • 208. Practice  Two examples of anti-patterns – Visitor design and JavaClasses ptidej.statement.creator.classfiles.loc.BCELLOCFinder – Blob (aka God Class) 208/213
  • 209. Outline  Definition  Quality  Form  Example  Catalogue  Practice  Conclusion 209/213
  • 210. Conclusion  Patterns ease communication  Patterns improve regularity and quality… even without a name…  Patterns avoid surprises i.e., reinventing the wheel differently each time  Patterns generate architectures 210/213
  • 211. Conclusion  Identify a recurring design problem  Identify a design pattern that potentially solve the problem  Assess the costs and benefits of implementing the proposed solution – Quality and quality without a name 211/213
  • 212. Conclusion  Identify a recurring design problem  Identify that the solution brings – Unneeded flexibility – Unnecessary complexity  Assess the costs and benefits of removing the proposed solution 212/213
  • 213. Conclusion  Tools supporting design patterns – “GoF” book • Lists, classifications, relationships [Gamma et al., 1996] – CASE Tools • Fragments [Florijn et al., 1997] • PatternsBox and Ptidej [Albin et al., 2001] • Refactoring tools… – Navigation • Tutor [Motelet, 2000] 213/213