Download as pdf or txt
Download as pdf or txt
You are on page 1of 30

Agenda

Pattern Oriented Development: A


Practical Approach to Building Introduce design patterns
Software Show how design patterns can be used in
analysis
Introduce Commonality / Variability Analysis: a
better design paradigm than looking for entities
and their behaviors in the our problem domain.
Show how taking advantage of CVA can improve
www.netobjectives.com
maintainability of software.
[email protected]
408-835-7016

©Net Objectives, 8/3/2004 1 NetObjectives ©Net Objectives, 8/3/2004 2 NetObjectives

When Adding Functionality – In a Nutshell


Where’s the Problem?
How can we design to accommodate change?
In writing the new code?
This requires:
In integrating it into the new system? identifying special cases
abstracting out commonalities
Which is greater? containing no more than one variation per class
We are not trying to anticipate change, per se,
Why? 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.
©Net Objectives, 8/3/2004 3 NetObjectives ©Net Objectives, 8/3/2004 4 NetObjectives
What Are Patterns? A Pattern in Carpentry

Patterns are best-practice solutions for


recurring problems in a particular context. Let’s say two carpenters are trying to decide on
Patterns have been classified as being:* how to build a dresser.
Architectural One says to the other: “should we build the joint
Design by first cutting down, then cutting up at a 45
Idiomatic
degree angle...”
Design patterns can also be thought of as describing
the relationships between the entities (objects) in our
problem domain.
“then back down and back up
Patterns have led to new modeling techniques:
handling variations in behavior the other way, then back down”
new ways of using inheritance to avoid rigidity and aid
testing and maintenance issues.
* Pattern Oriented Software Architecture, Buschmann, et. al.

©Net Objectives, 8/3/2004 5 NetObjectives ©Net Objectives, 8/3/2004 6 NetObjectives

We Are Describing a Dove-Tail Joint A Miter Joint

And keep this up until done.

Board shown (called tails)


Fits into groove in board coming
out of paper (called pens)

Commonly used in picture frames.

©Net Objectives, 8/3/2004 7 NetObjectives ©Net Objectives, 8/3/2004 8 NetObjectives


Patterns Work At All Levels Focusing on Detail
Loses the Big Picture
Dovetail Miter
Strong, high-cost, Weak, cheap, quick to
By having to describe how we implement the
Analysis/
decorative, humidity make, good for picture dove-tail joint, we can lose sight of why we
Motivation tolerant frames
might want to use it in the first place.
Design Interlaced joint Single abutting cut Dove-tail Joint vs. Miter Joint emphasizes:
do we want a strong, relatively expensive joint that is
of high quality and will last forever
Implementation Cut teeth .5” long, .4” 45 degree cut, ¼” thick
deep wood or do we want a weak, relatively inexpensive joint
that is easy to make but not of high quality

©Net Objectives, 8/3/2004 9 NetObjectives ©Net Objectives, 8/3/2004 10 NetObjectives

Reasons to Study Patterns Three Levels of Perspective

Re-uses existing, quality solutions Conceptual Perspective


Designs improved for modifiability (expand on Specification Perspective
good solutions)
Implementation Perspective
Create a new paradigm for object-oriented
design
Common terminology assists learning across all
levels
We will find that design is not a process of
synthesis, but one of differentiation.
From Martin Fowler’s UML Distilled, 2nd Edition
Shift to new level of thinking
©Net Objectives, 8/3/2004 11 NetObjectives ©Net Objectives, 8/3/2004 12 NetObjectives
The Different Perspectives Consider These

Conceptual
describes what you want, now how you’ll get it
requirements are often specified at a conceptual level
“we need to handle inventory in LIFO, FIFO, average
cost”
Specification
the interfaces of our classes
how objects “talk” to each other
our product class’ methods look like …
Implementation
the code itself Mop Broom Sponge

©Net Objectives, 8/3/2004 13 NetObjectives ©Net Objectives, 8/3/2004 14 NetObjectives

As Any Good Consultant Will Tell You:


Same or Different?
“IT DEPENDS!”

Who thinks they are the same?


As specific objects: they are different
Who thinks they are different?
As a concept: they are all Cleaning Utensils

©Net Objectives, 8/3/2004 15 NetObjectives ©Net Objectives, 8/3/2004 16 NetObjectives


Where does “Cleaning Utensil” exist? Abstract Class

Represents a concept and is therefore never


instantiated.
Used to define an interface for the real-world
classes (i.e., used to define how to communicate
with the objects that are derived from the
abstraction)

For example, a ‘cleaning utensil’ was an abstract


Not in the real world, but in our thoughts as an class for ‘mops, ‘brooms’, and ‘sponges’.
abstraction classification!
A “Cleaning Utensil” does not exist, but specific kinds do!

©Net Objectives, 8/3/2004 17 NetObjectives ©Net Objectives, 8/3/2004 18 NetObjectives

From a Modeling Perspective This Is an Example of Polymorphism

Allows for different behavior


s i
l Calling object does not need to know the exact
e
n
type of object involved
t
U Mop
Calling object only needs to know the
Person "Clean"
I conceptual type of object
n ... Broom
t
e In this case, anything having mops, brooms,
r
f a
ce and sponges only knows it has cleaning
utensils.

©Net Objectives, 8/3/2004 19 NetObjectives ©Net Objectives, 8/3/2004 20 NetObjectives


A Note About Encapsulation Objects at Different Perspectives

We often think of encapsulation as something At the implementation level:


we do at the object level (i.e., hide its data). data with methods
On reflection, however, we can see that we At the specification level:
have used encapsulation to hide a set of objects are the contracts they implement
classes (all the derived classes). At the conceptual level:
Abstract classes and interfaces essentially entities with responsibilities
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
©Net Objectives, 8/3/2004 21 NetObjectives ©Net Objectives, 8/3/2004 22 NetObjectives

The Problem

We are writing a web-enabled sales order


system.
A customer signs in and fills out the order.

©Net Objectives, 8/3/2004 23 NetObjectives ©Net Objectives, 8/3/2004 24 NetObjectives


Initial Solution The Challenge

TaskController
As soon as we get new variations in tax we
have to modify our SalesOrder object.
SalesOrder
It also has the problem of possibly creating a
large object if it is responsible for more than one
thing

Have TaskController instantiate SalesOrder that


handles filling out the sales order, etc.

©Net Objectives, 8/3/2004 25 NetObjectives ©Net Objectives, 8/3/2004 26 NetObjectives

New Requirement -
Using Inheritance for Specialization
Multiple Tax Domains
Eventually need to handle different tax rules.
We can solve this problem by specializing our
•US Tax
first SalesOrder object to handle the new tax
•Canadian Tax
rules.
TaskController
One Solution
original calcTax that
method calcTax does US tax
SalesOrder
// use switch on type of tax rule to be used + calcTax()
// TYPE US:
// calc tax based on US rules new (overriden) calcTax
// break that does Canadian tax
// TYPE CANADIAN:
// calc tax based on Canadian rules
// break
CanadianSalesOrder
+ calcTax()

©Net Objectives, 8/3/2004 27 NetObjectives ©Net Objectives, 8/3/2004 28 NetObjectives


This Will Lead to Duplication and Gang of Four Gives Us Guidelines*
Difficult Maintenance
If we get new variations, where do we put them? Design to interfaces
We either start using lots of switches (which Favor object aggregation** over class
makes the code difficult to understand), or we inheritance.
start over-specializing (which still makes things Consider what should be variable in your design
difficult). … and “encapsulate the concept that varies.”
1. Find what varies and encapsulate it in a class of its
We’d like to isolate the variation. own
2. Contain this class in another class to avoid multiple
variations in your class hierarchies
* Design Patterns: Elements of Reusable Object-Oriented Software, Gamma, E., Helm, R.,
Johnson, R., Vlissides, J., 1995, pg 18, 20, 29.
** In the GoF book they use the term “composition” but they are using Rumbaugh’s OMT. This is
equivalent to the term “aggregation” in the UML. This difference is not significant in garbage-
collected languages like Java and C#

©Net Objectives, 8/3/2004 29 NetObjectives ©Net Objectives, 8/3/2004 30 NetObjectives

Find What Varies and Encapsulate It

Identify varying behavior The Strategy Pattern


Define a class that encapsulates this variation,
contain (via composition) an instance of a
concrete class derived from the abstract class
defined earlier
Allows for decoupling of concepts
Allows for deferring decisions until runtime
Small performance hit
This is a “design up front” point of view, but can
be tailored for design as you go.
Extract variations that result from new requirements
Pull these out into their own classes.
©Net Objectives, 8/3/2004 31 NetObjectives ©Net Objectives, 8/3/2004 32 NetObjectives
The Strategy Pattern The Strategy Pattern

We need different behavior at different times; The Strategy pattern is a pattern that tells us
either for different things we are working on or how to identify a set of rules that conceptually
for different clients asking us to do work. do the same thing.
In our example: tax.
GoF Intent: Define a family of algorithms, 1) identify a common way to communicate with
encapsulate each one, and make them all implementations of the rule
interchangeable. Strategy lets the algorithm 2) define an interface or abstract class that
vary independently from clients that use it. * defines this communication
* Design
Patterns, Elements of Reusable Object-Oriented Software, 3) implement each variation of the rule as an
Gamma, Helm, Johnson, Vlissides implementation or derivation

©Net Objectives, 8/3/2004 33 NetObjectives ©Net Objectives, 8/3/2004 34 NetObjectives

Strategy Lives in Analysis, Design, Conceptually:


Implementation Encapsulating Tax Rules
In analysis, any time we find a varying business
rule, it is likely a Strategy pattern is present. a
T
If we know we need to use a Strategy, the x
US Tax
pattern tells us to encapsulate the varying rule I
behind an interface. n
t ... Can Tax
During implementation, the pattern gives e
r
“instant experience” in the implications of one fa
implementation over another. ce

The pattern is really about the relationship


between one object that uses one of several
conceptually similar rules.
©Net Objectives, 8/3/2004 35 NetObjectives ©Net Objectives, 8/3/2004 36 NetObjectives
In The UML Conceptually: How it is Used

T
a
CalcTax x
+ taxAmount(itemSold : Salable, qty : Double, unit : Double) : double Task US Tax
Controller Sales
I
Order n
USTax CanTax t ... Can Tax
e
r
fa
ce

©Net Objectives, 8/3/2004 37 NetObjectives ©Net Objectives, 8/3/2004 38 NetObjectives

In The UML Strategy Implementation


Partial Java/C# Example Partial C++ Example
class TaskController {
TaskController::processSalesOrder
processSalesOrder( string custID) { ( string custID) {
TaskController Tax myTax=
Tax *myTax=
Config.getTax( custID);
SalesOrder SalesOrder mySalesOrder=
Config.getTax( custID);
new SalesOrder(myTax); SalesOrder mySalesOrder=
... new SalesOrder(myTax);
mySalesOrder.process(); ...
CalcTax
} mySalesOrder.process();
+ taxAmount(itemSold : Salable, qty : double, price : double) : double } }

class SalesOrder {
SalesOrder::process {
public process ()
USTax CanTax ...
...
tax= myTax.calctax( qty, price); tax= myTax.calctax( qty, price);
... ...
} }
}
©Net Objectives, 8/3/2004 39 NetObjectives 40
Who Knows Which Rule to Use What Happens Now
With Changing Requirements
Before, TaskController needed to know either If we get a new tax requirement, we only need
the value of the tax switch to set or which to
SalesOrder to instantiate. derive the new class from the CalcTax class
It can now instantiate the appropriate CalcTax modify the TaskController or the Configuration file.
object. this may, in fact, work with a data dictionary so even it
doesn’t need to change
No other objects change
OR, can have a configuration file that the
SalesOrder class uses to figure out the correct
CalcTax object

©Net Objectives, 8/3/2004 41 NetObjectives ©Net Objectives, 8/3/2004 42 NetObjectives

Value of Strategy Why Bother?

Conceptually it is cleaner What happens if many things vary?


Each object worries only about one function In other words, in addition to the tax rules, we
(increasing cohesion) could have the following variations?
Better independence of different actions different shipping charges
(decreasing coupling) different monetary rules
If have more variations, have a better way of different address rules
handling them (e.g., routing of message)
Switches and inheritance do not scale.

©Net Objectives, 8/3/2004 43 NetObjectives ©Net Objectives, 8/3/2004 44 NetObjectives


Commonality - Variability Analysis
Commonality/Variability Analysis
Acknowledgement: Much of this work regarding
Commonality – Variability Analysis comes from
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/download/CoplienThesis.pdf

©Net Objectives, 8/3/2004 45 NetObjectives ©Net Objectives, 8/3/2004 46 NetObjectives

Commonalities Challenges in Finding Commonalities

“Commonality analysis is the search for common We are often data-centric


elements that helps us understand how family
members are the same.” *
Objects are too often thought of as “intelligent
data” instead of loci of related behaviors
Commonalities are
1. Recognized from experience
2. Learned through analysis (abstracted)

Commonalities can define basic concepts in a


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

©Net Objectives, 8/3/2004 47 NetObjectives ©Net Objectives, 8/3/2004 48 NetObjectives


Variability Analysis Reasons to Get Variations of
Commonalities
Variability makes sense only in a given commonality In analysis, don’t need detailed design, just
frame of reference. It is a variation of some need to determine:
commonality. the resources required for implementation
the risks involved
“From an architectural perspective, commonality Define scope (variations give us specific cases)
analysis gives the architecture its longevity; variability
analysis drives its fitness for use.”* Make sure variations define commonalities (do
we have enough cases to define the set of
public methods for the abstract class/interface
well enough?)

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

©Net Objectives, 8/3/2004 49 NetObjectives ©Net Objectives, 8/3/2004 50 NetObjectives

Commonality – Variability CVA Vs Relationships


Analysis Exercise
CVA does not include relationships between
Say we’re given the following requirements for an different variations.
e-commerce system:
US$ is used in the US, Euro$ used in Germany.
¾ Have to handle ¾ Max Weight in US is
European dates 70 lbs
CVA does not worry that money and nationality
¾ US Tax ¾ Canadian Freight
are related. US$ is not a variation of country.
¾ Canadian PST, GST Rules Euro$ is not a variation of country. They are
¾ European VAT ¾ US Freight Rules both variations of money.
¾ German Shipping ¾ US Phone #s CVA tells us to first find the Commonalities and
Rates ¾ European Phone #s Variabilities present in our problem domain,
¾ French Freight Rules ¾ Max Weight in
then identify the relationships present.
¾ Verification of valid Germany is 40 kg
addresses in different ¾ Euros in Europe, This keeps coupling of special cases down to a
countries Dollars in US, etc… minimum.
©Net Objectives, 8/3/2004 51 NetObjectives ©Net Objectives, 8/3/2004 52 NetObjectives
Why This Is Important The Commonalities and Variabilities
Continents Phone # Formats Freight Rates
European European German Rates
Coupling between variations does occur.
North US/Canadian
When the variation of Country is US, we use US$. American French Rate
Shipping Rules
Countries Canadian Rates
However, not always. France
French
Max Weights
German
Can have Spanish speaking people in the US. Germany Canadian German - 40 kg
Canada Date Formats * French – none
We're looking for a way to find the special cases US European/Canadian Canada – none
without inferring that the relationships in the Tax US US - 70 lbs
special cases are universal. European
Address Verification
Canadian * Note: perhaps better to say:
This allows new variations to be accommodated US yyyy/mm/dd
dd/mm/yyyy
French
more easily. Money mm/dd/yyyy German
US $ Canadian
Canadian $
US
Euro$

©Net Objectives, 8/3/2004 53 NetObjectives ©Net Objectives, 8/3/2004 54 NetObjectives

Notes About Commonalities CVA and the Eliciting


and Their Variations Requirements Process
Not all commonalities and their variations are Is a requirement as stated typically stated as a
useful. concept, a specification or an implementation?
Some are about when things apply. Requirements stated as implementations (e.g., use
DB2 as a database) often constrain the system
Others are about how things are implemented. unnecessarily.
Still others describe variations that can be Should requirements be stated at one level or
implemented by changing an attribute value another or all three?
(e.g., finance charge rate).
What to do if they are stated at the wrong level?
CVA is about adding clarity to your thinking - it
Should you try to get customers to talk at a
is a starting point.
particular level?

©Net Objectives, 8/3/2004 55 NetObjectives ©Net Objectives, 8/3/2004 56 NetObjectives


Commonality / Variability Analysis Using Commonality/Variability Analysis
and Design to Design Class Structures
by looking at what
Those things that are conceptually the same Commonality
analysis
Conceptual
perspective
Abstract
class
these objects must do
(conceptual perspective)
(found by commonality analysis) become the Operations we determine how to
call them (specification
abstract classes (or interfaces). Specification
perspective)

perspective Concrete Concrete


The derived concrete classes (or class class

implementations if we’re using interfaces) are Variability Implementation


Operations Operations

When implementing these classes, ensure that


discovered in variability analysis. analysis perspective
the API provides sufficient information to
enable proper implementation and decoupling

Relationship between specification and conceptual: Needed Interface


Relationship between specification and implementation: How Interface is Implemented
Motivating Question: How fixed will this Interface need to be?

©Net Objectives, 8/3/2004 57 NetObjectives ©Net Objectives, 8/3/2004 58 NetObjectives

Using Commonality / Variability Using Design Patterns


Analysis
CVA tells us to first find: Most design patterns are about the relationships
those things that don’t change between entities in our problem domain.
the commonalities of things that do change They give us a way to find what varies and encapsulate
Define interfaces/abstract classes for these it. That is, to isolate these variations.
commonalities This is important because initially, these variations don’t
appear to be very problematic.
Define the variations of these commonalities (i.e,
the specific cases) But in combination they can be very difficult to handle.
Determine how these classes relate to each other They illustrate the proper use of commonality/variability
analysis-- that is, how we can refer to conceptually
only after we have done this.
similar behavior that is implemented differently.
Avoids coupling:
encapsulate implementation
allows for future changes
end of
©Net Objectives, 8/3/2004 59 NetObjectives sem ©Net Objectives, 8/3/2004 60 NetObjectives
Handling Variation: A Case Study
The Analysis Matrix
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 Postal rules for verifying addresses. In
Canada, use GST and PST for tax. Use Fed Ex
for Canada shipping.

©Net Objectives, 8/3/2004 61 NetObjectives ©Net Objectives, 8/3/2004 62 NetObjectives

Break Requirements Into Cases How to Start the Design

Distilling the requirements into cases:


CASE 1: USA Customer Before we design anything, we should do some analysis
Calculate freight based on UPS charges, use US Postal of our problem domain.
rules for verifying addresses and calculate tax based on
We want to find what varies and encapsulate it.
sales and/or services depending upon locale. Handle
money in US $. An easy way to do this when the requirements are
CASE 2: Canadian Customer many, is to use something we call the ‘analysis matrix’.
Use Canadian $. Use Canadian Postal rules. Ship via This is simply a matrix where each column represents a
Fed Ex to Canada and calculate tax based on GST and given case. Each row is used to represent the concepts
PST. we discover in the cases.
We can start with a single requirement, and build this as
we go. This can be much easier to manage.

©Net Objectives, 8/3/2004 63 NetObjectives ©Net Objectives, 8/3/2004 64 NetObjectives


Start With One Continue…

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


US Sales US Sales
calculate freight use UPS rates calculate freight use UPS rates
verify address use US Postal rules

Different Concept Same Case

©Net Objectives, 8/3/2004 65 NetObjectives ©Net Objectives, 8/3/2004 66 NetObjectives

Continue… Handle Canadian Case

US Sales Canadian Sales


US Sales calculate freight use UPS rates
calculate freight use UPS rates verify address use US Postal rules
verify address use US Postal rules calculate tax use state and local
calculate tax use state and local taxes taxes
money US $ money US $ Canadian $

More Concepts More Examples for this Case


Existing Concept New Case

©Net Objectives, 8/3/2004 67 NetObjectives ©Net Objectives, 8/3/2004 68 NetObjectives


Next Canadian Case All Cases Handled

US Sales Canadian Sales


US Sales Canadian Sales
calculate freight use UPS rates
calculate freight use UPS rates use Canadian
verify address use US Postal rules use Canadian Postal
shipper
rules
verify address use US Postal rules use Canadian Postal
calculate tax use state and local
rules
taxes
calculate tax use state and local use GST and PST
money US $ Canadian $
taxes
money US $ Canadian $
Existing Concept Same Case

©Net Objectives, 8/3/2004 69 NetObjectives ©Net Objectives, 8/3/2004 70 NetObjectives

New Case - German Sales Can Check Our Understanding

US Sales Canadian Sales German Sales US Sales Canadian Sales German Sales
calculate use UPS rates use Canadian shipper use German shipper calculate use UPS rates use Canadian shipper use German shipper
freight freight
verify use US Postal use Canadian Postal use European Postal verify use US Postal use Canadian Postal use European Postal
address rules rules rules address rules rules rules
calculate tax use state and use GST and PST use German VAT calculate tax use state and use GST and PST use German VAT
local taxes local taxes
money US $ Canadian $ Euro $ money US $ Canadian $ Euro $
dates mm/dd/yyyy dd/mm/yyyy dd/mm/yyyy dates mm/dd/yyyy mm/dd/yyyy dd/mm/yyyy
max weight 30 kg max weight 70 lbs none 30 kg

Are there maximum weights in US and Canada? Maybe not. "Sometimes yes, sometimes no…"
Maybe so, and the customer forgot to mention them.
Now we have a good, specific question to ask.
Customers are good at answering specific questions.
©Net Objectives, 8/3/2004 71 NetObjectives ©Net Objectives, 8/3/2004 72 NetObjectives
It Does Get More Complicated Use Mini-Matrix for Complex Cases

US Sales Canadian Sales


Imagine in we can use Fed Ex and UPS in the calculate freight use UPS rates use Canadian
shipper
US and there is a max rate for one but not the verify address use US Postal rules use Canadian Postal
other. rules
calculate tax use state and local use GST and PST
Sometimes we combine the rows (calculate taxes
money US $ Canadian $
freight - max weight) and use a mini-matrix for
each entry. Calculate freight Use USPS Use UPS Use FedEx
Verify Address Use US Use US Postal Use US Postal
Postal Rules no PO Rules
Rules Boxes
Pick-up charge N/A $5.00 $4.00

Max weight 50 lbs 70 lbs No maximum

©Net Objectives, 8/3/2004 73 NetObjectives ©Net Objectives, 8/3/2004 74 NetObjectives

Thinking of Elements as Objects How To Use the Analysis Matrix

US Sales Canadian Sales German Sales


calculate USCalcFreight CanCalcFreight GermCalcFreight
Each row represents different ways a rule may
freight be implemented across all of the cases.
verify USAddrRules CanAddrRules GermanAddrRules
address This sounds quite a bit like a Strategy pattern.
calculate tax USCalcTax CanCalcTax GermanCalcTax It can be implemented as such.
money USMoney CanMoney GermanMoney
dates Date_mmddyy Date_mmddyy Date_ddmmyy How do we handle the instantiation of the
max weight USMaxWght CanMaxWght GermanMaxWght appropriate strategy objects?

©Net Objectives, 8/3/2004 75 NetObjectives ©Net Objectives, 8/3/2004 76 NetObjectives


Using The Strategy Pattern Concrete Implementation Rules:
for Implementation Columns
US Sales Canadian Sales German Sales US Sales Canadian Sales German Sales
calculate calculate
The objects in this row can be implemented as a Strategy pattern freight
freight encapsulating the “calculate freight” rule.

These implementations are used when we

These implementations are used when we

These implementations are used when we


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

calculate tax calculate tax

have a Canadian customer.


The objects in this row can be implemented as a Strategy pattern

have a German customer.


encapsulating the “calculate tax” rule.

have a US customer.
money We can use Money objects that can contain Currency andAmount money
fields that automatically convert as needed..
dates We can use Date objects that can display as required for the country dates
the customer is in.
max weight max weight
The objects in this row can be implemented as a Strategy pattern
encapsulating the “max weight” rule.

©Net Objectives, 8/3/2004 77 NetObjectives ©Net Objectives, 8/3/2004 78 NetObjectives

How Can We Control Instantiation? Abstract Factory

We have two issues to deal with:


1. using the desired objects in a de-coupled way
2. instantiating the correct set
Using the desired objects can be simplified
with the Strategy Pattern
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.
We need an object factory here.

©Net Objectives, 8/3/2004 79 NetObjectives ©Net Objectives, 8/3/2004 80 NetObjectives


The Abstract Factory Pattern The Abstract Factory Pattern

We need to create families of objects for The Abstract Factory pattern gives us a way to
particular situations. That is, particular clients implement a set of objects corresponding to a
need particular sets of instantiations. particular case.
In our problem, we can use an Abstract Factory
GoF Intent: Provide an interface [a set of to contain the rules for which objects we need
methods] for creating families of related or for each case we have.
dependent objects without specifying their The possible combinations are now handled by
concrete classes.* the Abstract Factory.
The rest of the software has to deal only with
* Design
Patterns, Elements of Reusable Object-Oriented Software, the objects as components.
Gamma, Helm, Johnson, Vlissides

©Net Objectives, 8/3/2004 81 NetObjectives ©Net Objectives, 8/3/2004 82 NetObjectives

The Abstract Factory Classes of The Abstract Factory

Client/Application AbstractFactory
y + makeCalcTax()
or + makeCalcFrieght()
t
c + makeAddrRules()
a
F US Case

I
Canada
n ... USAF CanAF
t Case
e
r
fa
ce
makeCalcTax: makeCalcTax:
return new USTax() return new CanTax()
makeCalcFreight: makeCalcFreight:
The interface of the Abstract Factory defines which objects return new USLocal() return new CanLocal()
the factory can create. Each implementation decides on makeAddrRules: makeAddrRules:
return new USAddr() return new CanAddr()
which ones to create. This enables a calling object to get the
objects it will need for a specific case.
©Net Objectives, 8/3/2004 83 NetObjectives ©Net Objectives, 8/3/2004 84 NetObjectives
Using The Abstract Factory The Abstract Factory Designed
y
o r
t
US Sales Canadian Sales German Sales c
a
calculate F US Case
freight Task T
Controller I a

These objects can be coordinated with the

These objects can be coordinated with the


Canada x

T These objects can be coordinated with


n ...

the use of the Abstract Factory pattern.


t Case US Tax
verify address e
I

use of the Abstract Factory pattern.

use of the Abstract Factory pattern.


r
f a n
ce
t ... Can Tax
calculate tax e
r
fa
Sales ce
s
money Order es
r
d
d
t A US
gh
dates 1) The Task Controller gives the i
e
Sales Order a reference to the r R
Abstract Factory. F US u ... Canadian
2) The Sales Order gets the l
max weight e
correct object it needs for each R s
variation it has. u ... Canadian I n
3) The Sales Order uses these l t.
e
objects without worrying about s
what version they are. I n
t.

©Net Objectives, 8/3/2004 85 NetObjectives ©Net Objectives, 8/3/2004 86 NetObjectives

Java
The Abstract Factory Designed Implementation of Factory
Abstract class AbstractFactory { class CanAF implements AbstractFactory {
TaskController
SalesOrder abstract CalcTax makeCalcTax();
CalcTax abstract CalcFreight makeCalcFreight(); public CalcTax makeCalcTax() {
+taxAmount():double abstract AddressRules makeAddrRules(); return new CanTax();
public static AbstractFactory }
getAFtoUse(){ public CalcFreight
USTax CanTax GermanTax // Decide whether to return makeCalcFreight() {
AbstractFactory // USAF instance or CanAF instace return new CanFreight();
} }
+makeCalcTax():CalcTax
+makeAddressRules:AddressRules } public AddressRules
+makeCalcFreight():CalcFreight makeAddrRules() {
class USAF implements AbstractFactory { return new CanAddr();
public CalcTax makeCalcTax() { }
AddressRules
USAF CanAF GermanAF return new USTax(); }
+validate():boolean }
public CalcFreight class SalesOrder {
makeCalcFreight() { private CalcTax myTax;
USAddr CanAddr GermanAddr return new USFreight(); private CalcFreight myFreight;
} private AddressRules myAddr;
public AddressRules makeAddrRules() { public SalesOrder
CalcFreight
return new USAddr(); (AbstractFactory myAF) {
+taxAmount():double
} myTax= myAF.makeCalcTax();
}
}
USFreight CanFreight GermanFreight }

©Net Objectives, 8/3/2004 87 NetObjectives 88


Java Java
Java Interfaces Putting it Together

interface CalcTax { /* It comes together by having a client object use a configuration


public double calcTax ( double qty, int id); object to create the correct abstract factory object (assuming the
} configuration object is not acting as the abstract factory). We
encapsulate the access to the configuration object within a static
method on the abstract factory class. The client object then makes a
interface AddressRules { sales order giving it this abstract factory object. */
public bool verify ( Address myAddress); …
} // let’s say we are in the middle of the client object and we already
// have our customer id.
interface CalcFreight {
public double calcFreight ( String fromCode, String toCode, AbstratFactory myAF= AbstratFactory.getAF2Use( customerID);
String frghtClass, double weight); mySalesorder= new SalesOrder( myAF);
}
// mySalesorder is now set up to use the correct strategies, etc.
// It will use myAF to get each particular concrete object

89 90

Implementing Variations What Variations Can Occur?

1. What is the responsibility of the method that’s Add a new case


varying? 1. uses existing variations
2. What inputs are needed for each variation? 2. has a new variant of something that is already
varying
3. What are the outputs needed for each
3. does something different than anybody does now
variation?
An existing case changes
4. Define common interface for each set of
1. changes one of its current options to something else
variations.
2. changes one of its current options to something no
5. Identify (conceptually) common objects and one else does
parameter classes. 3. does something different than anybody does now

©Net Objectives, 8/3/2004 91 NetObjectives ©Net Objectives, 8/3/2004 92 NetObjectives


Reasons to Get Variations of Summary
Commonalities
Make sure variations define commonalities (do
we have enough cases to define the set of Design patterns are really about analysis,
public methods for the abstract class/interface architecture, design, implementation and test.
well enough) They are based on valuable principles,
approaches and a way of looking at the problem
domain that focuses on change.
CVA is great for analysis.
Patterns can help us identify the concepts in our
Design patterns tie CVA into design and
problem domain.
implementation.
This can help us know when we have enough
information.

©Net Objectives, 8/3/2004 93 NetObjectives ©Net Objectives, 8/3/2004 94 NetObjectives

Net Objectives – Who We Are Conference Style Seminars


For Your Organization
We are happy to offer any of these seminars to:
Mission: Guiding and empowering our customers in your user group, if we are in your area and there will be sufficient attendance, at no charge
to your company for a modest fee.
their software development efforts via courses and Please contact Mike Shalloway at [email protected] or call 404-593-8375 if you are interested in us providing a
seminar for your user group or company.
coaching. Many of these talks have been presented at conferences such as SD Expo, OOPSLA, and OOP.
(All seminars are 90 minutes, unless noted otherwise.)
Agile Processes
Vision: Effective and efficient software development Agile Planning Game
Agility and Ceremony: How Can They Co-Exist?
without suffering. Comparing RUP, XP, and Scrum: Mixing a Process Cocktail for Your Team
The Need for Agility
Transitioning To Agile

We provide training, mentoring and consulting for all Analysis


Agile Use Cases
Introduction to Use Cases
phases of object-oriented software development. Agile Coding Practices
Design Patterns and Extreme Programming
Effective Coding Practices
We assist companies transitioning to agile and object- Emergent Design: Design Patterns and Refactoring for Agile Development
Pattern Oriented Development: Design Patterns From Analysis To Implementation
Test-First Techniques Using xUnit and Mock Objects
oriented development by providing mentoring Unit Testing For Emergent Design
C#
throughout the entire development process. C# for Java and C++ Developers
Effective C#
XML
The JDOM Alternative For XML Parsing
XML Data Binding With Castor
XSLT - Step By Step

©Net Objectives, 8/3/2004 95 NetObjectives ©Net Objectives, 8/3/2004 96 NetObjectives


Upcoming Free Seminars Use Case Analysis
in Northern California
Writing Effective Use Cases (WEUC) Use Cases are the best tool known for
capturing and documenting the functional requirements for a system.
Unfortunately, trying to capture a system's use cases all at once often leads to a
severe case of "analysis paralysis". The Ever-Unfolding Story is an incremental
technique for developing use cases and refining them into more detailed
requirements. Because it's incremental, the Ever-Unfolding Story allows for
frequent validation of the requirements as you document them, thus improving the
quality of your requirements document, and supports both artifact-driven and agile
Emergent Design: Design Patterns and Refactoring for development processes.

Agile Development – Aug 5, Berkeley Agile Use Cases (AUC) Agile software development is based on a simple
concept: work on the most important things first, and iteratively look for what is
'now' the most important thing. By doing this a development team is able to adapt
Test-First Techniques Using xUnit and Mock Objects – to changes as they occur, and maximize effectiveness of the development effort.
We use the term "Agile Use Cases" to refer to an incremental technique for
Aug 26, Cupertino iteratively developing Use Cases and refining them into software requirements
using the Ever-Unfolding Story. Agile Use Cases provide for frequent validation of
the requirements, thus supporting agile development.

These courses are similar in content, but with different focus: WEUC is for larger, more
traditional, projects; while AUC is designed to support agile developments. Each of these 3-day
courses consists of lecture and hands-on exercises, and the use case portion is largely based on
Alistair Cockburn's book "Writing Effective Use Cases" - winner of the Jolt Productivity Award for
For more information see 2001.

http://www.netobjectives.com/events/pr_main.htm

©Net Objectives, 8/3/2004 97 NetObjectives ©Net Objectives, 8/3/2004 98 NetObjectives

Agile Development - Management Agile Development - Programming

Agile Development Best Practices In simple terms, an Agile Project is Refactoring, Unit Testing, and Test-Driven Development
one that is predicated on making sure it is always doing the right thing, The practice of Agile Software Development requires, among
not merely following a plan that has since gone out of date. The other things, a high degree of flexibility in the coding process. As
cornerstone of this approach is getting and adapting to feedback as the we get feedback from clients, stakeholders, and end users, we
project progresses. Most projects can't do this, so they fall further behind want to be able to evolve our design and functionality to meet
and either fail or provide inferior products. Changes are of many types, their needs and expectations. This implies an incremental
but the most common (and important) changes are to the system's process, with frequent (almost constant) change to the code
requirements. This course analyzes what it means to be an agile project, we're working on. Refactoring, the discipline of changing code
and provides a number of best practices that provide and/or enhance without harming it, is an essential technique to enable this
agility. Different agile practices (including RUP, XP and Scrum) are process. Unit testing, which ensures that a given change has not
discussed. caused an unforeseen ripple effect in the system, is another.

Effective Project Management Managing software organizations is Agile Software Development with Design Patterns
difficult, as there are many different project personalities. The Developing software with Agility requires a flexible project
personalities that we find range from formal with high-ceremony (stuffy) management paradigm, with the guiding principles that Design
to informal with individual heroes. Teams seem to be either straight- Patterns can provide. This course analyzes what it means to be an agile
jacketed or thrashing - how can we achieve balance? One answer is project, and provides a number of best practices that enhance agility
agility, which loosens the straight-jackets on the one hand and adds a (focusing on XP). After teaching several patterns and the principles
little formality on the other. This course presents the basics of effective underneath them, the course goes further by showing how
Project Management, practiced in an agile manner. patterns can work together with agile development strategies to
create robust, flexible, maintainable designs.

©Net Objectives, 8/3/2004 99 NetObjectives ©Net Objectives, 8/3/2004 100 NetObjectives


Object-Oriented Design | Design Patterns Java: On-site and Instructor Led Web-
Based Training
Effective Object-Oriented Analysis and Design This course is taught Effective Object-Oriented Analysis, Design and Programming in Java
in C++, C#, and/or Java. C++, C#, and Java are powerful programming
languages. Their true value emerges only if they are applied with good Java is a powerful programming language, but its true value emerges only
object-oriented practices. Without these, they can be a difficult language when a solid understanding of Object Oriented Programming techniques are
to maintain and extend. Although many people understand the basics of applied. This two-day course focuses on the essential concepts of OO:
object-oriented programming (polymorphism, interfaces, encapsulation, Encapsulation, Inheritance, and Polymorphism, and includes practical
...) they don't understand how to use these effectively. This three-day
course starts with a better way to do analysis than is traditionally examples and exercises using Java code. Emphasis is placed on
taught. It follows up with 14 practices that both enable better object- implementation issues such as strong cohesion, loose coupling, and
oriented coding as well as create a better understanding of object- eliminating redundancy. Best practices, as illustrated by common design
oriented design. These practices come from both design patterns and patterns are also discussed.
new agile coding methods. (This course is about 40% lab)

Design Patterns Explained: A New Perspective on Object-Oriented On-line/Instructor Led Java Language Training This is our on-line
Design This course goes beyond merely teaching several design equivalent of our 5-day Java training. This is not a self-study program
patterns. It also teaches the principles and strategies that make design where you get e-mail answers to your question. This is a high-touch training
patterns good designs. This enables students to use these advanced program where you work in frequent (albeit remote) contact with both the
design techniques in their problems whether design patterns are even instructor and your student community. The core of the Java language is
present. After teaching several patterns and the principles underneath taught as well as some SWING and many of the core Java classes. It
them, the course goes further by showing how patterns can work requires about 4 hours a week from each participant and takes place over 12
together to create robust, flexible, maintainable designs. weeks.

©Net Objectives, 8/3/2004 101 NetObjectives ©Net Objectives, 8/3/2004 102 NetObjectives

C#: On-site and Instructor Led Web- Object-Oriented Programming in .NET


Based Training
C# for C++ and Java Developers C# is the flagship language for .NET, Effective Object-Oriented Analysis, Design and Programming in C#
and despite what many have suggested, it is neither Java with enhanced The emergence of .Net for distributed computing has brought along with it a
syntax. nor is it C++ with better manners. C# is a new language, with new flagship language: C# (C-Sharp). Those who are familiar with C, C++,
many new syntactic elements. Also, programming in .NET requires an and Java will find the syntax of C# relatively easy to absorb, but using the
understanding of the framework and the development process it is language properly will require a firm grounding in OO concepts and
designed to support. This 1-day course is intended to elucidate the C# practices. This two-day course focuses on the essential concepts of OO:
language in terms of syntax, process, and some early-adopter best Encapsulation, Inheritance, and Polymorphism, and includes practical
practices, making the transition for Java and C++ developers as smooth as examples and exercises using C# code. Emphasis is placed on
possible. implementation issues such as strong cohesion, loose coupling, and
eliminating redundancy. Best practices, as illustrated by common design
On-line/Instructor Led C# Language Training This course teaches the patterns are also discussed.
basics of the C# language as well as many of the standard C# classes that
support the language. It is equivalent to a 5-day C# training class. It Effective Object-Oriented Analysis, Design and Programming in
requires about 4 hours a week from each participant and takes place over VB.NET Visual Basic (VB) has undergone a major transformation with the
12 weeks. new version for .Net. What was once an object-based, procedural language
has now become an Object Oriented language akin to C++, Java, and C#.
While the primary aspects of its syntax has not changed, this shift to a true
Object Orientation will require those with an investment in VB knowledge to
learn new concepts such as inheritance, polymorphism, designing to
interfaces, and object composition. This 2-day course will take the
experienced VB 5.0 or VB 6.0 developer and teach them the OO concepts
they need to move to VB.Net.

©Net Objectives, 8/3/2004 103 NetObjectives ©Net Objectives, 8/3/2004 104 NetObjectives
C++ and XML Bibliography

Effective Object-Oriented Analysis, Design and Programming in C++


C++ is a powerful programming language, but its true value emerges only
when a solid understanding of Object Oriented Programming techniques are
applied. This two-day course focuses on the essential concepts of OO:
Encapsulation, Inheritance, and Polymorphism, and includes practical
examples and exercises using C++ code. Emphasis is placed on
implementation issues such as strong cohesion, loose coupling, and
eliminating redundancy. Best practices, as illustrated by common design
patterns are also discussed.

XML and Its Family of Technologies. XML is a powerful new standard for
data modeling and communication, controlling presentation, and inter/intra-
process communication. As XML is a cross-platform tool, it is a natural fit
for the Java programming language, which is also operating system
independent. This course introduces the student to XML and its primary
supportive technologies such as SAX/DOM, DTD/Schema, JDOM, and XSLT,
with an emphasis on the motivations behind these tools and the way they
interrelate. The instructor will then provide detailed, practical examples of
how these tools can be used in a Java-based project. Best place to buy books: www.bestbookbuys.com
Full bibliography at http://www.netobjectives.com/resources/rs_bks.htm

©Net Objectives, 8/3/2004 105 NetObjectives ©Net Objectives, 8/3/2004 106 NetObjectives

Net Objectives’ Bibliography – Patterns - Core


Community of Practice
We provide a public forum for discussion of topics Design Patterns: Elements of Reusable Object-Oriented
including: Software, Gamma, Helms, Johnson, Vlissides (still the best
Design patterns reference book on patterns)
Agile methods (including XP, Scrum, RUP) Design Patterns Explained: A New Perspective on Object-
Use cases Oriented Design, Shalloway, Trott
Emergent design Design Patterns Java Workbook, Metsker (good for Java
implementation)
We also have several books under development on-line
for review by the community. Pattern Oriented Software Architecture: A System of
Patterns, Bushmann, … (a little dated, but still useful)
Go to http://www.netobjectivesgroups.com for more
information. Timeless Way of Building, Alexander (a classic. The only book
in my top ten personal and top ten business). Fun to read, gives great
To subscribe to our e-zine, send an e-mail to insights.
[email protected] with “subscribe” in the subject
line
©Net Objectives, 8/3/2004 107 NetObjectives ©Net Objectives, 8/3/2004 108 NetObjectives
Bibliography – Patterns – Architectural, Bibliography - The UML and Use Cases
Network, Multithreaded
Core J2EE Patterns: Best Practices and Design Writing Effective Use-Cases, Cockburn. The best book on use-
cases by far.
Strategies, Alur, Crupi, Malks. This book is good for anyone
writing distributed network applications as many of the issues deal Patterns for Effective Use Cases, Adolph, Bramble, et. al. with
with network performance on a conceptual level. However, if you are contributions from our own Dr. Dan Rawsthorne
doing J2EE work, this is an essential read. UML Distilled, 3rd Ed., Fowler (easiest and best way to learn what
the UML is)
Patterns Of Enterprise Application Architecture, Fowler, et.
al.
Pattern Oriented Software Architecture Vol 2: Patterns for Bibliography - Miscellaneous
Concurrent and Networked Objects, Schmidt, Stal, Rohnert, (The) CRC Card Book , Bellin, Simone (CRC cards are a
great way to verify initial designs)
Buschmann, (great book for multithreaded, distributed patterns)
Multi-Paradigm Design for C++, Coplien (excellent
description of commonality/variability analysis -- I even
recommend the first part for Java programmers. See
http://www.netobjectives.com/download/CoplienThesis.pdf for the book’s
equivalent on the web)

©Net Objectives, 8/3/2004 109 NetObjectives ©Net Objectives, 8/3/2004 110 NetObjectives

Bibliography - Java Bibliography – Agile


Effective Java, Bloch. An excellent book. Read a chapter at a Management Oriented
time to best enjoy and absorb it.
Agile Software Development, Cockburn
Java Design, Coad (best book on how to do OO in Java by far)
Thinking in Java (3rd Ed), Eckel. Great book to learn Java and Agile Software Development With Scrum, Schwaber,
Beedle
object-oriented programming from.
Extreme Programming Explained: Embrace Change,
Beck
Bibliography – C++ Extreme Programming Installed, Jeffries
Accelerated C++, Koenig, Moo. The best book to learn C++ Extreme Programming Applied: Playing to Win, Auer,
from. Does not require C knowledge, but that doesn’t slow you Miller
down. An unusual teaching style that works. We use this in our
C++ course.
Effective C++, Meyers. Also used in our C++ course. Teaches
you both to avoid pitfalls and take advantage of strengths.
Thinking in C++ (2rd Ed), Eckel. Great book to learn C++ and
object-oriented programming from. A little more difficult than
Accelerated C++ but goes deeper into OO.
Advanced Programming in the UNIX(R) Environment,
Stevens. If you are on UNIX/LINUX using C/C++ this is a must.
©Net Objectives, 8/3/2004 111 NetObjectives ©Net Objectives, 8/3/2004 112 NetObjectives
Bibliography – Agile Bibliography –
Technically Oriented Resources For Unit Testing in the J2EE
Agile Software Development, Principles, Patterns, and JUnitEE. JUnitEE is a simple extension to JUnit which allows
Practices, Martin. standard test cases to be run from within a J2EE application server. It
Emergent Design: Refactoring and Design Patterns for is composed primarily of a servlet which outputs the test results as
html. www.junitee.org
Agile Development, Bain, Shalloway. 2004. For previews:
http://www.netobjectives.com/emergentdesign/ed_toc.htm EJB Unit Test page on a popular wiki. The purpose of
Java Tools for Extreme Programming: Mastering Open this page is to discuss and possibly define some guidelines for doing
Source Tools Including Ant, JUnit, and Cactus, Hightower, UnitTests on Enterprise Java Beans. www.c2.com/cgi/wiki?EjbUnitTest
Lesiecki
Test infect your Enterprise JavaBeans. Learn how to
Refactoring, Fowler (most in depth book on this old practice) test your J2EE components live and in the wild.
Test Driven Development: By Example, Beck. Not as great www.javaworld.com/javaworld/jw-05-2000/jw-0526-testinfect.html
as we were hoping, but very useful.
Cactus. You might also want to look at this. It's significantly more
complicated than JUnitEE, but it provides the http servlet objects to
your test case. jakarta.apache.org/cactus
JTest. A presumably good, but expensive product from Parasoft.
parasoft.com/jsp/home.jsp
©Net Objectives, 8/3/2004 113 NetObjectives ©Net Objectives, 8/3/2004 114 NetObjectives

On-Line Books Famous Sayings

The check is in the mail.


Many books are available on-line at:
www.netobjectivesbooks.com/N_O_BookFeedback_Wiki/owbase/ow.asp?OnLineBooks I’ll respect you in the morning.
We’ve got all the requirements.
That’ll never happen.
Specific Articles of Great Interest That always happens.
I'll write the tests later.
I can write bad code because I know refactoring….
Test Infected: Programmers Love Writing Tests Yes, I’m sure.
A great article on doing test driven development with Junit by
We’ll integrate it in later.
Gamma and Beck - the authors of JUnit.
http://members.pingnet.ch/gamma/junit.htm I’ll fix it later.

©Net Objectives, 8/3/2004 115 NetObjectives ©Net Objectives, 8/3/2004 116 NetObjectives
Notes Notes

©Net Objectives, 8/3/2004 117 NetObjectives ©Net Objectives, 8/3/2004 118 NetObjectives

Notes Notes

©Net Objectives, 8/3/2004 119 NetObjectives ©Net Objectives, 8/3/2004 120 NetObjectives

You might also like