Transcript Slide 1

SE Principles
Silver Bullets
CS 620/720
Software Engineering
January 15, 2004
Poor Engineering leads to ad-hoc structure!
The result of continuous building
without any thought toward design.
Result:
Stairs leading to ceiling;
Windows in the middle of room;
Doors opening to wall;
Non-intuitive floor plan!.
Poor Engineering Has Disastrous Consequences!
Aerodynamic phenomena in suspension
bridges were not adequately understood in
the profession nor had they been addressed
in this design. New research was necessary
to understand and predict these forces.
The remains, located on the bottom of the
Sound, are a permanent record of man's
capacity to build structures without fully
understanding the implications of the design.
http://www.nwrain.net/~newtsuit/recoveries/narrows/narrows.htm
Poor Engineering Has Disastrous Consequences!
$7 Billion Fire Works – One Bug, One Crash
On 4 June 1996, the maiden flight of the Ariane 5 launcher
ended in a failure. Only about 40 seconds after initiation of
the flight sequence, at an altitude of about 3700 m, the
launcher veered off its flight path, broke up and exploded.
The failure of the Ariane 501 was caused by the complete
loss of guidance and attitude information 37 seconds after
start of the main engine ignition sequence (30 seconds
after lift- off). This loss of information was due to
specification and design errors in the software of the
inertial reference system.
The launcher started to disintegrate at about H0 + 39 seconds because of high aerodynamic loads due to an angle of attack of more than 20 degrees that led to separation of the boosters from the
This angle of attack was caused by full nozzle deflections of the solid boosters and the Vulcain main engine.
These nozzle deflections were commanded by the On-Board Computer (OBC) software on the basis of data transmitted by the active Inertial Reference System (SRI 2). Part of these data at that ti
The reason why the active SRI 2 did not send correct attitude data was that the unit had declared a failure due to a software exception.
The OBC could not switch to the back-up SRI 1 because that unit had already ceased to function during the previous data cycle (72 milliseconds period) for the same reason as SRI 2.
The internal SRI software exception was caused during execution of a data conversion from 64-bit floating point to 16-bit signed integer value. The floating point number which was converted had a
The error occurred in a part of the software that only performs alignment of the strap-down inertial platform. This software module computes meaningful results only before lift-off. As soon as the lau
The alignment function is operative for 50 seconds after starting of the Flight Mode of the SRIs which occurs at H0 - 3 seconds for Ariane 5. Consequently, when lift-off occurs, the function continue
The Operand Error occurred due to an unexpected high value of an internal alignment function result called BH, Horizontal Bias, related to the horizontal velocity sensed by the platform. This value
The value of BH was much higher than expected because the early part of the trajectory of
Ariane 5 differs from that of Ariane 4 and results in considerably higher horizontal velocity values.
http://java.sun.com/people/jag/Ariane5.html
http://www.around.com/ariane.html
http://archive.eiffel.com/doc/manuals/technology/contract/ariane/page.htm
Poor Engineering Has Disastrous Consequences!

Software Runaways: Lessons Learned from
Massive Software Failures, Robert Glass


Safeware: System Safety and Computers,
Nancy Leveson


Denver Airport
Therac-25
http://sunnyday.mit.edu/papers/therac.pdf
Risks to the Public, Peter Neumann

http://www.csl.sri.com/users/risko/risks.txt
Poor Engineering Has Disastrous Consequences!

Can you think of other examples….?
1968: Birth of Software Engineering

1968 NATO Convention on new field of
Software Engineering


http://www.cs.ncl.ac.uk/old/people/brian.randell/home.formal/NATO/index.html
Virtual “Who’s Who”

Dijkstra,
Naur,
Perlis,
Gries
First Software Reuse paper

Doug McIlroy
1968 NATO SE

The conference must
have been tiring….
No Silver Bullet : Essence and Accident in
Software Engineering


IEEE Computer, April 1987
Brooks was the 2000 Turing Award winner



Brooks Law
Mythical Man Month
UNC
Silver Bullets
“But as we look to the horizon of a decade hence,
we see no silver bullet. There is no single
development, either in technology or management
technique, which by itself promises even one
order of magnitude improvement in productivity, in
reliability, in simplicity. Not only are there no silver
bullets in view, the very nature of software makes
it unlikely there will be any.”
Frederick Brooks, The Mythical Man Month
No magical cure for software crisis…
In a nutshell
“I believe the hard part of building software to
be the specification, design, and testing of
this conceptual construct, not the labour of
representing it and testing the fidelity of the
representation.”
SE: A Disciplined Approach
Kill the Snake-Oil
The first step toward the management of
disease was replacement of demon theories
and humours theories by the germ theory. That
very step, the beginning of hope, in itself
dashed all hopes of magical solutions. It told
workers that progress would be made stepwise,
at great effort, and that a persistent, unremitting
care would have to be paid to a discipline of
cleanliness. So it is with software engineering
today.
Essence and accident
All software construction involves
1.
essential tasks — the fashioning of the complex conceptual
structures that compose the abstract software entity [i.e.,
problem-space], and
2.
accidental tasks — the representation of the abstract entities in
programming languages and the mapping of these onto
machine languages within space and time constraints.
[Distinction originally due to Aristotle.]
Brooks’ thesis
Good news!

We have made great headway in solving the accidental
problems! Orders of magnitude improvements!
Bad news!


Progress on essential problems will be much slower going.
“There is no royal road, but there is a road.”
“No Silver Bullet” – Fred Brooks


Like physical hardware limits, there are
problems w/ SW that won’t be solved
Inherent difficulties of software production




complexity
conformity
changeability
invisibility
Complexity

Software is complex, even when done right.

Many components
Many kinds of interactions between components

Combinatorially many states, syntax must be just so or else.



Rich structure, interesting dependencies add to complexity.
 Good interfaces, design can lessen externally-visible complexity
Accidental (as practised) issues add to complexity.
 Efficient code is usually complicated code
 Use of prefab abstractions; reuse and generic components mean
complicated, stateful glue.
 Complex code is harder to evolve, results in design drift and even
more complexity.


16 bit word in HW -> 216 states
Def-use of variables and state changes
Complexity

Complexity is an inherent property because there really are that
many “moving parts”!
 Hardware engineering is achieved by replication of relatively
simple parts arranged just so to achieve a certain effect.
 Software is NOT a physical system, it is entirely a design.
 When two pieces of software perform the same task, we abstract
them into one!



Thus the size of a [well designed] system measures not “mass” but
complexity.
Complexity depends non-linearly on size
Results
 difficult to understand whole product


hard to manage


errors in specification & code
how can you estimate without understanding?
maintenance is a nightmare
Conformity

Invariably, have to coerce nice [problem-space] abstractions to fit someone
else’s prefab [solution-space] technology.






New kid on the block! (rules were already made)
Perceived as more flexible than hardware or humans
Result: bewildering diversity of requirements
Wrapping and unwrapping, data marshalling, etc.
Software has to be made to agree to common interfaces, protocols, standards, etc.
Interface with an existing system



Interface with a new system



e.g., plant built & asked to create SW to control
software must conform to the plant
misperception that SW is easier to conform
again, software will be forced to conform
Some translations/coercions can be automated and take care of themselves; it's
the other ones that will cause our systems to break, often in very subtle ways.
Changeability
“[…] the software product is embedded in a cultural matrix of applications, users, laws,
and machine vehicles. These all change continually, and their changes inexorably
force change upon the software product.”

We change software because we can!
 Easy to update existing systems in the field (in theory).

Can undo changes if desired (in theory).
 Not like a car recall.
To be successful is to be changed!
 Keep system flexible, marketable.
 Try to anticipate and/or react to future unforeseen uses
Pressure to change
 reality changes
 useful software will encourage new requests
 long lifetime (~15 yrs) vs. hardware (~4 yrs).



E.g., Windows update web site
Invisibility
“The reality of software is not inherently embedded in space.”

Software is invisible & unvisualizable

Different from physical laws and math theorems

no way to represent a complete product or overview
complete views (e.g., code)



partial views


misleading
Makes it hard to communicate to



incomprehensible
other software professionals
users & clients
Of course, we can use various techniques to help us visualize aspects of
software (control flow, data dependencies, UML, etc.)
 but that's NOT quite the same thing as, say, the blueprints of a building.
Attacks on accidental problems

HLLs
 Frees us from byte-level thinking (accidental complexity). Takes us up to
“generic problem space”.
e.g., C, sizeof(int), register allocation vs. pure objects and garbage
collection

What we need beyond this is common abstractions in problem space …


… and in solution space too


i.e., domain modelling: telephony, avionics, flight reservation
e.g., frameworks, libraries, components
HLLs and OOP


Good training/use will make for better systems.
When used well, bumps up the abstraction level


[replace “Ada” by “Java”]
… but still begs the question
Won't “solve” the SE problem, but the abstraction aspects of OO live in
problem space too.

This has been a HUGE win in attacking essential complexity.
Attacks on accidental problems

IDEs (SDEs)




This was novel then! Research systems can actually do
lots more than VC++.
Even a smartly tweaked vim/emacs is a big step forward.
In the old days, correct and reasonably efficient compiling
was a notable feat. It was hard to get Unix standalone
tools to interoperate.
Current: Eclipse
What about these silver bullets?

AI and expert systems



Mostly not.
Sometimes they help, e.g., test oracles
Certainly, AI techniques are useful in many
application domains, but not as a silver bullet to
solve the SE problem.

WWW, faster processors, cheap memory have
made some AI techniques quite useful, much more
so now than then.
What about these silver bullets?

“Automatic programming”


i.e., state the parameters, turn the crank, hey presto a
software system!
We can do this now in some cases, works quite well
[it didn't work very well at the time of writing]
 Some systems generate part of their source code:


Generative programming; model-based approaches
Will never work completely in the general case, but is
certainly useful.


Really, all this does is bump up the abstraction level by one;
Great potential in domain-specific environments


Parsers: yacc, lex
MIC/GME
What about these silver bullets?

Graphical programming




[e.g., UML, SDL, et al.]
Undeniably useful … as a tool … sometimes …
Always tempting to try, as certain aspects of software
systems do seem inherently “topological”.
 “A favourite topic for PhD dissertations in SE.”
In the general case, software is ethereal, unvisualizable
(unlike hardware) with truly bizarre dependencies.
Surprisingly difficult to do well as most visual metaphors
break down under scale (or bad design).
 Have you ever looked at a complicated SDL statemachine diagram? A class diagram with lots of
complex interdependencies? A use-case scenario
diagram with lots of variation?
 Improvement: Domain-specific visual languages
What about these silver bullets?

Formal program verification
(Dijkstra: formal derivation)
 Does program P implement specification S?
 Undecidable in the general case, can be done by hand
until scale overwhelms
 In practice, has been done with some great successes, but
only when investment seems to be worthwhile.



Tremendously expensive; requires expert logicians!
The hard part, as Brooks rightly points out, is making sure
you have the right specification S!
Validation versus verification
What about these silver bullets?

Better tools and faster computers


Always good. Usually solution-space though.
Technological Peter Principle:


in a hierarchically structured administration, people tend
to be promoted up to their "level of incompetence"
Cheap disks, fast modems? Napster!
Promising attacks on conceptual
essence

Buy, don't build.




Old days [IBM 1960s]: specialists developed highly
customized solutions Just For You.
Experience led to generic (or at least configurable)
products; now we have “shrinkwrapped” software (one size
fits all).
Advice to software developers: Learn how to build generic
components or systems. This is hard, though.
Modularization (next topic) plays a big role.
If customization is straightforward, this is a huge leap
forward and an attack on the conceptual essence.
Promising attacks on conceptual
essence

Rapid prototyping



Take requirements, build mock up, show to user, analyze
feedback, repeat.
Early feedback means less chance for requirements errors
(which are the most expensive), fast turnaround in problem
space to narrow misunderstandings and educate
customer.
Requirements are the essence of a software system.


Focusing on getting the requirements right is a direct attack
on essential problems.
Relevance to XP?
Promising attacks on conceptual
essence

Staged delivery
[aka organic/incremental development, daily build]





Get a skeleton system up and running ASAP; flesh it out as you
go.
Helps to get developers feeling like system is real. They add
their updates as they finish them. They care about them not
breaking.
Other extreme: big bang merging. Often lots of unpleasant
surprises.
Microsoft (and many others) uses this approach; works well for
them.
Need a culture that supports it. Lots of running around, not afraid
of change, group buy-in, product-centred, etc.
Promising attacks on conceptual
essence

Virtuoso designers (a.k.a. Cowboy code-slinger)
 Find good people and keep them.
 Pay them well, encourage them.
 Above all, listen to them.
 Ours is still a very young field … this reliance on magic and
gurus is worrisome and anti-engineering.


However, “great software design” is mostly “pure” design (not
engineering); it’s an act of creativity and innovation balanced
against experience and good engineering. It’s impossible to teach,
per se.
Note that great “artists” still require a grounding education in
“classical techniques” and exposure to “best practices”.
Other Promising Technologies?











AOP?
MIC or MDA?
WWW? [1998]
Extreme programming?
design patterns, software architecture?
“The emergent evolution of hard interfaces”
 e.g., imap, http, tcp/ip
Frameworks?
EJB, CORBA, COM, componentware?
scripting languages?
lawsuits?
your suggestions??
No Silver Bullet Refired


Brooks reflects on the “No Silver Bullet”
paper, ten years later
Lots of people have argued that their
methodology is the silver bullet


If so, they didn’t meet the deadline of 10 years!
Other people misunderstood what Brooks
calls “obscure writing”

For instance, when he said “accidental”, he did
not mean “occurring by chance”
Obtaining the Increase
Some people interpreted Brooks as saying
that the essence could never be attacked
 That’s not his point however; he said that no
single technique could produce an order of
magnitude increase by itself
 He argued that several techniques in tandem
could achieve that goal but that requires
industry-wide enforcement and discipline

SE Principles - Parnas
Definition

Parnas starts this paper with a definition of
SE as:


“multi-person construction of multi-version
programs.”
Do you agree with this definition?
Excludes solo-programming…
The argument, in some way, makes sense:

1.
2.
3.

Dividing the job
Specifying exact behavior
Team communication
…all of these things contribute to problems
that need to be solved by applying SE
principles.
But…



Is it not the case that developing a large
application, even by yourself, necessitates
the need for good SE?
Do we not need proper modularization when
developing solo-progams?
If building a house relies on good
construction and engineering skills, is it true
that building a dog house (solo effort) does
not?
Even building a dog house takes some
engineering…
From http://www.ttyler.8m.com/Dog%20House.htm
Initially started as a "basic" dog house but soon turned into a masterpiece
of quality workmanship. Total time spent was 8 hours at a cost of $110
US.
Start with a piece of paper and a idea: Design your dog house to the size
and quantity of your dogs. A perfectly built home is worthless if its to small to
properly accommodate your dog.
Framing: The framing process should be constructed with 2x4's or rip them in
half for smaller homes. A removable roof should be incorporated in assisting
the future cleaning and maintenance.
Wall Covering: Should be tong & grove for a tight fit, no warping, and to cut
down on cross drafts. For large homes, plywood is a economical material that
can be used.
Roof: 30 year home shingles cut down to the proper size. As for this house, an
oriental piece was constructed then topped of with a copper fence post top. An
additional hours work and $15 cost was needed
Trim & Finishing Touches: Trim can add a lot to the astidics of your dog
house. Trim can be bought with may different variations or with some
craftsmanshipcan can be made with the use of a router.
Sanding & Paint: Sink all nails below the surface and cover with wood
filler. Prepare surface for painting by sanding wood filler, rough spots, and
blemishes.
More SE Principles
It seems that the problems identified as 4-6
are not peculiar to solo-programming

4. How to write programs that are easily modifiable.

Programs in which a change in one part does not require
changes in many other places.
5. How to write programs with useful subsets. Remove
uneeded parts



E.g., Zen and CORBA footprint
6. How to write programs that are easily extended.
Structure


“The connections between program parts are
the assumptions that the parts make about
each other.”
Precursor to “Design by Contract”; Pre/Post
conditions


“the properties that it expects other parts to
satisfy”
“the system properties that it is required to
guarantee”
Changeability

Parnas writes that these two concerns help when we
ask:


“What changes can be made to one part without involving
change to other parts?”
Or, as Dijkstra has written elsewhere:

“... program structure should be such as to anticipate its
adaptations and modifications. Our program should not
only reflect (by structure) our understanding of it, but it
should also be clear from its structure what sort of
adaptations can be catered for smoothly. Thank goodness
the two requirements go hand in hand.”
Two Techniques for Controlling Structure

Decomposition




Precise Specification



Technique for dividing systems into modules
Well-structured program is one with minimal
interconnections between its modules (low-coupling)
More to be said in later lectures
“precisely describing the assumptions that the designers of
one module are permitted to make about other modules”
More also to be said on this later
Some examples of why it is easier in other
“engineering” endeavours…
Decomposition and Simple Specification
The prong and receptacle
parts of a Lego™ block
have been unchanged
since 1932 [Lego, 2002].
Simple Interface Specification
Since around 1850, the standard
dimensions for an “air cell” masonry
brick in the United States has been
2.5 x 3.75 x 8 inches [Chrysler and
Escobar, 2000].
For next lecture…

Read chapter 7 of Parnas




“On the criteria….”
Perhaps one of the top 5 most cited papers in
all of software engineering
I will also lecture on some things that you do
not have to read (e.g., cohesion and
coupling)
Pop quiz some time in semester possible

i.e., quiz not on typical Thursday, but Tuesday
A lot of review &
“On the Criteria…” (hopefully)
CS 620/720
Software Engineering
January 20, 2004
Basic Definitions of SE

Software engineering is a discipline whose
aim is the production of fault-free software,
delivered on time and within budget, which
satisfies the users needs [Schach]
Generic Lifecycle Models
Software Lifecycles
Linear Model
System/information
engineering
analysis
design
code
test
Requirements
Phase
Verify
Specification
Phase
Royce, 1970
Verify
Waterfall
Design
Phase
Verify
Object-Oriented and
Classical Software Engineering
Fifth Edition, WCB/McGraw-Hill, 2002
Stephen R. Schach
Implementation
Phase
Test
Integration
Phase
Changed
Requirements
Verify
Test
Maintenance
Phase
Retirement
Verification vs validation
Integration
Testing
Analysis
Rqmnts
Coding
Design
Relative Cost
Of
Software Development
Activities
Maintenance
The Cost of Change
More Overview

Abstraction, Information Hiding,
Encapsulation, Cohesion/Coupling….

… all in 15 minutes!!
Abstraction

A means of achieving stepwise refinement by
accentuating relevant details (and, by
implication, suppressing unnecessary
details).


Ex. Braking in your car, turning on the lights
Other examples?

How about examples in the medical field, or other
disciplines?
Abstraction – some definitions
"A view of a problem that extracts the essential information relevant to a
particular purpose and ignores the remainder of the information."
-- [IEEE, 1983]
"The essence of abstraction is to extract essential properties while omitting
inessential details.”
-- [Ross et al, 1975]
"Abstraction is a process whereby we identify the important aspects of a
phenomenon and ignore its details.“ -- [Ghezzi et al, 1991]
"Abstraction is generally defined as 'the process of formulating generalized
concepts by extracting common qualities from specific examples.'"
-- [Blair et al, 1991]
"Abstraction is the selective examination of certain aspects of a problem.
The goal of abstraction is to isolate those aspects that are important for
some purpose and suppress those aspects that are unimportant."
-- [Rumbaugh et al, 1991]
Abstraction – some definitions
"The meaning [of abstraction] given by the Oxford English Dictionary (OED)
closest to the meaning intended here is 'The act of separating in thought'. A
better definition might be 'Representing the essential features of something
without including background or inessential detail.”
-- [Graham, 1991]
"[A] simplified description, or specification, of a system that emphasizes
some of the system's details or properties while suppressing others. A good
abstraction is one that emphasizes details that are significant to the reader
or user and suppress details that are, at least for the moment, immaterial or
diversionary."
-- [Shaw, 1984]
"An abstraction denotes the essential characteristics of an object that
distinguish it from all other kinds of object and thus provide crisply defined
conceptual boundaries, relative to the perspective of the viewer."
-- [Booch, 1991]
Abstraction – my favorite definition

Abstraction is doing just what our small minds
need: making it possible for us to think about
important properties of our program – its
behavior – without having to think about the
entirety of the machinations.
[Kiczales, 1992]
Information Hiding


The focus of today’s paper
Hides the implementation details from other
modules
"The second decomposition was made using 'information hiding‘ ... as a
criterion. The modules no longer correspond to steps in the processing. ...
Every module in the second decomposition is characterized by its
knowledge of a design decision which it hides from all others. Its interface or
definition was chosen to reveal as little as possible about its inner
workings."
-- [Parnas, 1972b]
"... the purpose of hiding is to make inaccessible certain details that should not
affect other parts of a system." -- [Ross et al, 1975]
I’m sure glad
I don’t have to eat
this stuff!
Looks
Yummy!
The Restaurant
Messages invoke methods &
methods send messages.
Customer
Waiter (object)
Data:
name: Joe
tables: 1,2
tickets: 2
Turnstile (object)
Data:
tickets: 1
Methods:
isTicketReady
add Ticket
remove Ticket
Counter (object)
Methods:
takeOrder
putOrderonTurnstile
pickup Order
serverOrder
Data:
ordersAvailable
Methods:
isOrderReady
addOrder
removeOrder
Cook (object)
Data:
name: Arnold
specialties:
HamandEggs
Pancakes
FrenchToast
Private Methods:
makeHamandEggs
makePancakes
makeFrenchToast
Public Methods:
takeTicketFromTurnstile
putOrderOnCounter
Abstraction vs. Information Hiding



However, abstraction <> information hiding
It is possible to hide implementation details,
yet provide a very poor interface into the
module such that its key elements are still not
easy to comprehend
Abstraction is about providing a
representation of some thing which highlights
that thing’s essential elements
Encapsulation


The gathering together into one unit of all
aspects of the real-world entity modeled by
the abstract data unit.
Definitions:
"to enclose in or as if in a capsule“ -- [Mish, 1988]
"The concept of encapsulation as used in an object-oriented
context is not essentially different from its dictionary
definition. It still refers to building a capsule, in the case a
conceptual barrier, around some collection of things."
-- [Wirfs-Brock et al, 1990]
Encapsulation

Modularity is about separation: When we
worry about a small set of related things, we
locate them in the same place. This is how
thousands of programmers can work on the
same source code and make progress.
[Gabriel and Goldman, 2000]
Information Hiding vs. Encapsulation


The two are also not equal
It is possible to have an encapsulated module
that has all of its internal structure visible
from the outside

Commonality of module is collected in one place,
but the inner guts are not hidden (e.g., all
members of a class are public)
Cohesion/Coupling

Two factors that help increase reliability,
understandability, efficiency, and
maintainability within and between modules.



Cohesion - within a module
Coupling - between modules
Provides some initial objective measure to
the question “What makes a good design?”
A Brain Teaser:
Who’s joined to whom—and by what?
A
C
B
Global Data
G
D
E
F
Modular Cohesion


The degree of interaction within a module.
OR


The measure of the strength of functional
relatedness of elements (an instruction, group of
instructions, a data definition, or a call to another
module) within a module.
The term was borrowed from sociology by Larry
Constantine in the mid-1960s, where it means the
relatedness of humans within groups.
Scale of Cohesion

Stevens, Myers, Constantine, and Yourdon developed the
Scale of Cohesion as a measure of the “black boxness” of a
module, and as a result, the maintainability of a module.
Type
Scale
of
Cohesion
Functional
Informational **
Sequential
Communicational
Procedural
Temporal
Logical
Coincidental
Measure
Best
Best
Black Box
Black Box
Gray Box
Worst
**Originally not part of Scale
Transparent
or White Box
Coincidental Cohesion

A module whose elements perform multiple,
completely unrelated actions.

Such modules make systems less understandable
and less maintainable than systems with no
modularity at all.
GrossPay = PayRate * Hours
SalesTax = Cost * SalesTaxRate
Close File 1
Coincidental Cohesion cont.

Disadvantages of Coincidental Cohesion



Severe lack of maintainability of product.
Lack of reusability.
Corrective action

break the module into smaller modules.
Logical Cohesion

Occurs when overlapping parts of functions
that have the same lines of code or the same
buffers, but are not even executed at the
same time (switch statement dispatch).
function_code = 7;
New_operation(function_code, d1, d2, d3);
// d1, d2, d3 are dummy variables and not
// used when function_code = 7
Logical Cohesion cont.

Disadvantages




The interface is difficult to understand.
The code for more than one action may be
intertwined, leading to maintainability
problems.
The intertwining makes reusability of the
module difficult, if not impossible.
Corrective action

separate the functions and rewrite.
Logical (aka Illogical) Cohesion
“Not only does a logically cohesive module have
an ugly exterior with maybe a dozen different parameters
fighting to use four accesses, but its inside resembles a
plate of spaghetti mixed with noodles and worms.”
Meilir Page-Jones 1988
Temporal Cohesion

A module whose elements are involved in
activities that are related in time.


Disadvantage


Elements are usually more closely related to
activities in other modules than they are to one
another (leads to tight coupling).
Lack of reusability in other products.
Corrective Action

Take the procedure apart and rewrite code as
necessary
Procedural Cohesion (skip)

A module whose elements are involved in
different and possibly unrelated activities in
which control flows from each activity to the
next.

Related to each other by order of execution rather
than by any single problem-related function (Similar
to temporal cohesion).
Communicational Cohesion

A module whose elements contribute to
activities that use the same input or output
data.


E.g., “Update record in database and write it to log
file”
Makes the transition into modules more
easily maintainable, but still not easily
reusable.
Informational Cohesion

A module whose elements perform a number
of actions, each with its own entry point, with
independent code for each action, and all
performed on the same data structure.


Ex.
Abstract data types
Supports Structured Programming concepts.
Functional Cohesion

A module whose elements all contribute to
the execution of one and only one problemrelated task (but not necessarily one and only
one output).


Systems built chiefly of normally coupled,
functionally cohesive modules are by far the
easiest (and thus the cheapest) to maintain.
No matter how complicated, the sum of the
module is one problem-related function.
Functional Cohesion cont.

Advantages




Concept of module is easily understood.
Easily maintained.
Product is more easily updatable
or changeable.
Supports fault isolation (easily testable).
Supports heavy Reusability.
Comparisons
Modifiablity
Understandability
Effect on
overall system
maintain-ability
Functional /
Informational
Sequential
Communicational
Procedural
Temporal
Logical
Coincidental
Cleanliness of
Implementation
Cohesion Level
Coupling
Comparisons Between Levels of Cohesion
Good
Good
Medium
Variable
Poor
Bad
Bad
Good
Good
Medium
Poor
Medium
Bad
Poor
Good
Good
Medium
Variable
Medium
Bad
Bad
Good
Good
Medium
Variable
Medium
Poor
Bad
Good
Fairly good
Medium
Bad
Bad
Bad
Bad
Modular Coupling

The degree of interaction between two
modules.
Best (Lowest Interaction)
Normal
Levels
of
Coupling
Data
Stamp
Control
Commo
n
Content
Worst (Highest Interaction)
Content (alias Pathological) Coupling


Two modules exhibit content coupling if one
refers to the inside of the other in any way.
Value being accessed is not passed through
the parameter list.

Ex. if one module alters a statement in another,
or updates another modules global state.
Module p
Uses local
data a
Module q
Local data a
Common (alias Global) Coupling


Two modules that refer to the same global data
area.
Disadvantages:



Global areas may sometimes be drastically abused, as
in when different modules use the same area to store
quite different pieces of information, called overloading.
Programs using a lot of global data are extremely
difficult to understand because of the difficulty of
knowing what data are used by which module (very
expensive to correct); def-use pairs hard to see
Wulf and Shaw: “Global Variables Considered Harmful”
Control Coupling

Two modules where one passes to the other
a piece of information intended to control the
internal logic of the other.


Typically through the use of control flags.
Disadvantages




Leads to indirectness and obscurity.
Two modules are not independent.
Possibility of reuse is reduced.
Generally associated with modules that have
logical cohesion.
Stamp Coupling

Two modules where one passes to the other a
composite piece of data, that is, a piece of data with
a meaningful internal structure.


Ex.
All Employee Personnel Info, instead of just the
pay rate and SSN.
Disadvantages


The indirectness can cause a broad interface.
Data not necessarily can be accessed by the module
(creating dependencies between otherwise unrelated
modules).
Data Coupling

Two modules that communicate by
parameters, each parameter being an
elementary piece of data.

Communication of data between modules is
unavoidable and necessary, as long as it is kept to
a minimum.
Call D
Using X,
Y
C
X
Y
D
Data Coupling cont.

Advantages





Avoids sending unnecessary data
Is direct.
Flexible.
Highly reusable.
Maintainable.
Data Coupling - Warnings


1. Small is better. Keep the interface as
narrow as possible.
2. Avoid using tramp data,



Data that passes through modules that do not need it in
order to reach the recipient module (AspectJ wormhole
example)
pieces of information that shuffle aimlessly around a
system, unwanted by and meaningless to most of the
modules through which it passes. Usually a symptom
of poor organization of modules.
To varying degrees, tramp data violates all five of the
principles for good coupling
Comparisons
Comparisons Between Levels of Coupling
Coupling Level
Data
Tramp
Stamp
Bundling
Control
Hybrid
Common
Content
Module's
Understandusability in
Modifiablity
ability
other systems
Good
Good
Good
Medium
Medium
Poor
Medium
Medium
Medium
Medium
Poor
Poor
Poor
Poor
Poor
Bad
Bad
Bad
Medium
Bad
Poor
Bad
Bad
Bad
The Goal of Good Modularity?

High Cohesion


Functional or Information
Low Coupling

Data, Stamp, Control
When to Use What?

Cohesion’s Goal

To create a procedure
that performs one
functionally-related task.

Coupling’s Goal

To protect global data
and local data from being
used within a procedure
without declaring it on the
procedure’s header
Both significantly affect maintenance.
When used correctly, maintenance can be reduced;
when used incorrectly, maintenance can be a nightmare!
Enough of that….


Sample code from last week
Parnas paper
Simple C++ Example
class B {
public:
B() { }
void f() { cout << "B::f()" << endl; }
virtual void g() { cout << "B::g()" << endl; }
};
class D : public B {
public:
D() { }
void f() { cout << "D::f()" << endl; }
void g() { cout << "D::g()" << endl; }
};
int main(int,char*[]) {
B* bp; D* dp;
bp = new B; bp->f(); bp->g();
dp = new D; dp->f(); dp->g();
bp = dp; bp->f(); bp->g();
}
Output:
B::f()
B::g()
D::f()
D::g()
B::f()
D::g()
A Sketchy Evolution of Software Design

1960s

Structured Programming




1970s

Structured Design


Methodology/guidelines for dividing programs into subroutines.
1980s

Modular (object-based) programming



(“Goto Considered Harmful”, E.W.Dijkstra)
Emerged from considerations of formally specifying the semantics of
programming languages, and proving programs satisfy a predicate.
Adopted into programming languages because it’s a better way to think
about programming
Ada, Modula, Euclid, …
Grouping of sub-routines into modules with data.
1990s


Object-Oriented Languages started being commonly used (60s origin)
Object-Oriented Analysis and Design for guidance.
Module Structure

David Parnas (birthday anecdote)


“On the Criteria To Be Used in Decomposing Systems into
Modules” Comm. ACM 15, 12 (Dec. 1972), 1053-1058
Perhaps most popular paper in SE



Discusses “modularization”


Module = a collection of subroutines and data elements
Critique of Procedural Design


Initial CACM rejection (“Nobody does it that way”)
Universal acceptance (“Parnas wrote about common practice”)
Pointing the way to object-based and OO design.
Describes two ways to modularize a program that
generates KWIC (Key Word in Context) indices.

Modularization 1 - Based on the sequence of steps to
perform

Modularization 2 - Based on the principle of “information
hiding”
Weiss quote
The way to evaluate a modular decomposition,
particularly one that claims to rest on
information hiding, is to ask what changes it
accommodates.
[Hoffman and Weiss, 2001]
KWIC

Input
Designing Software for Ease of Construction
Figs are Good

Output
are Good Figs
for Ease of Construction Designing Software
of Construction Designing Software for Ease
Construction Designing Software for Ease of
Designing Software for Ease of Construction
Ease of Construction Designing Software for
Figs are Good
Good Figs are
Software for Ease of Construction Designing
KWIC Modularization 1
Master control
Input
Characters
Input medium
Circular Shift
Alphabetizer
Index
Output
Alphabetized
Index
Output medium
KWIC Modularization 2
Master control
Lines
Input medium
Circular Shifter
Ith(i)
doAlph
nWords(i)
getc(i,w,j)
cssetup
nWords(i)
Output
getc(i,w,j)
setc(i,w,j,c)
Input
Alphabetizer
Output medium
Criteria for decomposition

Modularization 1


Each major step in the processing was a module
Modularization 2

Information hiding



Lines


how characters/lines are stored
Circular Shifter


Each module has one or more "secrets”
Each module is characterized by its knowledge of design decisions
which it hides from all others.
algorithm for shifting, storage for shifts
Alphabetizer

algorithm for alpha, laziness of alpha
General Comparison

General



Note: both systems might share the same data structures
and the same algorithms
Differences are in the way they are divided into work
assignments
Systems are substantially different even if identical in the
runnable representation


Possible because the runnable representation is used only for
running
Other representations are used for




Changing
Documenting
Understanding
…
Changeability Comparison

Design decisions that may change (design1, design2)

Input format


All lines stored in memory


(all, 1)
Make an index for circular shifts rather than store them


(all, 1)
Pack characters 4 to a word


(1, 1)
(3,1)
Alphabetize once, rather than either



Search for each item as needed
Partially alphabetize, partially search
(3,1)
Independent Development

Modularization 1



Modularization 2



Must design all data structures before parallel work can
proceed
Complex descriptions needed
Must design interfaces before parallel work can begin
Simple descriptions only
Comprehensibility

Modularization 2 is better

Parnas subjective judgment
Comparing Rationales
Modularization 1
Modularization 2
Design
Criterion
Each major processing
step is made into a
module
Modules are designed
using the principle of
information hiding
Is taskspecific?
Yes. For e.g., the Add
module is responsible
for directly adding a
contact into the address
book.
Yes. For e.g., the Add
module is responsible
for directly adding a
contact into the
address book
Interdependence
HIGH. All modules are
heavily dependent on
the Data Storage
module
NONE. All modules
are independent!
Information Hiding

Before decomposing a system into modules, a
list of all possible design changes is made Hiding Assumption List

Each module hides the implementation of an
important design decision so that only the
constituents of that module know the details

All design decisions are independent of each
other
Information Hiding in Modularization 2

Modularization 2 used this principle of
Information Hiding.

All of its modules are independent and
have well-defined interfaces.

There is very low coupling between them.
Information Hiding in Modularization 2

Each module is very task-specific. All
modules are highly cohesive.

For example, the sorting algorithm is known
only to the Sort module. Similarly, the format of
data storage is known only to the Read/Write
Interface module.
Benefits of Good Modular Design

Independent Development
Since each module is
independent, they can be
developed independently at the
same time  Shortened
Development Time!
Benefits of Good Modular Design

Changeability, Product Flexibility & Reusability
Modules can be easily modified without
affecting the rest of them. Moreover,
modules can be easily replaced to add,
enhance or change product capabilities.
Benefits of Good Modular Design

Comprehensibility
It is easier for programmers to fully
understand the design of the
entire product by individually
studying the modules.
Comprehensibility Quote

In many pieces of code the problem of
disorientation is acute. People have no idea
what each component of the code is for and
they experience considerable mental stress
as a result.
[Gabriel, 1995]
Historical Content in Present
Context

Paper is 30 years old, but only some details
might make this fact apparent:





Terminology
Previous concerns
Past design processes (flowcharts)
Changing guidelines
Code reuse (not a major point)
Terminology
Parnas uses some terms that are not used anymore, or
are used nowadays with different meanings, such as:
- CORE
Then: main memory, general storage space
Now: internal functionality, internals
- JOB
Then: Implied batch processing
Now: ???
- Nowadays, we speak of memory in a more abstract
way (data structures, etc). “Memory” was more often
understood as referring to physical storage
(addresses, records…)
Previous Concerns

Parnas mentions as “major advancements in the area of
modular programming”…


The development of ASSEMBLERS
Nowadays, we could mention higher level languages, mainly
object-oriented languages that better:
“(1) allow one module to be written with little knowledge of the
code in another module, and
(2) allow modules to be reassembled and replaced
without reassembly of the whole system”

Aspect Languages
Past Design Processes

Use of flowcharts


When paper was written, the use of flowchart by
programmers before was almost mandatory. With a
flowchart in hands, the programmer would “move from
there to a detailed implementation.” This caused
modularizations like the first one to be created.
Parnas could see the problem with this approach and
condemned it; A flowchart would work ok for a small
system, but not with a larger one.
Changing Guidelines

“The sequencing of instructions necessary to call a given
routine and the routine itself are part of the same module.”
This pertains to worries of programmers at the time because
they were programming in assembly and other low-level
languages. Concerns such as code optimization were very
important and involved creating smaller sets of machine
instructions for a given task.

“The sequence in which certain items will be processed
should be hidden within a single module.”
It has become irrelevant most times.
Code Reuse
• Parnas does not emphasize code reuse so much in
this paper. The reason might be the nature of
programs written in assembly or lower-level
languages programmers (not very portable/reusable).
• If the paper were to be reviewed by Parnas, reuse
would certainly be a point he would emphasize more.
It is important to notice that these points
do not disturb the current relevance of
Parnas’ ideas.
Effects on Current Programming

“Fathered” key ideas of OOP:




Information hiding
Encapsulation before functional relations
Easier understandability/maintainability
Design more important than
implementation


Good design leads to good implementation
Proper design allows for different
implementations (easily modifiable)
New forms of Separation…

Early plug for course next Fall…

CS 692/792




Reflection and Metaprogramming
Advanced Separation of Concerns
Model-integrated Computing
Adaptive Middleware
Intermingled Decisions
Concern Separation
Making Modules Easier to Change
Parnas Transparency (skip 9.6 and 9.7)
OO Design Principles:
Open-Closed
Liskov Substitutability
Dependency Inversion
CS 620/720
Software Engineering
January 22, 2004
Next Week

Tue:






Reading: Demeter
Reading: Parnas Extension/Contraction
Reading: Big Ball of Mud
Lead into patterns, frameworks, refactoring
May not cover all of this!
Thu:




Finish what is left from Tue lecture
Patterns intro
Quiz 2
HW1 assigned
Parnas Transparency
Top Down Design




Also called “Outside In” Design
Describes and creates a system from the highest
hierarchical level where the full specifications of a
design must be known
Difficult or infeasible to obtain full specification
Can result in software that is unnecessarily inflexible
For these reasons, pure
Top Down has problems
Bottom Up Design





Create the system “Inside Out” from a set of lower
level components (i.e. “start at the bottom”)
Work upwards, solving entire project
Reuse components from other projects
More practical to implement internal structures first,
creating separate modules and joining them
together
Bottom Up is more flexible. Hard to design “general
purpose” system / library using top-down
Bottom Up Design (cont.)


As you move up the system hierarchy, you
create structural levels
Base Machine


the lower level of a hierarchy, maybe hardware or
an intermediate software level
Virtual Machine

a level above the base machine, it hides the
complexity of the base machine to make
interaction with the system easier
Transparency in Bottom Up Design

Transparency


Complete transparency


describes the implementation completeness of the virtual
machine with respect to the base machine’s functionality
the virtual machine has ALL of the functionality of the base
machine
Loss of transparency


a lack of functionality with respect to the base machine
exists in the virtual machine
There is some sequence that can be specified in the base
machine that can not be expressed in the virtual machine
Driving with strings and steering wheel
Base machine
New virtual machine
Example positions
What figures suggest a loss of transparency?
In this case, is the loss of transparency ok?
Virtual machine for register access
Many possible implementations:
• register is an array: indexing; shifting for insert/delete
• register is one-way linked list: linear search
• register is indexed link list
•register is linked list of small arrays
Completeness of the abstraction

What operation does Parnas show is not
possible in the virtual machine, which
suggests a loss of transparency?
Other Examples of Transparency


Hardware
Search Engine
Example – Graphics Card Transparency
Hierarchical Level
Description
0
Graphics Card – silicon
1
Driver
2
API – DirectX,OpenGL
3
Application – Game, CAD
Graphics Card Example (cont.)

Positive results of transparency


Much easier to program with API than directly with
driver. Using an API lets an application run on
different hardware
Negative results of transparency

Depending on implementation, an application
might not run as fast on a particular piece of
hardware. I.e., it won’t fully utilize certain
hardware features
Nvidia’s Unified Driver Architecture
A way of dealing with a changing base machine.
Image courtesy of AnandTech1
Anand Lal Shimpi, “NVIDIA's Detonator3 Drivers - Teaching an ‘old’ dog new tricks”,
August 14, 2000, http://www1.anandtech.com/showdoc.html?i=1297&p=2.
Nvidia’s Unified Driver Architecture


All drivers communicate with a hardware
abstraction level (HAL) that resides on silicon
“temporary degree of transparency”


Basic functionality exists with older drivers
Higher performance arrives with newer drivers
Search Engine Example
A case where loss is not too bad…



Simple user interface which interacts with a
complex database
User can only run simple queries
User cannot modify data through the interface
Search Engine Example




Large loss of transparency yields mainly positive
effects
Maintains data integrity
Loss of transparency does not hinder usability from
the user’s perspective
Few significant negative can be effects identified
Suggestive and Misleading Transparency


Suggestive: Sometimes the virtual machine should
give “suggestions” to the base machine.
Misleading: Sometimes the virtual machine
implementation is inefficient because of a lack of
information at a lower level
Conclusion


“… a fundamental ‘tradeoff’ which exists
between transparency and flexibility of a
design.”
Determining the right level of transparency for
the higher level structure is crucial in order to
obtain its goals
Discussion



How do you determine the right level of
transparency for a hierarchically structured system?
When there exists too much of a loss of
transparency, should there exist a way of accessing
the base machine?
What if you cannot know all the types of programs to
be created from the base machine?
SE Principles for OO Development

Open-Closed Principle

Liskov Substitution Principle

Dependency Inversion Principle

Has anyone heard of these before?

Reference:


http://www.objectmentor.com/resources/listArticles?key=topic&topic=Design%20Principles
The representative papers are also on the network drive
Open-Closed Principle (OCP)
Software entities should be open for extension,
but closed for modification
B. Meyer, 1988 / quoted by R. Martin, 1996

"Software Systems change during their life time"
 both better designs and poor designs have to face
the changes;
 good designs are stable
 Be open for extension
 module's behavior can be extended
 Be closed for modification
 source code for the module must not be changed
 Modules should be written so they can be extended without requiring
them to be modified
The Open-Closed Principle (OCP)




We should write our modules so that they can
be extended, without requiring them to be
modified.
We want to change what the modules do,
without changing the source code of the
modules.
Why is it bad to change source code?
How is this OCP implemented?
The Open/Closed Principle (OCP) Example
An Example of
What not to do!
What is wrong
with this code?
The Open/Closed Principle (OCP) Example

The Problem: Changeability…




If I need to create a new shape, such as a Triangle, I must
modify the ‘drawShape()' function.
In a complex application the switch/case statement above is
repeated over and over again for every kind of operation that
can be performed on a shape .
Worse, every module that contains such a switch/case
statement retains a dependency upon every possible shape
that can be drawn, thus, whenever one of the shapes is
modified in any way, the modules all need recompilation, and
possibly modification
However, when the majority of modules in an application
conform to the open/closed principle, then new features
can be added to the application by adding new code
rather than by changing working code. Thus, the
working code is not exposed to breakage.
The Open/Closed Principle (OCP) Example
Open the door ...


How to make the Car run efficiently with a
TurboEngine?
Only by changing the Car!
...in the given design
... But Keep It Closed!



A class must not depend on a concrete class!
It must depend on an abstract class ...
...using polymorphic dependencies (calls)
OCP Heuristics
Make all object-data private
No Global Variables!

Changes to public data are always at risk to “open”
the module



They may have a rippling effect requiring changes at many
unexpected locations;
Errors can be difficult to completely find and fix. Fixes may
cause errors elsewhere.
Non-private members are modifiable

Case 1: "I swear it will not change"


may change the status of the class
Case 2: a Time class with open members

may result in inconsistent times
Liskov Substitution Principle (LSP)
 The key of OCP: Abstraction and Polymorphism
 Implemented by inheritance
 How do we measure the quality of inheritance?
Inheritance should ensure that any property proved about
supertype objects also holds for subtype objects
B. Liskov, 1987
Functions that use pointers or references to base classes
must be able to use objects of derived classes
without knowing it.
R. Martin, 1996
Contravariance/covariance…
The Liskov Substitution Principle (LCP) Example
Inheritance Appears Simple
class Bird {
// has beak,
wings,...
public: virtual void fly();
// Bird can fly
};
class Parrot : public Bird {
public: virtual void mimic();
// Parrot is a bird
// Can Repeat
words...
};
// ...
Parrot mypet;
mypet.mimic();
mypet.fly();
// my pet being a parrot can Mimic()
// my pet “is-a” bird, can fly
Penguins Fail to Fly!
class Penguin : public Bird {
public: void fly() {
error (“Penguins don’t fly!”); }
};
void PlayWithBird (Bird& abird) {
abird.fly();
// OK if Parrot.
// if bird happens to be Penguin...OOOPS!!
}
 Does not model: “Penguins can’t fly”
 It models “Penguins may fly, but if they try it is error”
 Run-time error if attempt to fly  not desirable
 Think about Substitutability - Fails LSP
Design by Contract

Advertised Behavior of an object:


advertised Requirements (Preconditions)
advertised Promises (Postconditions)
When redefining a method in a derivate class, you may only
replace its precondition by a weaker one, and
its postcondition by a stronger one
B. Meyer, 1988
 Derived class services should require no more and promise no less
int Base::f(int x);
int Derived::f(int x);
// REQUIRE: x is odd
// PROMISE: return even int
// REQUIRE: x is int
// PROMISE: return 8
Square IS-A Rectangle?
Square
?

Should I inherit Square from Rectangle?
The Answer is ...

Override setHeight and setWidth


duplicated code...
static binding (in C++)



void f(Rectangle& r) { r.setHeight(5); }
change base class to set methods virtual
The real problem
void g(Rectangle& r) {
r.setWidth(5); r.setHeight(4);
// How large is the area?
}

20! ... Are you sure? ;-)
LSP is about Semantics and Replacement

The meaning and purpose of every method and class must be
clearly documented



Lack of user understanding will induce violations of LSP
In previous example, we have intuition about squares/rectangles,
but this is not the case in most other domains
Replaceability is crucial


Whenever any class is referenced by any code in any system,
any future or existing subclasses of that class must be 100%
replaceable
Because, sooner or later, someone will substitute a subclass;


it’s almost inevitable.
Violations of LSP are latent violations of OCP.
LSP and Replaceability

Any code which can legally call another class’s
methods

must be able to substitute any subclass of that class
without modification:
Client
Service Class
Service Class
Client
Unexpected
Subclass
LSP Related Heuristic (2)
It is illegal for a derived class, to override
a base-class method with a NOP method


NOP = a method that does nothing
Solution 1: Inverse Inheritance Relation

if the initial base-class has only additional behavior


e.g. Dog - DogNoWag
Solution 2: Extract Common Base-Class


if both initial and derived classes have different behaviors
for Penguins  Birds, FlyingBirds, Penguins
Example of Rigidity and Immobility
Copy
Read
Keyboard
Write
Printer
Write
Disk
enum OutputDevice {printer, disk};
void Copy(OutputDevice dev){
int c;
while((c = ReadKeyboard())!= EOF)
if(dev == printer)
WritePrinter(c);
else
WriteDisk(c);
}
void Copy(){
int c;
while ((c = ReadKeyboard()) != EOF)
WritePrinter(c);
}
Dependency Inversion Principle
I. High-level modules should not depend on low-level
module implementations. Both levels should depend
on abstractions.
II. Abstractions should not depend on details.
Details should depend on abstractions
R. Martin, 1996
 OCP states the goal; DIP states the mechanism
 A base class in an inheritance hierarchy should not know
any of its subclasses
 Modules with detailed implementations are not depended
upon, but depend themselves upon higher abstractions
Specification inheritance vs. implementation inheritance
Dependency Inversion Principle


Dependency Inversion is the strategy of
depending upon interfaces or abstract
functions and classes, rather than upon
concrete functions and classes.
Every dependency in the design should
target an interface, or an abstract class. No
dependency should target a concrete class.
Procedural vs. OO Architecture
Procedural
Architecture
Object-Oriented
Architecture
DIP Applied on Example
class Reader {
public:
virtual int read()=0;
};
Copy
Reader
Writer
Keyboard
Reader
Printer
Writer
class Writer {
public:
virtual void write(int)=0;
};
Disk
Writer
void Copy(Reader& r, Writer& w){
int c;
while((c = r.read()) != EOF)
w.write(c);
}
DIP Related Heuristic
Design to an interface,
not an implementation!

Use inheritance to avoid direct bindings to
classes:
Interface
(abstract class)
Client
Implementation
(concrete class)
Design to an Interface

Abstract classes/interfaces:




tend to change much less frequently
abstractions are ‘hinge points’ where it is easier to
extend/modify
shouldn’t have to modify classes/interfaces that represent
the abstraction (OCP)
Exceptions

Some classes are very unlikely to change;



therefore little benefit to inserting abstraction layer
Example: String class
In cases like this can use concrete class directly

as in Java or C++
DIP Related Heuristic
Avoid Transitive Dependencies

Avoid structures in which higher-level layers
depend on lower-level abstractions:

In example below, Policy layer is ultimately
dependant on Utility layer.
Policy
Layer
Depends on
Mechanism
Layer
Depends on
Utility
Layer
Solution to Transitive Dependencies

Use inheritance and abstract ancestor classes to
effectively eliminate transitive dependencies:
Policy
Layer
depends on
Mechanism
Interface
Mechanism
Layer
depends on
Utility
Interface
Utility
Layer
DIP - Related Heuristic
When in doubt, add a level of indirection

If you cannot find a satisfactory solution for the class
you are designing, try delegating responsibility to
one or more classes:
Problem
Holder
Problem
Solver
When in doubt ...

It is generally easier to remove or by-pass
existing levels of indirection than it is to
add them later:
Blue class’s indirect message
calls to red class fail to meet
some criteria (e.g. real-time
constraints, etc.)
So, Blue class re-implements
some or all of green class’s
responsibilities for efficiency
and calls red object directly
X
The Founding Principles

The three principles are closely related

Violating either LSP or DIP invariably results in
violating OCP

LSP violations are latent violations of OCP

It is important to keep in mind these principles to get
most out of OO development...

... and go beyond buzzwords and hype ;)
Demeter
Parnas
CS 620/720
Software Engineering
January 28, 2004
For Thursday

Quiz 2




Demeter (some sections skipped)
Parnas Chapters 9 and 14
Hw 1 Assigned
Lecture


Finish Modularization with Ball of Mud paper
Begin Design Patterns
Law of Demeter Principle



Each unit should only use a limited set of
other units: only units “closely” related to
the current unit.
“Each unit should only talk to its friends.”
“Don’t talk to strangers.”
Main Motivation: Goal is to organize and
reduce dependencies between classes


Restricts the message sending structure between
objects
Eases evolution of a class hierarchy
Law of Demeter
Acquaintances
FRIENDS
“closely related”
Benefits of Demeter







Coupling control
 “effectively reduces the methods you can call inside a given
method and therefore limits the coupling of methods”
Information hiding
 Prevents a method from directly retrieving a subpart of an object
Information restriction
 Restricts the use of methods that provide information
Few interfaces
 Restricts the classes that can be used in a method
Small interfaces
 Restricts the amount of information passed in a method
Explicit interfaces
 Explicitly states which classes can be used in a method
Disadvantage: May increase overall number of methods
The Law of Demeter
Any object receiving a message in a given method must be
one of a restricted set of objects.
1. Strict Form: Every supplier class or object to a method
must be a preferred supplier
2. Minimization Form: Minimize the number of
acquaintance classes / objects of each method
Lieberherr and Holland
Key idea: Structure shy code
Demeter Definitions

Strict Form – all methods may access only preferred suppliers


Inside of a method M of a class C, data can be accessed in and
messages can be sent to only the following objects:

Arguments of the method M

this, super

Data fields (data members) of class C

Objects created by functions called by M

Global variables

Temporary variables created in method M
Acquaintance classes
do NOT meet these criteria
Preferred supplier classes
meet all of these criteria
Preferred acquaintance classes
are the last two bullets
Strongest Form

Must use accessor function to access inherited data members
Demeter’s Law for Functions
class Demeter {
private:
A *a;
public:
// …
void example(B& b);
int func();
void Demeter::example(B& b) {
C c;
int f = func();
b.invert();
a = new A();
a->setActive(); …
c.print();
}
Any methods of an object
should call only methods
belonging to:
itself
passed parameters
created objects
directly held component objects
Demeter’s “Good Style”

Access supplier methods only through
methods of “preferred acquaintances”

bypass preferred supplier only if later
optimization demands direct access
Acquaintance
Client
Supplier
X
Good style dictates that red client
only access blue supplier via a
method in a certified acquaintance
Red client violates LoD if it performs
any direct calls to the blue supplier, no
matter how it got the reference
The Law of Demeter (cont.)
Violation of the Law
class A {public: void m(); P p(); B b; };
class B {public: C c; };
class C {public: void foo(); };
class P {public: Q q(); };
class Q {public: void bar(); };
void A::m() {
this.b.c.foo(); this.p().q().bar();}
Example from paper

Look at page 43…
Acceptable LoD Violations

If optimization requires violation


If module accessed is a fully stabilized “Black
Box”


Speed or memory restrictions
No changes to interface can reasonably be
expected due to extensive testing, usage, etc.
Otherwise, do not violate this law!!

Long-term costs will be very prohibitive
Designing Software for Ease of
Extension and Contraction

ICSE 1991 Most Influential Paper Award…

Do you agree?
Motivation

Industry has produced (is still producing) a
number of complaints




Cannot produce a “proper subset” of functionality
Contraction requires major re-writes
Cannot customize systems due to lack of flexibility
Extension requires major re-writes
“Design for change” is here to stay



Idea: Software design that eases identification of
working system subsets and addition of extensions
is a special case of design for change, and therefore
should be pursued.
How: Parnas suggests methodology that helps
achieve better, more flexible design structure
Key points:
 Family of Programs
 “Uses” Relations
 Information Hiding
 Virtual Machines
Flexibility vs. Generality

Generality – the ability of a system, without
modification, to be valid for several users.

Generality implies variable use



Run-time cost
Easier maintenance (single version)
Flexibility – the ability of a design to be easily
changed to accommodate new applications.

Flexible implies ease of change


Design-time cost
Multiple versions
Inhibiting Factors

Excessive information distribution


Chain of data-transforming components


Typical consequence of flow-chart method; poor coupling
Multi-function components


Too many components assume existence of a feature
Combining of multiple functions in one module; poor cohesion
Loops in the “uses” relation
The Methodology

Minimal subsets and minimal increments


Interface definitions using information hiding


“secrets” – items that are most likely to change
Design as virtual machines


“one first searches for the minimal subset that
conceivably perform a useful service and then
searches for a set of minimal increments”
“stop thinking of systems in terms of components
that correspond to steps in the processing”
“Uses” hierarchy
Defining the Uses Relation


Program A uses Program B if there exist
situations in which the correct functioning of
A depends on the availability of a correct
implementation of B.
How uses differs from invokes:


A does not use B if A must only invoke B to
satisfy A’s specification; B could be absent or
incorrect.
A does use B if A may implicitly invoke B
(e.g. as an interrupt handler)
When should A use B?




A is essentially simpler because it uses B;
B is not substantially more complex because
it is not allowed to use A;
There is a useful subset containing B and not
A; and
There is no conceivably useful subset
containing A but not B.
Example – The Automated Kitchen

Minimal subsets and increments

Level 0






Boil
Bake
Sauté
Refrigerate
Slice
Dice
The Automated Kitchen continued...

Minimal subsets and increments

Level 1





Make tea, coffee, soup
Toast bread, bagels
Bake muffins, pot roast
Sauté eggs, pancakes
Chill juice, fruit, preserve foods
The Automated Kitchen continued...

Minimal subsets and increments

Level 2



Prepare breakfast
Prepare lunch
Prepare dinner
The Automated Kitchen continued...

Minimal subsets and increments

Level 3

Prepare food
The Automated Kitchen continued...

Interface definitions using information hiding

Level 0



Level 1



Slicing is done with ginsu or veg-o-matic
Boiling is done with gas, electric, coal or microwave
Coffee is prepared on stovetop or drip brew
Bread is made in oven or bread machine
Level 2

Breakfast is instant or drip coffee and sauté eggs or
microwave breakfast
The Automated Kitchen continued...

Design as virtual machines




Coffee maker
Bread machine
Scramble eggs
Boil water
The Automated Kitchen finally!

“Uses” hierarchy
}
make breakfast
Level i uses at least 1 program on i-1
and nothing higher than i-1
brew coffee scramble eggs make toast make pancakes
boil
saute
bake
slice
mix
}
Level 0 uses no other program
Playing in the Mud
Introduction to MVC
CS 620/720
Software Engineering
January 29, 2004
Escape from the Spaghetti
Code Jungle
Brian Foote
University of Illinois at
Urbana-Champaign
17 February 1998
SOOUG Winter ‘98
Big Ball of Mud
The

Why
de-facto standard software architecture
“Haphazardly structured, sprawling, sloppy, duct-tape and
bailing wire, spaghetti code jungle”
is the gap between what we preach and what we
practice so large?
Where does Mud Come From






Throwaway Code
Legacy Mush
Urban Sprawl
Slash and Burn Tactics
Merciless Deadlines
Sheer Neglect
Silver Buckshot

We will even look at some of these, albeit
briefly for some, during the semester:






Objects
Frameworks
Patterns
Architecture
Process/Organization
Tools
Objects




The revolution is over, and objects won
O-O Programming has become Programming
O-O Languages set the stage for the
evolution of O-O Frameworks and
Components
O-O Reuse works, but is not a panacea
Frameworks

An Object-Oriented Framework is a collection of cooperating
classes that together define a generic or template solution to a
family of domain-specific requirements.

Frameworks are often characterized by an inversion of control in
which the framework plays the role of a main program in
coordinating and sequencing application activity.

Frameworks embody design insight
A Comparison of Class Libraries,
Frameworks, & Components
Class Library Architecture
APPLICATIONSPECIFIC
FUNCTIONALITY
LOCAL
INVOCATIONS
ADTs
Component Architecture
LOCAL/REMOTE
Math
APPLICATION- INVOCATIONS
SPECIFIC
FUNCTIONALITY
Naming
Files
Strings
Trading
GUI
EVENT
LOOP
GLUE
CODE
Locks
IPC
EVENT
LOOP
Often compile-time
Framework Architecture
ADTs
Strings
INVOKES
Files
Locks
Locking
GLUE
CODE
Events
Often run-time
Logging
Hollywood Principle
Old Reuse
Your Code
Library
New Reuse
Framework
Your Code
Notables on Frameworks

Interface design and functional factoring constitute the key
intellectual content of software and are far more difficult to
create or recreate than code
L. Peter Deutsch

A framework is the design for an application or subsystem; A
set of abstract classes and the way objects in those classes
collaborate
Ralph E. Johnson
Lehman and Belady
Lehman and Belady have studied the history of successive
releases in a large operating system. They find that the
total number of modules increases linearly with release
number, but that the number of modules affected increases
exponentially with release number. All repairs tend to
destroy the structure to increase the entropy and
disorder of the system.
Less and less effort is spent fixing original design flaws;
more and more is spent on fixing flaws introduced in earlier
fixes. As time passes, the system becomes less and less
well ordered...
Software Tectonics

Reconstruction

Major Upheaval
Throw it away
Incremental Change




Evolution
Piecemeal Growth
Throwaway Code


Sometimes this is the right
approach
There is the danger that
such code will take on a life
of its own
Reconstruction


Atlanta’s Fulton County
Stadium was built in 1966
and razed in 1997.
Two single purpose stadia,
with skyboxes, are
replacing it
Sweep It Under the Rug

You may not know how to get rid of a
problem, but at least you can cordon it
off...
Piecemeal Growth

Mir was designed to accommodate
maintenance and growth

Core 1986
Kvant 1 1987
Kvant 2 1989
Kristall 1990
Spekter 1995
Docking 1995
Priroda 1996






Mir is a complex of different modules that have been through many mutations;
modules get added and moved around, like a giant tinker toy in the sky.
Refactoring





Arresting entropy
Software gentrification
Refactorings are program transformations that preserve
program semantics, while improving structure
Refactoring has traditionally been done by hand, but tools are
starting to emerge
Languages differ significantly in the degree to which they support
refactoring
Conclusions






Frameworks embody architecture
Patterns communicate design insight
Refactoring facilitates evolution
Architecture emerges as a domain is explored
Design pervades the lifecycle, and the
organization
Tools can help. Better Tools are on the way
Coming Up




Next 2-3 weeks will be focused on design
patterns and the GoF book
Please look on the syllabus for the assigned
readings – I will let you know of any changes
I may ask questions from this first chapter
that are not covered in class – so read the
material 
Start to read some of the creational patterns
MVC – The Earliest Pattern
MVC History

Invented by Trygve Reenskaug and introduced into
the Smalltalk-80 programming environment
developed at Xerox PARC.

MVC was central to the architecture of the multiwindowed Smalltalk environment used to create the first
graphical user interfaces. The approach taken was
borrowed by the developers of the Apple Macintosh and
many imitators in the years since.

Elements of MVC appear in many modern GUIs
(MFC, Swing, … )
More info:


Buschmann et al. (1996) Pattern-Oriented Software
Archtiecture. John Wiley & Sons, pp. 125-143.
MVC motivation

The UI of an application is subject to many changes:






Change of UI for different users
Same info can be shown in different windows
Changes to underlying data should be reflected quickly
everywhere
Changes to UI should be easy, even at runtime
Different “look and feel” should not affect functional core
So separate processing, output, and input
MVC

MVC divides application into:





Model of core functionality and data
Views displaying information to user
Controllers handling user input
Views and Controllers comprise UI
Change-propagation mechanism ensures
consistency between Model and UI

Event-driven programming
MVC Schematic
Display
Each piece is an object
View
Model
Keyboard
Mouse
Etc.
Controller
Design Patterns in Smalltalk MVC
View
character-based
Controller
View
View
GUI, Document
1
GUI, Document 2


Implements algorithms (business logic)
Independent of environment
View:



Model
EUR -> US $
Model


Model
US $ -> EUR
Communicates with environment
Implements I/O interface for model
Controller:

Controls data exchange (notification protocol) between
model and view
MVC Architecture
http://java.sun.com/blueprints/patterns/j2ee_patterns/model_view_controller/
Model


Store and manage data elements, such as
state information
Encapsulates application-specific data and
functionality, providing:



methods to edit data, which Controller can call
methods to access state, which View and
Controller can request
Maintains registry of dependent Views and
Controllers to be notified about data changes
Model Examples



text editor: model is text string
slider: model is an integer
spreadsheet: collection of values related by
functional constraints
View


Mechanism needed to map model data to
rendition (view / display)
When Model changes, View is informed


View requests relevant model information
View arranges to update screen



Declare damaged areas
Redraw when requested
E.g., a button has a colored background, appears in a
raised perspective, and contains an icon and text; the
text is rendered in a certain font in a certain color
View Examples


Slider: text-field, line with bead, temp. gauge
Spreadsheet:



Tabular representation
Bar chart
Histogram
MVC Concepts – multiple views

Any number of views can subscribe to the
model
View #1
View #2
View #3
Radio
button
model
Controller tasks



Receive user inputs from mouse and
keyboard
Map these into commands that are sent to
the model and/or viewport to effect changes
in the view
E.g, detect that a button has been pressed
and inform the model that the button state
has changed
Controller Examples



Textual commands
Mouse (point and click) commands
No input
MVC Dynamics


1. User input event
routed by Window
System to appropriate
Controller.
2. Controller may
require View to “pick”
object of focus for
event.
V
M
C
MVC Dynamics


3. Controller requests
method of Model to
change its state.
4. Model changes its
internal state
V
M
C
MVC Dynamics


5. Model notifies all
dependent Views that
data has changed.
6. View requests from
Model current data
values.
V
M
C
MVC Dynamics


7. Model notifies all
dependent Controllers
that data has
changed.
8. Controller requests
from Model current
data values.
V
M
C
MVC Dynamics


9. Controller informs
View if elements are
disabled.
10. View requests
redraw
V
M
C
View + Controller linking

Controller almost always has to “talk to” view



As a result, VC tend to be very tightly coupled, and
considered as one


need geometry of output to interpret input (e.g., picking)
need to do feedback
M(VC)
Multiple View/Controller pairs can be attached to a
single Model
Benefits of MVC Architecture

Improved maintainability


Promotes code reuse


Due to OO approach (e.g., subclassing, inheritance)
Model independence


Due to modularity of software components
Designers can enhance and/or optimize model without
changing the view or controller
Pluggable look and feel


New L&F without changing model
Multiple views use the same data
MVC: More Pros and Cons

Pro:




Multiple views of same model
Synchronized views
Pluggable V & C and “look and feel”
Con:




Complexity for simple interactors
Potentially excessive updates/messages
Tight coupling, in practice (V-C, VC-M)
Some toolkits make MVC framework hard
MVC Example - Swing
MVC and Swing



Swing designers found it difficult to write a
generic controller that didn’t know the
specifics about the view
So, they collapsed the view and controller
into a single UI (user interface) object known
as a delegate (the UI is delegated to this
object)
This object is known as a UI delegate
VC – Swing Views and Controllers







In Swing, the term look and feel (L&F) is common
The look is the view
The feel is the controller
In practice, the view and controller parts of MVC are
very tightly connected
Swing combines the view and controller into a single
entity known as a UI delegate
Advantage: combining the view and controller allows the
appearance and behavior (L&F) of a component to be
treated as a single unit, thus facilitating changes to the
UI are possible
This is known as pluggable look and feel (next 3 slides)
MVC and Swing (2)
Swing component
Display
UI delegate
View
Model
Keyboard
Mouse
Etc.
Controller
M - Swing Models

In Swing, many models exist as interfaces



Eg., ButtonModel, BoundedRangeModel,
ComboBoxModel, ListModel, ListSelectionModel,
TableModel, Document
The interface is implemented in model classes
Usually there is a default model class that is
automatically associated with a component


E.g., DefaultButtonModel implements ButtonModel
E.g, AbstractDocument implements Document
(PlainDocument is a subclass of AbstractDocument)
Example Program
Instead of passing the data directly to the JTable object,
we create a data model, pass the data to the model, then
pass the model to the JTable object.
Example Program
JTextField’s default data model is
PlainDocument. We can create a custom
data model for a JTextField by creating
our own data model and substituting it for
PlainDocument
Example Program
On to patterns intro….
What is a Pattern ?
The “Alexandrian” 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 a way that
you can use this solution a million times over,
without ever doing it the same way twice
C. Alexander, “The Timeless Way of Building”, 1979
The Quality without a Name
There is a central quality which is the root
criterion of life and spirit in [all things]. This quality
is objective and precise, but it cannot be named.
... The search which we make for this quality, in
our own lives, is the central search of any person.
... It is the search for those moments and
situations when we are most alive.
C. Alexander
Alexander's View of a Pattern


Three part rule that expresses a relation between a certain
context, a problem and a solution.
Element of the world – a relationship between




Element of language – an instruction




a context
a system of forces that occur repeatedly in the context
a spatial configuration which allow forces to resolve themselves
describes how the spatial configuration can be repeated
to resolve the given system of forces
wherever the context makes it relevant
The “thing – process” dualism


a thing that happens in the world
a process (rule) which will generate that thing
Design Patterns

Design patterns represent solutions to
problems that arise when developing
software within a particular context



Patterns = Problem/Solution pair in Context
Capture static and dynamic structure and
collaboration among key participants in
software designs
Facilitate reuse of successful software
architectures and design

i.e. the “design of masters”… ;)
What Makes it a Pattern ?
A pattern must...

...solve a problem


...have a context


i.e. it must be useful
it must describe where
the solution can be used
...recur

must be relevant in other
situations
 ... teach
 provide sufficient
understanding to tailor the
solution
 ... have a name
 referred consistently
GoF Form of a Design Pattern
Pattern name and classification
Intent
what does pattern do
Also known as
other known names of pattern (if any)
Motivation
the design problem
Applicability
situations where pattern can be applied
Structure
a graphical representation of classes in the pattern
Participants
the classes/objects participating and their responsibilities
Collaborations
of the participants to carry out responsibilities
GoF Form of a Design Pattern
Consequences
trade-offs, concerns
Implementation
hints, techniques
Sample code
code fragment showing possible implementation
Known uses
patterns found in real systems
Related patterns
closely related patterns
Algorithmic Form of Patterns
IF
you find yourself in CONTEXT
for example EXAMPLES,
with PROBLEM,
entailing FORCES
THEN for some REASONS,
apply DESIGN FORM AND/OR RULE
to construct SOLUTION
leading to NEW CONTEXT and
OTHER PATTERNS
Why are Patterns Important?




“Patterns provide an incredibly dense means of efficient and
effective communication between those who know the language.”
Nate Kirby
“Human communication is the bottleneck in software development.
If [patterns] can help [developers] communicate with their clients,
their customers, and each other, then [patterns] help fill a crucial
need in [our industry].”
Jim Coplien
“Patterns don’t give you code you can drop into your application,
they give you experience you can drop into your head.”
Patrick Logan
“Giving someone a piece of code is like giving him a fish; giving
him a pattern is like teaching him to fish.”
Don Dwiggins
Reuse Benefits


Mature engineering disciplines have handbooks of solutions to
recurring problems. All certified professional engineers in these fields
have been trained in the contents of these handbooks.
In an experiment, teams of leading heart surgeons from five New
England medical centers observed one another’s operating room
practices and exchanged ideas about their most effective techniques.
The result? A 24% drop in their overall mortality rate for coronary
bypass surgery = 74 fewer deaths than predicted.
Becoming a Chess Master

Learn the rules and physical requirements


Learn the principles


e.g. relative value of certain pieces, strategic values of center squares,
power of a threat etc.
To become a master, one must study the games of other masters


e.g. pieces, legal movements, chess board geometry and orientation.
these games contain patterns that must be understood, memorized and
applied repeatedly
There are hundreds, if not thousands, of such patterns
Becoming a Software Design Master

First learn the rules


e.g. the algorithms, data structures and languages of software
Then learn the principles

e.g. principles that govern different programming paradigms


To truly master software design, one must study the design of other
masters


structured, modular, object-oriented, etc
these designs contain patterns that must be understood, memorized and
applied repeatedly
There are hundreds of these patterns
Drawbacks of Design Patterns

Patterns do not lead to direct code reuse

Patterns are deceptively simple

Integrating patterns into a software development
process is a human-intensive activity

Teams may suffer from patterns overload
When your only tool is a hammer, all the
problems look like a nail…

When first learning patterns, all problems
begin to look like the problem under
consideration – try to avoid this!

Similar to someone just learning to play chess and
using the same strategy everywhere – eventually
you will get burned!
Problem X
Problem Y
Problem Z
Designing for Change –
Causes for Redesign (I)

Creating an object by specifying a class explicitly





Commits to a particular implementation instead of an
interface
Can complicate future changes
Create objects indirectly
Patterns: Abstract Factory, Factory Method, Prototype
Dependence on specific operations



Commits to one way of satisfying a request
Compile-time and runtime modifications to request handling
can be simplified by avoiding hard-coded requests
Patterns: Chain of Responsibility, Command
Causes for Redesign (II)

Dependence on hardware and software platform




External OS-APIs vary
Design system to limit platform dependencies
Patterns: Abstract Factory, Bridge
Dependence on object representations or
implementations



Clients that know how an object is represented, stored,
located, or implemented might need to be changed when
object changes
Hide information from clients to avoid cascading changes
Patterns: Abstract factory, Bridge, Memento, Proxy
Causes for Redesign (III)

Algorithmic dependencies




Algorithms are often extended, optimized, and replaced
during development and reuses
Algorithms that are likely to change should be isolated
Patterns: Builder, Iterator, Strategy, Template Method,
Visitor
Tight coupling



Leads to monolithic systems
Tightly coupled classes are hard to reuse in isolation
Patterns: Abstract Factory, Bridge, Chain of Responsibility,
Command, Facade, Mediator, Observer
Causes for Redesign (IV)

Extending functionality by subclassing





Requires in-depth understanding of the parent class
Overriding one operation might require overriding another
Can lead to an explosion of classes (for simple extensions)
Patterns: Bridge, Chain of Responsibility, Composite,
Decorator, Observer, Strategy
Inability to alter classes conveniently



Sources not available
Change might require modifying lots of existing classes
Patterns: Adapter, Decorator, Visitor
Design Pattern Space
Purpose
Defer object creation to
another class
Creational
Scope Class
Structural
Behavioral
Factory Method Adapter (class) Interpreter
Template Method
Object Abstract
Factory
Builder
Prototype
Singleton
Defer object creation to
another object
Describe ways to
assemble objects
Adapter
(object)
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Describe algorithms and
flow control
Chain of
Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Relations among Design Patterns
Memento
Proxy
saving state
of iteration
Builder
Adapter
Bridge
Iterator
Enumerating
children
composed
using
Composite
Decorator
adding
respnsibilities
to objects
sharing
composites
changing skin
versus guts
Flyweight
State
defining
algorithm´s
steps
Prototype
Singleton
single
instance
defining
grammar
Visitor
Chain of
Responsibility
Interpreter
sharing
strategies
Strategy
Command
Mediator
Observer
Template Method
Factory Method
Abstract Factory
single
instance
Facade
Many different kinds of patterns

Small printing industry grew out of patterns:


Stop and see the dozen or so patterns books in my office
as evidence
Patterns for many different contexts:






Analysis/Requirements patterns
Middleware/infrastructure
Domain-specific patterns
Real-time patterns
UML and Patterns
Anti-patterns

Mud (?)
Overview of Patterns & Pattern Languages
Patterns
•Present solutions to common software
problems arising within a certain context
•Help resolve key design forces
•Capture recurring structures & dynamics
among software participants to facilitate
reuse of successful designs
•Generally codify expert knowledge of
design constraints & “best practices”
Pattern Languages
• Define a vocabulary for
talking about software
development problems
• Provide a process for the
orderly resolution of these
problems
• Help to generate & reuse
software architectures
www.posa.uci.edu
•Flexibility The Proxy
•ExtensibilityPattern
•Dependability
•Predictability
•Scalability
•Efficiency
More Pattern Information

Mike Duell’s non-software examples
http://www.agcs.com/supportv2/techpapers/patterns/papers




Patterns Listservers http://hillside.net/patterns/Lists.html
Wiki Wiki Web http://c2.com/cgi/wiki
Home pages for Jim Coplien, Doug Schmidt, Doug
Lea, and others, see AGCS site
http://www.agcs.com/supportv2/techpapers/patterns/
More Pattern URLs
Robert C. Martin’s Chess Analogy
http://www.cs.wustl.edu/~schmidt/cs242/learning.html
John Vlissides' "Top 10 Misconceptions"
http://www.research.ibm.com/designpatterns/pubs/top10misc.html
Linda Rising's QWAN in software
http://www.lindarising.org -- click on Articles
Seven Habits of Successful Pattern Writers
http://hillside.net/patterns/papers/7habits.html
Brad Appleton's "Patterns in a Nutshell"
http://www.enteract.com/~bradapp/docs/patterns-nutshell.html
Introduction to MVC and Patterns
CS 620/720
Software Engineering
February 3, 2004
Coming Up


Next 2-3 weeks will be focused on design
patterns and the GoF book
Please look on the syllabus for the assigned
readings – I will let you know of any changes



So far, 1 lecture behind
I may ask questions from this first chapter
that are not covered in class – so read the
material 
Start to read some of the creational patterns
MVC – The Earliest Pattern
MVC History

Invented by Trygve Reenskaug and introduced into
the Smalltalk-80 programming environment
developed at Xerox PARC.

MVC was central to the architecture of the multiwindowed Smalltalk environment used to create the first
graphical user interfaces. The approach taken was
borrowed by the developers of the Apple Macintosh and
many imitators in the years since.

Elements of MVC appear in many modern GUIs
(MFC, Swing, … )
More info:


Buschmann et al. (1996) Pattern-Oriented Software
Archtiecture. John Wiley & Sons, pp. 125-143.
MVC motivation

The UI of an application is subject to many changes:






Change of UI for different users
Same info can be shown in different windows
Changes to underlying data should be reflected quickly
everywhere
Changes to UI should be easy, even at runtime
Different “look and feel” should not affect functional core
So separate processing, output, and input
MVC

MVC divides application into:





Model of core functionality and data
Views displaying information to user
Controllers handling user input
Views and Controllers comprise UI
Change-propagation mechanism ensures
consistency between Model and UI

Event-driven programming
MVC Schematic
Display
Each piece is an object
View
Model
Keyboard
Mouse
Etc.
Controller
Design Patterns in Smalltalk MVC
View
character-based
Controller
View
View
GUI, Document
1
GUI, Document 2


Implements algorithms (business logic)
Independent of environment
View:



Model
EUR -> US $
Model


Model
US $ -> EUR
Communicates with environment
Implements I/O interface for model
Controller:

Controls data exchange (notification protocol) between
model and view
MVC Architecture
http://java.sun.com/blueprints/patterns/j2ee_patterns/model_view_controller/
Model


Store and manage data elements, such as
state information
Encapsulates application-specific data and
functionality, providing:



methods to edit data, which Controller can call
methods to access state, which View and
Controller can request
Maintains registry of dependent Views and
Controllers to be notified about data changes
Model Examples



text editor: model is text string
slider: model is an integer
spreadsheet: collection of values related by
functional constraints
View


Mechanism needed to map model data to
rendition (view / display)
When Model changes, View is informed


View requests relevant model information
View arranges to update screen



Declare damaged areas
Redraw when requested
E.g., a button has a colored background, appears in a
raised perspective, and contains an icon and text; the
text is rendered in a certain font in a certain color
View Examples


Slider: text-field, line with bead, temp. gauge
Spreadsheet:



Tabular representation
Bar chart
Histogram
MVC Concepts – multiple views

Any number of views can subscribe to the
model
View #1
View #2
View #3
Radio
button
model
Controller tasks



Receive user inputs from mouse and
keyboard
Map these into commands that are sent to
the model and/or viewport to effect changes
in the view
E.g, detect that a button has been pressed
and inform the model that the button state
has changed
Controller Examples



Textual commands
Mouse (point and click) commands
No input
MVC Dynamics


1. User input event
routed by Window
System to appropriate
Controller.
2. Controller may
require View to “pick”
object of focus for
event.
V
M
C
MVC Dynamics


3. Controller requests
method of Model to
change its state.
4. Model changes its
internal state
V
M
C
MVC Dynamics


5. Model notifies all
dependent Views that
data has changed.
6. View requests from
Model current data
values.
V
M
C
MVC Dynamics


7. Model notifies all
dependent Controllers
that data has
changed.
8. Controller requests
from Model current
data values.
V
M
C
MVC Dynamics


9. Controller informs
View if elements are
disabled.
10. View requests
redraw
V
M
C
View + Controller linking

Controller almost always has to “talk to” view



As a result, VC tend to be very tightly coupled, and
considered as one


need geometry of output to interpret input (e.g., picking)
need to do feedback
M(VC)
Multiple View/Controller pairs can be attached to a
single Model
Benefits of MVC Architecture

Improved maintainability


Promotes code reuse


Due to OO approach (e.g., subclassing, inheritance)
Model independence


Due to modularity of software components
Designers can enhance and/or optimize model without
changing the view or controller
Pluggable look and feel


New L&F without changing model
Multiple views use the same data
MVC: More Pros and Cons

Pro:




Multiple views of same model
Synchronized views
Pluggable V & C and “look and feel”
Con:




Complexity for simple interactors
Potentially excessive updates/messages
Tight coupling, in practice (V-C, VC-M)
Some toolkits make MVC framework hard
MVC Example - Swing
VC – Swing Views and Controllers







In Swing, the term look and feel (L&F) is common
The look is the view
The feel is the controller
In practice, the view and controller parts of MVC are
very tightly connected
Swing combines the view and controller into a single
entity known as a UI delegate
Advantage: combining the view and controller allows the
appearance and behavior (L&F) of a component to be
treated as a single unit, thus facilitating changes to the
UI are possible
This is known as pluggable look and feel (next 3 slides)
MVC and Swing
Swing component
Display
UI delegate
View
Model
Keyboard
Mouse
Etc.
Controller
M - Swing Models

In Swing, many models exist as interfaces



Eg., ButtonModel, BoundedRangeModel,
ComboBoxModel, ListModel, ListSelectionModel,
TableModel, Document
The interface is implemented in model classes
Usually there is a default model class that is
automatically associated with a component


E.g., DefaultButtonModel implements ButtonModel
E.g, AbstractDocument implements Document
(PlainDocument is a subclass of AbstractDocument)
Example Program
Instead of passing the data directly to the JTable object,
we create a data model, pass the data to the model, then
pass the model to the JTable object.
Example Program
JTextField’s default data model is
PlainDocument. We can create a custom
data model for a JTextField by creating
our own data model and substituting it for
PlainDocument
Example Program
On to patterns intro….
What is a Pattern ?
The “Alexandrian” 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 a way that
you can use this solution a million times over,
without ever doing it the same way twice
C. Alexander, “The Timeless Way of Building”, 1979
The Quality without a Name
There is a central quality which is the root
criterion of life and spirit in [all things]. This quality
is objective and precise, but it cannot be named.
... The search which we make for this quality, in
our own lives, is the central search of any person.
... It is the search for those moments and
situations when we are most alive.
C. Alexander
Alexander's View of a Pattern


Three part rule that expresses a relation between a certain
context, a problem and a solution.
Element of the world – a relationship between




Element of language – an instruction




a context
a system of forces that occur repeatedly in the context
a spatial configuration which allow forces to resolve themselves
describes how the spatial configuration can be repeated
to resolve the given system of forces
wherever the context makes it relevant
The “thing – process” dualism


a thing that happens in the world
a process (rule) which will generate that thing
Design Patterns

Design patterns represent solutions to
problems that arise when developing
software within a particular context



Patterns = Problem/Solution pair in Context
Capture static and dynamic structure and
collaboration among key participants in
software designs
Facilitate reuse of successful software
architectures and design

i.e. the “design of masters”… ;)
What Makes it a Pattern ?
A pattern must...

...solve a problem


...have a context


i.e. it must be useful
it must describe where
the solution can be used
...recur

must be relevant in other
situations
 ... teach
 provide sufficient
understanding to tailor the
solution
 ... have a name
 referred consistently
GoF Form of a Design Pattern
Pattern name and classification
Intent
what does pattern do
Also known as
other known names of pattern (if any)
Motivation
the design problem
Applicability
situations where pattern can be applied
Structure
a graphical representation of classes in the pattern
Participants
the classes/objects participating and their responsibilities
Collaborations
of the participants to carry out responsibilities
GoF Form of a Design Pattern
Consequences
trade-offs, concerns
Implementation
hints, techniques
Sample code
code fragment showing possible implementation
Known uses
patterns found in real systems
Related patterns
closely related patterns
Algorithmic Form of Patterns
IF
you find yourself in CONTEXT
for example EXAMPLES,
with PROBLEM,
entailing FORCES
THEN for some REASONS,
apply DESIGN FORM AND/OR RULE
to construct SOLUTION
leading to NEW CONTEXT and
OTHER PATTERNS
Why are Patterns Important?




“Patterns provide an incredibly dense means of efficient and
effective communication between those who know the language.”
Nate Kirby
“Human communication is the bottleneck in software development.
If [patterns] can help [developers] communicate with their clients,
their customers, and each other, then [patterns] help fill a crucial
need in [our industry].”
Jim Coplien
“Patterns don’t give you code you can drop into your application,
they give you experience you can drop into your head.”
Patrick Logan
“Giving someone a piece of code is like giving him a fish; giving
him a pattern is like teaching him to fish.”
Don Dwiggins
Reuse Benefits


Mature engineering disciplines have handbooks of solutions to
recurring problems. All certified professional engineers in these fields
have been trained in the contents of these handbooks.
In an experiment, teams of leading heart surgeons from five New
England medical centers observed one another’s operating room
practices and exchanged ideas about their most effective techniques.
The result? A 24% drop in their overall mortality rate for coronary
bypass surgery = 74 fewer deaths than predicted.
Becoming a Chess Master

Learn the rules and physical requirements


Learn the principles


e.g. relative value of certain pieces, strategic values of center squares,
power of a threat etc.
To become a master, one must study the games of other masters


e.g. pieces, legal movements, chess board geometry and orientation.
these games contain patterns that must be understood, memorized and
applied repeatedly
There are hundreds, if not thousands, of such patterns
Becoming a Software Design Master

First learn the rules


e.g. the algorithms, data structures and languages of software
Then learn the principles

e.g. principles that govern different programming paradigms


To truly master software design, one must study the design of other
masters


structured, modular, object-oriented, etc
these designs contain patterns that must be understood, memorized and
applied repeatedly
There are hundreds of these patterns
Drawbacks of Design Patterns

Patterns do not lead to direct code reuse

Patterns are deceptively simple

Integrating patterns into a software development
process is a human-intensive activity

Teams may suffer from patterns overload
When your only tool is a hammer, all the
problems look like a nail…

When first learning patterns, all problems
begin to look like the problem under
consideration – try to avoid this!

Similar to someone just learning to play chess and
using the same strategy everywhere – eventually
you will get burned!
Problem X
Problem Y
Problem Z
Designing for Change –
Causes for Redesign (I)

Creating an object by specifying a class explicitly





Commits to a particular implementation instead of an
interface
Can complicate future changes
Create objects indirectly
Patterns: Abstract Factory, Factory Method, Prototype
Dependence on specific operations



Commits to one way of satisfying a request
Compile-time and runtime modifications to request handling
can be simplified by avoiding hard-coded requests
Patterns: Chain of Responsibility, Command
Causes for Redesign (II)

Dependence on hardware and software platform




External OS-APIs vary
Design system to limit platform dependencies
Patterns: Abstract Factory, Bridge
Dependence on object representations or
implementations



Clients that know how an object is represented, stored,
located, or implemented might need to be changed when
object changes
Hide information from clients to avoid cascading changes
Patterns: Abstract factory, Bridge, Memento, Proxy
Causes for Redesign (III)

Algorithmic dependencies




Algorithms are often extended, optimized, and replaced
during development and reuses
Algorithms that are likely to change should be isolated
Patterns: Builder, Iterator, Strategy, Template Method,
Visitor
Tight coupling



Leads to monolithic systems
Tightly coupled classes are hard to reuse in isolation
Patterns: Abstract Factory, Bridge, Chain of Responsibility,
Command, Facade, Mediator, Observer
Causes for Redesign (IV)

Extending functionality by subclassing





Requires in-depth understanding of the parent class
Overriding one operation might require overriding another
Can lead to an explosion of classes (for simple extensions)
Patterns: Bridge, Chain of Responsibility, Composite,
Decorator, Observer, Strategy
Inability to alter classes conveniently



Sources not available
Change might require modifying lots of existing classes
Patterns: Adapter, Decorator, Visitor
Design Pattern Space
Purpose
Defer object creation to
another class
Creational
Scope Class
Structural
Behavioral
Factory Method Adapter (class) Interpreter
Template Method
Object Abstract
Factory
Builder
Prototype
Singleton
Defer object creation to
another object
Describe ways to
assemble objects
Adapter
(object)
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Describe algorithms and
flow control
Chain of
Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Relations among Design Patterns
Memento
Proxy
saving state
of iteration
Builder
Adapter
Bridge
Iterator
Enumerating
children
composed
using
Composite
Decorator
adding
respnsibilities
to objects
sharing
composites
changing skin
versus guts
Flyweight
State
defining
algorithm´s
steps
Prototype
Singleton
single
instance
defining
grammar
Visitor
Chain of
Responsibility
Interpreter
sharing
strategies
Strategy
Command
Mediator
Observer
Template Method
Factory Method
Abstract Factory
single
instance
Facade
Many different kinds of patterns

Small printing industry grew out of patterns:


Stop and see the dozen or so patterns books in my office
as evidence
Patterns for many different contexts:






Analysis/Requirements patterns
Middleware/infrastructure
Domain-specific patterns
Real-time patterns
UML and Patterns
Anti-patterns

Mud (?)
Overview of Patterns & Pattern Languages
Patterns
•Present solutions to common software
problems arising within a certain context
•Help resolve key design forces
•Capture recurring structures & dynamics
among software participants to facilitate
reuse of successful designs
•Generally codify expert knowledge of
design constraints & “best practices”
Pattern Languages
• Define a vocabulary for
talking about software
development problems
• Provide a process for the
orderly resolution of these
problems
• Help to generate & reuse
software architectures
www.posa.uci.edu
•Flexibility The Proxy
•ExtensibilityPattern
•Dependability
•Predictability
•Scalability
•Efficiency
More Pattern Information

Mike Duell’s non-software examples
http://www.agcs.com/supportv2/techpapers/patterns/papers




Patterns Listservers http://hillside.net/patterns/Lists.html
Wiki Wiki Web http://c2.com/cgi/wiki
Home pages for Jim Coplien, Doug Schmidt, Doug
Lea, and others, see AGCS site
http://www.agcs.com/supportv2/techpapers/patterns/
More Pattern URLs
Robert C. Martin’s Chess Analogy
http://www.cs.wustl.edu/~schmidt/cs242/learning.html
John Vlissides' "Top 10 Misconceptions"
http://www.research.ibm.com/designpatterns/pubs/top10misc.html
Linda Rising's QWAN in software
http://www.lindarising.org -- click on Articles
Seven Habits of Successful Pattern Writers
http://hillside.net/patterns/papers/7habits.html
Brad Appleton's "Patterns in a Nutshell"
http://www.enteract.com/~bradapp/docs/patterns-nutshell.html
Creational Patterns
CS 620/720
Software Engineering
February 5, 2004
Leonard Jowers
Design Pattern Space
Purpose
Creational
Structural
Class Factory Method Adapter (class)
S
C
O
P
E
O
B
J
E
C
T
Abstract Factory
Builder
Prototype
Singleton
Adapter (object)
Bridge
Composite
Decorator
Facade
Flyweight
Proxy
Behavioral
Interpreter
Template Method
Chain of Responsibility
Command
Iterator
Mediator
Memento
Observer
State
Strategy
Visitor
Creational Patterns
Concerns the process of object creation.

Will Cover


Abstract Factory/
Factory Method
Singleton

Will not cover


Builder
Prototype
Structural Patterns
Deals w/ the composition of classes or objects.

Will Cover





Adapter
Facade
Composite
Decorator
Proxy

Will not cover


Bridge
Flyweight
Behavioral Patterns
Characterizes the ways in which classes or
objects interact and distribute responsibility.

Will Cover





Visitor
Observer
Strategy
Command
Chain of Responsibility

Will not cover






Interpreter
Iterator
Mediator
Memento
State
Template
Creational Patterns

Abstract the instantiation process


Important if systems evolve to depend more on
object composition than on class inheritance



Make a system independent of how its objects are created,
composed, and represented
Emphasis shifts from hardcoding fixed sets of behaviors
towards a smaller set of composable fundamental
behaviors
Encapsulate knowledge about concrete classes a
system uses
Hide how instances of classes are created and put
together
Basic Definitions

Instantiation – the creation of an object from a class.

Abstract Class – defines a common interface for its
subclasses; defers some implementation to its
subclasses; cannot be instantiated.

Concrete Class – classes which can be instantiated.
ABSTRACT FACTORY Motivation
Let’s start simple...

We can modify the internal Widget code without
modifying the ApplicationClass

What happens when we discover a new widget
and would like to use it in the
ApplicationClass?
Problems with Changes

Multiple coupling between Widget and
ApplicationClass

ApplicationClass knows the interface of Widget

ApplicationClass explicitly uses the Widget type


hard to change because Widget is a concrete class
ApplicationClass explicitly creates new Widgets
in many places

if we want to use the new Widget instead of the initial one,
changes are spread all over the code
Apply “Program to an Interface”


ApplicationClass depends now on an
(abstract) interface
But we still have hard coded which widget to
create!
ABSTRACT FACTORY
Motivation Example
Widget Factory
Client
CreateScrollBar()
CreateWindow()
Windows
PMWindow
MotifWidgetFactory
MotifWindow
PMWidgetFactory
CreateScrollBar()
CreateScrollBar()
CreateWindow()
CreateWindow()
ScrollBar
PMScrollBar
MotifScrollBar
GoF Form of a Design Pattern
The Pattern Name
Pattern name and classification, Intent, and Also-Known-As
 The Problem
Motivation, and Applicability
 The Solution
Structure (graphical), Participants (their classes/ objects/
responsibilities), Collaborations (of the participants),
Implementation (hints, techniques), Sample code,
Known uses, and Related patterns
 The Consequences
Consequences (trade-offs, concerns)

ABSTRACT FACTORY, aka Kit

Intent:


Provide an interface for creating families of related or
dependent objects w/o specifying their concrete
classes
Motivation:



User interface toolkit supports multiple look-and-feel
standards (Motif, Presentation Manager)
Different appearances and behaviors for UI widgets
Apps should not hard-code its widgets
ABSTRACT FACTORY, Solution

Place Abstract Factory Class between application
layer and a Concrete Factory Class(es).

Create an Abstract WidgetFactory class from a
related set of Abstract Interfaces (Abstract Products);
e.g., Abstract Interfaces for creating each basic kind
of widget.

Create Concrete WidgetFactory for specific
implementations; e.g., classes implement specific
look-and-feel, and allow for different look-and-feel.
Applicability
Use the Abstract Factory pattern when




A system should be independent of how its
products are created, composed, and represented
A system should be configured with one of
multiple families of products
A family of related product objects is designed to
be used together, and you need to enforce this
constraint
You want to provide a class library of products,
and you want to reveal just their interfaces, not
their implementations
ABSTRACT FACTORY
Structure
Abstract Factory
Client
CreateProductA()
CreateProductB()
AbstractProductA
ProductA2
ConcreteFactory1
ConcreteFactory2
CreateProductA()
CreateProductA()
CreateProductB()
CreateProductB()
ProductA1
AbstractProductB
ProductB2
ProductB1
ABSTRACT FACTORY, Participants

AbstractFactory


ConcreteFactory


Declares an interface for a type of product object
ConcreteProduct



Implements operations to create concrete product objects
AbstractProduct


Declares interface for operations that create abstract
product objects
Defines a product object to be created by concrete factory
Implements the abstract product interface
Client

Uses only interfaces declared by AbstractFactory and
AbstractProduct classes
Evaluation of Solution




Explicit creation of Widget objects is not anymore
dispersed; hence, is easier to change.
Functional methods in ApplicationClass are
decoupled from various concrete implementations of
widgets.
Use of Factories forces adherence to interfaces and
encapsulates both interface definitions and
implementations.
Avoids ugly code duplication in
ApplicationClassB

subclasses reuse the functional methods, just
implementing the concrete Factory Method needed
ABSTRACT FACTORY
Example
AbstractFactory
Client
Client()
main()
getFactory()
getWindow()
AbstractWindow
XWindow
xWindow()
show()
MotifFactory
MotifFactory()
getWindow()
WindowsFactory
WindowsFactory()
getWindow()
MotifWindow
MotifWindow()
show()
Abstract Factory Example
// Code for class AbstractFactory:
public abstract class AbstractFactory {
public static final String MOTIF_WIDGET_NAME = "Motif";
public static final String WINDOWS_WIDGET_NAME = "Windows";
public static AbstractFactory getFactory(String name) {
if (name.equals(MOTIF_WIDGET_NAME))
return new MotifFactory( );
else if (name.equals(WINDOWS_WIDGET_NAME))
return new WindowsFactory( );
return null;
} // end of getFactory
public abstract AbstractWindow getWindow();
}; // end of class AbstractFactory
Abstract Factory Example (Cont’d)
// Code for class MotifFactory:
public class MotifFactory extends AbstractFactory {
public MotifFactory() { }
public AbstractWindow getWindow() {
return new MotifWindow();
} // end of getWindow
}; // end of MotifFactory
// Code for class WindowsFactory:
public class WindowsFactory extends AbstractFactory {
public WindowsFactory() { }
public AbstractWindow getWindow() {
return new WindowsWindow();
} // end of getWindow
}; // end of WindowsFactory
Abstract Factory Example (Cont’d)
// Code for class AbstractWindow:
public abstract class AbstractWindow {
public abstract void show();
}; // end of AbstractWindow
Abstract Factory Example (Cont’d)
//Code for class MotifWindow:
public class MotifWindow extends AbstractWindow {
public MotifWindow() { }
public void show() {
JFrame frame = new JFrame();
try {
UIManager.setLookAndFeel("com.sun.java.swing.plaf.motif.MotifLookAndFeel");
} catch (Exception e) {
e.printStackTrace();
}
//updating the components tree after changing the LAF
SwingUtilities.updateComponentTreeUI(frame);
frame.setSize(300, 300);
frame.setVisible(true);
} // end of show
}; // end of MotifWindow
Abstract Factory Example (Cont’d)
// Code for class Client:
public class Client {
public Client(String factoryName) {
AbstractFactory factory =
AbstractFactory.getFactory(factoryName);
AbstractWindow window = factory.getWindow();
window.show();
} // end of Client
public static void main(String [] args)
{
//args[0] contains the name of the family of widgets
//to be used by the Client class (Motif or Windows)
new Client(args[0]);
} // end of main
}; // end of class Client
Example – Maze

This Room Maze will be a common example
used to illustrate the creational patterns.
Class Diagram for the Maze
4
MapSite
enter()=0;
1
Maze
rooms
1
Room
* enter()
setSide()
getSide()
roomNumber
Wall
Door
enter()
enter()
isOpen
Common abstract class for all Maze
Components
enum Direction {North, South, East, West};
class MapSite {
public:
virtual void enter() = 0;
}; // end of class MapSite

Meaning of enter() depends on what you are
entering.


room  location changes
door  if door is open go in; else hurt your nose ;)
Components of the maze – Wall &
Door & Room
class Room : public MapSite {
public:
Room(int roomNo);
MapSite* getSide(Direction) const;
void setSide(Direction, MapSite*);
void enter();
private:
MapSite* sides[4];
int roomNumber;
}; // end of class Room
class Wall : public MapSite {
public:
Wall();
virtual void enter();
}; // end of class Wall
class Door : public MapSite {
public:
Door(Room* = 0, Room* = 0);
virtual void enter();
Room* otherSideFrom(Room*);
private:
Room* room1;
Room* room2;
bool isOpen;
}; // end of class Door
Components of the maze – Maze
class Maze {
public:
void addRoom(Room*);
Room * roomNo(int) const;
private:
}; // end of class Maze
A maze is a collection
of rooms. Maze can
find a particular room
given the room number.
roomNo() could do a
lookup using a linear
search or a hash table
or a simple array.
Structure of a game
4
enter()=0;
MazeGame
1
1
Maze
1..n
Player
MapSite
Room
1..n enter()
setSide()
getSide()
rooms
1
roomNumber
Wall
Door
enter()
enter()
isOpen
Creating the Maze
Maze* MazeGame::createMaze() {
Maze* aMaze = new Maze;
Room* r1 = new Room(1);
Room* r2 = new Room(2);
Door* theDoor = new Door(r1, r2);
aMaze->addRoom(r1);
aMaze->addRoom(r2);
r1->setSide(North, new Wall); r1->setSide(East, theDoor);
r1->setSide(South, new Wall); r1->setSide(West, new Wall);
r2->setSide(North, new Wall); r2->setSide(East, new Wall);
r2->setSide(South, new Wall); r2->setSide(West, theDoor);
};

The problem is inflexibility.


hard-coding of maze layout
Pattern can make game creation more
flexible... not smaller!
We want Flexibility in Maze Creation

Be able to vary the kinds of mazes



Rooms with bombs
Walls that have been bombed
Enchanted rooms

Need a spell to enter the door!
Idea 1:
Subclass MazeGame, override createMaze
Maze* BombedMazeGame::createMaze() {
Maze* aMaze = new Maze;
Room* r1 = new RoomWithABomb(1);
Room* r2 = new RoomWithABomb(2);
Door* theDoor = new Door(r1, r2);
aMaze->addRoom(r1);
aMaze->addRoom(r2);
r1->setSide(North, new BombedWall);
r1->setSide(East, theDoor);
r1->setSide(South, new BombedWall);
r1->setSide(West, new BombedWall);
// etc...etc...
}

Lots of code duplication... :((
Idea 2:
Use a Factory Method
4
MapSite
enter()=0;
MazeGame
makeWall()
createMaze()
1
BombedMazeGame
makeWall()
Room
enter()
setSide()
getSide()
Wall
Door
enter()
enter()
isOpen
roomNumber
BombedWall
return new BombedWall
enter()
Parameterizing the Factory
class Creator {
public:
virtual Product * create(productId);
};
Product* Creator::create(ProductId id) {
if (id == MINE) return new MyProduct;
if (id == YOURS) return new YourProduct;
}
Product *
if (id
if (id
if (id
return
}
MyCreator::create(ProductId id) {
== MINE) return new YourProduct;
== YOURS) return new MyProduct;
== THEIRS) return TheirProduct;
Creator::create(id); // called if others fail
 selectively extend or change products that get created
Creational/Structural Design Patterns
CS 620/720
Software Engineering
February 12, 2004
Overview

Today:




Abstract Factory review
Singleton
First structural: Adapter
Next week:

Remaining Structural Patterns:
 Decorator
 Façade
 Composite
 Proxy
Abstract Factory Review
Motivation/Solution

Avoid instantiating concrete classes throughout your
code when you want to offer variability



This makes it hard to change later to a different set of
concrete classes that accomplish similar goals
E.g., concrete look and feel classes make it difficult to
change to different presentation style later
An abstract factory takes a description (often a
string) of a specific type of member in a family of
implementations and returns a concrete object

String passed as parameter, obtained from command line,
environment variable, XML file, etc
Main problems with this pattern

When you want to add new products to be
created by the factory, it forces a change to
the abstract factory interface and all concrete
subclasses

E.g., adding a new type of widget
Examples

Nachiketa Mishra – XML configuration to
drive abstract factory pattern
Singleton
Basics

Intent


Applicability






Ensure a class has only one instance and provide a global
point of access to it
want exactly one instance of a class
accessible to clients from one point
want the instance to be extensible
can also allow a countable number of instances
improvement over global namespace
Examples


Only one print spooler or file system is often needed in an
OS
Embedded system with resource constraints may not want
multiple copies of the same objects
Structure of the Pattern
Put constructor in private/protected data section
Participants and Collaborations

Singleton

defines an Instance method that becomes the
single "gate" by which clients can access its unique
instance.



Instance is a class method (static member function in
C++)
may be responsible for creating its own unique
instance
Clients access Singleton instances solely
through the Instance method
Implementation: Ensuring a Unique Instance
Significance?
Significance?
Implementation: Subclassing Singletons
But where do
singletons get
registered?
(constructor?)
Making a single MazeFactory
What if there are subclasses of
MazeFactory?
The Adapter Pattern
Adapter Pattern

Problem


Context




Have an object with an interface that’s close to, but
not exactly, what we need
Want to re-use an existing class
Can’t change its interface
Impractical to extend class hierarchy more generally
Solution

Wrap a particular class or object with the interface
needed
Electrical Adapter…
Some Additional Definitions

Before we go into the adapter pattern let’s
review some motivation and introduce
some terms
Reuse

Main goal:





Reuse knowledge from previous experience to current problem
Reuse functionality already available
Composition (also called Black Box Reuse)
 New functionality is obtained by aggregation
 The new object with more functionality is an aggregation of
existing components
Inheritance (also called White-box Reuse)
 New functionality is obtained by inheritance.
Three ways to get new functionality:



Implementation inheritance
Interface inheritance
Delegation
Implementation Inheritance vs
Interface Inheritance

Implementation inheritance




Also called class inheritance
Goal: Extend an applications’ functionality by
reusing functionality in parent class
Inherit from an existing class with some or all
operations already implemented
Interface inheritance


Also called subtyping
Inherit from an abstract class with all operations
specified, but not yet implemented
Implementation Inheritance

A very similar class is already implemented
that does almost the same as the desired
List
class implementation.
Add()
Remove()
Example: I have a List
class, I need a Stack
“Already
implemented”
class. How about
subclassing the Stack
Stack
class from the List class
Push()
and providing three
Pop()
methods, Push() and
Top()
Pop(), Top()?
Problem with implementation inheritance:
Some of the inherited operations might exhibit unwanted
behavior. What happens if the Stack user calls Remove()
instead of Pop()?


Delegation

Delegation is a way of making composition (for
example aggregation) as powerful for reuse as
inheritance


Instead of “inheriting from” a class, we “delegate to”
another object
In Delegation two objects are involved in handling a
request


A receiving object delegates operations to its delegate.
The developer can make sure that the receiving object
does not allow the client to misuse the delegate object
Client
calls
Receiver
Delegates to
Delegate
Delegation instead of Inheritance

Delegation: Catching an operation and
sending it to another object.
Stack implemented by Inheritance
List
+Add()
+Remove()
Stack
+Push()
+Pop()
+Top()
Stack implemented by Delegation
Stack
+Push()
+Pop()
+Top()
List
Remove()
Add()
Key to understanding
Many design patterns
use a combination of
inheritance and
delegation
Adapter Pattern

“Convert the interface of a class into another interface clients
expect.”




Adapter lets classes work together that couldn’t otherwise
because of incompatible interfaces
Used to provide a new interface to existing legacy
components (Interface engineering, reengineering).
Also known as a “wrapper”
Two adapter patterns:

Class adapter:


Object adapter:


Uses multiple inheritance to adapt one interface to another
Uses single inheritance and delegation
We will mostly use object adapters and call them simply
adapters
Class Adapter Pattern
(based on Multiple Inheritance)
Client
Target
Adaptee (Legacy Object)
Request()
ExistingRequest()
Adapter
In both adapter patterns, Client is
unaware that an adapter is used;
simply makes calls to Target
interface, and wrapper Adapter
overrides Request with calls to
legacy code.
Request()
Request()
{
return ExistingRequest();
}
Adapter pattern (object adapter)
Client
Target
Adaptee
Request()
ExistingRequest()
adaptee
Adapter



Delegation is used to bind an
Adapter and an Adaptee
Interface inheritance is used to specify
the interface of the Adapter class.
Target may be realized as an interface in Java.
Request()
Request()
{
return adaptee.ExistingRequest();
}
Participants of the Adapter Pattern




Client: Collaborates with objects conforming
to the target interface.
Target: Defines the application-specific
interface that clients use.
Adaptee: Defines an existing interface that
needs adapting.
Adapter: Adapts the interface of the adaptee
to the target interface.
Example of the Adapter Pattern
Class Shape
class Shape {
public:
Shape( );
virtual void BoundingBox (
Point& bottomLeft,
Point& topRight);
virtual Manipulator*
CreateManipulator( ) const;
};
Class TextView
class TextView {
public:
TextView( );
void GetOrigin(Coord&
void GetExtent(Coord&
Coord&
virtual bool IsEmpty(
};
x, Coord& y);
width,
height);
) const;
Class TextShape
class TextShape : public Shape {
public:
TextShape(TextView*);
virtual void BoundingBox(
Point& bottomLeft,
Point& topRight);
virtual bool IsEmpty( );
virtual Manipulator*
CreateManipulator( );
private:
TextView* text;
};
Method BoundingBox
void TextShape::BoundingBox(
Point& bottomLeft,
Point& topRight )
{
Coord bottom, left, width, height;
text->GetOrigin(bottom, left);
text->GetExtent(width, height);
bottomLeft = Point(bottom, left);
topRight = Point(bottom+height,
left+width);
}
Exercise

How would you convert the object adapter
solution just provided, into a class adapter?




Are any changes needed to the client code?
Are any changes needed to the Shape class?
Are any changes needed to TextView?
Are any chances needed to TextShape?
Adapter Summary


Adapters are all about interface mapping
between two artifacts
Often, the goal is to find a "narrow" interface
for Adaptee; that is, the smallest subset of
operations that lets us do the adaptation.
Structural Design Patterns
CS 620/720
Software Engineering
February 17, 2004
Agenda

Today




Decorator
Façade
Composite
Thursday:




HW1 due
Quiz also
Finish Structural Patterns: Proxy
Behavioral Patterns – start to read (in this order)


Observer, Visitor, Strategy, Chain of Responsibility, Command
Next Tuesday


No midterm!
Video: Quiz next Thursday may have question from video
Decorator Pattern
Changing the skin of an object
Motivation

A TextView has 2 features:

borders:


scroll-bars:


3 options: none, flat, 3D
4 options: none, side, bottom, both
How many Classes?
 3 x 4 = 12 !!!

e.g. TextView, TextViewWithNoBorder&SideScrollbar,
TextViewWithNoBorder&BottomScrollbar,
TextViewWithNoBorder&Bottom&SideScrollbar, TextViewWith3DBorder,
TextViewWith3DBorder&SideScrollbar,
TextViewWith3DBorder&BottomScrollbar,
TextViewWith3DBorder&Bottom&SideScrollbar, ... .....
Solution 1: Use Object Composition

Is it Open-Closed?
Solution 2: Change the Skin, not the
Guts!


TextView has no borders or scrollbars!
Add borders and scrollbars on top of a
TextView
Punt…

We’ll come back to this example a little
later…
Decorator - Basic Aspects

Intent


Attach additional responsibilities to an object dynamically.
provide a flexible alternative to subclassing


Also Known As


for extending functionality
Wrapper
Applicability

Add responsibilities to objects dynamically and transparently


i.e. without affecting other objects
Extension by subclassing is impractical

may lead to too many subclasses
Structure
What is significance of this?
Participants & Collaborations

Component


ConcreteComponent


defines the interface for objects that can have responsibilities added
dynamically
the "base" object to which additional responsibilities can be added
Decorator

defines an interface conformant to Component's interface



for transparency
maintains a reference to a Component object
ConcreteDecorator

adds responsibilities to the component
Decorator observations





The more flexible containment approach
encloses the component in another object that
adds the border
The enclosed object is known as the decoree
The enclosing object is called the decorator
The decorator conforms to the interface of the
component so its presence is transparent to
clients
The decorator forwards requests to the
component and may perform additional actions
(such as drawing a Border) before or after any
forwarding
Consequences


Transparency – very good
More flexibility than static inheritance



Avoid feature-laden classes high-up in the hierarchy



allows to mix and match responsibilities
allows to apply a property twice
"pay-as-you-go" approach
easy to define new types of decorations
A decorator and its component aren't identical

checking object identification can cause problems


e.g. if ( aComponent instanceof TextView ) blah
Lots of little objects

easy to customize, but hard to learn and debug
Implementation Issues

Keep Decorators lightweight



Don't put data members in VisualComponent
use it for shaping the interface
Omitting the abstract Decorator class


if only one decoration is needed
subclasses may pay for what they don't need
First Detailed Example:
Decorate SalesTicketPrinter



Assume the SalesTicketPrinter currently creates an
html sales receipt Airline Ticket
New Requirement: Add header with company
name, add footer that is an advertisement, during
the holidays add holiday relevant header(s) and
footer(s)….we’re not sure how many such things
One solution

Place control in SalesTicketPrinter

Then you need flags to control what header(s) get printed
Decorator Again


A layered approach
Start chain with decorators, end with original object
Decorator
1
Decorator
2
Concrete
Componen
t
C omponent
prints
+printTicket():void
C onfi gurati on
1
+getSalesTicket():Component
1
Ti cketDecorator
ll er
SalesTicket
-myComponent:Component
+TicketDecorator()
+TicketDecorator(c:Component)
+printTicket():void
FooterD ecorator2
H eaderD ecorator1
+printTicket():void
+main(args:String[]):void
H eaderD ecorator2
FooterD ecorator1
+FooterDecorator2(c:Component) +HeaderDecorator1(c:Component) +HeaderDecorator2(c:Component)
+FooterDecorator1(c:Compo
+printTicket():void
+printTicket():void
+printTicket():void
+printTicket():void
+printFooter():void
+printHeader():void
+printHeader():void
+printFooter():void
double
A SimpleTicket implementation
// Instances of this class are the sales tickets
// that may be decorated
public class SalesTicket extends Component
{
public void printTicket()
{ // Hard coded here, but simpler than
// adding a new Customer class now
System.out.println("Customer: Bob");
System.out.println("The sales ticket itself");
System.out.println("Total: $123.45");
}
}
TicketDecorator
public abstract class TicketDecorator extends Component
{
private Component myComponent;
public TicketDecorator()
{ myComponent = null; }
public TicketDecorator(Component c)
{ myComponent = c; }
public void printTicket()
{ if(myComponent != null)
myComponent.printTicket();
}
}
A Header Decorator
public class HeaderDecorator1 extends TicketDecorator
{
public HeaderDecorator1(Component c)
{ super(c); }
public void printTicket()
{ this.printHeader();
super.printTicket();
}
public void printHeader()
{
System.out.println("@@ Header One @@");
}
}
A Footer Decorator
public class FooterDecorator1 extends TicketDecorator
{
public FooterDecorator1(Component c)
{ super(c); }
public void printTicket()
{ super.printTicket();
this.printFooter();
}
public void printFooter()
{ System.out.println("## FOOTER two ##");
}
}
SalesOrder a client
public class SalesOrder
{
public static void main(String[] args)
{
SalesOrder s = new SalesOrder();
s.printTicket();
}
public void printTicket()
{ // Get an object decorated dynamically
Component myST = Configuration.getSalesTicket();
myST.printTicket();
}
// calcSalesTax ...
}
Simple Configuration
// This object will determine how to decorate the
// SalesTicket. This could become a Factory
public class Configuration
{
public static Component getSalesTicket()
{ // Return a decorated SalesTicket
return
new HeaderDecorator1(
new HeaderDecorator2(
new FooterDecorator1(
new FooterDecorator2(
new SalesTicket() ))));
}
}
Output with Current Configuration
Output:
@@ Header One @@
>> Header Two <<
Customer: Bob
The sales ticket itself
Total: $123.45
%% FOOTER two %%
## FOOTER two ##
The Decorator Pattern
Summary before Another example

Intent


Also Known As


Attach additional responsibilities to an object dynamically.
Decorators provide a flexible alternative to subclassing for
extending flexibility
Wrapper
Motivation


Want to add properties such as borders or scrollbars to a GUI
component or more methods to an existing object.
Can be done with inheritance, but this limits flexibility (couldn’t
change borders at runtime). A better way is to use composition.
Review of Motivating Example


Suppose there is a TextView GUI component and
you want to add different kinds of borders and/or
scrollbars to it
Currently, there are three types of borders


And two scrollbars


Plain, 3D, Fancy
Horizontal and Vertical
An inheritance solution requires >12 classes for one
view
That’s a lot of classes!
1.
2.
3.
4.
5.
6.
7.
8.
9.
10.
11.
12.
13.
14.
15.
TextView-Plain
TextView-Fance
TextView-3D
TextView-Horizontal
TextView-Vertical
TextView-Horizontal-Vertical
TextView-Plain-Horizontal
TextView-Plain-Vertical
TextView-Plain-Horizontal-Vertical
TextView-3D-Horizontal
TextView-3D-Vertical
TextView-3D-Horizontal-Vertical
TextView-Fancy-Horizontal
TextView-Fancy-Vertical
TextView-Fancy-Horizontal-Vertical
Disadvantages




Inheritance solution has an explosion of classes
If another type of border were added, how many more
classes do we need?
If another view were added, say ImageView or
StreamingVideoView, how many more classes do we need?
Have to instantiate specific classes at compiletime



would be better to be able to change borders at runtime
This is inflexible, can’t change view or border at runtime
Use the Decorator Pattern instead (Java does)
VisualComponent
draw()
resize()
TextView
draw()
resize()
1
ImageComponent
draw()
resize()
Border
draw()
resize()
Plain
draw()
resize()
3D
draw()
resize()
Fancy
draw()
resize()
Decorator contains a visual component
Decorator
draw()
resize()
1
ScrollBar
draw()
resize()
Horiz
draw()
resize()
Vert
draw()
resize()
Applicability
The TextView class knows nothing about Borders and Scrollbars
public class TextView
{
public void draw()
{
// Code to draw this Text object
}
public void resize ()
{
// Code to resize this Text object
}
}
Applicability
The ImageView knows nothing about Borders and Scrollbars
public class ImageView
{
public void draw()
{
// Code to draw this Image Object
}
public void resize ()
{
// Code to resize this Image Object
}
}
Decorators Contain Components

But the decorators need to know about components
public class FancyBorder
{
private Component component;
public FancyBorder(VisualComponent visual)
{
component = visual;
}
public void draw()
{
component.draw(); // forward draw message contained obj
// Code to draw this FancyBorder object
}
}
How to use Decorators
public class Client
{
public static void main(String[] args)
{
TextView data = new TextView();
Component borderData = new FancyBorder(data);
Component scrolledData = new VertScrollbar(data);
Component borderAndScrolledData
= new HorzScrollbar(borderData);
}
}
Decorator Pattern in Java

InputStreamReader

... from byte streams to character streams: It reads bytes and
translates them into characters using the specified character encoding.
JavaTMAPI

BufferedReader

Read text from a character-input stream, buffering characters so as to
provide for the efficient reading of characters, arrays, and lines.
JavaTMAPI

Programmer's can now code like this
BufferedReader keyboard =
new BufferedReader(new
InputStreamReader(System.in));
Java streams

With > 60 streams in Java, you can create a wide
variety of input and output streams




this provides flexibility good
it also adds complexity bad
Flexibility made possible with inheritance and classes
that accept many different classes that extend the
parameter
You can have an InputStream instance or any
instance of a class that extends InputStream
public InputStreamReader(InputStream in)
Façade Pattern
Façade

Dictionary definitions:


n 1: the face or front of a building [syn: frontage]
2: a showy misrepresentation intended to conceal
something unpleasant [syn: window dressing]
The face of a building, especially the principal
face. An artificial or deceptive front: ideological
slogans that were a façade for geopolitical power
struggles.
Façade

Intent:


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.
Abstracts the essence of a complex set of
interface interactions.
Motivation:





Structuring a system into subsystems helps reduce
complexity.
Minimize communication and dependencies between
subsystems.
Facade may provide a single, simplified interface to the
more general facilities of a subsystem.
Applicability
Use the Facade pattern:
 to provide a simple interface to a complex
subsystem.


when there are many dependencies between clients
and the implementation classes of an abstraction.


Subsystems often get more complex as they evolve.
Introduce a facade to decouple the subsystems from clients
and other subsystems, thereby promoting subsystem
independence and portability.
to layer subsystems.


Use facade to define an entry point to each subsystem
level.
Minimize subsystem inter-dependencies
FACADE - Motivation
client classes
Facade
Subsystem classes
Facade: Example
Compiler Façade
class Compiler {
public:
Compiler();
virtual void Compile(istream&, BytecodeStream&);
};
void Compiler::Compile ( istream& input, BytecodeStream& output {
Scanner scanner(input);
ProgramNodeBuilder builder;
Parser parser;
parser.Parse(scanner, builder);
RISCCodeGenerator generator(output);
ProgramNode* parseTree = builder.GetRootNode();
parseTree->Traverse(generator);
}
Participants and Collaborations
Participants:
 Facade (Compiler)



Knows which subsystem classes may handle a request
Delegates client requests to appropriate subsystem objects
Subsystem classes (Scanner, Parser, ProgramNode)


Implement subsystem functionality
Have no knowledge of the facade (i.e., keep no references to it)
Collaborations:



Clients communicate with the subsystem by sending requests
to Facade, which forwards them to the appropriate subsystem
object(s).
The facade may have to translate its interface to subsystem
interfaces.
Clients may have to access subsystem objects directly, as well.
Facade: Summary





Shields clients from subsystem components, thereby reducing
the number of objects that clients deal with and making the
subsystem easier to use.
Promotes weak coupling between the subsystem and its clients.
Often the components in a subsystem are strongly coupled.
Weak coupling lets you vary the components of the subsystem
without affecting its clients.
Help layer a system and the dependencies between objects;
eliminates complex or circular dependencies.
Reducing compilation dependencies is vital in large software
systems.
It doesn't prevent applications from using subsystem classes if
they need to.
Composite Pattern
Motivation

GUI Windows and GUI elements


How does the window hold and deal with the
different items it has to manage?
Widgets are different than WidgetContainers
Composite Pattern

Problem


Context



Distinguishing between composite and simple objects
makes applications more complex
Want to represent whole-part hierarchies
Want to hide differences between composite and
simple objects from clients
Solution

Encapsulate composite and simple objects behind a
common interface
Implementation Ideas

Nightmare Implementation




for each operation deal with each category of objects
individually
no uniformity and no hiding of complexity
a lot of code duplication
Program to an Interface


uniform dealing with widget operations
but still containers are treated different
Structure



Component class role gives a consistent interface
Leaf class role is for components without further substructure
Composite class role is for components with multiple parts
Participants & Collaborations

Component



declares interface for objects in the composition
implements default behavior for components when possible
Composite


defines behavior for components having children
stores child components


Leaf


implement child-specific operations
defines behavior for primitive objects in the composition
Client

manipulates objects in the composition through the
Component interface
Consequences

Defines uniform class hierarchies


Make clients simple



recursive composition of objects
don't know whether dealing with a leaf or a composite
simplifies code because it avoids dealing in a different
manner with each class
Easier to extend


easy to add new Composite or Leave classes
awesome example of Open-Closed principle
Applying Composite to Widget Problem

See code

Component implements default behavior when possible


Button, Menu, etc override Component methods when needed
WidgetContainer will have to override all widget operations
Example of the Composite Pattern
Graphic
Draw()
Add(Graphic)
Remove(Graphic)
GetChild(int)
graphics
Line
Rect.
Text
Draw()
Draw()
Draw()
Picture
Draw()
Add(Graphic)
Remove(Graphic)
GetChild(int)
forall g in graphics
g.Draw()
Issue: Where to Place Container Operations ?

adding, deleting, managing components in
composite


should they be placed in Component or in Composite?
Pro-Transparency Approach

Declaring them in the Component gives all subclasses the
same interface


Safety problem


All subclasses can be treated alike.
clients may do stupid things like adding objects to leaves
Pro-Safety Approach

Declaring them in WidgetContainer is safer


Adding or removing widgets to non-WidgetContainers is an
error
What should be the proper response to adding a TextArea
to a button? Throw an exception?
Structural Design Patterns
CS 620/720
Software Engineering
February 19, 2004
Agenda

Today




Tuesday


Quiz 4
HW1 due tonight
Patterns: Composite, Proxy
Alexander video
Next Thursday:


Quiz 5
Behavioral Patterns – start to read (in this order)
 Observer, Visitor, Strategy, Chain of Responsibility,
Command
Composite Pattern
Motivation

GUI Windows and GUI elements


How does the window hold and deal with the
different items it has to manage?
Widgets are different than WidgetContainers
Composite Pattern

Problem


Context



Distinguishing between composite and simple objects
makes applications more complex
Want to represent whole-part hierarchies
Want to hide differences between composite and
simple objects from clients
Solution

Encapsulate composite and simple objects behind a
common interface
Implementation Ideas

Nightmare Implementation




for each operation deal with each category of objects
individually
no uniformity and no hiding of complexity
a lot of code duplication
Program to an Interface


uniform dealing with widget operations
but still containers are treated different
Structure



Component class role gives a consistent interface
Leaf class role is for components without further substructure
Composite class role is for components with multiple parts
Participants & Collaborations

Component



declares interface for objects in the composition
implements default behavior for components when possible
Composite


defines behavior for components having children
stores child components


Leaf


implement child-specific operations
defines behavior for primitive objects in the composition
Client

manipulates objects in the composition through the
Component interface
Consequences

Defines uniform class hierarchies


Make clients simple



recursive composition of objects
don't know whether dealing with a leaf or a composite
simplifies code because it avoids dealing in a different
manner with each class
Easier to extend


easy to add new Composite or Leave classes
awesome example of Open-Closed principle
Applying Composite to Widget Problem

See code

Component implements default behavior when possible


Button, Menu, etc override Component methods when needed
WidgetContainer will have to override all widget operations
Example of the Composite Pattern
Graphic
Draw()
Add(Graphic)
Remove(Graphic)
GetChild(int)
graphics
Line
Rect.
Text
Draw()
Draw()
Draw()
Picture
Draw()
Add(Graphic)
Remove(Graphic)
GetChild(int)
forall g in graphics
g.Draw()
Issue: Where to Place Container Operations ?

adding, deleting, managing components in
composite


should they be placed in Component or in Composite?
Pro-Transparency Approach

Declaring them in the Component gives all subclasses the
same interface


Safety problem


All subclasses can be treated alike.
clients may do stupid things like adding objects to leaves
Pro-Safety Approach

Declaring them in WidgetContainer is safer


Adding or removing widgets to non-WidgetContainers is an
error
What should be the proper response to adding a TextArea
to a button? Throw an exception?
Proxy Pattern
Basic Idea
proxy (n. pl prox-ies) The agency for a person who acts as a
substitute for another person, authority to act for another

Intent


provide a surrogate or placeholder for another object to
control access to it
Applicability





whenever there is a need for a more flexible or sophisticated
reference to an object than a simple pointer
remote proxy
virtual proxy
protection proxy
enhancement proxies (smart pointers)

prevent accidental delete of objects (counts references)
Proxy Pattern

Problem


Need to access an object but may not have access
(or may need to defer cost of access) until just before
use
Context


Client may need interface to target object initially
Implementation of target object may be created later


Maybe on a remote machine, etc.
Solution

Provide a proxy (a placeholder) with same interface
as the target object
Loading "Heavy" Objects

Document Editor that can embed multimedia objects


MMobjects are expensive to create  opening of
document slow
avoid creating expensive objects


Creating each expensive object on demand !


they are not all necessary as they are not all visible at the
same time
i.e. when image has to be displayed
What should we put instead?


hide the fact that we are "lazy"!
don't complicate the document editor!
Idea:


Use a Placeholder!
create only when needed for drawing
keeps information about the dimensions
(extent)
Structure


Proxy “stands in” for target object
Proxy exhibits same interface as target object

Forwards method invocations it receives to the target object
Participants

Proxy


maintains a reference that lets the proxy access
the real subject.
provides an interface identical to Subject's


controls access to the real subject


so that proxy can be substituted for the real subject
may be responsible for creating or deleting it
Subject

defines the common interface for RealSubject and
Proxy
Collaborations
Remote Proxy

Hide real details of accessing an object


actual object is on a remote machine (remote
address space)
used in RMI and CORBA
Further Reasons to Use Proxies

Virtual Proxy

Creates/accesses expensive objects on demand



It may be too expensive to keep entire state of the object in
memory at one time
Protection Proxy


may wish to delay creating an expensive object until it is really
accessed
Provides different levels of access to original object
Cache Proxy (Server Proxy)

Multiple local clients can share results from expensive
operations

remote accesses or long computations
Synchronization/Protection Proxy

Synchronize multiple accesses to real subject
Consequences

Proxies introduce a level of indirection

used differently depending on the kind of proxy:




hide different address space (remote p.)
creation on demand (virtual p.)
allow additional housekeeping activities (protection, smart pointers)
Copy-On-Write [J.Coplien92 - The "Handle Class" Idiom]



copying large and complicated objects is expensive
use proxy to pay the price of copying only when the new object
is modified
Subject must be reference counted



proxy increments counter on copy
when modified, do copy and decrement counter
if (counter == 0) delete Subject
Handle Class Idiom

String contains a StringRep object



StringRep holds the text and reference count
String passes actual string operations to StringRep object
String handles pointer operations and deleting StringRep
object when reference count reaches zero
Behavioral Patterns
CS 620/720
Software Engineering
February 26, 2004
Overview


Today:
 Observer
 Visitor
 Strategy (?)
Next Tuesday
 Finish design patterns



With Faizan Javed
Next Thursday:
 Quiz
 HW 2 assigned
 Begin talk on formal specification


Strategy (?)
Chain of Responsibility
Command
Observer

A key part of the MVC that we studied earlier
A design problem


}
I want to notify the secretary and the students every time
there is a new midterm. The secretary would then book the
rooms and the students would (hopefully) prepare for the
exam.
1st pass: I know who is interested, and call them directly:
void setMidterm(…) {
…
// let the secretary know
mySecretary.bookRoom(…);
// let the students know
while (students.hasNext()) {
Student s = (Student)students.next();
s.study(…);
}
A design problem

The problem:
I need to know about all the people
interested (the observers)
 What if a new person is interested?


What if Janitor needs to know room schedule?
What if a given student is *not* interested?
 I need to know what method to invoke on
each interested party (e.g., study, clean)


We need a more generalized solution…
Design Pattern
Problem:
 How can I “define a one-to-many dependency
between objects so that when one object
changes state, all its dependents are notified
and updated automatically”?
 We want to notify objects:



without having to know how many there are
without having to know who they are
Basically we want to “decouple” the professor
from the people who should be notified
Observer Pattern
Solution:
 A publish-subscribe mechanism:





the subject (a.k.a. the thing being observed) maintains a
list of observers
the observers get added to that list by subscribing to the
subject
all observers implement a common interface, namely an
update() method
when a change occurs, the subject iterates through the list
of observers and calls the update method on them
Examples:

CORBA Event Services, Event Channel
eBay (or, some web notification service)

http://java.sun.com/j2se/1.4/docs/api/java/util/Observable.html

Data Example
Subject
Interface
Browser
PDA
Cell Phone
Terminal
XML
xyz…
Data is sent to the various observers
Web
Browser
Cell
Phone
PDA
Observers
Terminal
Generalized Observer Pattern
Observer Pattern
Participants:
 Subject




Observer


defines an updating interface for objects that should be notified of
changes in a Subject.
ConcreteSubject



knows its observers. Any number of Observer objects may
observe a Subject.
provides an interface for adding and removing Observer objects.
provides an interface for “setting state” and triggering notification
stores state of interest to ConcreteObserver objects.
sends a notification to its observers when its state changes.
ConcreteObserver


maintains a reference to a ConcreteSubject object.
implements the Observer interface to keep its state consistent with
the Subject.
Observer Pattern: Subscription
Observer Pattern: Notification
Safeguards





Dangling references to deleted subjects should be
avoided
Subject state should be self-consistent before
notification
Observer-specific update protocols
 Push – subject sends observers detail at will
 Pull – observers ask for detail after notification is sent
Specify modifications of interest explicity
Encapsulate complex update semantics
Observer Code
class Observer {
public:
virtual ~ Observer();
virtual void Update(Subject* theChangedSubject) = 0;
protected:
Observer();
};
Subject Code
class Subject {
public:
virtual ~Subject();
virtual void Attach(Observer*);
virtual void Detach(Observer*);
virtual void Notify();
protected:
Subject();
private:
List<Observer*> *_observers;
};
void Subject::Attach (Observer* o) { _observers->Append(o); }
void Subject::Detach (Observer* o) { _observers->Remove(o); }
void Subject::Notify () {
ListIterator<Observer*> i(_observers);
for (i.First(); !i.IsDone(); i.Next()) {
i.CurrentItem()->Update(this); }
}
ClockTimer Subject
class ClockTimer : public Subject {
public:
ClockTimer();
virtual int GetHour();
virtual int GetMinute();
virtual int GetSecond();
void Tick();
};
void ClockTimer::Tick () {
// update internal time-keeping state
// ...
Notify();
}
DigitalClock Observer
class DigitalClock: public Widget, public Observer {
public:
DigitalClock(ClockTimer*);
virtual ~DigitalClock();
virtual void Update(Subject*);
// overrides Observer operation
virtual void Draw();
// overrides Widget operation;
// defines how to draw the digital clock
private:
ClockTimer* _subject;
};
DigitalClock – ctor, dtor
DigitalClock::DigitalClock (ClockTimer* s) {
_subject = s;
_subject->Attach(this);
}
DigitalClock::~DigitalClock () {
_subject->Detach(this);
}
DigitalClock – Update, Draw
void DigitalClock::Update (Subject* theChangedSubject) {
if (theChangedSubject == _subject)
Draw();
}
void DigitalClock::Draw () {
// get the new values from the subject
int hour = _subject->GetHour();
int minute = _subject->GetMinute();
// etc.
// draw the digital clock
}
Two Clocks
ClockTimer* timer = new ClockTimer;
AnalogClock* analogClock = new AnalogClock(timer);
DigitalClock* digitalClock = new DigitalClock(timer);


What is the “Model” in the above?
What are the “Views”?
Visitor Pattern
Motivation




Compiler represents
programs as abstract syntax
trees (AST)
Need to perform operations
on AST for semantic
analysis, code-generation,
pretty-printing and so on
AST has different types of
nodes for variable reference,
assignment, operator, etc.
Code for an operation is
specific to the node type
Node
TypeCheck()
GenerateCode()
PrettyPrint()
VariableRefNode
AssignmentNode
TypeCheck()
GenerateCode()
PrettyPrint()
TypeCheck()
GenerateCode()
PrettyPrint()
Motivation


Adding operation code to each node type has the following
drawbacks that makes it hard to understand and maintain:
 Code for each operation is distributed across multiple classes
(AssignmentNode, VariableRefNode, etc)
 Code for different unrelated operations are mixed together as
methods on a single node
 Adding a new operation would mean changing and recompiling
all the node classes
Better Approach:
 Node classes independent of the operations that apply to them
 Can be achieved using a visitor design pattern
Visitor

Solution using Visitor:
 Visitor is an abstract class that has a different method for each
type of object on which it operates
 Each operation is a subclass of Visitor and overloads the typespecific methods
 Objects that are operated on, accept a Visitor and call back their
type-specific method passing themselves as operands
 Object types are independent of the operations that apply to
them
 New operations can be added without modifying the object types
Visitor Solution
Node
Accept( NodeVisitor v )


Nodes accept visitors and
call appropriate method of
the visitor
Visitors implement the
operations and have one
method for each type of
node they visit
VariableRefNode
AssignmentNode
Accept(NodeVisitor v)
{v->VisitVariableRef(this)}
Accept(NodeVisitor v)
{v->VisitAssignment(this)}
NodeVisitor
VisitAssignment( AssignmentNode )
VisitVariableRef( VariableRefNode )
TypeCheckingVisitor
VisitAssignment( AssignmentNode )
VisitVariableRef( VariableRefNode )
CodeGeneratingVisitor
VisitAssignment( AssignmentNode )
VisitVariableRef( VariableRefNode )
Applicability
Use the Visitor pattern:
 When an object structure contains different classes of objects
with different interfaces and operations on these objects depend
on their concrete classes
 Many unrelated operations need to be performed on the objects
and you want to keep related operations together
 The classes defining the object structure rarely change (structure
is stable), but you want to define new operations over the
structure
 If the object structure classes change often, it is better to define
the operations in those classes
Consequences of using Visitor



Addition of new operations is easy
 New operations can be created by simply adding a new visitor
Gathers related operations together
 All operation related code is in the visitor
 Code for different operations are in different sub-classes of
visitor
 Unrelated operations are not mixed together in the object
classes
Adding a new concrete type in the object structure is hard
 Each Visitor has to be recompiled with an appropriate method for
the new type
Visitor Example (Equipment and Card)
abstract class Equipment {
abstract double netPrice();
abstract double discountPrice();
abstract void accept(Visitor vis);
}
class Card extends Equipment {
double netPrice() {return 10.00;}
double discountPrice() {return 2.00;}
void accept(Visitor vis) {vis.atCard(this);}
}
Visitor Example (CompositeEquip and Cabinet)
abstract class CompositeEquip extends Equipment {
Equipment[] parts;
CompositeEquipment() { ... }
double netPrice() { ... }
double discountPrice() { ... }
void accept(Visitor vis) {
for (int i=0; i<parts.length; i++)
parts[i].accept(vis);
}
}
class Cabinet extends CompositeEquip {
Cabinet() { ….}
void accept(Visitor vis) {
vis.atCabinet(this);
super.accept(vis);
}
}
Visitor Example (abstract Visitor)
abstract class Visitor {
void atCard(Card e){}
void atDrive(Drive e){}
void atBoard(Board e){}
void atCabinet(Cabinet e){}
void atBus(Bus e){}
void atChassis(Chassis e){}
}
Visitor Example (Pricing Visitor)
class PricingVisitor extends Visitor {
private float total;
PricingVisitor() { total=0;}
float value(){return total;}
void atCard(Card e) { total+=e.netPrice();}
void atDrive(Drive e) { total+=e.netPrice();}
void atBoard(Board e) { total+=e.netPrice();}
void atCabinet(Cabinet e){total+=e.discountPrice();}
void atBus(Bus e) { total+=e.discountPrice();}
void atChassis(Chassis e){total+=e.discountPrice();}
}
Visitor Example (Inventory Visitor)
class InventoryVisitor extends Visitor {
private Vector inv;
InventoryVisitor() { inv = new Vector(10,5);}
int size(){return inv.size();}
void atCard(Card e) { inv.addElement(e);}
void atDrive(Drive e) { inv.addElement(e);}
void atBoard(Board e) { inv.addElement(e);}
void atCabinet(Cabinet e) { inv.addElement(e);}
void atBus(Bus e) { inv.addElement(e);}
void atChassis(Chassis e) { inv.addElement(e);}
}
Visitor Example (Main)
public class Sample {
public static void main(String argv[]) {
Equipment equip = new Cabinet();
PricingVisitor vis = new PricingVisitor();
equip.accept(vis);
System.out.println(“Pricing” + vis.value());
InventoryVisitor inv = new InventoryVisitor();
equip.accept(inv);
System.out.println("Number elements" + inv.size());
}
}
Another Example – Modem operations

Hierarchy of modem objects

The base class has the generic methods common to all
modems
The derivatives represent the drivers for many different
modem manufacturers and types
You have a requirement to add a new method to the
hierarchy to configure the modem to work with the Unix
operating system


Source: http://www.cuj.com/java/
Modem Interface
USR
Unix Configuration Visitor
visit (MOT)
Interfaces
public interface Modem
{
public void dial(String pno);
public void hangup();
public void send(char c);
public char recv();
public void accept(ModemVisitor v);
}
public interface ModemVisitor
{
public void visit(HayesModem modem);
public void visit(MotModem modem);
public void visit(ErnieModem modem);
}
Hayes Modem
public class HayesModem implements Modem
{
public void dial(String pno){}
public void hangup(){}
public void send(char c){}
public char recv() {return 0;}
public void accept(ModemVisitor v) {v.visit(this);}
String configurationString = null;
}
Unix Configuration
public class UnixModemConfigurator implements ModemVisitor
{
public void visit(HayesModem m) { m.configurationString = "&s1=4&D=3"; }
public void visit(MotModem m)
}
{ m.configurationValue = 42; }
Strategy Pattern
Basic Aspects

Intent



Define a family of algorithms, encapsulate each one, and
make them interchangeable
Let the algorithm vary independently from clients that use it
Applicability


You need different variants of an algorithm
An algorithm uses data that clients shouldn't know about


avoid exposing complex, algorithm-specific data structures
Many related classes differ only in their behavior

configure a class with a particular behavior
Structure of the Strategy Pattern
The Strategy Pattern has three
participants that include
Context, Strategy
and Concrete Strategy
Strategy Pattern Example
Situation: A GUI container object wants to decide at
run-time what strategy it should use to layout the GUI
components it contains. Many different layout
strategies are already available.
Solution: Encapsulate the different layout strategies
using the Strategy pattern!
Example: Java Layout Managers

GUI container classes in Java



frames, dialogs, applets (top-level)
panels (intermediate)
Each container class has a layout manager
determine the size and position of components
 20 types of layouts
 ~40 container-types
 imagine to combine them
freely by inheritance ;)


Consider also sorting...

open-ended number of
sorting criteria
Sample Code implementation
// Abstract Strategy class
abstract class Strategy {
public abstract void RunAlgorithm();
}
// Context class
class Context {
//Default Algorithm
private Strategy strategy = new ConcreteStrategyA();
public void changeStrategy(Strategy newStrategy) {
strategy=newStrategy;
}
public void getResult() {
strategy.RunAlgorithm();
}
}
Sample Code implementation
// ConcreteStrategyA class
class ConcreteStrategyA extends Strategy{
public void RunAlgorithm(){
// ConcreteStrategyA implementation
}
}
// ConcreteStrategyB class
class ConcreteStrategyB extends Strategy{
public void RunAlgorithm(){
// ConcreteStrategyB implementation
}
}
//Client class
public class Client {
public static void main(String args[]){
Context ctx=new Context();
ctx.getResult();
ctx.changeStrategy(newConcreteStrategyB());
ctx.getResult();
}
}
Resulting Context 




The strategy pattern allows you to select
one of several algorithms dynamically.
Since the Context switches at your
request, you have more flexibility than if
you simply call a derived class.
Strategies eliminate conditional
statements. The Strategy pattern offers an
alternative to conditional statements for
selecting desired behavior.
Provides an alternative to subclassing the
Context class to get a variety of algorithms
of behaviours.
Resulting Context 

Clients might be exposed to implementation
issues. A client must understand how
Strategies differ before it can select the
appropriate one.

Communication overhead between Strategy
and Context.

Strategies increase the number of objects in
an application.
Known uses



Java AWT implements this pattern with its
LayoutManagers
Borland's ObjectWindows uses strategies
to encapsulate validation algorithms for
dialog box entry fields.
Java Swing GUI text components. Every
text component has a reference to a
document model which provides the
required user input validation strategy.
Behavioral Patterns, Part II
CS 620/720
Software Development
March 2nd, 2004
Overview

Finish up patterns:




Strategy
Chain of Responsibility
Command
Thursday March 4th 2004:



Petri Nets?
HomeWork 2 assigned
Quiz on behavioral patterns
Strategy Pattern
Basic Aspects

Intent



Define a family of algorithms, encapsulate each one, and
make them interchangeable
Let the algorithm vary independently from clients that use it
Applicability


You need different variants of an algorithm
An algorithm uses data that clients shouldn't know about


avoid exposing complex, algorithm-specific data structures
Many related classes differ only in their behavior

configure a class with a particular behavior
Structure of the Strategy Pattern
The Strategy Pattern has three
participants that include
Context, Strategy
and Concrete Strategy
Strategy Pattern Example
Situation: A GUI container object wants to decide at
run-time what strategy it should use to layout the GUI
components it contains. Many different layout
strategies are already available.
Solution: Encapsulate the different layout strategies
using the Strategy pattern!
Example: Java Layout Managers

GUI container classes in Java



frames, dialogs, applets (top-level)
panels (intermediate)
Each container class has a layout manager
determine the size and position of components
 20 types of layouts
 ~40 container-types
 imagine to combine them
freely by inheritance ;)


Consider also sorting...

open-ended number of
sorting criteria
Sample Code implementation
// Abstract Strategy class
abstract class Strategy {
public abstract void RunAlgorithm();
}
// Context class
class Context {
//Default Algorithm
private Strategy strategy = new ConcreteStrategyA();
public void changeStrategy(Strategy newStrategy) {
strategy=newStrategy;
}
public void getResult() {
strategy.RunAlgorithm();
}
}
Sample Code implementation
// ConcreteStrategyA class
class ConcreteStrategyA extends Strategy{
public void RunAlgorithm(){
// ConcreteStrategyA implementation
}
}
// ConcreteStrategyB class
class ConcreteStrategyB extends Strategy{
public void RunAlgorithm(){
// ConcreteStrategyB implementation
}
}
//Client class
public class Client {
public static void main(String args[]){
Context ctx=new Context();
ctx.getResult();
ctx.changeStrategy(newConcreteStrategyB());
ctx.getResult();
}
}
Resulting Context 




The strategy pattern allows you to select
one of several algorithms dynamically.
Since the Context switches at your
request, you have more flexibility than if
you simply call a derived class.
Strategies eliminate conditional
statements. The Strategy pattern offers an
alternative to conditional statements for
selecting desired behavior.
Provides an alternative to subclassing the
Context class to get a variety of algorithms
of behaviours.
Resulting Context 

Clients might be exposed to implementation
issues. A client must understand how
Strategies differ before it can select the
appropriate one.

Communication overhead between Strategy
and Context.

Strategies increase the number of objects in
an application.
Known uses



Java AWT implements this pattern with its
LayoutManagers
Borland's ObjectWindows uses strategies
to encapsulate validation algorithms for
dialog box entry fields.
Java Swing GUI text components. Every
text component has a reference to a
document model which provides the
required user input validation strategy.
Chain of Responsibility
Pattern
Basic Aspects

Intent

Decouple sender of request from its receiver


Put receivers in a chain and pass the request along the
chain


by giving more than one object a chance to handle the request
until an object handles it
Motivation

context-sensitive help


Which one?



a help request is handled by one of several UI objects
depends on the context
The object that initiates the request does not know the
object that will eventually provide the help
Other examples?
When to Use?

Applicability

more than one object many handle a request

and handler isn't known a priori

send a request to several objects without
specifying the receiver

set of objects that can handle the request should
be dynamically specifiable
Non-software Example
http://www.agcs.com/supportv2/techpapers/patterns/papers/tutnotes/sld019.htm
Non-software Example
Chain of Commands

Like the military, or a business hierarchy


a request is made
it goes up the chain of command until someone
has the authority to answer the request
Structure
Participants & Collaborations

Handler



defines the interface for handling requests
may implement the successor link
ConcreteHandler

either handles the request it is responsible for ...



if possible
... or otherwise it forwards the request to its
successor
Client

initiates the request to a ConcreteHandler object
in the chain
The Context-Help System
Another Software Example

Exception handling?

TCS Database Error Handler…

Handout






Pg 1. TExHandler - abstract Handler
Pg. 2-4 Specific handlers for each error
Pg. 5-6 Attachment of Handler to container
Pg. 7 Iteration through all handlers
Pg. 8 Default display method
Pg. 9-16 Details of handlers for each type of error
Consequences

Reduced Coupling




Flexibility in assigning responsibilities to objects



frees the client (sender) from knowing who will handle its
request
sender and receiver don't know each other
instead of sender knowing all potential receivers, just keep a
single reference to next handler in chain.
responsibilities can be added or changed
chain can be modified at run-time
Requests can go unhandled

chain may be configured improperly
Connecting Successors


If there are no pre-existing references for building the chain
Successor link usually managed by Handler

default implementation



just forwards request to successor
frees uninterested ConcreteHandler's to implement request
handling
Sample Implementation (C++)
class HelpHandler {
public:
HelpHandler(HelpHandler* s) : _successor(s) { }
virtual void HandleHelp();
private: HelpHandler* _successor;
};
void HelpHandler::HandleHelp () {
if (_successor) _successor->HandleHelp();
}
Command Pattern
Basic Aspects

Intent

Encapsulate requests as objects, allowing you to:




parameterize clients with different requests
queue or log requests
support undoable operations
Applicability

Parameterize objects





replacement for callbacks
Specify, queue, and execute requests at different times
Support undo
Support for logging changes
Model transactions


structure systems around high-level operations built on primitive
ones
common interface  invoke all transaction same way
Structure
Participants

Command


ConcreteCommand


asks the command to carry out the request
Receiver


binds a request with a concrete action
Invoker


declares the interface for executing the operation
knows how to perform the operations associated
with carrying out a request.
Client

creates a ConcreteCommand and sets its receiver
Collaborations

Client  ConcreteCommand



creates and specifies receiver
Invoker  ConcreteCommand
ConcreteCommand  Receiver
Composed Commands
Example: Menu Callbacks
Consequences


Decouples Invoker from Receiver
Commands are first-class objects


Composite Commands


see also Composite pattern
Easy to add new commands



can be manipulated and extended
Invoker does not change
it is Open-Closed
Potential for an excessive number of
command classes
Intelligence of Command objects

"Dumb"



"Genius"




delegate everything to Receiver
used just to decouple Sender from Receiver
does everything itself without delegating at all
useful if no receiver exists
let ConcreteCommand be independent of further
classes
"Smart"

find receiver dynamically
Undoable Commands

Need to store additional state to reverse execution



receiver object
parameters of the operation performed on receiver
original values in receiver that may change due to request


receiver must provide operations that makes it possible for
command object to return it to its prior state
History list

sequence of commands that have been executed



used as LIFO with reverse-execution  undo
used as FIFO with execution  redo
Commands may need to be copied

when state of commands change by execution
Command pattern:
Editor with unlimited undos
Structuring the objects
ConcreteCommands
(Control objects)
Invoker
(Boundary objects)
UndoQueue
Menu
MoveCommand
Triangle
Editor
Rectangle
Receiver
(Entity objects)
Circle
Let’s talk about it…

How do you think undo is implemented?
Pattern Conclusion

….