se principles silver bullets

569
SE Principles Silver Bullets CS 620/720 Software Engineering January 15, 2004

Upload: claudia-hendrix

Post on 30-Dec-2015

31 views

Category:

Documents


1 download

DESCRIPTION

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; - PowerPoint PPT Presentation

TRANSCRIPT

Page 1: SE Principles Silver Bullets

SE PrinciplesSilver Bullets

CS 620/720

Software Engineering

January 15, 2004

Page 2: SE Principles Silver Bullets

Poor Engineering leads to ad-hoc structure!

The result of continuous buildingwithout any thought toward design.

Result: Stairs leading to ceiling; Windows in the middle of room; Doors opening to wall; Non-intuitive floor plan!.

Page 3: SE Principles Silver Bullets

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

Page 4: SE Principles Silver Bullets

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.

http://java.sun.com/people/jag/Ariane5.htmlhttp://www.around.com/ariane.htmlhttp://archive.eiffel.com/doc/manuals/technology/contract/ariane/page.html

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 main stage, in turn triggering the self-destruct system of the launcher. 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 time did not contain proper flight data, but showed a diagnostic bit pattern of the computer of the SRI 2, which was interpreted as flight data. 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 value greater than what could be represented by a 16-bit signed integer. This resulted in an Operand Error. The data conversion instructions (in Ada code) were not protected from causing an Operand Error, although other conversions of comparable variables in the same place in the code were protected. 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 launcher lifts off, this function serves no purpose. 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 continues for approx. 40 seconds of flight. This time sequence is based on a requirement of Ariane 4 and is not required for Ariane 5. 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 is calculated as an indicator for alignment precision over time.

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.

Page 5: SE Principles Silver Bullets

Poor Engineering Has Disastrous Consequences!

Software Runaways: Lessons Learned from Massive Software Failures, Robert Glass Denver Airport

Safeware: System Safety and Computers, Nancy Leveson Therac-25

http://sunnyday.mit.edu/papers/therac.pdf Risks to the Public, Peter Neumann

http://www.csl.sri.com/users/risko/risks.txt

Page 6: SE Principles Silver Bullets

Poor Engineering Has Disastrous Consequences!

Can you think of other examples….?

Page 7: SE Principles Silver Bullets

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

Page 8: SE Principles Silver Bullets

First Software Reuse paper

Doug McIlroy

Page 9: SE Principles Silver Bullets

1968 NATO SE

The conference must have been tiring….

Page 10: SE Principles Silver Bullets

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

Page 11: SE Principles Silver Bullets

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…

Page 12: SE Principles Silver Bullets

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.”

Page 13: SE Principles Silver Bullets

SE: A Disciplined ApproachKill the Snake-OilThe 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.

Page 14: SE Principles Silver Bullets

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.]

Page 15: SE Principles Silver Bullets

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.”

Page 16: SE Principles Silver Bullets

“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

Page 17: SE Principles Silver Bullets

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.

16 bit word in HW -> 216 states Def-use of variables and state changes

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.

Page 18: SE Principles Silver Bullets

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

errors in specification & code hard to manage

how can you estimate without understanding? maintenance is a nightmare

Page 19: SE Principles Silver Bullets

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

e.g., plant built & asked to create SW to control software must conform to the plant

Interface with a new system 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.

Page 20: SE Principles Silver Bullets

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).

E.g., Windows update web site 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).

Page 21: SE Principles Silver Bullets

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)

incomprehensible partial views

misleading Makes it hard to communicate to

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.

Page 22: SE Principles Silver Bullets

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 …

i.e., domain modelling: telephony, avionics, flight reservation … and in solution space too

e.g., frameworks, libraries, components HLLs and OOP [replace “Ada” by “Java”]

Good training/use will make for better systems. When used well, bumps up the abstraction level

… 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.

Page 23: SE Principles Silver Bullets

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

Page 24: SE Principles Silver Bullets

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.

Page 25: SE Principles Silver Bullets

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

Page 26: SE Principles Silver Bullets

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 state-machine diagram? A class diagram with lots of complex interdependencies? A use-case scenario diagram with lots of variation?

Improvement: Domain-specific visual languages

Page 27: SE Principles Silver Bullets

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

Page 28: SE Principles Silver Bullets

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!

Page 29: SE Principles Silver Bullets

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.

Page 30: SE Principles Silver Bullets

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?

Page 31: SE Principles Silver Bullets

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.

Page 32: SE Principles Silver Bullets

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”.

Page 33: SE Principles Silver Bullets

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??

Page 34: SE Principles Silver Bullets

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”

Page 35: SE Principles Silver Bullets

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

Page 36: SE Principles Silver Bullets

SE Principles - Parnas

Page 37: SE Principles Silver Bullets

Definition

Parnas starts this paper with a definition of SE as: “multi-person construction of multi-version

programs.” Do you agree with this definition?

Page 38: SE Principles Silver Bullets

Excludes solo-programming… The argument, in some way, makes sense:

1. Dividing the job

2. Specifying exact behavior

3. Team communication …all of these things contribute to problems

that need to be solved by applying SE principles.

Page 39: SE Principles Silver Bullets

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?

Page 40: SE Principles Silver Bullets

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.

Page 41: SE Principles Silver Bullets

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.

Page 42: SE Principles Silver Bullets

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”

Page 43: SE Principles Silver Bullets

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.”

Page 44: SE Principles Silver Bullets

Two Techniques for Controlling Structure Decomposition

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

Precise Specification “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…

Page 45: SE Principles Silver Bullets

Decomposition and Simple Specification

The prong and receptacle parts of a Lego™ block have been unchanged since 1932 [Lego, 2002].

Page 46: SE Principles Silver Bullets

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].

Page 47: SE Principles Silver Bullets

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

Page 48: SE Principles Silver Bullets

A lot of review &

“On the Criteria…” (hopefully)

CS 620/720

Software Engineering

January 20, 2004

Page 49: SE Principles Silver Bullets

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]

Page 50: SE Principles Silver Bullets

Generic Lifecycle Models

Page 51: SE Principles Silver Bullets

Software Lifecycles

analysis design code test

System/informationengineering

Linear Model

Page 52: SE Principles Silver Bullets

Waterfall

IntegrationPhase

Test

MaintenancePhase

Retirement

RequirementsPhase

Verify

SpecificationPhase

Verify

DesignPhase

Verify

ImplementationPhase

Test

ChangedRequirements

Verify

Object-Oriented and Classical Software Engineering Fifth Edition, WCB/McGraw-Hill, 2002Stephen R. Schach

Verification vs validation

Royce, 1970

Page 53: SE Principles Silver Bullets

Analysis

Rqmnts

Integration

Testing

Coding

Design

Maintenance

Relative Cost Of

Software DevelopmentActivities

Page 54: SE Principles Silver Bullets

The Cost of Change

Definition Development After release

1x

1.5-6x

60-100x

Page 55: SE Principles Silver Bullets

More Overview

Abstraction, Information Hiding, Encapsulation, Cohesion/Coupling….

… all in 15 minutes!!

Page 56: SE Principles Silver Bullets

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?

Page 57: SE Principles Silver Bullets

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]

Page 58: SE Principles Silver Bullets

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]

Page 59: SE Principles Silver Bullets

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]

Page 60: SE Principles Silver Bullets

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]

Page 61: SE Principles Silver Bullets

Looks Yummy!

I’m sure gladI don’t have to eat

this stuff!

Page 62: SE Principles Silver Bullets

Customer

Waiter (object)

Data: name: Joetables: 1,2tickets: 2

Methods: takeOrder putOrderonTurnstile pickup Order serverOrder

Turnstile (object)

Data: tickets: 1

Methods: isTicketReady add Ticket remove Ticket

Cook (object)

Data: name: Arnold specialties: HamandEggs Pancakes FrenchToast

Private Methods:makeHamandEggsmakePancakesmakeFrenchToast

Public Methods: takeTicketFromTurnstile putOrderOnCounter

Counter (object)

Data:ordersAvailable

Methods:isOrderReadyaddOrderremoveOrder

Messages invoke methods &methods send messages.

The Restaurant

Page 63: SE Principles Silver Bullets

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

Page 64: SE Principles Silver Bullets

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-orientedcontext is not essentially different from its dictionarydefinition. It still refers to building a capsule, in the case aconceptual barrier, around some collection of things."

-- [Wirfs-Brock et al, 1990]

Page 65: SE Principles Silver Bullets

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]

Page 66: SE Principles Silver Bullets

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)

Page 67: SE Principles Silver Bullets

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?”

Page 68: SE Principles Silver Bullets

A Brain Teaser: Who’s joined to whom—and by what?

A

B

F

G

C

ED

Global Data

Page 69: SE Principles Silver Bullets

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.

Page 70: SE Principles Silver Bullets

Type Measure Black BoxFunctional Best Black BoxInformational ** BestSequential CommunicationalProcedural Gray BoxTemporalLogicalCoincidental Worst Transparent

or White Box**Originally not part of Scale

Scale of

Cohesion

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.

Page 71: SE Principles Silver Bullets

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

Page 72: SE Principles Silver Bullets

Coincidental Cohesion cont.

Disadvantages of Coincidental Cohesion Severe lack of maintainability of product. Lack of reusability.

Corrective action break the module into smaller modules.

Page 73: SE Principles Silver Bullets

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

Page 74: SE Principles Silver Bullets

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.

Page 75: SE Principles Silver Bullets

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

Page 76: SE Principles Silver Bullets

Temporal Cohesion

A module whose elements are involved in activities that are related in time. Elements are usually more closely related to

activities in other modules than they are to one another (leads to tight coupling).

Disadvantage Lack of reusability in other products.

Corrective Action Take the procedure apart and rewrite code as

necessary

Page 77: SE Principles Silver Bullets

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).

Page 78: SE Principles Silver Bullets

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.

Page 79: SE Principles Silver Bullets

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.

Page 80: SE Principles Silver Bullets

Functional Cohesion

A module whose elements all contribute to the execution of one and only one problem-related 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.

Page 81: SE Principles Silver Bullets

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.

Page 82: SE Principles Silver Bullets

Comparisons

Cohesion Level Coupling

Cle

anliness o

f

Imple

men-

tation

Modifi

ablity

Unders

tand-

ability

Effect on

overa

ll s

yste

m

main

tain

-ability

Functional / Informational Good Good Good Good GoodSequential Good Good Good Good Fairly goodCommunicational Medium Medium Medium Medium MediumProcedural Variable Poor Variable Variable BadTemporal Poor Medium Medium Medium BadLogical Bad Bad Bad Poor BadCoincidental Bad Poor Bad Bad Bad

Comparisons Between Levels of Cohesion

Page 83: SE Principles Silver Bullets

Modular Coupling

The degree of interaction between two modules.

Levels of

Coupling

Best (Lowest Interaction)

Worst (Highest Interaction)

Normal Data Stamp Control

Common

Content

Page 84: SE Principles Silver Bullets

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 pUses local

data a

Module qLocal data a

Page 85: SE Principles Silver Bullets

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”

Page 86: SE Principles Silver Bullets

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.

Page 87: SE Principles Silver Bullets

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).

Page 88: SE Principles Silver Bullets

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

X

Y

C D

Page 89: SE Principles Silver Bullets

Data Coupling cont.

Advantages Avoids sending unnecessary data Is direct. Flexible. Highly reusable. Maintainable.

Page 90: SE Principles Silver Bullets

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

Page 91: SE Principles Silver Bullets

Comparisons

Comparisons Between Levels of Coupling

Coupling Level ModifiablityUnderstand-

ability

Module's usability in

other systemsData Tramp

GoodMedium

GoodMedium

GoodPoor

Stamp Bundling

MediumMedium

MediumPoor

MediumPoor

Control Hybrid

PoorBad

PoorBad

PoorBad

Common Medium Bad PoorContent Bad Bad Bad

Page 92: SE Principles Silver Bullets

The Goal of Good Modularity?

High Cohesion Functional or Information

Low Coupling Data, Stamp, Control

Page 93: SE Principles Silver Bullets

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!

Page 94: SE Principles Silver Bullets

Enough of that….

Sample code from last week Parnas paper

Page 95: SE Principles Silver Bullets

Simple C++ Exampleclass 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()

Page 96: SE Principles Silver Bullets

A Sketchy Evolution of Software Design 1960s

Structured 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 1970s

Structured Design Methodology/guidelines for dividing programs into subroutines.

1980s Modular (object-based) 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.

Page 97: SE Principles Silver Bullets

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 Initial CACM rejection (“Nobody does it that way”) Universal acceptance (“Parnas wrote about common practice”)

Discusses “modularization” Module = a collection of subroutines and data elements Critique of Procedural Design

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”

Page 98: SE Principles Silver Bullets

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]

Page 99: SE Principles Silver Bullets

KWIC Input

Designing Software for Ease of ConstructionFigs are Good

Outputare 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

Page 100: SE Principles Silver Bullets

KWIC Modularization 1Master control

Input medium Output medium

Characters IndexAlphabetized

Index

Input Circular Shift Alphabetizer Output

Page 101: SE Principles Silver Bullets

KWIC Modularization 2Master control

Input medium Output medium

Input Output

Lines

setc

(i,w

,j,c)

getc

(i,w

,j)

nWor

ds(i)

Circular Shifter

getc

(i,w

,j)

nWor

ds(i)

csse

tup

Alphabetizer

doA

lph

Ith

(i)

Page 102: SE Principles Silver Bullets

Criteria for decomposition Modularization 1

Each major step in the processing was a module Modularization 2

Information hiding Each module has one or more "secrets” Each module is characterized by its knowledge of design decisions which it

hides from all others.

Lines how characters/lines are stored

Circular Shifter algorithm for shifting, storage for shifts

Alphabetizer algorithm for alpha, laziness of alpha

Page 103: SE Principles Silver Bullets

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 …

Page 104: SE Principles Silver Bullets

Changeability Comparison Design decisions that may change (design1, design2)

Input format (1, 1)

All lines stored in memory (all, 1)

Pack characters 4 to a word (all, 1)

Make an index for circular shifts rather than store them (3,1)

Alphabetize once, rather than either Search for each item as needed Partially alphabetize, partially search

(3,1)

Page 105: SE Principles Silver Bullets

Independent Development

Modularization 1 Must design all data structures before parallel work can

proceed Complex descriptions needed

Modularization 2 Must design interfaces before parallel work can begin Simple descriptions only

Comprehensibility Modularization 2 is better

Parnas subjective judgment

Page 106: SE Principles Silver Bullets

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 task-specific?

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

Inter-dependence

HIGH. All modules are heavily dependent on the Data Storage module

NONE. All modules are independent!

Page 107: SE Principles Silver Bullets

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

Page 108: SE Principles Silver Bullets

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.

Page 109: SE Principles Silver Bullets

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.

Page 110: SE Principles Silver Bullets

Benefits of Good Modular Design

Independent Development

Since each module is

independent, they can be

developed independently at the

same time Shortened

Development Time!

Page 111: SE Principles Silver Bullets

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.

Page 112: SE Principles Silver Bullets

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.

Page 113: SE Principles Silver Bullets

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]

Page 114: SE Principles Silver Bullets

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)

Page 115: SE Principles Silver Bullets

Terminology

Parnas uses some terms that are not used anymore, or are used nowadays with different meanings, such as:- COREThen: main memory, general storage spaceNow: internal functionality, internals- JOBThen: Implied batch processingNow: ???- 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…)

Page 116: SE Principles Silver Bullets

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

Previous Concerns

Page 117: SE Principles Silver Bullets

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.

Past Design Processes

Page 118: SE Principles Silver Bullets

“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.

Changing Guidelines

Page 119: SE Principles Silver Bullets

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.

Page 120: SE Principles Silver Bullets

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)

Page 121: SE Principles Silver Bullets

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

Page 122: SE Principles Silver Bullets

Intermingled Decisions

Page 123: SE Principles Silver Bullets

Concern Separation

Page 124: SE Principles Silver Bullets

Making Modules Easier to Change

Page 125: SE Principles Silver Bullets

Parnas Transparency (skip 9.6 and 9.7)OO Design Principles:

Open-ClosedLiskov SubstitutabilityDependency Inversion

CS 620/720

Software Engineering

January 22, 2004

Page 126: SE Principles Silver Bullets

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

Page 127: SE Principles Silver Bullets

Parnas Transparency

Page 128: SE Principles Silver Bullets

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

Page 129: SE Principles Silver Bullets

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

Page 130: SE Principles Silver Bullets

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

Page 131: SE Principles Silver Bullets

Transparency in Bottom Up Design Transparency

describes the implementation completeness of the virtual machine with respect to the base machine’s functionality

Complete transparency 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

Page 132: SE Principles Silver Bullets

Driving with strings and steering wheel

Base machine New virtual machine

Page 133: SE Principles Silver Bullets

Example positions

What figures suggest a loss of transparency?In this case, is the loss of transparency ok?

Page 134: SE Principles Silver Bullets

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

Page 135: SE Principles Silver Bullets

Completeness of the abstraction What operation does Parnas show is not

possible in the virtual machine, which suggests a loss of transparency?

Page 136: SE Principles Silver Bullets

Other Examples of Transparency Hardware Search Engine

Page 137: SE Principles Silver Bullets

Example – Graphics Card Transparency

Hierarchical Level Description

0 Graphics Card – silicon

1 Driver

2 API – DirectX,OpenGL

3 Application – Game, CAD

Page 138: SE Principles Silver Bullets

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

Page 139: SE Principles Silver Bullets

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.

Page 140: SE Principles Silver Bullets

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

Page 141: SE Principles Silver Bullets

Search Engine ExampleA 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

Page 142: SE Principles Silver Bullets

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

Page 143: SE Principles Silver Bullets

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

Page 144: SE Principles Silver Bullets

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

Page 145: SE Principles Silver Bullets

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?

Page 146: SE Principles Silver Bullets

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

Page 147: SE Principles Silver Bullets

Open-Closed Principle (OCP)

"Software Systems change during their life time" both better designs and poor designs have to face the changes; good designs are stable

Software entities should be open for extension, but closed for modification

B. Meyer, 1988 / quoted by R. Martin, 1996

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

Page 148: SE Principles Silver Bullets

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?

Page 149: SE Principles Silver Bullets

The Open/Closed Principle (OCP) Example

CircleData

radius : floatcenter : Point

SquareData

origin : Pointlength : floatwidth : float

ShapeManipulator

drawShape(shapeData : ShapeData)drawCircle(circle : CircleData)drawSquare(square : SquareData)

ShapeData

shapeType : int

public void drawShape(ShapeData shapeData) { switch (shapeData.shapeType) {

case SQUARE:drawSquare((SquareData)shapeData);break;

case CIRCLE:drawCircle((CircleData)shapeData);break;

} }

An Example of What not to do!

What is wrong with this code?

Page 150: SE Principles Silver Bullets

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.

Page 151: SE Principles Silver Bullets

The Open/Closed Principle (OCP) Example

ShapeInterface

draw()move()

<<Interface>>

Circle

draw()move()

Square

draw()move()

SmartShapeManipulator

drawShape(shape : ShapeInterface)

public void drawShape(ShapeInterface shape){ shape.draw ();}

Page 152: SE Principles Silver Bullets

Open the door ...

How to make the Car run efficiently with a TurboEngine? Only by changing the Car!

...in the given design

Page 153: SE Principles Silver Bullets

... But Keep It Closed!

A class must not depend on a concrete class! It must depend on an abstract class ... ...using polymorphic dependencies (calls)

Page 154: SE Principles Silver Bullets

OCP Heuristics

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

Make all object-data privateNo Global Variables!

Page 155: SE Principles Silver Bullets

Liskov Substitution Principle (LSP)

Inheritance should ensure that any property proved about supertype objects also holds for subtype objects

B. Liskov, 1987

The key of OCP: Abstraction and Polymorphism Implemented by inheritance How do we measure the quality of inheritance?

Functions that use pointers or references to base classesmust be able to use objects of derived classes

without knowing it.R. Martin, 1996

Contravariance/covariance…

Page 156: SE Principles Silver Bullets

The Liskov Substitution Principle (LCP) Example

Policy

getUnitsOfRisk()getPolicyCoverages()getRateSteps()

AutoPolicy

PersonalAutoPolicy CommercialAutoPolicy

PolicyRateModule

This module should not break regardless of whether a Personal Auto or Commercial Auto or Home Owner Policy is passed to it

HomeOwnerPolicy

Page 157: SE Principles Silver Bullets

Inheritance Appears Simpleclass Bird { // has beak, wings,... public: virtual void fly(); // Bird can fly};

class Parrot : public Bird { // Parrot is a bird public: virtual void mimic(); // Can Repeat words...};

// ...Parrot mypet;mypet.mimic(); // my pet being a parrot can Mimic()mypet.fly(); // my pet “is-a” bird, can fly

Page 158: SE Principles Silver Bullets

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

Page 159: SE Principles Silver Bullets

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 oneB. Meyer, 1988

Derived class services should require no more and promise no less

int Base::f(int x);// REQUIRE: x is odd// PROMISE: return even int

int Derived::f(int x);// REQUIRE: x is int// PROMISE: return 8

Page 160: SE Principles Silver Bullets

Square IS-A Rectangle?

Should I inherit Square from Rectangle?

Square

?

Page 161: SE Principles Silver Bullets

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 problemvoid g(Rectangle& r) {

r.setWidth(5); r.setHeight(4);

// How large is the area?

} 20! ... Are you sure? ;-)

Page 162: SE Principles Silver Bullets

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.

Page 163: SE Principles Silver Bullets

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

Client

Service Class

Unexpected Subclass

Page 164: SE Principles Silver Bullets

LSP Related Heuristic (2)

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

It is illegal for a derived class, to override a base-class method with a NOP method

Page 165: SE Principles Silver Bullets

Example of Rigidity and Immobility

Copy

ReadKeyboard

WritePrinter

void Copy(){ int c; while ((c = ReadKeyboard()) != EOF) WritePrinter(c);}

WriteDisk

enum OutputDevice {printer, disk};

void Copy(OutputDevice dev){

int c;

while((c = ReadKeyboard())!= EOF)

if(dev == printer)

WritePrinter(c);

else

WriteDisk(c);

}

Page 166: SE Principles Silver Bullets

Dependency Inversion PrincipleI. 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 abstractionsR. 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

Page 167: SE Principles Silver Bullets

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.

Page 168: SE Principles Silver Bullets

Procedural vs. OO Architecture

Procedural Architecture

Object-Oriented Architecture

Page 169: SE Principles Silver Bullets

DIP Applied on Example

Copy

Reader Writer

KeyboardReader

PrinterWriter

DiskWriter

class Reader { public: virtual int read()=0;};

class Writer { public: virtual void write(int)=0;};

void Copy(Reader& r, Writer& w){ int c; while((c = r.read()) != EOF) w.write(c);}

Page 170: SE Principles Silver Bullets

DIP Related Heuristic

Use inheritance to avoid direct bindings to classes:

Design to an interface, not an implementation!

Client

Interface(abstract class)

Implementation(concrete class)

Page 171: SE Principles Silver Bullets

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++

Page 172: SE Principles Silver Bullets

DIP Related Heuristic

Avoid structures in which higher-level layers depend on lower-level abstractions: In example below, Policy layer is ultimately dependant on Utility

layer.

Avoid Transitive Dependencies

Policy Layer

MechanismLayer

UtilityLayer

Depends on Depends on

Page 173: SE Principles Silver Bullets

Solution to Transitive Dependencies

Use inheritance and abstract ancestor classes to effectively eliminate transitive dependencies:

Policy Layer

MechanismLayer

UtilityLayer

depends on

depends on UtilityInterface

MechanismInterface

Page 174: SE Principles Silver Bullets

DIP - Related Heuristic

If you cannot find a satisfactory solution for the class you are designing, try delegating responsibility to one or more classes:

When in doubt, add a level of indirection

Problem Holder

ProblemSolver

Page 175: SE Principles Silver Bullets

When in doubt ... It is generally easier to remove or by-pass

existing levels of indirection than it is to add them later:

XSo, Blue class re-implements some or all of green class’s responsibilities for efficiency and calls red object directly

Blue class’s indirect message calls to red class fail to meet some criteria (e.g. real-time constraints, etc.)

Page 176: SE Principles Silver Bullets

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 ;)

Page 177: SE Principles Silver Bullets

DemeterParnas

CS 620/720

Software Engineering

January 28, 2004

Page 178: SE Principles Silver Bullets

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

Page 179: SE Principles Silver Bullets

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

Page 180: SE Principles Silver Bullets

Law of Demeter

FRIENDS

Acquaintances

Page 181: SE Principles Silver Bullets

“closely related”

Page 182: SE Principles Silver Bullets

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

Page 183: SE Principles Silver Bullets

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

Page 184: SE Principles Silver Bullets

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

Strongest Form

Must use accessor function to access inherited data members

Acquaintance classes do NOT meet these criteria

Preferred supplier classes meet all of these criteria

Preferred acquaintance classesare the last two bullets

Page 185: SE Principles Silver Bullets

directly held component objects

created objects

passed parameters

itself

Demeter’s Law for Functionsclass 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:

Page 186: SE Principles Silver Bullets

Demeter’s “Good Style” Access supplier methods only through

methods of “preferred acquaintances” bypass preferred supplier only if later

optimization demands direct access

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

AcquaintanceSupplierClient

Page 187: SE Principles Silver Bullets

The Law of Demeter (cont.)Violation of the Lawclass 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();}

Page 188: SE Principles Silver Bullets

Example from paper

Look at page 43…

Page 189: SE Principles Silver Bullets

Acceptable LoD Violations If optimization requires violation

Speed or memory restrictions

If module accessed is a fully stabilized “Black Box” 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

Page 190: SE Principles Silver Bullets

Designing Software for Ease of Extension and Contraction

ICSE 1991 Most Influential Paper Award…

Do you agree?

Page 191: SE Principles Silver Bullets

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

Page 192: SE Principles Silver Bullets

“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

Page 193: SE Principles Silver Bullets

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

Page 194: SE Principles Silver Bullets

Inhibiting Factors

Excessive information distribution Too many components assume existence of a feature

Chain of data-transforming components Typical consequence of flow-chart method; poor coupling

Multi-function components Combining of multiple functions in one module; poor cohesion

Loops in the “uses” relation

Page 195: SE Principles Silver Bullets

The Methodology

Minimal subsets and minimal increments “one first searches for the minimal subset that

conceivably perform a useful service and then searches for a set of minimal increments”

Interface definitions using information hiding “secrets” – items that are most likely to change

Design as virtual machines “stop thinking of systems in terms of components

that correspond to steps in the processing” “Uses” hierarchy

Page 196: SE Principles Silver Bullets

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)

Page 197: SE Principles Silver Bullets

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.

Page 198: SE Principles Silver Bullets

Example – The Automated Kitchen Minimal subsets and increments

Level 0 Boil Bake Sauté Refrigerate Slice Dice

Page 199: SE Principles Silver Bullets

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

Page 200: SE Principles Silver Bullets

The Automated Kitchen continued... Minimal subsets and increments

Level 2 Prepare breakfast Prepare lunch Prepare dinner

Page 201: SE Principles Silver Bullets

The Automated Kitchen continued... Minimal subsets and increments

Level 3 Prepare food

Page 202: SE Principles Silver Bullets

The Automated Kitchen continued... Interface definitions using information hiding

Level 0 Slicing is done with ginsu or veg-o-matic Boiling is done with gas, electric, coal or microwave

Level 1 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

Page 203: SE Principles Silver Bullets

The Automated Kitchen continued... Design as virtual machines

Coffee maker Bread machine Scramble eggs Boil water

Page 204: SE Principles Silver Bullets

The Automated Kitchen finally! “Uses” hierarchy

make breakfast

brew coffeescramble eggsmake toastmake pancakes

boil saute bake slice mix Level 0 uses no other program}

Level i uses at least 1 program on i-1and nothing higher than i-1}

Page 205: SE Principles Silver Bullets

Playing in the MudIntroduction to MVC

CS 620/720

Software Engineering

January 29, 2004

Page 206: SE Principles Silver Bullets

Escape from the Spaghetti Code Jungle

Brian FooteUniversity of Illinois at Urbana-Champaign

17 February 1998

SOOUG Winter ‘98

Page 207: SE Principles Silver Bullets

Big Ball of MudThe de-facto standard software architecture

“Haphazardly structured, sprawling, sloppy, duct-tape and bailing wire, spaghetti code jungle”

Why is the gap between what we preach and what we practice so large?

Page 208: SE Principles Silver Bullets

Where does Mud Come From

Throwaway Code Legacy Mush Urban Sprawl Slash and Burn Tactics Merciless Deadlines Sheer Neglect

Page 209: SE Principles Silver Bullets

Silver Buckshot

We will even look at some of these, albeit briefly for some, during the semester: Objects Frameworks Patterns Architecture Process/Organization Tools

Page 210: SE Principles Silver Bullets

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

Page 211: SE Principles Silver Bullets

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

Page 212: SE Principles Silver Bullets

A Comparison of Class Libraries, Frameworks, & Components

Class Library Architecture

ADTs

Strings

LocksIPC

MathLOCAL INVOCATIONSAPPLICATION-

SPECIFICFUNCTIONALITY

EVENTLOOP

GLUECODE

Files

GUI Logging

Component ArchitectureLOCAL/REMOTE INVOCATIONSAPPLICATION-

SPECIFICFUNCTIONALITY

EVENTLOOP

GLUECODE

Naming

Trading

Events

Locking

Framework Architecture

ADTs

Locks

INVOKES

Strings

Files

Often compile-time Often run-time

Page 213: SE Principles Silver Bullets

Hollywood Principle

Library

Old Reuse

Framework

Your Code

New Reuse

Your Code

Page 214: SE Principles Silver Bullets

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

Page 215: SE Principles Silver Bullets

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...

Page 216: SE Principles Silver Bullets

Software Tectonics

Reconstruction Major Upheaval Throw it away Incremental Change Evolution Piecemeal Growth

Page 217: SE Principles Silver Bullets

Throwaway Code

Sometimes this is the right approach

There is the danger that such code will take on a life of its own

Page 218: SE Principles Silver Bullets

Reconstruction

Atlanta’s Fulton County Stadium was built in 1966 and razed in 1997.

Two single purpose stadia, with skyboxes, are replacing it

Page 219: SE Principles Silver Bullets

Sweep It Under the Rug

You may not know how to get rid of a problem, but at least you can cordon it off...

Page 220: SE Principles Silver Bullets

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.

Page 221: SE Principles Silver Bullets

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

Page 222: SE Principles Silver Bullets

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

Page 223: SE Principles Silver Bullets

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

Page 224: SE Principles Silver Bullets

MVC – The Earliest Pattern

Page 225: SE Principles Silver Bullets

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 multi-windowed 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.

Page 226: SE Principles Silver Bullets

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

Page 227: SE Principles Silver Bullets

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

Page 228: SE Principles Silver Bullets

MVC Schematic

KeyboardMouse

Etc.Controller

View

Model

Display Each piece is an object

Page 229: SE Principles Silver Bullets

Design Patterns in Smalltalk MVC

Model Implements algorithms (business logic) Independent of environment

View: Communicates with environment Implements I/O interface for model

Controller: Controls data exchange (notification protocol) between model and view

ViewGUI, Document 2

ControllerModel

US $ -> EUR

ModelEUR -> US $

ViewGUI, Document 1

Viewcharacter-based

Page 230: SE Principles Silver Bullets

MVC Architecture

http://java.sun.com/blueprints/patterns/j2ee_patterns/model_view_controller/

Page 231: SE Principles Silver Bullets

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

Page 232: SE Principles Silver Bullets

Model Examples

text editor: model is text string slider: model is an integer spreadsheet: collection of values related by

functional constraints

Page 233: SE Principles Silver Bullets

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

Page 234: SE Principles Silver Bullets

View Examples

Slider: text-field, line with bead, temp. gauge Spreadsheet:

Tabular representation Bar chart Histogram

Page 235: SE Principles Silver Bullets

MVC Concepts – multiple views Any number of views can subscribe to the

model

Radiobuttonmodel

View #1

View #2

View #3

Page 236: SE Principles Silver Bullets

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

Page 237: SE Principles Silver Bullets

Controller Examples

Textual commands Mouse (point and click) commands No input

Page 238: SE Principles Silver Bullets

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. C

V

M

Page 239: SE Principles Silver Bullets

MVC Dynamics

3. Controller requests method of Model to change its state.

4. Model changes its internal state

C

V

M

Page 240: SE Principles Silver Bullets

MVC Dynamics

5. Model notifies all dependent Views that data has changed.

6. View requests from Model current data values.

C

V

M

Page 241: SE Principles Silver Bullets

MVC Dynamics

7. Model notifies all dependent Controllers that data has changed.

8. Controller requests from Model current data values.

C

V

M

Page 242: SE Principles Silver Bullets

MVC Dynamics

9. Controller informs View if elements are disabled.

10. View requests redraw

C

V

M

Page 243: SE Principles Silver Bullets

View + Controller linking

Controller almost always has to “talk to” view need geometry of output to interpret input (e.g., picking) need to do feedback

As a result, VC tend to be very tightly coupled, and considered as one M(VC)

Multiple View/Controller pairs can be attached to a single Model

Page 244: SE Principles Silver Bullets

Benefits of MVC Architecture

Improved maintainability Due to modularity of software components

Promotes code reuse Due to OO approach (e.g., subclassing, inheritance)

Model independence 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

Page 245: SE Principles Silver Bullets

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

Page 246: SE Principles Silver Bullets

MVC Example - Swing

Page 247: SE Principles Silver Bullets

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

Page 248: SE Principles Silver Bullets

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)

Page 249: SE Principles Silver Bullets

MVC and Swing (2)

KeyboardMouse

Etc.Controller

View

Model

Display

Swing component

UI delegate

Page 250: SE Principles Silver Bullets

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)

Page 251: SE Principles Silver Bullets

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.

Page 252: SE Principles Silver Bullets

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

Page 253: SE Principles Silver Bullets

Example Program

Page 254: SE Principles Silver Bullets

On to patterns intro….

Page 255: SE Principles Silver Bullets

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

Page 256: SE Principles Silver Bullets

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

Page 257: SE Principles Silver Bullets

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

a context a system of forces that occur repeatedly in the context a spatial configuration which allow forces to resolve themselves

Element of language – an instruction 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

Page 258: SE Principles Silver Bullets

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”… ;)

Page 259: SE Principles Silver Bullets

What Makes it a Pattern ?

A pattern must...

...solve a problem i.e. it must be useful

...have a context 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

Page 260: SE Principles Silver Bullets

GoF Form of a Design PatternPattern 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 appliedStructure

a graphical representation of classes in the patternParticipants

the classes/objects participating and their responsibilitiesCollaborations

of the participants to carry out responsibilities

Page 261: SE Principles Silver Bullets

GoF Form of a Design PatternConsequences

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

Page 262: SE Principles Silver Bullets

Algorithmic Form of Patterns

IF you find yourself in CONTEXT for example EXAMPLES, with PROBLEM, entailing FORCESTHEN for some REASONS, apply DESIGN FORM AND/OR RULE to construct SOLUTION leading to NEW CONTEXT and OTHER PATTERNS

Page 263: SE Principles Silver Bullets

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

Page 264: SE Principles Silver Bullets

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.

Page 265: SE Principles Silver Bullets

Becoming a Chess Master

Learn the rules and physical requirements e.g. pieces, legal movements, chess board geometry and orientation.

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 these games contain patterns that must be understood, memorized and

applied repeatedly

There are hundreds, if not thousands, of such patterns

Page 266: SE Principles Silver Bullets

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

structured, modular, object-oriented, etc

To truly master software design, one must study the design of other masters these designs contain patterns that must be understood, memorized and

applied repeatedly

There are hundreds of these patterns

Page 267: SE Principles Silver Bullets

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

Page 268: SE Principles Silver Bullets

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 XProblem Y

Problem Z

Page 269: SE Principles Silver Bullets

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

Page 270: SE Principles Silver Bullets

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

Page 271: SE Principles Silver Bullets

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

Page 272: SE Principles Silver Bullets

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

Page 273: SE Principles Silver Bullets

PurposeCreational Structural Behavioral

Scope Class Factory Method Adapter (class) InterpreterTemplate Method

Object Abstract FactoryBuilderPrototypeSingleton

Adapter (object)BridgeCompositeDecoratorFacadeFlyweightProxy

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Defer object creation to another class

Defer object creation to another object

Describe algorithms and flow control

Describe ways to assemble objects

Design Pattern Space

Page 274: SE Principles Silver Bullets

Relations among Design Patterns

Builder

Proxy

saving stateof iteration

creatingcomposites

Memento

Adapter

Bridge

Command

IteratorAvoidinghysteresis

Composite

Decorator

Enumeratingchildren

addingrespnsibilitiesto objects

composedusing

sharingcomposites

Flyweightdefininggrammar

Interpreter

Visitor

addingoperations

definingtraversals

definingthe chain

Chain of Responsibility

sharing

strategies

changing skinversus guts

Strategy

adding

operations

State

sharingstrategies

sharingterminalsymbols

Mediator Observer

complexdependencymanagement

Template Method

definingalgorithm´ssteps

Prototype

Abstract Factory

Singleton Facade

Factory Method

implement

usingsingleinstance

singleinstance

configure factorydynamically

often uses

Page 275: SE Principles Silver Bullets

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 (?)

Page 276: SE Principles Silver Bullets

•Present solutions to common software problems arising within a certain context

Overview of Patterns & 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

Patterns

Pattern Languages

•Help resolve key design forces

•Flexibility

•Extensibility

•Dependability

•Predictability

•Scalability

•Efficiency

The Proxy Pattern

•Capture recurring structures & dynamics among software participants to facilitate reuse of successful designs

•Generally codify expert knowledge of design constraints & “best practices”

www.posa.uci.edu

Page 277: SE Principles Silver Bullets

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/

Page 278: SE Principles Silver Bullets

More Pattern URLs

Robert C. Martin’s Chess Analogyhttp://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 softwarehttp://www.lindarising.org -- click on Articles

Seven Habits of Successful Pattern Writershttp://hillside.net/patterns/papers/7habits.html

Brad Appleton's "Patterns in a Nutshell"http://www.enteract.com/~bradapp/docs/patterns-nutshell.html

Page 279: SE Principles Silver Bullets

Introduction to MVC and Patterns

CS 620/720

Software Engineering

February 3, 2004

Page 280: SE Principles Silver Bullets

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

Page 281: SE Principles Silver Bullets

MVC – The Earliest Pattern

Page 282: SE Principles Silver Bullets

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 multi-windowed 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.

Page 283: SE Principles Silver Bullets

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

Page 284: SE Principles Silver Bullets

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

Page 285: SE Principles Silver Bullets

MVC Schematic

KeyboardMouse

Etc.Controller

View

Model

Display Each piece is an object

Page 286: SE Principles Silver Bullets

Design Patterns in Smalltalk MVC

Model Implements algorithms (business logic) Independent of environment

View: Communicates with environment Implements I/O interface for model

Controller: Controls data exchange (notification protocol) between model and view

ViewGUI, Document 2

ControllerModel

US $ -> EUR

ModelEUR -> US $

ViewGUI, Document 1

Viewcharacter-based

Page 287: SE Principles Silver Bullets

MVC Architecture

http://java.sun.com/blueprints/patterns/j2ee_patterns/model_view_controller/

Page 288: SE Principles Silver Bullets

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

Page 289: SE Principles Silver Bullets

Model Examples

text editor: model is text string slider: model is an integer spreadsheet: collection of values related by

functional constraints

Page 290: SE Principles Silver Bullets

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

Page 291: SE Principles Silver Bullets

View Examples

Slider: text-field, line with bead, temp. gauge Spreadsheet:

Tabular representation Bar chart Histogram

Page 292: SE Principles Silver Bullets

MVC Concepts – multiple views Any number of views can subscribe to the

model

Radiobuttonmodel

View #1

View #2

View #3

Page 293: SE Principles Silver Bullets

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

Page 294: SE Principles Silver Bullets

Controller Examples

Textual commands Mouse (point and click) commands No input

Page 295: SE Principles Silver Bullets

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. C

V

M

Page 296: SE Principles Silver Bullets

MVC Dynamics

3. Controller requests method of Model to change its state.

4. Model changes its internal state

C

V

M

Page 297: SE Principles Silver Bullets

MVC Dynamics

5. Model notifies all dependent Views that data has changed.

6. View requests from Model current data values.

C

V

M

Page 298: SE Principles Silver Bullets

MVC Dynamics

7. Model notifies all dependent Controllers that data has changed.

8. Controller requests from Model current data values.

C

V

M

Page 299: SE Principles Silver Bullets

MVC Dynamics

9. Controller informs View if elements are disabled.

10. View requests redraw

C

V

M

Page 300: SE Principles Silver Bullets

View + Controller linking

Controller almost always has to “talk to” view need geometry of output to interpret input (e.g., picking) need to do feedback

As a result, VC tend to be very tightly coupled, and considered as one M(VC)

Multiple View/Controller pairs can be attached to a single Model

Page 301: SE Principles Silver Bullets

Benefits of MVC Architecture

Improved maintainability Due to modularity of software components

Promotes code reuse Due to OO approach (e.g., subclassing, inheritance)

Model independence 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

Page 302: SE Principles Silver Bullets

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

Page 303: SE Principles Silver Bullets

MVC Example - Swing

Page 304: SE Principles Silver Bullets

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)

Page 305: SE Principles Silver Bullets

MVC and Swing

KeyboardMouse

Etc.Controller

View

Model

Display

Swing component

UI delegate

Page 306: SE Principles Silver Bullets

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)

Page 307: SE Principles Silver Bullets

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.

Page 308: SE Principles Silver Bullets

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

Page 309: SE Principles Silver Bullets

Example Program

Page 310: SE Principles Silver Bullets

On to patterns intro….

Page 311: SE Principles Silver Bullets

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

Page 312: SE Principles Silver Bullets

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

Page 313: SE Principles Silver Bullets

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

a context a system of forces that occur repeatedly in the context a spatial configuration which allow forces to resolve themselves

Element of language – an instruction 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

Page 314: SE Principles Silver Bullets

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”… ;)

Page 315: SE Principles Silver Bullets

What Makes it a Pattern ?

A pattern must...

...solve a problem i.e. it must be useful

...have a context 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

Page 316: SE Principles Silver Bullets

GoF Form of a Design PatternPattern 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 appliedStructure

a graphical representation of classes in the patternParticipants

the classes/objects participating and their responsibilitiesCollaborations

of the participants to carry out responsibilities

Page 317: SE Principles Silver Bullets

GoF Form of a Design PatternConsequences

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

Page 318: SE Principles Silver Bullets

Algorithmic Form of Patterns

IF you find yourself in CONTEXT for example EXAMPLES, with PROBLEM, entailing FORCESTHEN for some REASONS, apply DESIGN FORM AND/OR RULE to construct SOLUTION leading to NEW CONTEXT and OTHER PATTERNS

Page 319: SE Principles Silver Bullets

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

Page 320: SE Principles Silver Bullets

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.

Page 321: SE Principles Silver Bullets

Becoming a Chess Master

Learn the rules and physical requirements e.g. pieces, legal movements, chess board geometry and orientation.

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 these games contain patterns that must be understood, memorized and

applied repeatedly

There are hundreds, if not thousands, of such patterns

Page 322: SE Principles Silver Bullets

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

structured, modular, object-oriented, etc

To truly master software design, one must study the design of other masters these designs contain patterns that must be understood, memorized and

applied repeatedly

There are hundreds of these patterns

Page 323: SE Principles Silver Bullets

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

Page 324: SE Principles Silver Bullets

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 XProblem Y

Problem Z

Page 325: SE Principles Silver Bullets

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

Page 326: SE Principles Silver Bullets

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

Page 327: SE Principles Silver Bullets

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

Page 328: SE Principles Silver Bullets

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

Page 329: SE Principles Silver Bullets

PurposeCreational Structural Behavioral

Scope Class Factory Method Adapter (class) InterpreterTemplate Method

Object Abstract FactoryBuilderPrototypeSingleton

Adapter (object)BridgeCompositeDecoratorFacadeFlyweightProxy

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Defer object creation to another class

Defer object creation to another object

Describe algorithms and flow control

Describe ways to assemble objects

Design Pattern Space

Page 330: SE Principles Silver Bullets

Relations among Design Patterns

Builder

Proxy

saving stateof iteration

creatingcomposites

Memento

Adapter

Bridge

Command

IteratorAvoidinghysteresis

Composite

Decorator

Enumeratingchildren

addingrespnsibilitiesto objects

composedusing

sharingcomposites

Flyweightdefininggrammar

Interpreter

Visitor

addingoperations

definingtraversals

definingthe chain

Chain of Responsibility

sharing

strategies

changing skinversus guts

Strategy

adding

operations

State

sharingstrategies

sharingterminalsymbols

Mediator Observer

complexdependencymanagement

Template Method

definingalgorithm´ssteps

Prototype

Abstract Factory

Singleton Facade

Factory Method

implement

usingsingleinstance

singleinstance

configure factorydynamically

often uses

Page 331: SE Principles Silver Bullets

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 (?)

Page 332: SE Principles Silver Bullets

•Present solutions to common software problems arising within a certain context

Overview of Patterns & 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

Patterns

Pattern Languages

•Help resolve key design forces

•Flexibility

•Extensibility

•Dependability

•Predictability

•Scalability

•Efficiency

The Proxy Pattern

•Capture recurring structures & dynamics among software participants to facilitate reuse of successful designs

•Generally codify expert knowledge of design constraints & “best practices”

www.posa.uci.edu

Page 333: SE Principles Silver Bullets

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/

Page 334: SE Principles Silver Bullets

More Pattern URLs

Robert C. Martin’s Chess Analogyhttp://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 softwarehttp://www.lindarising.org -- click on Articles

Seven Habits of Successful Pattern Writershttp://hillside.net/patterns/papers/7habits.html

Brad Appleton's "Patterns in a Nutshell"http://www.enteract.com/~bradapp/docs/patterns-nutshell.html

Page 335: SE Principles Silver Bullets

Creational Patterns

CS 620/720

Software Engineering

February 5, 2004

Leonard Jowers

Page 336: SE Principles Silver Bullets

Design Pattern Space

Purpose

Creational Structural Behavioral

SCOPE

Class Factory Method Adapter (class) InterpreterTemplate Method

OBJECT

Abstract FactoryBuilderPrototypeSingleton

Adapter (object)BridgeCompositeDecoratorFacadeFlyweightProxy

Chain of ResponsibilityCommandIteratorMediatorMementoObserverStateStrategyVisitor

Page 337: SE Principles Silver Bullets

Creational Patterns

Will Cover Abstract Factory/

Factory Method Singleton

Will not cover Builder Prototype

Concerns the process of object creation.

Page 338: SE Principles Silver Bullets

Structural Patterns

Will Cover Adapter Facade Composite Decorator Proxy

Will not cover Bridge Flyweight

Deals w/ the composition of classes or objects.

Page 339: SE Principles Silver Bullets

Behavioral Patterns

Will Cover Visitor Observer Strategy Command Chain of Responsibility

Will not cover Interpreter Iterator Mediator Memento State Template

Characterizes the ways in which classes or objects interact and distribute responsibility.

Page 340: SE Principles Silver Bullets

Creational Patterns Abstract the instantiation process

Make a system independent of how its objects are created, composed, and represented

Important if systems evolve to depend more on object composition than on class inheritance 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

Page 341: SE Principles Silver Bullets

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.

Page 342: SE Principles Silver Bullets

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?

Page 343: SE Principles Silver Bullets

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

Page 344: SE Principles Silver Bullets

Apply “Program to an Interface”

ApplicationClass depends now on an (abstract) interface

But we still have hard coded which widget to create!

Page 345: SE Principles Silver Bullets

Widget Factory

CreateScrollBar()

CreateWindow()

MotifWidgetFactory

CreateScrollBar()

CreateWindow()

PMWidgetFactory

CreateScrollBar()

CreateWindow()

Client

Windows

PMWindow MotifWindow

ScrollBar

PMScrollBar MotifScrollBar

ABSTRACT FACTORYMotivation Example

Page 346: SE Principles Silver Bullets

GoF Form of a Design Pattern The Pattern NamePattern name and classification, Intent, and Also-Known-As The ProblemMotivation, and Applicability The SolutionStructure (graphical), Participants (their classes/ objects/

responsibilities), Collaborations (of the participants), Implementation (hints, techniques), Sample code, Known uses, and Related patterns

The ConsequencesConsequences (trade-offs, concerns)

Page 347: SE Principles Silver Bullets

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

Page 348: SE Principles Silver Bullets

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.

Page 349: SE Principles Silver Bullets

ApplicabilityUse 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

Page 350: SE Principles Silver Bullets

Abstract Factory

CreateProductA()

CreateProductB()

ConcreteFactory1 ConcreteFactory2

Client

AbstractProductA

ProductA2 ProductA1

ProductB2 ProductB1

CreateProductA()

CreateProductB()

CreateProductA()

CreateProductB()AbstractProductB

ABSTRACT FACTORYStructure

Page 351: SE Principles Silver Bullets

ABSTRACT FACTORY, Participants AbstractFactory

Declares interface for operations that create abstract product objects

ConcreteFactory Implements operations to create concrete product objects

AbstractProduct Declares an interface for a type of product object

ConcreteProduct 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

Page 352: SE Principles Silver Bullets

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

Page 353: SE Principles Silver Bullets

AbstractFactory

getFactory()getWindow()

MotifFactory

MotifFactory()getWindow()

WindowsFactory

WindowsFactory()getWindow()

Client

AbstractWindow

XWindow MotifWindow

ABSTRACT FACTORYExample

Client()main()

MotifWindow()show()

xWindow()show()

Page 354: SE Principles Silver Bullets

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

Page 355: SE Principles Silver Bullets

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

Page 356: SE Principles Silver Bullets

Abstract Factory Example (Cont’d)

// Code for class AbstractWindow:

public abstract class AbstractWindow { public abstract void show();}; // end of AbstractWindow

Page 357: SE Principles Silver Bullets

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

Page 358: SE Principles Silver Bullets

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

Page 359: SE Principles Silver Bullets

Example – Maze

This Room Maze will be a common example used to illustrate the creational patterns.

Page 360: SE Principles Silver Bullets

Class Diagram for the Maze

rooms

MapSite

Room Wall DoorMaze

enter()=0;

enter()setSide()getSide()

roomNumber

enter() enter()

isOpen

1 *

1

4

Page 361: SE Principles Silver Bullets

Common abstract class for all Maze Components

Meaning of enter() depends on what you are entering. room location changes door if door is open go in; else hurt your nose ;)

enum Direction {North, South, East, West};

class MapSite {public: virtual void enter() = 0;}; // end of class MapSite

Page 362: SE Principles Silver Bullets

Components of the maze – Wall & Door & Roomclass 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

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

Page 363: SE Principles Silver Bullets

Components of the maze – Maze

class Maze {public: void addRoom(Room*); Room * roomNo(int) const;private:}; // end of class Maze

A maze is a collectionof rooms. Maze canfind a particular roomgiven the room number.

roomNo() could do alookup using a linear search or a hash table or a simple array.

Page 364: SE Principles Silver Bullets

Structure of a game

rooms

MapSite

Room Wall DoorMaze

enter()=0;

enter()setSide()getSide()

roomNumber

enter() enter()

isOpen

1 1..n

1

4

MazeGame

Player

1..n

1

Page 365: SE Principles Silver Bullets

Creating the Maze

The problem is inflexibility. hard-coding of maze layout

Pattern can make game creation more flexible... not smaller!

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);};

Page 366: SE Principles Silver Bullets

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!

Page 367: SE Principles Silver Bullets

Idea 1: Subclass MazeGame, override createMaze

Lots of code duplication... :((

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...}

Page 368: SE Principles Silver Bullets

Idea 2: Use a Factory Method

MapSite

Room Wall Door

enter()=0;

enter()setSide()getSide()

roomNumber

enter() enter()

isOpen

1

4

MazeGame

BombedMazeGame

makeWall() createMaze()

makeWall()

BombedWall

enter()return new BombedWall

Page 369: SE Principles Silver Bullets

Parameterizing the Factoryclass Creator {public: virtual Product * create(productId);};

Product* Creator::create(ProductId id) { if (id == MINE) return new MyProduct; if (id == YOURS) return new YourProduct;}

Product * MyCreator::create(ProductId id) { if (id == MINE) return new YourProduct; if (id == YOURS) return new MyProduct; if (id == THEIRS) return TheirProduct; return Creator::create(id); // called if others fail}

selectively extend or change products that get created

Page 370: SE Principles Silver Bullets

Creational/Structural Design Patterns

CS 620/720

Software Engineering

February 12, 2004

Page 371: SE Principles Silver Bullets

Overview

Today: Abstract Factory review Singleton First structural: Adapter

Next week: Remaining Structural Patterns:

Decorator Façade Composite Proxy

Page 372: SE Principles Silver Bullets

Abstract Factory Review

Page 373: SE Principles Silver Bullets

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

Page 374: SE Principles Silver Bullets

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

Page 375: SE Principles Silver Bullets

Examples

Nachiketa Mishra – XML configuration to drive abstract factory pattern

Page 376: SE Principles Silver Bullets

Singleton

Page 377: SE Principles Silver Bullets

Basics Intent

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

Applicability 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

Page 378: SE Principles Silver Bullets

Structure of the Pattern

Put constructor in private/protected data section

Page 379: SE Principles Silver Bullets

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

Page 380: SE Principles Silver Bullets

Implementation: Ensuring a Unique Instance

Significance?

Significance?

Page 381: SE Principles Silver Bullets

Implementation: Subclassing Singletons

But where do singletons get

registered?(constructor?)

Page 382: SE Principles Silver Bullets

Making a single MazeFactory

Page 383: SE Principles Silver Bullets

What if there are subclasses of MazeFactory?

Page 384: SE Principles Silver Bullets

The Adapter Pattern

Page 385: SE Principles Silver Bullets

Adapter Pattern Problem

Have an object with an interface that’s close to, but not exactly, what we need

Context 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

Page 386: SE Principles Silver Bullets

Electrical Adapter…

Page 387: SE Principles Silver Bullets

Some Additional Definitions

Before we go into the adapter pattern let’s review some motivation and introduce some terms

Page 388: SE Principles Silver Bullets

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

Page 389: SE Principles Silver Bullets

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

Page 390: SE Principles Silver Bullets

Implementation Inheritance A very similar class is already implemented

that does almost the same as the desired class implementation.

Problem with implementation inheritance:

Some of the inherited operations might exhibit unwanted behavior. What happens if the Stack user calls Remove() instead of Pop()?

Example: I have a List class, I need a Stack class. How about subclassing the Stack class from the List class and providing three methods, Push() and Pop(), Top()?

Add()Remove()

List

Push()Pop()

Stack

Top()

“Already implemented”

Page 391: SE Principles Silver Bullets

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 Receiver DelegateDelegates to calls

Page 392: SE Principles Silver Bullets

Delegation instead of Inheritance Delegation: Catching an operation and

sending it to another object.

+Add()+Remove()

List

Stack

+Push()+Pop()+Top()

Stack

Add()Remove()

List

+Push()+Pop()+Top()

Stack implemented by DelegationStack implemented by Inheritance

Page 393: SE Principles Silver Bullets

Key to understanding

Many design patterns use a combination of

inheritance and delegation

Many design patterns use a combination of

inheritance and delegation

Page 394: SE Principles Silver Bullets

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: Uses multiple inheritance to adapt one interface to another

Object adapter: Uses single inheritance and delegation

We will mostly use object adapters and call them simply adapters

Page 395: SE Principles Silver Bullets

Class Adapter Pattern (based on Multiple Inheritance)

ClientTarget

Request()

Adaptee (Legacy Object)

ExistingRequest()

Adapter

Request()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()

{ return ExistingRequest();}

Page 396: SE Principles Silver Bullets

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.

Adapter pattern (object adapter)

ClientTarget

Request()

Adaptee

ExistingRequest()

Adapter

Request()

adaptee

Request(){ return adaptee.ExistingRequest();}

Page 397: SE Principles Silver Bullets

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.

Page 398: SE Principles Silver Bullets

Example of the Adapter Pattern

Page 399: SE Principles Silver Bullets

Class Shape

class Shape {public:Shape( );virtual void BoundingBox (

Point& bottomLeft, Point& topRight);

virtual Manipulator* CreateManipulator( ) const;

};

Page 400: SE Principles Silver Bullets

Class TextView

class TextView {public:TextView( );void GetOrigin(Coord& x, Coord& y); void GetExtent(Coord& width,

Coord& height);virtual bool IsEmpty( ) const;

};

Page 401: SE Principles Silver Bullets

Class TextShapeclass TextShape : public Shape {public:TextShape(TextView*);virtual void BoundingBox(

Point& bottomLeft, Point& topRight);virtual bool IsEmpty( );virtual Manipulator* CreateManipulator( );

private:TextView* text;

};

Page 402: SE Principles Silver Bullets

Method BoundingBoxvoid 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);}

Page 403: SE Principles Silver Bullets

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?

Page 404: SE Principles Silver Bullets

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.

Page 405: SE Principles Silver Bullets

Structural Design Patterns

CS 620/720

Software Engineering

February 17, 2004

Page 406: SE Principles Silver Bullets

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

Page 407: SE Principles Silver Bullets

Decorator Pattern

Changing the skin of an object

Page 408: SE Principles Silver Bullets

Motivation A TextView has 2 features:

borders: 3 options: none, flat, 3D

scroll-bars: 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, ... .....

Page 409: SE Principles Silver Bullets

Solution 1: Use Object Composition

Is it Open-Closed?

Page 410: SE Principles Silver Bullets

Solution 2: Change the Skin, not the Guts!

TextView has no borders or scrollbars! Add borders and scrollbars on top of a TextView

Page 411: SE Principles Silver Bullets

Punt…

We’ll come back to this example a little later…

Page 412: SE Principles Silver Bullets

Decorator - Basic Aspects Intent

Attach additional responsibilities to an object dynamically. provide a flexible alternative to subclassing

for extending functionality

Also Known As 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

Page 413: SE Principles Silver Bullets

StructureWhat is significance of this?

Page 414: SE Principles Silver Bullets

Participants & Collaborations Component

defines the interface for objects that can have responsibilities added dynamically

ConcreteComponent 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

Page 415: SE Principles Silver Bullets

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

Page 416: SE Principles Silver Bullets

Consequences Transparency – very good More flexibility than static inheritance

allows to mix and match responsibilities allows to apply a property twice

Avoid feature-laden classes high-up in the hierarchy "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

Page 417: SE Principles Silver Bullets

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

Page 418: SE Principles Silver Bullets

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

Page 419: SE Principles Silver Bullets

Decorator Again

A layered approach Start chain with decorators, end with original object

Decorator 1

Decorator 2

Concrete Componen

t

Page 420: SE Principles Silver Bullets

prints

1

1

1

1..*

1

1

I have an instance of myself

I have an instance of myself

Component

+printTicket():void

TicketDecorator

-myComponent:Component

+TicketDecorator()+TicketDecorator(c:Component)+printTicket():void

SalesTicket

+printTicket():void+main(args:String[]):void

HeaderDecorator2

+HeaderDecorator2(c:Component)+printTicket():void+printHeader():void

FooterDecorator1

+FooterDecorator1(c:Component)+printTicket():void+printFooter():void

HeaderDecorator1

+HeaderDecorator1(c:Component)+printTicket():void+printHeader():void

Configuration

+getSalesTicket():Component

FooterDecorator2

+FooterDecorator2(c:Component)+printTicket():void+printFooter():void

Page 421: SE Principles Silver Bullets

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");

}

}

Page 422: SE Principles Silver Bullets

TicketDecoratorpublic 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(); }}

Page 423: SE Principles Silver Bullets

A Header Decoratorpublic 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 @@"); }}

Page 424: SE Principles Silver Bullets

A Footer Decoratorpublic 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 ##"); }}

Page 425: SE Principles Silver Bullets

SalesOrder a clientpublic 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 ...}

Page 426: SE Principles Silver Bullets

Simple Configuration// This object will determine how to decorate the// SalesTicket. This could become a Factorypublic class Configuration { public static Component getSalesTicket() { // Return a decorated SalesTicket return new HeaderDecorator1( new HeaderDecorator2( new FooterDecorator1( new FooterDecorator2( new SalesTicket() )))); }}

Page 427: SE Principles Silver Bullets

Output with Current Configuration

Output:

@@ Header One @@

>> Header Two <<

Customer: Bob

The sales ticket itself

Total: $123.45

%% FOOTER two %%

## FOOTER two ##

Page 428: SE Principles Silver Bullets

The Decorator Pattern Summary before Another example Intent

Attach additional responsibilities to an object dynamically. Decorators provide a flexible alternative to subclassing for extending flexibility

Also Known As 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.

Page 429: SE Principles Silver Bullets

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 Plain, 3D, Fancy

And two scrollbars Horizontal and Vertical

An inheritance solution requires >12 classes for one view

Page 430: SE Principles Silver Bullets

That’s a lot of classes!

1. TextView-Plain2. TextView-Fance3. TextView-3D4. TextView-Horizontal5. TextView-Vertical6. TextView-Horizontal-Vertical7. TextView-Plain-Horizontal8. TextView-Plain-Vertical9. TextView-Plain-Horizontal-Vertical10. TextView-3D-Horizontal11. TextView-3D-Vertical12. TextView-3D-Horizontal-Vertical13. TextView-Fancy-Horizontal14. TextView-Fancy-Vertical15. TextView-Fancy-Horizontal-Vertical

Page 431: SE Principles Silver Bullets

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)

Page 432: SE Principles Silver Bullets

VisualComponent

draw()

resize()

TextView

draw()

resize()

Border

draw()

resize()

Decorator

draw()

resize()

ScrollBar

draw()

resize()

ImageComponent

draw()

resize()

1

1

Plain

draw()

resize()

3D

draw()

resize()

Fancy

draw()

resize()

Decorator contains a visual component

Horiz

draw()

resize()

Vert

draw()

resize()

Page 433: SE Principles Silver Bullets

ApplicabilityThe 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 }}

Page 434: SE Principles Silver Bullets

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 }}

Page 435: SE Principles Silver Bullets

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 }}

Page 436: SE Principles Silver Bullets

How to use Decoratorspublic 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);

}

}

Page 437: SE Principles Silver Bullets

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));

Page 438: SE Principles Silver Bullets

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)

Page 439: SE Principles Silver Bullets

Façade Pattern

Page 440: SE Principles Silver Bullets

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.

Page 441: SE Principles Silver Bullets

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.

Page 442: SE Principles Silver Bullets

ApplicabilityUse the Facade pattern: to provide a simple interface to a complex subsystem.

Subsystems often get more complex as they evolve. when there are many dependencies between clients

and the implementation classes of an abstraction. 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

Page 443: SE Principles Silver Bullets

client classes

Subsystem classes

Facade

FACADE - Motivation

Page 444: SE Principles Silver Bullets

Facade: Example

Scanner

scan(fileName : String)

Parser

parse(data : String)

TypeChecker

check(data : String)

ByteCodeGenerator

generate(data : String)

ProgramNodeGenerator

generate(data : String)

Statement Expression Variable Literal

Token

create(data : String)

ProgramNode

execute()

Compiler

compile(fileName : String)

Application

add(d : Document)

+theCompiler

+theToken

Page 445: SE Principles Silver Bullets

Compiler Façadeclass 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); }

Page 446: SE Principles Silver Bullets

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.

Page 447: SE Principles Silver Bullets

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.

Page 448: SE Principles Silver Bullets

Composite Pattern

Page 449: SE Principles Silver Bullets

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

Page 450: SE Principles Silver Bullets

Composite Pattern Problem

Distinguishing between composite and simple objects makes applications more complex

Context 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

Page 451: SE Principles Silver Bullets

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

Page 452: SE Principles Silver Bullets

Structure

Component class role gives a consistent interface Leaf class role is for components without further sub-structure Composite class role is for components with multiple parts

Page 453: SE Principles Silver Bullets

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

implement child-specific operations

Leaf defines behavior for primitive objects in the composition

Client manipulates objects in the composition through the Component

interface

Page 454: SE Principles Silver Bullets

Consequences Defines uniform class hierarchies

recursive composition of objects

Make clients simple 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

Page 455: SE Principles Silver Bullets

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

Page 456: SE Principles Silver Bullets

Example of the Composite Pattern

GraphicDraw()Add(Graphic)Remove(Graphic)GetChild(int)

Line TextRect.

Draw() Draw()Draw()

PictureDraw()

Add(Graphic)Remove(Graphic)

GetChild(int)

forall g in graphicsg.Draw()

graphics

Page 457: SE Principles Silver Bullets

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 All subclasses can be treated alike.

Safety problem 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?

Page 458: SE Principles Silver Bullets

Structural Design Patterns

CS 620/720

Software Engineering

February 19, 2004

Page 459: SE Principles Silver Bullets

Agenda

Today Quiz 4 HW1 due tonight Patterns: Composite, Proxy

Tuesday Alexander video

Next Thursday: Quiz 5 Behavioral Patterns – start to read (in this order)

Observer, Visitor, Strategy, Chain of Responsibility, Command

Page 460: SE Principles Silver Bullets

Composite Pattern

Page 461: SE Principles Silver Bullets

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

Page 462: SE Principles Silver Bullets

Composite Pattern Problem

Distinguishing between composite and simple objects makes applications more complex

Context 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

Page 463: SE Principles Silver Bullets

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

Page 464: SE Principles Silver Bullets

Structure

Component class role gives a consistent interface Leaf class role is for components without further sub-structure Composite class role is for components with multiple parts

Page 465: SE Principles Silver Bullets

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

implement child-specific operations

Leaf defines behavior for primitive objects in the composition

Client manipulates objects in the composition through the Component

interface

Page 466: SE Principles Silver Bullets

Consequences Defines uniform class hierarchies

recursive composition of objects

Make clients simple 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

Page 467: SE Principles Silver Bullets

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

Page 468: SE Principles Silver Bullets

Example of the Composite Pattern

GraphicDraw()Add(Graphic)Remove(Graphic)GetChild(int)

Line TextRect.

Draw() Draw()Draw()

PictureDraw()

Add(Graphic)Remove(Graphic)

GetChild(int)

forall g in graphicsg.Draw()

graphics

Page 469: SE Principles Silver Bullets

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 All subclasses can be treated alike.

Safety problem 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?

Page 470: SE Principles Silver Bullets

Proxy Pattern

Page 471: SE Principles Silver Bullets

Basic Idea

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 (n. pl prox-ies) The agency for a person who acts as a substitute for another person, authority to act for another

Page 472: SE Principles Silver Bullets

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

Page 473: SE Principles Silver Bullets

Loading "Heavy" Objects Document Editor that can embed multimedia objects

MMobjects are expensive to create opening of document slow avoid creating expensive objects

they are not all necessary as they are not all visible at the same time

Creating each expensive object on demand ! 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!

Page 474: SE Principles Silver Bullets

Idea: Use a Placeholder!

create only when needed for drawing keeps information about the dimensions (extent)

Page 475: SE Principles Silver Bullets

Structure

Proxy “stands in” for target object Proxy exhibits same interface as target object

Forwards method invocations it receives to the target object

Page 476: SE Principles Silver Bullets

Participants

Proxy maintains a reference that lets the proxy access the real subject. provides an interface identical to Subject's

so that proxy can be substituted for the real subject controls access to the real subject

may be responsible for creating or deleting it

Subject defines the common interface for RealSubject and Proxy

RealSubject defines the real object that the proxy holds place for

Page 477: SE Principles Silver Bullets

Collaborations

Page 478: SE Principles Silver Bullets

Remote Proxy

Hide real details of accessing an object actual object is on a remote machine (remote address space) used in RMI and CORBA

Page 479: SE Principles Silver Bullets

Further Reasons to Use Proxies Virtual Proxy

Creates/accesses expensive objects on demand may wish to delay creating an expensive object until it is really

accessed It may be too expensive to keep entire state of the object in

memory at one time Protection Proxy

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

Page 480: SE Principles Silver Bullets

Synchronization/Protection Proxy Synchronize multiple accesses to real subject

Page 481: SE Principles Silver Bullets

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

Page 482: SE Principles Silver Bullets

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

Page 483: SE Principles Silver Bullets

Behavioral Patterns

CS 620/720

Software Engineering

February 26, 2004

Page 484: SE Principles Silver Bullets

Overview

Today: Observer Visitor Strategy (?)

Next Tuesday Finish design patterns

Strategy (?) Chain of Responsibility Command

With Faizan Javed Next Thursday:

Quiz HW 2 assigned Begin talk on formal specification

Page 485: SE Principles Silver Bullets

Observer

A key part of the MVC that we studied earlier

Page 486: SE Principles Silver Bullets

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 knowmySecretary.bookRoom(…);// let the students knowwhile (students.hasNext()) {Student s = (Student)students.next();

s.study(…);}

}

Page 487: SE Principles Silver Bullets

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…

Page 488: SE Principles Silver Bullets

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

Page 489: SE Principles Silver Bullets

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

Page 490: SE Principles Silver Bullets

Data Example

XML

Web Browser

PDACell

PhoneTerminal

Observers

Subject

xyz…

InterfaceBrowser

PDACell PhoneTerminal

Data is sent to the various observers

Page 491: SE Principles Silver Bullets

Generalized Observer Pattern

Page 492: SE Principles Silver Bullets

Observer PatternParticipants: Subject

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

Observer defines an updating interface for objects that should be notified of

changes in a Subject. ConcreteSubject

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.

Page 493: SE Principles Silver Bullets

Observer Pattern: Subscription

Page 494: SE Principles Silver Bullets

Observer Pattern: Notification

Page 495: SE Principles Silver Bullets

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

Page 496: SE Principles Silver Bullets

Observer Code

class Observer {

public:

virtual ~ Observer();

virtual void Update(Subject* theChangedSubject) = 0;

protected:

Observer();

};

Page 497: SE Principles Silver Bullets

Subject Codeclass 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); } }

Page 498: SE Principles Silver Bullets

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(); }

Page 499: SE Principles Silver Bullets

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; };

Page 500: SE Principles Silver Bullets

DigitalClock – ctor, dtor

DigitalClock::DigitalClock (ClockTimer* s) { _subject = s;

_subject->Attach(this);

}

DigitalClock::~DigitalClock () {

_subject->Detach(this);

}

Page 501: SE Principles Silver Bullets

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 }

Page 502: SE Principles Silver Bullets

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”?

Page 503: SE Principles Silver Bullets

Visitor Pattern

Page 504: SE Principles Silver Bullets

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()

AssignmentNode

TypeCheck()GenerateCode()PrettyPrint()

VariableRefNode

TypeCheck()GenerateCode()PrettyPrint()

Page 505: SE Principles Silver Bullets

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

Page 506: SE Principles Silver Bullets

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 type-

specific 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

Page 507: SE Principles Silver Bullets

Visitor Solution

NodeVisitor

VisitAssignment( AssignmentNode )VisitVariableRef( VariableRefNode )

TypeCheckingVisitor

VisitAssignment( AssignmentNode )VisitVariableRef( VariableRefNode )

CodeGeneratingVisitor

VisitAssignment( AssignmentNode )VisitVariableRef( VariableRefNode )

Node

Accept( NodeVisitor v )

VariableRefNode

Accept(NodeVisitor v){v->VisitVariableRef(this)}

AssignmentNode

Accept(NodeVisitor v){v->VisitAssignment(this)}

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

Page 508: SE Principles Silver Bullets

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

Page 509: SE Principles Silver Bullets

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

Page 510: SE Principles Silver Bullets

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 (Equipment and Card)

Page 511: SE Principles Silver Bullets

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 (CompositeEquip and Cabinet)

Page 512: SE Principles Silver Bullets

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 (abstract Visitor)

Page 513: SE Principles Silver Bullets

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 (Pricing Visitor)

Page 514: SE Principles Silver Bullets

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 (Inventory Visitor)

Page 515: SE Principles Silver Bullets

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()); }}

Visitor Example (Main)

Page 516: SE Principles Silver Bullets

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/

Another Example – Modem operations

Page 517: SE Principles Silver Bullets

USR

Modem Interface

Page 518: SE Principles Silver Bullets

visit (MOT)

Unix Configuration Visitor

Page 519: SE Principles Silver Bullets

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);

}

Interfaces

Page 520: SE Principles Silver Bullets

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;

}

Hayes Modem

Page 521: SE Principles Silver Bullets

public class UnixModemConfigurator implements ModemVisitor

{

public void visit(HayesModem m) { m.configurationString = "&s1=4&D=3"; }

public void visit(MotModem m) { m.configurationValue = 42; }

}

Unix Configuration

Page 522: SE Principles Silver Bullets

Strategy Pattern

Page 523: SE Principles Silver Bullets

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

Page 524: SE Principles Silver Bullets

Structure of the Strategy Pattern

The Strategy Pattern has three participants that include

Context, Strategy and Concrete Strategy

Page 525: SE Principles Silver Bullets

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!

This is what the Java AWT does with its LayoutManagers!

Page 526: SE Principles Silver Bullets

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

Page 527: SE Principles Silver Bullets

Sample Code implementation// Abstract Strategy class abstract class Strategy {

public abstract void RunAlgorithm(); }

// Context classclass Context { //Default Algorithm private Strategy strategy = new ConcreteStrategyA();

public void changeStrategy(Strategy newStrategy) { strategy=newStrategy; }

public void getResult() { strategy.RunAlgorithm();

} }

Page 528: SE Principles Silver Bullets

// ConcreteStrategyA class class ConcreteStrategyA extends Strategy{ public void RunAlgorithm(){

// ConcreteStrategyA implementation } }

// ConcreteStrategyB classclass 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(); }}

Sample Code implementation

Page 529: SE Principles Silver Bullets

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.

Page 530: SE Principles Silver Bullets

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.

Page 531: SE Principles Silver Bullets

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.

Page 532: SE Principles Silver Bullets

Behavioral Patterns, Part II

CS 620/720

Software Development

March 2nd, 2004

Page 533: SE Principles Silver Bullets

Overview

Finish up patterns: Strategy Chain of Responsibility Command

Thursday March 4th 2004: Petri Nets? HomeWork 2 assigned Quiz on behavioral patterns

Page 534: SE Principles Silver Bullets

Strategy Pattern

Page 535: SE Principles Silver Bullets

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

Page 536: SE Principles Silver Bullets

Structure of the Strategy Pattern

The Strategy Pattern has three participants that include

Context, Strategy and Concrete Strategy

Page 537: SE Principles Silver Bullets

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!

This is what the Java AWT does with its LayoutManagers!

Page 538: SE Principles Silver Bullets

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

Page 539: SE Principles Silver Bullets

Sample Code implementation// Abstract Strategy class abstract class Strategy {

public abstract void RunAlgorithm(); }

// Context classclass Context { //Default Algorithm private Strategy strategy = new ConcreteStrategyA();

public void changeStrategy(Strategy newStrategy) { strategy=newStrategy; }

public void getResult() { strategy.RunAlgorithm();

} }

Page 540: SE Principles Silver Bullets

// ConcreteStrategyA class class ConcreteStrategyA extends Strategy{ public void RunAlgorithm(){

// ConcreteStrategyA implementation } }

// ConcreteStrategyB classclass 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(); }}

Sample Code implementation

Page 541: SE Principles Silver Bullets

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.

Page 542: SE Principles Silver Bullets

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.

Page 543: SE Principles Silver Bullets

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.

Page 544: SE Principles Silver Bullets

Chain of Responsibility Pattern

Page 545: SE Principles Silver Bullets

Basic Aspects Intent

Decouple sender of request from its receiver by giving more than one object a chance to handle the request

Put receivers in a chain and pass the request along the chain until an object handles it

Motivation context-sensitive help

a help request is handled by one of several UI objects Which one?

depends on the context The object that initiates the request does not know the object that

will eventually provide the help Other examples?

Page 546: SE Principles Silver Bullets

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

Page 547: SE Principles Silver Bullets

Non-software Example

http://www.agcs.com/supportv2/techpapers/patterns/papers/tutnotes/sld019.htm

Page 548: SE Principles Silver Bullets

Non-software Example

Page 549: SE Principles Silver Bullets

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

Page 550: SE Principles Silver Bullets

Structure

Page 551: SE Principles Silver Bullets

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

Page 552: SE Principles Silver Bullets

The Context-Help System

Page 553: SE Principles Silver Bullets

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

Page 554: SE Principles Silver Bullets

Consequences Reduced Coupling

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.

Flexibility in assigning responsibilities to objects responsibilities can be added or changed chain can be modified at run-time

Requests can go unhandled chain may be configured improperly

Page 555: SE Principles Silver Bullets

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();

}

Page 556: SE Principles Silver Bullets

Command Pattern

Page 557: SE Principles Silver Bullets

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

Page 558: SE Principles Silver Bullets

Structure

Page 559: SE Principles Silver Bullets

Participants Command

declares the interface for executing the operation ConcreteCommand

binds a request with a concrete action Invoker

asks the command to carry out the request Receiver

knows how to perform the operations associated with carrying out a request.

Client creates a ConcreteCommand and sets its receiver

Page 560: SE Principles Silver Bullets

Collaborations

Client ConcreteCommand creates and specifies receiver

Invoker ConcreteCommand ConcreteCommand Receiver

Page 561: SE Principles Silver Bullets

Composed Commands

Page 562: SE Principles Silver Bullets

Example: Menu Callbacks

Page 563: SE Principles Silver Bullets

Consequences Decouples Invoker from Receiver Commands are first-class objects

can be manipulated and extended Composite Commands

see also Composite pattern Easy to add new commands

Invoker does not change it is Open-Closed

Potential for an excessive number of command classes

Page 564: SE Principles Silver Bullets

Intelligence of Command objects "Dumb"

delegate everything to Receiver used just to decouple Sender from Receiver

"Genius" does everything itself without delegating at all useful if no receiver exists let ConcreteCommand be independent of further classes

"Smart" find receiver dynamically

Page 565: SE Principles Silver Bullets

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

Page 566: SE Principles Silver Bullets

Command pattern: Editor with unlimited undos

Page 567: SE Principles Silver Bullets

Structuring the objects

MenuMoveCommand

RectangleEditor

UndoQueue

Invoker (Boundary objects)

ConcreteCommands(Control objects)

Receiver(Entity objects)

Triangle

Circle

Page 568: SE Principles Silver Bullets

Let’s talk about it…

How do you think undo is implemented?

Page 569: SE Principles Silver Bullets

Pattern Conclusion

….