104
MI Halfday Tutorial 6/3/2013 8:30 AM "Design Patterns Explained: From Analysis through Implementation" Presented by: Alan Shalloway Net Objectives Brought to you by: 340 Corporate Way, Suite 300, Orange Park, FL 32073 8882688770 9042780524 [email protected] www.sqe.com

Design Patterns Explained: From Analysis through Implementation

Embed Size (px)

DESCRIPTION

Alan Shalloway takes you beyond thinking of design patterns as “solutions to a problem in a context.” Patterns are really about handling variations in your problem domain while keeping code from becoming complex and difficult to maintain as the system evolves. Alan begins by describing the classic use of patterns. He shows how design patterns implement good coding practices and then explains key design patterns including Strategy, Bridge, Adapter, Façade, and Abstract Factory. In small group exercises, learn how to use patterns to create robust architectures that can readily adapt as new requirements arise. Lessons from these patterns are used to illustrate how to do domain analysis based on abstracting out commonalities in a problem domain and identifying particular variations that must be implemented. Leave with a working understanding of what design patterns are and a better way to build models of your application domains.

Citation preview

Page 1: Design Patterns Explained: From Analysis through Implementation

 

 

MI Half‐day Tutorial 6/3/2013 8:30 AM 

      

"Design Patterns Explained: From Analysis through

Implementation"    

Presented by:

Alan Shalloway Net Objectives

       

Brought to you by:  

  

340 Corporate Way, Suite 300, Orange Park, FL 32073 888‐268‐8770 ∙ 904‐278‐0524 ∙ [email protected] ∙ www.sqe.com

Page 2: Design Patterns Explained: From Analysis through Implementation

Alan Shalloway Net Objectives

With more than forty years of experience, the founder and CEO of Net Objectives Alan Shalloway is an industry thought leader in lean, kanban, product portfolio management, Scrum, and agile design. Alan helps companies transition enterprise-wide to lean and agile methods, and teach courses in these areas. He is the primary author of Lean-Agile Software Development: Achieving Enterprise Agility, Design Patterns Explained, Lean-Agile Pocket Guide for Scrum Teams, and Essential Skills for the Agile Developer. Cofounder and board member for the Lean Software and Systems Consortium, Alan is a popular speaker at prestigious conferences worldwide.  

Page 3: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

1

copyright © 2010 Net Objectives Inc.

Design Patterns

ExplainedAnalysis to Implementation

Al Shalloway, CEO

Net Objectives

Page 4: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

2

Lean Enterprise

Business

Management

Team

ASSESSMENTS

CONSULTING

TRAINING

COACHING

Lean Management

Project ManagementLean-Agile

Kanban / Scrum

ATDD / TDD / Design Patterns

technical process

Lean for Executives

Product Portfolio Management

Business Product Owner

Scaled Agile Framework

Purpose of This Tutorial

– Provide an innovative look at Design Patterns

– Incorporates:

Object-Oriented Principles

– a “new” way to look at object-oriented design

– a better way to identify and define our entities

The general design advice patterns represent

– Consider how domain analysis can enhance design

– Consider the difference between

Knowing Patterns

Being “Pattern-Oriented”

Page 5: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

3

What Tutorial Covers

– Basic object-oriented principles

Encapsulation

Polymorphism

Inheritance – What to use it for

General Advice from the “Gang of Four”

– Design patterns – what they really are

– Learn why design patterns are good designs

– Learn how to use design patterns together

When Adding Functionality –

Where’s the Problem?

In writing the new code?

In integrating it into the new system?

Which is likely to be the source of difficulties?

Why?

Page 6: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

4

In a Nutshell

How can we design to accommodate change?

We are not trying to anticipate change, per se, as much

as writing our code to accommodate change better

– Trying to anticipate change can lead to “paralysis by analysis”

Designing from context will guide us as to when we

need to get the details. It also gives us the bigger

picture from within which to design

copyright © 2010 Net Objectives Inc.

Design Patterns

Page 7: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

5

What Are Patterns?

Patterns are best-practice solutions for recurring problems in a particular context.

Patterns have been classified as being:*– Architectural

– Design

– Idiomatic

Design patterns can also be thought of as describing the relationships between the entities (objects) in our problem domain.

Patterns have led to new modeling techniques:

– handling variations in behavior

– new ways of using inheritance to avoid rigidity and aid testing and maintenance issues.

* Pattern Oriented Software Architecture, Buschmann, et. al.

Drawer

Front Top

Please Don’t Turn the Page Until Instructed to Do So

Page 8: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

6

A Pattern in Carpentry

Let’s say two carpenters are trying to decide on how to

build a dresser.

One says to the other: “should we build the joint by

first cutting down, then cutting up at a 45 degree

angle...”

“then back down and back up

the other way, then back down”

Dove-Tail

Tails and Pins

Reliable

Strong

Humidity Tolerant

Page 9: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

7

A Miter Joint

Commonly used in picture frames.

Patterns Work At All Levels

Dovetail Miter

Forces Strong, High-Cost, Decorative, Humidity Tolerant

Weak, Cheap, Fast, Good for Picture Frames

Design Interlaced joint Single Abutting Cut

Implementation Cut teeth, .5" long, .4" deep, match teeth to gaps

45 degree angle cut attached with staple or other spanning connector

Page 10: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

8

Focusing on Detail

Loses the Big Picture

By having to describe how we implement the dove-tail

joint, we can lose sight of why we might want to use it

in the first place.

Dove-tail Joint vs. Miter Joint emphasizes:

– do we want a strong, relatively expensive joint that is of high

quality and will last forever

– or do we want a weak, relatively inexpensive joint that is easy

to make but not of high quality

The Different Perspectives

Conceptual

– describes what you want, not how you’ll get it

– requirements are often specified at a conceptual level

– “we need to handle inventory in LIFO, FIFO, avg cost”

Specification

– the interfaces of our classes

– how objects “talk” to each other

– our product class’ methods look like …

Implementation

– the code itself

Page 11: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

9

Consider These

Mop Broom Sponge

Are they the same

or different?

Same or Different?

Who thinks they are the same?

Who thinks they are different?

Page 12: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

10

As Any Good Consultant Will Tell

You: “IT DEPENDS!”

As specific objects: they are different

As a concept: they are all Cleaning Utensils

Where does “Cleaning Utensil”

exist?

Not in the real world, but in our thoughts as an

abstraction classification!

A “Cleaning Utensil” does not exist, but specific kinds do!

Page 13: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

11

Three Levels of Perspective*

Conceptual Perspective

Specification Perspective

Implementation Perspective

* From Martin Fowler’s UML Distilled

A Note About Encapsulation

We often think of encapsulation as something we do at the object level (i.e., hide its data).

On reflection, however, we can see that we have used encapsulation to hide a set of classes (all the derived classes).

Abstract classes and interfaces essentially encapsulate all of their derivations and implementations -- no one need know they exist.

Encapsulation can be used to contain rules - good idea to put one rule in one place

Page 14: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

12

Commonality-Variability Analysis

James Coplien’s “Multi-paradigm Design for C++”

– “Abstraction, in the common English language sense, means

to focus on the general and put aside the specific. We

abstract by emphasizing what is common and de-emphasizing

details. Abstraction is a fundamental analysis tool.”

His thesis is on line at:http://www.netobjectives.com/files/CoplienThesis.pdf(link is case-sensitive)

Commonalities

“Commonality analysis is the search for common

elements that helps us understand how family members

are the same” *

Commonalities are

– Recognized from experience

– Learned through analysis (abstracted)

Commonalities can define basic concepts in a domain

* Multi-Paradigm Design in C++, Jim Coplien

Page 15: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

13

Variability Analysis

Variability makes sense only in a given commonality

frame of reference. It is a variation of some

commonality

– “From an architectural perspective, commonality analysis

gives the architecture its longevity; variability analysis drives

its fitness for use”*

* Multi-Paradigm Design in C++, Jim Coplien

Reasons to Get Variations of Commonalities

In analysis, we don’t need detailed design, we just need

to determine:

– The resources required for implementation

– The risks involved

Define scope (variations give us specific cases)

Make sure variations define commonalities (do we have

enough cases to define the interface?)

~3

Page 16: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

14

copyright © 2010 Net Objectives Inc.

Example Problem

The Problem

We are writing a web-enabled sales order system

A customer signs in and fills out the order

Page 17: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

15

Initial Solution

Have TaskController instantiate SalesOrder that

handles filling out the sales order, etc.

TaskController

SalesOrder

The Challenge

As soon as we get new variations in tax we have to

modify our SalesOrder object

Where should we add the new responsibility if taxation

begins to vary?

Page 18: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

16

New Requirement -

Multiple Tax Domains

One Solution

method calcTax

// use switch on type of tax rule to be used

// TYPE US:

// calc tax based on US rules

// break

// TYPE CANADIAN:

// calc tax based on Canadian rules

// break

Eventually need to handle different tax rules

•US Tax

•Canadian Tax

Direct Inheritance for Specialization

We can solve this problem by specializing our first SalesOrder object to handle the new tax rules

new (overriden) calcTaxthat does Canadian tax

TaskController

SalesOrder+ calcTax()

CanadianSalesOrder+ calcTax()

original calcTax that does US tax

Page 19: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

17

Abstract Inheritance for

Specialization

This is a bit better…

SalesOrder+ calcTax()

CanadianSalesOrder+ calcTax()

USSalesOrder+ calcTax()

This May Lead to Maintenance Problems

If we get new variations, where do we put them?

We either start using lots of switches (which makes the

code difficult to understand), or we start over-

specializing (which still makes things difficult)

What if we need to switch tax algorithms at runtime?

SalesOrder+ calcTax()

CanadianSalesOrder+ calcTax()

USSalesOrder+ calcTax()

EnglishCanadianSO+ language()

FrenchCanadianSOlanguage()

Page 20: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

18

copyright © 2010 Net Objectives Inc.

Advice From the

Gang of Four

Advice from the Gang of Four

Design to interfaces

Favor object delegation over class

inheritance

Consider what varies in your design …

and “encapsulate the concept that varies”

Gamma, Helms, Johnson, Vlissides: Design Patterns: Elements of Reusable Object-Oriented Design

Page 21: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

19

Design to Interfaces: Methods

Craft method signatures from the

perspective of the consuming entities

Hides the implementation of your methods

Programming by intention is a systematized

way of designing to interfaces

Design to Interfaces

AbstractionA

Impl1 Impl2 Impl3

AbstractionB

Impl4 Impl5

Relationship

Relationship

1→1 or 1→many

Page 22: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

20

Favor delegation over inheritance

specializing function with inheritance is a

short path to problems

Proper use of inheritance

Define a class that encapsulates variation,

contain (via delegation) an instance of a concrete class

derived from the abstract class defined earlier

Chip

1. Decoupling of concepts

2. Deferring decisions until runtime

3. Small performance hit

Chip_64e Chip_128e

Encryption

64e 128e

Chip

Class Inheritance to SpecializeClass Inheritance to Categorize

Page 23: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

21

Find what varies

and encapsulate it

Base classes encapsulate their implementing subclasses

This encapsulates varying behavior

Encryption

64 128

Chip

Find what varies and encapsulate it

A varying anything:

– Varying design

– Varying object creation

– Varying relationships (1-1, 1-many)

– Varying sequences and workflows

– Etc…

Page 24: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

22

Encapsulate variations

Encapsulating variation means to make it appear as if the

varying issue is not varying

Each pattern encapsulates a different varying thing

The Net Objectives

Patterns Repository

Behavior Strategy Bridge Template Method Null Object

Sequence DecoratorChain of Responsibility

Template Method __

Workflow Template Method Visitor Bridge Null Object

Cardinality DecoratorChain of Responsibility

Proxy Observer

Construction Singleton Abstract Factory __ __

SelectionChain of Responsibility

__ __ __

Structure Composite Template Method __ __

Entity Facade Adapter Proxy __

Relationships Observer Command Mediator Visitor

Dependencies Mock Object __ __ __

Page 25: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

23

This Advice Relates to Principles

Deal with things at an abstract level

Why?

Impl4

AbstractionA

Impl1 Impl2 Impl3

Client

Relates to: The Open-Closed Principle

This Advice Promotes Quality

Design to Interfaces:– Helps eliminate redundant relationships

– Avoids subclass coupling

Encapsulate Variation– Promotes encapsulation

– Decouples client objects from the services they use

– Leads to component-based architectures

Favor aggregation over inheritance– Promotes strong cohesion

– Helps eliminate redundant implementation

Page 26: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

24

At First Level of Understanding

Design Patterns Are Examples

Each pattern is an example of a design that follows this general advice well, in a given context

Design patterns are discovered, not invented: they are what successful design have done to solve the same problem

Studying design patterns is a good way to study good design, and how it plays out under various circumstances

copyright © 2010 Net Objectives Inc.

The Strategy Pattern

Page 27: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

25

The Strategy Pattern

We need different behavior at different times; either

for different things we are working on or for different

clients asking us to do work.

GoF Intent: Define a family of algorithms, encapsulate

each one, and make them interchangeable. Strategy

lets the algorithm vary independently from clients that

use it. *

Design Patterns: Elements of Reusable Object-Oriented Software by Gamma, Helm, Johnson, Vlissides. Addison-Wesley Professional. 1995.

The Strategy Pattern

The Strategy pattern is a pattern that tells us how to

identify a set of rules that conceptually do the same

thing

In our example: tax

– identify a common way to communicate with all

implementations of the rule

– define an interface or abstract class that defines this

communication

– implement each variation of the rule as an implementation or

derivation

Page 28: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

26

Strategy Lives in Analysis,

Design, Implementation

In analysis:

– Any time we find a varying business rule, it is likely a Strategy

pattern is present

– If we know we need to use a Strategy, the pattern tells us to

encapsulate the varying rule behind an interface

During implementation

– The pattern gives “instant experience” in the implications of

one implementation over another

The pattern is really about the relationship between

one object that uses one of several conceptually similar

rules

In The UML

USTax CanTax

TaskController

CalcTax

+ taxAmount(itemSold : Salable, qty : double, price : double) : double

SalesOrder

Page 29: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

27

The Canonical Strategy Pattern

StrategyA+ algorithm()

StrategyB+ algorithm()

Context+ request(Strategy)

Strategy+ algorithm()

Client

Strategy as an Example

of GoF Approach

(1) find what varies (the strategies) and

(2) encapsulate it (Strategy)

(3) favor object-aggregation over class-inheritance

(1)

(2) encapsulates variation

(3)

(1)

StrategyA+ algorithm()

StrategyB+ algorithm()

Context+ request(Strategy)

Strategy+ algorithm()

Client

Page 30: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

28

Who Knows Which Rule to Use

Before, TaskController needed to know either the

value of the tax switch to set or which SalesOrder to

instantiate

It can now instantiate the appropriate CalcTax object

OR, we can have a creational object (factory) make the

proper CalcTax object

Another Version of the Strategy Pattern

StrategyA+ algorithm()

StrategyB+ algorithm()

Context

+ request(Strategy)

Strategy+ algorithm()

Client

Factory

*

1

Page 31: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

29

What Happens Now

With Changing Requirements

If we get a new tax requirement, we :

1. Derive the new class from the CalcTax class

2. Modify the TaskController or the Factory object

Which may, in fact, work with a data dictionary so even it

doesn’t need to change

No other objects change

Value of Strategy

Conceptually it is cleaner

Each object is concerned with one function

Better independence of different actions

Issues that are separated into different encapsulated

entities also makes unit testing easier

Page 32: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

30

Why Bother?

What happens if many things vary?

In other words, in addition to the tax rules, we could

have the following variations?

– different shipping charges

– different monetary rules

– different address rules

Switches and direct inheritance do not scale

copyright © 2010 Net Objectives Inc.

Code Qualities

Where Good Design Begins

What Good Design Reflects

Why Patterns are What they Are

Page 33: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

31

Qualities

Consider a string of Christmas lights

What do you do if it fails…

– On the Table?

– On the Tree?

Is this a complex device?

It’s not so much the complexity as it is the:

– Dependencies

– Fragility

– Duplication

Predictability

We can’t predict how our requirements are going to

change

We can predict how different coding styles will adapt

to unpredictable requirements changes

What is the style that adapts more readily?

Page 34: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

32

Another One:

Who Thinks We Spend a lot of Time Fixing Bugs?

The Time on Bugs Myth

We usually spend very little time fixing bugs…

We OFTEN spend a lot of time finding bugs and in the

discovery process of seeing how things affect each

other

We should therefore put our efforts more into finding

errors when they occur than worrying about the

amount of typing we do

Page 35: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

33

Many Factors to Consider

What are the first principles?

Cohesion

Cohesion refers to how “closely the operations in a routine [or class] are related.” I have heard other people refer to cohesion as “clarity” because the more operations are related in a routine [or class] the easier it is to understand the code and what it's intended to do. *

Strong cohesion is related to clarity and understanding

No "schizophrenic classes”

No "12-page methods"

* Code Complete, Steve McConnell, 1993, p. 81. This concept was first described by Larry Constantine in 1975, but we like McConnell’s definition best.

Page 36: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

34

Strong Cohesion

Class Cohesion – A class has a single responsibility

– Practice: Commonality/Variability Analysis (tomorrow)

Method Cohesion – Each method is a single function

– Practice: Programming by Intention (next slide)

Coupling

Coupling refers “to the strength of a connection between two routines [or classes]. Coupling is a complement to cohesion. Cohesion describes how strongly the internal contents of a routine [or class] are related to each other. Coupling describes how strongly a routine is related to other routines. The goal is to create routines [and classes] with internal integrity (strong cohesion) and small, direct, visible, and flexible relations to other routines [and classes] (loose coupling).”*

Tight coupling is related to highly interconnected code

* Code Complete, Steve McConnell, 1993, p. 81. This concept was first described by Larry Constantine in 1975, but we like McConnell’s definition best.

Page 37: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

35

No Redundancy

"One Rule in One Place"

Good example of violating this: – Y2K

Redundancy is not just:– Redundant state

– Redundant functions

It can also be redundant relationships, design, construction, etc…

_______ = new Connection(url);

Anything that you would have to change in more than one place

_______ = new Connection(url, port);

Encapsulation and Other Qualities

Encapsulation and Coupling

– Hidden things cannot be coupled to

Encapsulation and Cohesion?

– Cohesive issues are easier to hide

Encapsulation and Redundancy?

– When an issue is hidden, multiple clients cannot make use of

the same behavior

– When it’s revealed, then no duplication is needed

– It's an issue of balance

Page 38: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

36

Encapsulation, Coupling, and Redundancy

Class A

-Redundant Issue

Class B

-Redundant Issue

Class A and Class B have a redundant bit of

state or functionality, or a redundant

relationship to another object

The redundant issue is currently

encapsulated, however

How can we resolve this redundancy?

It Depends!

…on the relationship between these classes

Is it:

– Conceptual? Are classes A and B variations of some

common concept?

or

– A relationship of consistent use? Are classes A and B two

distinct entities that have a need that can be resolved in a

common way?

Class A

-Redundant Issue

Class B

-Redundant Issue

Page 39: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

37

Using Inheritance

Class A Class B

We could use Inheritance. So long as we

don't mind coupling these classes to a

superclass, this resolves the redundancy

while keeping the Issue encapsulated

SuperClass

#Redundant Issue

Still encapsulated from other objects

Conceptual

Concrete

Using Delegation

Class A

Class B

We could use Delegation. This exposes the “Redundant issue” as the interface of the service class (Class C). However, remember, the rule is “encapsulate by policy, reveal by need”. Eliminating redundancy is a definite need.

Class C

+Redundant Issue

Must be public for Class A and Class B to use it

Page 40: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

38

Patterns Promote Quality

StrategyA+ algorithm()

StrategyB+ algorithm()

Context

+ request(Strategy)

Strategy+ algorithm()

Client

Factory

Cohesion: Each class is focused on a single responsibilityCoupling: Base Strategy hides concrete typesRedundancy : Anything common pushed into the base classEncapsulation: Factory hides types, design, implementation

How the GoF Advice Promotes Quality

Design to Interfaces:Helps eliminate redundant relationships

Avoids subclass coupling

Encapsulate VariationPromotes encapsulation

Decouples client objects from the services they use

Leads to component-based architectures

Favor aggregation over inheritancePromotes strong cohesion

Helps eliminate redundancies

Makes designs more dynamic

Page 41: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

39

copyright © 2010 Net Objectives Inc.

Testability and

Design

Testability and Design

Considering how to test your objects before designing

them is, in fact, a kind of design

It forces you to look at:

– The public method definitions

– What the responsibilities of the object are

Easy testability is tightly correlated to loose coupling

and strong cohesion

Page 42: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

40

Testability

Code that is difficult to unit test is often:

– Tightly Coupled: "I cannot test this without

instantiating half the system"

– Weakly Cohesive: "This class does so many things,

the test will be enormous and complex!"

– Redundant: "I'll have to test this in multiple places to

ensure it works everywhere"

The Role of Testability

Unit testing is a good thing. You should do it

Whether you agree or not

– You should always ask yourself "if I were to test this, how

would I do it?"

– If you find the design would be very hard to test, or if you

cannot see a way to test it, ask yourself "why isn't this more

testable?"

This is a thought process that can capture coupling,

cohesion, and redundancy issues that you might

otherwise miss

Page 43: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

41

Trim Tabs

"If you try to change the course of a supertanker by

pushing at the bow you will not see any change. If you

push on the rudder your chances of changing the

course of the supertanker are guaranteed, but the

amount of energy needed is still prohibitive. To be the

most effective we need to push on the trim tabs, those

small fins on the end of the rudder, by moving them,

the rudder in turn moves and the tanker makes its

turn.”

R. Buckminster Fuller

"Critical Path"

~3

Testable?

StrategyA+ algorithm()

StrategyB+ algorithm()

Context

+ request(Strategy)

Strategy+ algorithm()

Client

Factory

MockStrgy+ algorithm()

Page 44: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

42

“Design” Patterns

Patterns are not just about “Design”

They are used in

– Architecture

– Design

– Testing

– Deployment

– Refactoring

– …and analysis

copyright © 2010 Net Objectives Inc.

The Analysis Matrix

Page 45: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

43

Motivation

Information overload

– Too much information

– Chaotically arranged

– Not sure how to organize it

– Not sure how to begin

Motivation Example

Designing a document control system that includes documents from:

– All airlines

– Most manufacturers Boeing, McDonnell Douglas

Pratt & Whitney, Rolls Royce, GE

– About 100 cases all told

– Documents are conceptually the same Collection of text and graphics

Version control required

Page 46: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

44

Example Requirements

~s

11-1

1-2

1-3

aa

a

11a

1b

1c

-1-1

-1

-1

Boeing Rolls-Royce

Handling Variation: A Case Study

Let’s say we’ve been given these requirements:

We have to build a sales order system for Canada and

the United States. We want to calculate freight based

on the country we’re in. Money will also be handled by

the country we are in. In the US, tax will be calculated

by the locale. Use US and Canadian Postal rules for

verifying addresses. In Canada, use GST and PST for

tax. Use Canadian shipper

Page 47: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

45

Break Requirements into Cases

Distilling the requirements into cases:

– CASE 1: USA Customer

Calculate freight based on UPS charges, use US Postal rules for

verifying addresses and calculate tax based on sales and/or services

depending upon locale. Handle money in US $.

– CASE 2: Canadian Customer

Use Canadian $. Use Canadian Postal rules. Use Canadian shipper

and calculate tax based on GST and PST.

How to Start the Design

We want to find what varies and encapsulate it

Each column represents a given case

Each row is used to represent the concept that case is an example of

We can start with a single requirement, and build this as we go. This can be much easier to manage

Page 48: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

46

Start with One

In the US, we calculate freight based on UPS charges

US Sales

calculate freight use UPS rates

Requirement (concept) One way to do it, in one case

Continue…

In the US, we use US Postal rules for verifying addresses

US Sales

calculate freight use UPS rates

verify address use US Postal rules

Different Concept Same Case

Page 49: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

47

Continue…

In the US, we calculate tax based on sales and/or services

depending upon locale

In the US we Handle money in US$

US Sales

calculate freight use UPS rates

verify address use US Postal rules

calculate tax use state and local

taxes

money US $

More Concepts More Implementations

for this Case

Handle Canadian Case

US Sales Canadian Sales

calculate freight use UPS rates

verify address use US Postal rules

calculate tax use state and local

taxes

money US $

Existing Concept New Case

In Canada we Use Canadian$

Canadian $

Page 50: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

48

Next Canadian Case

US Sales Canadian Sales

calculate freight use UPS rates

verify address use US Postal rules

calculate tax use state and local

taxes

money US $

Canadian $

Existing Concept Same Case

In Canada we use Canadian Postal rules.

Canadian Postal Rules

All Cases Handled

US Sales Canadian Sales

calculate freight use UPS rates use Canadian

shipper

verify address use US Postal rules use Canadian Postal

rules

calculate tax use state and local

taxes

use GST and PST

money US $ Canadian $

In Canada we use a Canadian shipper

In Canada we calculate tax based on GST and PST

“That’s all I can think of, so I guess that’s it”

Page 51: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

49

A Note about Customers

They usually know their problem domains very well

They often use the term “All” for “the most common

cases”

“Always” means “usually”, or “we always have”

“Never” means “seldom”, or “we never have”

The German Case

CASE 3: German Customer

– Use a German shipper, which has a maximum weight of 30

kilograms. Use Value Added Tax for taxes, European postal

rules, and the dd/mm/yy date format. Currency used will be

the Euro

Page 52: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

50

New Case: German Sales

US Sales Canadian Sales German Sales

calculate freight use UPS rates use Canadian

shipper

use German

shipper

verify address use US Postal

rules

use Canadian

Postal rules

use European

Postal rules

calculate tax use state and local

taxes

use GST and PST use VAT

money US $ Canadian $ Euro

date format mm/dd/yyyy dd/mm/yyyy dd/mm/yyyy

max weight 30 kg

Are there maximum weights in US and Canada? Maybe not. Maybe so, and the customer forgot to mention them

Now I have a good, specific question to ask

My customers are good at answering specific questions

Can Check Our Understanding

US Sales Canadian Sales German Sales

calculate freight use UPS rates use Canadian

shipper

use German

shipper

verify address use US Postal

rules

use Canadian

Postal rules

use European

Postal rules

calculate tax use state and local

taxes

use GST and PST use German VAT

money US $ Canadian $ Euro

date format mm/dd/yyyy dd/mm/yyyy dd/mm/yyyy

max weight 70 lbs none 30 kg

"Sometimes yes, sometimes no…"

Page 53: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

51

Does Get More Complicated

Imagine there is a more complicated relationship between two concepts (say between calculating freight and address verification) in the US but not in the other cases

Sometimes we can do a “drill down” to capture the extra complexity, when it is not needed in all cases

Use Mini-Matrix for Complex Cases

Calculate freight Use USPS Use UPS Use FedEx

Verify Address Use US

Postal

Rules

Use US Postal

Rules no PO

Boxes

Use US Postal

Rules

Pick-up charge N/A $5.00 $4.00

Max weight 50 lbs 70 lbs No maximum

US Sales Canadian Sales

calculate freight use UPS rates use Canadian

shipper

verify address use US Postal rules use Canadian Postal

rules

calculate tax use state and local

taxes

use GST and PST

money US $ Canadian $

Page 54: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

52

Do Not Really Need Table

Calculate Freight

– UPS Rates

– USPS Rates

– FedEx Rates

Verify Address

– US Postal rules

– US Postal rules with no PO

Boxes

Pick-up Charge

– none

– $5.00

– $4.00

Max Weight

– 50 lbs

– 70 lbs

– No maximum

~3

How to Use the Analysis Matrix

Note how each column in the analysis matrix

represents one particular case. In our case, this

represents one country

Each Row is a concept that cuts across all cases

Each entry can be thought of as an object

Page 55: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

53

Thinking of Elements as Objects

US Sales Canadian Sales German Sales

calculate

freight

USCalcFreight CanCalcFreight GermCalcFreight

verify

address

USAddrRules CanAddrRules GermanAddrRules

calculate tax USCalcTax CanCalcTax GermanCalcTax

money USMoney CanMoney GermanMoney

date format Date_mmddyy Date_ddmmyy Date_ddmmyy

max weight USMaxWght CanMaxWght GermanMaxWght

How to Use the Analysis Matrix

Each row represents different ways a rule may be implemented across all of the cases

This sounds quite a bit like a Strategy pattern

– At least at this level

It can be implemented as such

How do we handle the instantiation of the appropriate strategy objects?

Page 56: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

54

Using the Strategy Pattern

US Sales Canadian Sales German Sales

calculate

freight

verify address

calculate tax

money

date format

max weight

The objects in this row can be implemented as a Strategy pattern encapsulating the “calculate freight” rule.

The objects in this row can be implemented as a Strategy pattern encapsulating the “verify address” rule.

The objects in this row can be implemented as a Strategy pattern encapsulating the “calculate tax” rule.

We can use Money objects that can contain Currency and Amount fields that automatically convert as needed..

We can use Date objects that can display as required for the country the customer is in.

The objects in this row can be implemented as a Strategy pattern encapsulating the “max weight” rule.

Concrete Implementation Rules: Columns

US Sales Canadian Sales German Sales

calculate

freight

verify address

calculate tax

money

date format

max weight Th

ese

imp

lem

enta

tion

s ar

e u

sed

wh

en w

e

hav

e a

US

cu

stom

er.

Th

ese

imp

lem

enta

tion

s ar

e u

sed

wh

en w

e

hav

e a

Can

adia

n c

ust

om

er.

Th

ese

imp

lem

enta

tion

s ar

e u

sed

wh

en w

e

hav

e a

Ger

man

cust

om

er.

Page 57: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

55

How Sales Order Will Work

CalcTax

+taxAmount():double

USTax CanTax GermanTax

AddressRules

+validate():boolean

USAddr CanAddr GermanAddrCalcFreight

+rate():double

USFreight CanFreight GermanFreight

TaskController SalesOrder

...and then, a miracle occurs

How Can We Control Instantiation?

We have two issues to deal with:1. Using the desired objects in a de-coupled way

2. Instantiating the correct set

To instantiate the correct set we need a way to instantiate a “family” of objects

We can see the "sets" now, in our design, which gives us a motivation in how we create them

Which object factory does that?

Page 58: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

56

copyright © 2010 Net Objectives Inc.

The Abstract Factory

The Abstract Factory Pattern

We need to create families of objects for particular

situations. That is, particular clients need particular

sets of instantiations

GoF Intent: Provide an interface [a set of methods] for

creating families of related or dependent objects

without specifying their concrete classes*

*Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides

Page 59: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

57

The Abstract Factory Pattern

The Abstract Factory pattern gives us a way to

instantiate the legitimate a set of objects corresponding

to a particular case

It will build the allowable combinations only

…but it also encapsulates something else…

The “Cases” are hidden

...Canada

Case

US Case

t

e

nt

I

e

ac

rf a c

o

F

yr

Here, we hide “country”. The notion only appears in the factory.

What’s the advantage?

Page 60: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

58

Classes of the Abstract Factory

The "Abstract Factory"

Why is this pattern called "The Abstract Factory"?

Page 61: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

59

Using the Abstract Factory

US Sales Canadian Sales German Sales

calculate

freight

verify address

calculate tax

money

date format

max weight

Thes

e obje

cts

can b

e co

ord

inat

ed w

ith t

he

use

of

the

Abst

ract

Fac

tory

pat

tern

.

T T

hes

e obje

cts

can b

e co

ord

inat

ed w

ith

the

use

of

the

Abst

ract

Fac

tory

pat

tern

.

Thes

e obje

cts

can b

e co

ord

inat

ed w

ith t

he

use

of

the

Abst

ract

Fac

tory

pat

tern

.

Abstractions

The Abstract Factory in Action

Page 62: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

60

The Abstract Factory in Action

The Abstract Factory in Action

Page 63: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

61

The Abstract Factory in Action

The US Case: Sequence Diagram

Page 64: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

62

The Canada Case: Sequence Diagram

Implementation of Factories

abstract class AbstractFactory {

abstract CalcTax MakeCalcTax();

abstract CalcFreight MakeCalcFreight();

abstract AddressRules MakeAddrRules();

public static AbstractFactory

GetAFtoUse(customerID){

// Decide whether to return

// instance of USAF CanAF

}

}

class USAF : AbstractFactory {

public override CalcTax MakeCalcTax() {

return new USTax();

}

public override CalcFreight

MakeCalcFreight() {

return new USFreight();

}

public override AddressRules

MakeAddrRules() {

return new USAddr();

} }

class CanAF : AbstractFactory {

public override CalcTax MakeCalcTax() {

return new CanTax();

}

public override CalcFreight

MakeCalcFreight() {

return new CanFreight();

}

public override AddressRules

MakeAddrRules() {

return new CanAddr();

}

}

class SalesOrder {

private CalcTax myTax;

private CalcFreight myFreight;

private AddressRules myAddr;

public SalesOrder (AbstractFactory myAF) {

myTax= myAF.MakeCalcTax();

myFreight= myAF.MakeCalcFreight();

myAddr= myAF.MakeAddrRules();

}

}

C#

Page 65: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

63

C# Interfaces

interface CalcTax {

public double CalcTax (double qty, int id);

}

interface AddressRules {

public bool Verify (Address myAddress);

}

interface CalcFreight {

public double CalcFreight (

string fromCode,

string toCode,

string frghtClass,

double weight);

}

C#

Putting It Together

// In the tier controller, or similar

AbstractFactory myAF = AbstractFactory. getAFtoUse( customerID);

mySalesorder = new SalesOrder( myAF);

// mySalesorder is now set up to use the correct strategies, etc.

C#

Page 66: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

64

What Variations Can Occur?

What if we add a new country

– Uses existing variations (France uses Euro) New Factory for France

Use existing Euro object

– Has a new implementation of a concept (no VAT in Italy) New Factory for Italy

New "ItalyTax" object

– Have a new requirement for UK only Certain products (pharmaceuticals) pay no tax if over 65

How can you avoid changing the interface of calcTax?

– Introduces a brand new concept (China!) Trade Restrictions in China

Everything will have to be maintained

Vulnerability

In design, our greatest vulnerability is often:

A wrong or missing abstraction

Page 67: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

65

A Note on the Abstract Factory

The Abstract Factory Pattern says to define an interface for the instantiation of objects

In practice, there are several ways to implement an Abstract Factory

Abstract Factory Variations

1. Extend an abstract type

2. Make a concrete factory object where each creation method contains a switch (based on a common variable: nationality)

3. Make a concrete factory object that is driven from a configuration file

4. Use run-time class loading driven by a database

Page 68: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

66

Single Object with Switch

// do same for each method

CalcTax makeCalcTax (string ID) {

optionNum= Config.getCalcTaxOption(ID);

switch (optionNum) {

case option1:

return new CalcTax1();

case option2:

return new CalcTax2();

. . .

}

}

// do same for each method

C#

~3

Single Object with Database

CalcTax makeCalcTax (string ID) {

string record[];

record= Database.getRecord( ID);

string classToInstantiate;

classToInstantiate= record[CALC_TAX]; // CALC_TAX

// holds column #

//instantiate the object

//classToInstantiate needs to be in Namespace.class format

CalcTax myCalcTax = (CalcTax)

Activator.CreateInstance(Type.GetType(classToInstantiate));

}

C#

~3

Page 69: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

67

copyright © 2010 Net Objectives Inc.

The Adapter Pattern

The Adapter Pattern

We need to change the interface of a class that has the

right stuff but has the wrong interface

GoF Intent: Convert the interface of a class into

another interface clients expect. Adapter lets classes

work together that couldn’t otherwise because of

incompatible interfaces*

*Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides

Page 70: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

68

Our Problem

Shape

+ setLocation()

+ getLocation()

+ display()

+ fill()

+ setColor()

+ undisplay()

Point

+ display()

+ fill()

+ undisplay()

Line

+ display()

+ fill()

+ undisplay()

Square

+ display()

+ fill()

+ undisplay()

What We Have

XX_Circle

+ set_location()

+ get_location()

+ display_it()

+ fill_it()

+ set_its_color()

+ undisplay_it()

Page 71: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

69

What We Want

XX_Circle to behave like a Shape to a Client object

Unfortunately, we cannot get polymorphism with

XX_Circle:

Shape

XX_CIRCLE

=

Our Problem

Our client can’t behave with our XX_Circle in the

same way it does with the Square because XX_Circle is

not a Shape

Author of XX_Circle may not be willing or able to

change XX_Circle’s interface

Page 72: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

70

How to Implement the Pattern

Shape

+ setLocation()

+ getLocation()

+ display()

+ fill()

+ setColor()

+ undisplay()

Point

+ display()

+ fill()

+ undisplay()

Line

+ display()

+ fill()

+ undisplay()

Square

+ display()

+ fill()

+ undisplay()

XX_Circle

+ set_location()

+ get_location()

+ display_it()+ fill_it()

+ set_its_color()

+ undisplay_it()

Circle

+ display()

+ fill()

+ getLocation()+ setLocation()

+ setColor()

+ undisplay()

If circle contained an XX_circle, it could handle the "communication’ with the client and let XX_circle handle the work

Example

class Circle : Shape {

private XX_circle pxc;

public Circle () {

pxc= new XX_circle();

}

public void override display() {

pxc.display_it();

}

}

C#

Page 73: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

71

General Approach

If we want a client object to work with objects from

two other classes we are writing in the same way

without "knowing" which one it has, then either:

– We create an Interface (if we’re in Java or C#) or an abstract

class

– And have each class implement/derive from the

interface/abstract class

If we are using objects from two classes, then we may

need to adapt one or both of them

This is also called "wrapping“ – but the more specific

terms is preferred (decorators, proxies, and façades are

also called “wrappers”)

copyright © 2010 Net Objectives Inc.

The Bridge Pattern

Page 74: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

72

The Bridge Pattern

GoF Intent: De-couple an abstraction from its implementation so

that the two can vary independently *

The normal reaction to reading this is:

“Huh?"

Mine was:

“How come I understand every word in this sentence but I have

no idea what it means?”

*Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides

Rectangle Drawing Program

Page 75: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

73

Code Example

abstract class Rectangle {private int _x1, _y1, _x2, _y2;void public Draw () {

DrawLine(_x1,_y1,_x2,_y1);DrawLine(_x2,_y1,_x2,_y2);DrawLine(_x2,_y2,_x1,_y2);DrawLine(_x2,_y1,_x1,_y1);

}abstract void DrawLine( double x1, double y1,

double x2, double y2);}

class V1Rectangle : Rectangle {void override DrawLine( double x1, double y1,

double x2, double y2) {DP1.draw_a_line( x1,y1,x2,y2);

}}

class V2Rectangle : Rectangle {void override DrawLine(double x1, double y1,

double x2, double y2) {DP2.drawline( x1,x2,y1,y2);

}}

C#

Get New Requirements

Told we must now handle Circles

We decide to handle it in a similar way

Make a V1Circle class and a V2Circle class

Decouple the client from the specific shapes by deriving

them from a common base class

Page 76: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

74

Handling New Shape Class

Handling New Shape Class

Page 77: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

75

Code Example

abstract class Shape {

public abstract void draw();

}

abstract class Rectangle : Shape {

private int _x1, _y1, _x2, _y2;

public override void draw() {

drawLine(_x1, _y1, _x2, _y1);

drawLine(_x2, _y1, _x2, _y1);

drawLine(_x2, _y2, _x1, _y2);

drawLine(_x1, _y2, _x1, _y1);

}

abstract void drawLine(

double x1, double y1,

double x2, double y2);

} }

class V1Rectangle : Rectangle {

public override void drawLine(

double x1, double y1,

double x2, double y2){

DP1.draw_a_line(x1,y1,

x2, y2);

}

}

class V2Rectangle : Rectangle {

public override void drawLine(

double x1, double y1,

double x2, double y2){

DP2.drawline(x1, x2, y1, y2);

} }

abstract class Circle : Shape {

private double _x, _y, _r;

public override void draw () {

drawArc( _x, _y, _r, 0, 360);

}

abstract void drawArc( double x,

double y, double r, double a1,

double a2);

}

class V1Circle : Circle {

protected override void

drawArc(double x, double y,

double r, double a1, double a2){

DP1.draw_an_arc(x,y,r,a1,a2);

} }

class V2Circle : Circle {

protected override void

drawArc(double x, double y,

double r, double a1, double a2){

DP2.drawarc(_r,_x,_y,a1,a2);

} }

C#

Redundant Relationships

Page 78: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

76

Did We Resolve the Redundancy?

Don't Trade One Redundancy for Another

Page 79: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

77

Problems with this Approach

Doesn’t scale well– If we add another type of Shape, we have 6 implementations

– Number of implementations will equal # types of Shapes times # of drawing programs

Redundant– Clearly accessing each of the drawing programs across the different types

of Shapes will involve duplication or require greater modularization

– There will be many redundancies between V1Rectangle and V2Rectangle, etc…

Static– Must make new objects when any issue varies at runtime

Intent Makes Sense Now

*GoF Intent: De-couple an abstraction from its implementation so that the two can vary independently

Abstraction: The entity, what something “is”. In this case – Shape

Implementation: What something “does”. In this case, the drawing behavior – Drawing

*Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides

Page 80: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

78

Conceptual Point!

Many people say:

– We use patterns to solve problems

This is sometimes true, but it’s much more useful to

consider this:

– Patterns are in the problems themselves

– We just need a way to see them

Seeing the Pattern in the Problem

Note that we can see that the Bridge pattern

potentially applies without knowing anything about the

details

…but what if we didn’t?

Could we discover it in the problem itself?

Page 81: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

79

Discovering the Bridge Pattern

We use the following approach to discover the Bridge pattern

1. Find what is common in the problem domain

2. Define an abstraction to represent each common concept

3. Determine the nature of the variations, and create concrete entities

Lastly:

– Observe how these abstractions relate to each other

We Have the Following

Commonalities

Our Shape class represents our commonality of

abstraction. It represents a varying entity.

We also have a behavioral implementation which varies

CVA separates these issues into is-a relationships

Page 82: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

80

Derive Variations

Determine Remaining Relationships

Don't want them down here: "Design to Interfaces”

Which Way?

Page 83: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

81

Use Qualities to Define Relationship

Find different ways these CVA structures can work

together:

– Shapes use drawing programs to draw themselves

– Client gives drawing program a shape to draw

– A Manager coordinates them both

Whichever has better qualities is what we want

(whether it happens to be a pattern or not)

New patterns can be discovered in this way

Scoring

Shapes use DP DP given Shape

3rd Module

Loose Coupling

Strong Cohesion

No Redundancy

Encapsulation

Testable

Focus

Page 84: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

82

Shapes Using Drawing Programs

Drawing Programs Using Shapes

Page 85: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

83

Control Program Using Shapes

Scoring

Shapes use DP DP given Shape

3rd Module

Loose Coupling Yes DPs coupled to Shapes

Module coupled to Shapes

Strong Cohesion Yes DPs concerned with Shapes

Weak: Shape and Draw stuff

No Redundancy Yes Knowledge of shapes duplicated in DPs

Knowledge of shapes duplicated in CP

Encapsulation implementation and type

implementation only

implementation only

Testable N + M N * M N + M

Assertive Yes No No

Focus Yes Shapes spread out a little

Yes

Shapes using DPs wins!

~3

Page 86: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

84

Add the Relationship

The A

dap

ter Pattern

Why Didn't We Need Adapters Here?

Page 87: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

85

Patterns as Operators

"Each pattern is an operator which differentiates space: that is, it creates distinctions where no distinction was before “

Christopher Alexander, The Timeless Way of Building

Illustrating the Separation

Abstraction Implementation

Page 88: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

86

Example Implementation

class Client {

public static void Main

(String argv[]) {

Shape s1;

Shape s2;

Drawing dp;

// See comments below to see what

// gets returned

dp= Factory.getDP();

s1= Factory.getShape(dp);

dp= Factory.getDP();

s2= Factory.getShape(dp);

s1.draw();

s2.draw();

}

}

// Factory:

// first call: getDP returns V1Drawing

// first call: getShape returns

// new Rectangle(dp,1,1,2,2);

// second call: getDP returns V2Drawing

// second call: getShape returns

// new Circle( dp,2,2,4);

abstract class Shape {

private Drawing _dp;

Shape (Drawing dp) {

_dp= dp;

}

abstract void draw ();

protected void drawLine (

double x1, double y1,

double x2, double y2) {

_dp.drawLine( x1, y1, x2, y2);

}

protected void drawArc (

double x, double y,

double radius, double fromAngle,

double toAngle){

_dp.drawArc( x,y,radius,

fromAngle, toAngle);

}

}

C#

Example Continued

class Rectangle : Shape {

Rectangle : base(dp) (Drawing dp,

double x1, double y1,

double x2, double y2) {

_x1= x1; _y1= y1;

_x2= x2; _y2= y2;

}

public override void draw () {

drawLine(_x1, _y1, _x2, _y1);

drawLine(_x2, _y1, _x2, _y2);

drawLine(_x2, _y2, _x2, _y1);

drawLine(_x2, _y1, _x1, _y1);

} }

class Circle : Shape {

Circle : base(dp)(Drawing dp,

double x, double y,

double radius) {

_x= x; _y= y; _radius= radius;

}

public override void draw () {

drawArc(_x,_y,_radius, 0, 360);

} }

abstract class Drawing {

abstract void drawLine ( double x1,

double y1, double x2, double y2);

abstract void drawArc(

double x,double y,double radius,

double fromAngle, double toAngle);

}

class V1Drawing : Drawing {

public override void drawLine (

double x1, double y1,

double x2, double y2) {

DP1.draw_a_line( x1, y1, x2, y2);

}

public override void drawArc (

double x, double y, double radius,

double fromAngle, double toAngle) {

DP1.draw_an_arc( x, y,radius,

fromAngle,toAngle);

} }

C#

Page 89: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

87

Example Continued

class V2Drawing : Drawing {

public override void drawLine (

double x1, double y1,

double x2, double y2) {

DP2.drawline( x1, x2, y1, y2);

}

public override void drawArc (

double x, double y, double radius, double fromAngle, double toAngle) {

DP2.drawarc(radius, x, y, fromAngle, toAngle);

} }

class DP1 {

static void draw_a_line ( double x1, double y1, double x2, double y2) {

// draw_a_line implementation given to us

}

static void draw_an_arc( double x, double y, double radius,

double from_angle, double to_angle) {

// draw_an_arc implementation given to us

} }

class DP2 {

static void drawline ( double x1, double y1, double x2, double y2) {

// drawline implementation given to us

}

static void drawarc( double radius, double x, double y,

double fromangle, double toangle) {

// drawarc implementation given to us

} }

C#

Canonical Bridge Pattern

Concrete1

ImpA+ opImp1()

+ opImp2()

ImpB+ opImp1()

+ opImp2()

Abstraction

+ operation()

Implementation

+ opImp1()

+ opImp2()

operation() {

imp.opImp1()

}

Concrete2

operation() {

imp.opImp2()

}

Page 90: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

88

Bridge Pattern and the GoF Advice

(1)

(2)

(3)

(1)

(1) Find what varies and

(2) Encapsulate it. Use inheritance to categorize.

(3) Design to Interfaces

(2)

(1) (1)

Another Way to Think of Bridge

Consider the following:

– The cost of having a common interface for the

implementation

– The benefits of separating the issues, testability, cohesion,

clarity, extensibility, etc…

If the benefits are greater than the cost, use it

If not, the pattern tells you “Don’t use me!”

Page 91: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

89

The Two Designs…

Bridge

Strategy

Comparing Strategy and Bridge

Strategy Bridge

Contains variation of behavior? Yes Yes

Behaviors are isolated Yes No, dependant

Risk of Interface Bloat No Yes

Open-Closed to… New behavior

New entity, behavior, way of using behaviors

How many variations are encapsulated

1 3

Page 92: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

90

copyright © 2010 Net Objectives Inc.

The Façade

The Façade Pattern

We want to use a sub-set of the functionality of a

complex system, or to simplify its interface, or to

improve how it is used, or to provide OO access to a

non-OO system

GoF 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

*Design Patterns, Elements of Reusable Object-Oriented Software, Gamma, Helm, Johnson, Vlissides

Page 93: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

91

8’ of Manuals: One Complex System

Using a Complex System

If you were in a group of developers that had to use

parts of a complex system, would you:

A. have everyone learn how to use it?

B. draw straws where the loser had to learn it and make a set

of classes for you to use?

If you picked B, what that person created would be a

Façade

Page 94: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

92

Insulating Ourselves From the

Complex System

Faça

de

Standard Façade vs.

Encapsulating Facade

The Façade normally is used to simplify the use of a complex system

However, clients may use it or not -- they may use the complex system directly too

An Encapsulating Façade restricts access to the complex system -- clients must use the Façade

This has advantages

Page 95: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

93

Advantages of the Encapsulating Façade

The Façade itself can be varied, using polymorphism, to

allow for:

– Testing (Dummy Façade)

– Marketing/Presentations - Demonstration Façade is used to

simulate a remote system

– Training

– "Demo" versions of commercial software

– etc…

Comparing Façade With Adapter

Client Pre-Existing

?which pattern?

Façade Adapter

Pre-Existing, or Foreign classes?

Yes Yes

Is there an existing interface we must adhere to?

No Yes

Are we trying to enable polymorphism?

No Usually

Are we creating a new interface for simplification?

Yes No

Is statefullness a concern? Yes, Façades tend to be large

Not usually

Page 96: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

94

Adapter and Façade Mean: Defer Having to Worry About Your Interface

You can use the Adapter and Façade patterns to make

the interfaces of classes you have been given to be

exactly the way you want them to

This is an example of design by context. First figure

out what you want, then adapt (or simplify with a

Facade) the interface to how you want it

copyright © 2010 Net Objectives Inc.

The Thought Process

of PatternsProgramming by Intention

Page 97: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

95

Programming by Intention

public void printReport (String CustomerID) {

Employee[] emps = getEmployees(CustomerID);

if(needsSorting(emps)) sortEmployees(emps);

printHeader(CustomerID);

printFormattedEmployees(emps);

printFooter(CustomerID);

paginate();

}

"Private"* Methods

"Sergeant" Method

C#/Java/…

*Note: These methods may not be literally private, as we may need to make some of them public or protected for testing. But we treat them as private from client objects, to limit coupling.

copyright © 2010 Net Objectives Inc.

The Thought Process

of PatternsShalloway’s Law

Page 98: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

96

Shalloway’s Law

If ‘N’ things need to change and ‘N>1’,

Shalloway will find at most ‘N-1’ of these things

Shalloway’s Principle

Avoid situations where Shalloway’s Law Applies

Page 99: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

97

copyright © 2010 Net Objectives Inc.

The Thought Process

of PatternsEncapsulate that!

Our Situation

We have multiple processors in a real-time environment.

We know there will be a performance problem. We just

don’t know where / how.

What can we do?

Page 100: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

98

Our Options

1. Figure out where / how the performance problem will

show up.

2. Just use what appears best at first and fix it later if it

becomes clear later that we need something else

3. Use Scott Bain’s magic consultant card

~3

Scott Bain’s Magic Consultant Card

Scott, a Net Objectives’ Design Patterns Instructor, has

a magic card that tells you how to solve design

problems

It requires, however, that you explicitly and concisely

state what your problem is

Fortunately, we know what our problem is:

– We do not know the nature of the collection we need

~3

Page 101: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

99

Instructions for Using the Magic

Consultant Card

1. Hold magic card face down in front of you

2. State aloud three times what your problem is

3. Flip the card over

4. Read the card

~3

Using the Magic Design Card

"Encapsulate That"

~3

Page 102: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

100

Limits of the Magic Design Card

and Where Design Patterns Help

First the good news – the magic card is always right!

Now the bad news – it doesn’t tell you how to do what

it tells you to do!

That’s where design patterns come in

– Encapsulate what varies

~3

• Attend to code qualities

• Gang of Four Advice

– Design to interfaces

– Delegate

– Encapsulate what varies

• Use testability as a design tool

• Program by intention

• Encapsulate

• Shalloway’s Principle

• Patterns hide variation

Summary

Page 103: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

101

Net Objectives’ Webinars

_s

Business & Agile Webinar Series – April – December 2013

An Introduction to Agile from a Business / Executive Point of View

Agile Implementations: Overviews of Scrum, Kanban, and Scrumban

How to Start an Agile Implementation

Team Kanban: Manifesting Lean at the Team Level

Enhancing and Extending Scrum With Lean

Patterns of Scaling Agile Across Teams

Patterns of Scaling Agile Across an Enterprise (will discuss the Scaled Agile Framework as well as our own Lean-Agile Roadmap

The Net Objectives Enterprise Agility Roadmap: Patterns of Successful Lean-Agile Adoption

Technical Agility Series

Technical Agility: What Design Patterns Were Made For

Emergent Design: The Practical Application of Design Patterns in the Agile World

Acceptance Test-Driven Development: An Essential Practice That Saves More Time Than It Takes

Sustainable Test-Driven Development: How to Have TDD Improve Your Designs and Tests Without Slowing You Down

See www.netobjectives.com/events to learn more

Register at www.netobjectives.com/register for slides & more

copyright © 2010 Net Objectives Inc.

Register at www.netobjectives.com/register

See www.netobjectives.com/resources

Contact me at [email protected]

Twitter tag @alshalloway

Thank You!

Page 104: Design Patterns Explained: From Analysis through Implementation

12 April 2013Copyright © 2007 Net Objectives. All Rights Reserved.

102

Lean Enterprise

Business

Management

Team

ASSESSMENTS

CONSULTING

TRAINING

COACHING

Lean for Executives

Product Portfolio Management

Business Product Owner

Scaled Agile Framework

Lean Management

Project ManagementLean-Agile

Kanban / Scrum

ATDD / TDD / Design Patterns

technical process

QUE S T I O N S?

For more info on free resources see:www.netobjectives.com/resources