Upload
others
View
1
Download
0
Embed Size (px)
Citation preview
Software Architecture, Process and ManagementDesign Patterns
Allan Clark
School of InformaticsUniversity of Edinburgh
http://www.inf.ed.ac.uk/teaching/courses/sapmSemester Two 2012-13
SAPM
Who and what?
SAPM
It is Ada Lovelace
I Regarded as the world’s first computer programmer
I The picture is a modern tabular version of her ‘note G’ widelyregarded as the world’s first computer program
I It computes Bernoulli numbersI shockingly it does not print “Hello world”
I It isn’t implemented in any programming language of courseI She describes the difference between the “analytical engine”
and other calculating machines of the timeI Its ability to be programmed to solve problems of any
complexityI She recognised that its potential extended beyond numbers to
more abstract objects
I Unfortunately she died before the machine was completedenough to execute her algorithm
SAPM
Small Code
1 print ‘‘Hello World’’
Hello World
SAPM
Small Code
1 print ‘‘Hello World’’2 goto 1
Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World...
SAPM
Small Code
1 x = 102 print ‘‘Hello World’’3 x = x − 14 if x > 0: goto 2
Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World
SAPM
Small Code
1 x = 102 do3 print ‘‘Hello World’’4 x = x − 15 while x > 0
Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World
SAPM
Small Code
1 for x = 10; x > 0; x = x − 12 print ‘‘Hello World’’
Hello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello WorldHello World
SAPM
Small Code Re-use: Methods
I These are all incremental improvements
I A huge improvement in code is the realisation that code canbe parameterised
I Leading to procedures, methods or functions
SAPM
Functions
1 void print_html_greeting(String name){
2 print "\n"
3 print "Greeting\n"
4 print "Hello "
5 print ""
6 print name
7 print ""
8 print "\n"
9 }
10
11 print_html_greeting("level 10s");
12 print_html_greeting("level 11s");
I The alternative here is copy and paste
I Clearly bad, for example should I wish to update howgreetings are formatted
SAPM
Higher-Order Functions
I Allow us to parameterise not only with data values but withcomputation/evaluation as well
I Doing so additionally allows us to make use of “curried”function definitions to allow “partial instantiation”
I1 add x y:
2 return x + y
3 increment = add 1
I Now we have a function for incrementing, not a huge win indefinition but when used inline can beconvenient/clear/concise
I1 map (add 1) xs
SAPM
Object-Oriented Code
I Objects similarly arose from patterns that programmers werealready using in existing code
I Allowing encapsulation as well as parameterising code withother code
1 void perform_many(PerformerList performers){
2 for-each performer in performers{
3 performer.perform()
4 }
5 }
SAPM
Object Polymorphism
1 public abstract class Human
2 {
3 ...
4 public abstract void goPee();
5 }
Courtesy of Chris Cudmore on StackExchange
SAPM
Object Polymorphism
1 public class Male extends Human
2 {
3 ...
4 public void goPee()
5 {
6 System.out.println("Stand Up");
7 }
8 }
Courtesy of Chris Cudmore on StackExchange
SAPM
Object Polymorphism
1 public class Female extends Human
2 {
3 ...
4 public void goPee()
5 {
6 System.out.println("Sit Down");
7 }
8 }
Courtesy of Chris Cudmore on StackExchange
SAPM
Object Polymorphism
1 public static void main(String args)
2 {
3 ArrayList group = new ArrayList();
4 group.add(new Male());
5 group.add(new Female());
6 // ... add more...
7
8 // tell the class to take a pee break
9 for (Human person : group) person.goPee();
10 }
Yielding
Stand UpSit Down...
Courtesy of Chris Cudmore on StackExchange
SAPM
Bottom line:
I Reuse in the small is a largely solved problem
I But re-use in the large is not
SAPM
Modules and “Functors”
1 module Dictionary
2 type dict k v = [(k,v)]
3 empty_dict : dict
4 empty_dict = []
5
6 add : k -> v -> dict -> dict
7 add k v d = (k,v) :: d
8
9 lookup : k -> dict -> v
10 lookup k [] = raise Error
11 lookup k ((x,v)::rest) =
12 if k == x then v else lookup k rest
13 end
SAPM
Modules and “Functors”
1 sig DICTIONARY
2 type dict
3 val empty_dict : dict
4 val add k v : k -> v -> dict -> dict
5 end
6 module Dictionary
7 type dict k v = [(k,v)]
8 empty_dict : dict
9 empty_dict = []
10
11 add : k -> v -> dict -> dict
12 add k v d = (k,v) :: d
13
14 lookup : k -> dict -> v
15 lookup k [] = raise Error
16 lookup k ((x,v)::rest) =
17 if k == x then v else lookup k rest
18 end
SAPM
Modules and “Functors”
1 module WordCounter(DICTIONARY D)
2 word_count : [ word ] -> D.dict word int
3 word_count [] = D.empty_dict
4 word_count (w :: rest) =
5 let d = word_count rest in
6 add w (lookup w d) d
7 end
I “Functor” is a terrible word for this
I This hasn’t been a hugely popular module system
I It’s not clear why
I part of the reason might be that figuring out ahead of timewhich parts of a module to parameterise is difficult
SAPM
The DRY Principle
I DRY: Don’t Repeat Yourself
I The DRY principle is essentially a call to avoid copy-and-pastewhilst programming
I Copied code exists in two places, and updates at one place arenot automatically applied in the other
I This is considered likely to cause future problems
SAPM
Design Patterns
I A design pattern is a standardised solution to a problemcommonly encountered during object-oriented softwaredevelopment (Gamma et al. 1995).
I A pattern is not a piece of reusable code, but an overallapproach that has proven to be useful in several differentsystems already
I Gamma, E., Helm, R., Johnson, R., & Vlissides, J. (1995).Design Patterns: Elements of Reusable Object-OrientedSoftware. Reading, MA: Addison-Wesley.
SAPM
Design Patterns
SAPM
Contents of a Design PatternI Design patterns usually include:
I A pattern nameI A statement of the problem solved by the pattern and/or the
situations in which it is appropriateI A description of the solutionI A list of advantagesI A list of liabilities
SAPM
Composite: Problem Solution Advantages Liabilities
I There is a situation in which an object can be a primitive or acontainer of such objects which may themselves be primitivesor otherwise
I Two obvious examples:I Graphics libraries in which a widget may be a primitive such as
a text label, or a container such as a dialog which containsbuttons each of which contains a primitive text label
I Abstract syntax trees in which an expression may be a primitivesuch as a variable or integer literal, or an application expressionconsisting of smaller expressions (for the caller and arguments)
I The user wishes to ignore the differences
I Surrounding code would get complex if it were alwaysconditional on whether an object was a group or a primitive
SAPM
Composite: Problem Solution Advantages LiabilitiesI Three classes:
1. Component: The shared interface between both primitives andcontainers
2. Leaf: A primitive, implemented directlyI The text label is actually drawn to the screenI A variable expression returns its name as the list of names
mentioned in the expression, an integer literal the empty list
3. Composite/container: Implements the shared interfacegenerally by calling the same method on its children objects
Component
+ operation()
Leaf
+ operation()
Composite
+ operation()+ add()+ remove()+ getChild()
1
0..*
parent
child
SAPM
Composite Example
SAPM
Composite: Problem Solution Advantages Liabilities
I Simple support for arbitrarily complex hierarchies
I Clients can be simple as they do not need to know aboutcomposition
I New Composite and Leaf classes can be introduced withoutchanging Component
SAPM
Composite: Problem Solution Advantages Liabilities
I Hard for client to predict/restrict what components might beencountered
I Hard to test that client works for all components
I Often need to define operations on Components that makesense only for some Component types, e.g. Composites
SAPM
Design Pattern ExamplesI Creational Patterns:
I E.g. Abstract Factory, Factory Method
I Structural Patterns:I CompositeI Proxy
I Behavioral Patterns:I E.g. Command, Visitor
I These are from Gamma et al. (1995) (a.k.a. the Gang of Fourbook), but there are many other pattern collections
I reading: Click on ‘Composite’ (or any of the others) at:http://en.wikipedia.org/wiki/Design_pattern_(computer_science)
http://en.wikipedia.org/wiki/ Design_pattern_(computer_science)http://en.wikipedia.org/wiki/ Design_pattern_(computer_science)
SAPM
Design Patterns and Large-Scale Development
I For a large team, design patterns are useful in creating ashared vocabulary
I First, everyone agrees on a standard reference text(s),commonly simply Wikipedia is the standard reference but:
I Large groups can develop and name their own patterns
I Informal discussions, class naming, etc. can then use thepattern names
I Code documentation is greatly enhanced:I // This class implements the Visitor pattern for the AST
SAPM
Why don’t we write a “Patterns Compiler”I This question is sometimes phrased:
I “Are patterns missing languages features?” orI “Are patterns a language smell?”
I Patterns generally implies some kind of duplication
I Which is almost explicitly a violation of the DRY principle
SAPM
Yes, Patterns are a language smell
I Recall the re-use in the small code examples
I We started with goto code, which involved a pattern forlooping
I This was then formalised into a language construct: “while”I Grouping the looped statementsI A condition to exit the loop
I This was further “patterned” into “for-loop”I initialisationI while-loop conditionI updating the invariant, for example incrementing i
SAPM
Yes, Patterns are a language smell
1 for (int i = 0; i < my_array.length(); i++){
2 SomeType item = my_array[i];
3 ...
4 }
Became patterned with the use of iterators and a for-each
1 for (SomeType item : my_array){
2 ...
3 }
SAPM
Yes, Patterns are a language smell
1 flag = False
2 for x in priveledged:
3 if x = y:
4 print "y is on the list"
5 flag = True
6 break
7 if flag == False:
8 print "y is not on the list"
Became patterned with a for-else:
1 for x in priveledged:
2 if x = y:
3 print "y is on the list"
4 break
5 else:
6 print "y is not on the list"
SAPM
Design Patterns vs Language ConstructsA small list of some of the design patterns which have recognisedlanguage features which largely obviates the need for the pattern
Pattern Language Feature
SingletonPattern MetaClasses
VisitorPattern GenericFunctions or MultipleDispatch
FactoryPattern MetaClasses, closures
IteratorPattern Anonymous/higher order functions
InterpreterPattern Macros (extending the language)
CommandPattern Closures, AnonymousFunctionsLexicalScope, FirstClassFunctions
RunAndReturnSuccessor TailCallOptimization
HandleBodyPattern Delegation, Macros, MetaClasses
Abstract-Factory, Flyweight,Factory-Method, State, Proxy,Chain-of-Responsibility FirstClass types (Norvig)
FacadePattern Modules (Norvig)
SAPM
Yes, Patterns are a language smell
I Patterns are a sign that the language is missing some feature
I But, so what? If we do not know how to solve that particularproblem, then we won’t have a language feature anytime soon
I Or we might not know how that particular feature can beintegrated into the language in question
I In the meantime, a pattern is the best we can do
I The fact that we have now moved on to larger “designpatterns” is evidence for the fact that code re-use in the smallis mostly a solved problem
I It is also evidence that code re-use in the large is still mostlyan unsolved problem
SAPM
Why aren’t patterns just interfaces?
I Patterns often encompass more than a single class
I In theory we could have nested signatures
SAPM
Design Patterns vs Code ReuseI Recall the techniques for code reuse in the small
I loopsI methodsI functions and typesI classes and objectsI modules and functors?
I Notice that these are all grounded in formal mathematics
I They are all a technology based solution
I Design patterns are an attempt to assist, but are not offeredas any kind of formal solution
I Design patterns mostly aid communication
SAPM
Communication
I That word again
I I warned you that there would be no technological silverbullets
I Programming in the large is mostly about communication
I Communicating through code
I Communicating through maintenance, such as comments anddocumentation
I Communicating by simply talking
SAPM
A Glasgow Screwdriver
I My dad calls this a “A Glasgow Screwdriver”I Once one has a hammer there is a temptation to treat
everything as a nailI This phenomenon has lead to some programs becoming
“design-pattern heavy” or “patterns top-heavy”
SAPM
A Glasgow Screwdriver
I Blind use of patterns is as bad as blind use of any othertechnique or concept
I Factory patterns are notoriously over-used
I The SingletonPattern is often used inappropriately
I Over-designed code can be as difficult to comprehend andmaintain as the results of happy hacking
1 public class RoutingInformationProtocol {
2 public static void main (String[] args){
3 Simulator mysimulator= new Simulator();
4 }
5 }
I Even with a mysimulator.run method, what was the plan?
I Create a list of simulators and sort them?
SAPM
Summary
I Many, many other patterns available
I Design patterns help provide a library of solutions to commonObject-Oriented problems
I The history of programming language evolution has been aseries of successes, mostly involving abstractions tosupplement code re-use
I This has been applied on larger and larger scales
I Patterns have been a key driving force behind this evolution
I Design patterns hints that we are somewhat stuck at thecurrent size of code reusability
I Design pattern definitions provide a vocabulary which can beused to aid communication
SAPM
Without such communication one may build a rabbit hutch, butnot a Sheth Tower
SAPM — Related Reading
I Required ReadingI Wikipedia entry on Design Patterns (skim)I M. Fowler. Avoiding RepetitionI T. Winn, P. Calder. Is This a Pattern?
I Suggested ReadingI F. Buschmann, K. Henney, D.C. Schmidt. Past, Present, and
Future Trends in Software Patterns.I Erich Gamma, Richard Helm, Ralph E. Johnson, and John M.
Vlissides. Design Patterns: Abstraction and Reuse ofObject-Oriented Design.
I D. Manolescu, W. Kozaczynski, A. Miller, J. Hogg. TheGrowing Divide in the Patterns World
I M.P. Cline. The pros and cons of adopting and applying designpatterns in the real world
I L. D’Adderio, R. Dewar, A. Lloyd, P. Stevens. Has the patternemperor any clothes? A controversy in three acts
I Gamma, Helm, Johnson, and Vlissides 1995, Design Patterns:Elements of Reusable Object-Oriented Software
I L. Rising. Understanding the Power of Abstraction in Patterns
SAPM
Charles Babbage
I At the time Mr Babbage was demonstrating the potential ofhis machine to members of parliament
I Namely that it may replace or supplement the work of“computers”
I “computers” at the time being actual people how wouldperform calculations, generally for tax purposes
I “On two occasions I have been asked, ‘Pray, Mr. Babbage, ifyou put into the machine wrong figures, will the right answerscome out?’ I am not able rightly to apprehend the kind ofconfusion of ideas that could provoke such a question.” —Charles Babbage
SAPM
Charles Babbage
I At the time Mr Babbage was demonstrating the potential ofhis machine to members of parliament
I Namely that it may replace or supplement the work of“computers”
I “computers” at the time being actual people how wouldperform calculations, generally for tax purposes
I “On two occasions I have been asked, ‘Pray, Mr. Babbage, ifyou put into the machine wrong figures, will the right answerscome out?’ I am not able rightly to apprehend the kind ofconfusion of ideas that could provoke such a question.” —Charles Babbage
Any Questions
Any Questions?