Sei sulla pagina 1di 221

Software Design and Architecture

An Introduction to Object Oriented


Analysis and Design Using the
Unified Modelling Language

Bill Keller
Spring 2004
Lecture 1: Introduction
 Introduction
– What the course is about
– What the course is not about
 Aims and Outcomes
 Teaching and Assessment
– Design Case Study
– Design Task
 Recommended Reading

BK -- Spring 2004 Software Design 2


What the course is about
 An introduction to object-oriented analysis and design:
– The software development process
– Object-orientation
– Requirements analysis and modelling
– Software quality
 The Unified Modelling Language (UML):
– Use case diagrams
– Static structure and the class model
– Object collaboration and interaction
– Object state and behaviour
 Team-working
– Managing the process

BK -- Spring 2004 Software Design 3


What the course isn’t about
 To keep the course manageable, we won’t cover:
– Requirements capture
– Interface design and HCI Issues
– Deployment and maintenance
 Some UML dealt with only briefly or not at all:
– Packages and components
– Deployment diagrams
– Object constraint language

BK -- Spring 2004 Software Design 4


Course Aims

This course aims to provide first year students with:

– An introduction to fundamental concepts of object-


oriented analysis and design of software
– practical experience of software modelling and design
techniques
– experience of team-working
– an introduction to the Unified Modelling Language

BK -- Spring 2004 Software Design 5


Learning Outcomes
 On successful completion of the course
students should be able to:
– Appreciate the problems inherent in the design of high-
quality software
– Demonstrate the skills needed to model software
components using basic elements of the UML
– Work effectively as a part of a software design team
– Document design decisions appropriately

BK -- Spring 2004 Software Design 6


Why UML?
 UML is a visual modelling language which
– supports analysis and modelling at all stages
– is an emerging standard for software modelling
– Is process neutral: i.e. is not tied to any one particular
design process
 We will cover core aspects of UML, including:
– Use-case diagrams,
– Class diagrams,
– Interaction diagrams: collaboration/sequence
– Statechart and activity diagrams

BK -- Spring 2004 Software Design 7


Teaching Sessions:
Lectures
 Generally there will be two lectures each week:
– Monday: ?? in the Biology Lecture Theatre
– Wednesday: ?? in the Biology Lecture Theatre
Weeks of term Lectures
1–4 1–8
5 no set lectures
6–8 9 – 14
9 no set lectures
10 no set lectures

BK -- Spring 2004 Software Design 8


Lecture Topics

1. Introduction 9. Collaborations and Interactions


2. Software Development 10. Object Behaviour
3. Object Orientation 11. Other UML Notations
4. Requirements and Use Cases 12. Design Quality
5. An Overview of UML 13. Product Quality
6. Class Models and Diagrams 14. Software Patterns
7. More About Class Diagrams
8. Collaboration

BK -- Spring 2004 Software Design 9


Design Case Study:
Automated Teller Machine (ATM)
Statement of purpose:
An ATM is an electronic device designed for
automated dispensing of money. A user can withdraw
money quickly and easily after authorization. The
user interacts with the system through a card reader
and a numerical keypad. A small display screen
allows messages and information to be displayed to
the user. Bank members can access special
functions such as ordering a statement

BK -- Spring 2004 Software Design 10


Teaching Sessions:
Design Workshops
 There will be a design workshop each week
– work together in small teams
– focus on a single design task
 Based around structured design exercises
– work through the development process
– hands-on experience of design techniques
– develop understanding of lecture material

BK -- Spring 2004 Software Design 11


Formal Assessment
 Assessment for the course:
– is based entirely on coursework
– focuses on a single software design task
 Assessed work will consist of
– two submissions of design documentation
– an oral presentation
 Each submission for assessment will involve:
– a team component
– an individual component

BK -- Spring 2004 Software Design 12


Design Task:
Online Bookshop
Statement of Purpose
The eVersity online bookshop allows students and staff
to purchase course books quickly and easily. A user is
able to browse the book catalogue or search for
individual items by title or author. Required books may
be added to a purchase order. Payment is by debit
card although college staff can also pay by salary
deduction. College tutors can order in textbooks for
courses that they teach.

BK -- Spring 2004 Software Design 13


Why Teamwork?
 Software design is usually a team effort:
– Real-world software systems too large and complex to
be tackled by a single individual
– good design requires various sorts of expertise
 Successful design projects need:
– planning,
– communication
– management
 Teamwork plays a central role in this course

BK -- Spring 2004 Software Design 14


Course Texts
 Key text:
– Pooley, R and Stevens P (1998) Using UML: Software Engineering
with Objects and Components, Addison-Wesley
 Recommended texts:
– Lunn, K. (2003) Software Development with UML, Palgrave
– Bennet, S, McRobb, S, and R Farmer (2002) Object-Oriented
Systems Analysis and Design, McGraw-Hill
– Bennet, S, Skelton, J and K Lunn (2001) UML, Schaum’s Outlines
series, McGraw-Hill
– Budgen, D (1994) Software Design, Addison-Wesley

BK -- Spring 2004 Software Design 15


Other Resources
 The course web site:
– Course outline information
– Lecture notes
– Seminar notes
– Details of design task and exercises
– Etc. etc.
 Look under:
Informatics: home > teaching > course directory
or
http://www.cogs.susx.ac.uk/users/billk/sd.html

BK -- Spring 2004 Software Design 16


Summary
 The course covers key ideas in
– object oriented analysis and design
– UML
 Teaching is provided by a combination of
– lectures
– hands-on design workshops
 Assessment is entirely by coursework
– Based on a single design task
– Students work together in design teams

BK -- Spring 2004 Software Design 17


Lecture 2: Software Development
 Software Development Terminology
 Design Objectives and Design Problems
 Why Do Things Go Wrong?
 Project Life Cycles
– The waterfall model
– The spiral model
– The Unified Process

BK -- Spring 2004 Software Design 18


Software Development:
Terminology
 Systems Analysis:
– Process of seeking to understand organization of system
– Investigation and modelling of system requirements
 Software Design:
– Process of producing solution to analysed requirements
– Specifying detail of how system will meet requirements
 Software Engineering:
– Application of a systematic, disciplined approach
– Adherence to high standards of professional ethics

BK -- Spring 2004 Software Design 19


What Do We Need?
 We need software that is:
– Useful and usable: ‘fit for purpose’
– Reliable: free of bugs
– Flexible: can adapt to changing needs of users
– Affordable: to buy and to maintain
– Available: delivered, portable and maintainable
 Objectives are:
– Easy to state, but…
– …may be hard to achieve in practice!

BK -- Spring 2004 Software Design 20


What Are the Problems?
 Total failure of software:
– The London Ambulance Service
– TAURUS stock trading system
– ARIANE 5 Launcher
– August 14th 2003, east coast USA power blackout
 Failure can be catastrophic and very costly
– but, it’s the exception rather than the rule
 Nature of problem depends on stakeholder you ask
– The end users
– The ‘clients’
– The software developers

BK -- Spring 2004 Software Design 21


The End-user’s Perspective
The new system doesn’t:
 do the right thing:
– wrong tasks
– incomplete
 do things right:
– dreadful to use
– poor interface
 doesn’t arrive:
– ‘vapourware’!

BK -- Spring 2004 Software Design 22


The Client’s Perspective
I would never have agreed if:
 I’d known the cost
– Development costs way over budget
 I’d know how long it would take
– It was needed months ago
– The system is already obsolete
 I’d had a choice
– I didn’t want it in the first place!

BK -- Spring 2004 Software Design 23


The Developer’s Perspective
Don’t blame me:
 It’s what you said you wanted
– I can’t help it if you’ve changed your minds
 It’s the best I could do in the time available
– I’ve never done Java/OOA/GUI design/etc. … before
– I always said it was impossible anyway
– I don’t know how it’s supposed to work
 The system’s fine
– it’s the users!

BK -- Spring 2004 Software Design 24


Why Do Things Go Wrong?
 No one reason for failure
– Complexity of software
– Complexity of development process
 Failures broadly due to:
– Unacceptable quality
– Poor productivity

BK -- Spring 2004 Software Design 25


Avoiding the Problems
We need to:
 Adopt a well-defined development process
– Clear phases with deliverables
– Built in verification and validation
– Effective management
 Be clear about project requirements
 Make use of relevant knowledge
 Make sensible use of tools

BK -- Spring 2004 Software Design 26


Project Life Cycles
 The development process can be divided
into various phases
 A number of different models:
– The traditional waterfall life cycle
– The spiral model (Boehm 1988)
– The unified process

BK -- Spring 2004 Software Design 27


The Waterfall Life Cycle
Analysis Waterfall model: process
moves from one stage to
Design another, but never back!
Construction
Testing

Deployment

Maintenance

BK -- Spring 2004 Software Design 28


Pros and Cons of the Waterfall
 Advantages:
– Highly structured with clear phases and deliverables
– Easy to evaluate project progress
– Can be effective for risk management
 Disadvantages:
– Requires perfect decision-making
– Projects rarely follow a simple sequence
– Iterations and revisions are almost inevitable

BK -- Spring 2004 Software Design 29


Waterfall with Iteration
Analysis Models ability to revise earlier
Design stages in the process.

Construction
Testing

Deployment
Revision can be costly
and difficult to manage Maintenance

BK -- Spring 2004 Software Design 30


The Spiral Model (Boehm 1988)

Design, Evaluate
deploy, test

Analyse Analyse risks


requirements and plan
for this
iteration

BK -- Spring 2004 Software Design 31


Advantages of the Spiral Model
 Iteration
– embraces iterative nature of process
 Prototyping
– each loop of the spiral leads a system prototype
 Risk analysis
– adds notion of risk management as a central
concept

BK -- Spring 2004 Software Design 32


The Unified Process
(Booch, Jacobson, Rumbaugh)
 Four distinct phases:
– Inception: determine scope and purpose of the project
– Elaboration: requirements capture and system
architecture
– Construction: build software system
– Transition: installation
 Workflows within each phase:
– Requirements, Analysis, Design, Deployment, Test

BK -- Spring 2004 Software Design 33


The Unified Process
 Project passes through four stages in a sequential
manner (phases)
 Iterations occur within each phase (spiral model)
 Each iteration involves a series of different
activities (workflows)
 Amount of work spent on each activity changes
between phases/iterations

BK -- Spring 2004 Software Design 34


Other Process Models
 Phased release model:
– Waterfall extended to include incremental development
 The evolutionary model
– Emphasizes overlap in loops of spiral model
– Makes explicit differing amounts of effort needed
 Concurrent engineering model
– Accounts for the divide and conquer principle
 Extreme programming

BK -- Spring 2004 Software Design 35


Summary
 Software development is a complex process
– Many possible paths from start to end-product
– Involves balancing needs of various stakeholders
 Development has distinct stages (waterfall)
 Software life cycle iterative (e.g. spiral)
– Prototyping
– Risk management
 There is no one ‘best’ process model
– Different methodologies suit different projects

BK -- Spring 2004 Software Design 36


Lecture 3: Object-Orientation
 What is object-orientation?
– Analysis, Design and Programming
 Why object-orientation?
 Objects concepts:
– State, behaviour and identity
– Abstraction and Encapsulation
– Modularity
– Classes and inheritance
 Summary

BK -- Spring 2004 Software Design 37


What is Object Orientation?
An approach to problem-solving which:
– organizes process and data around discrete,
coherent units known as objects
– represents real-world entities in terms of objects
and their composition
– models system behaviour in terms of object
interaction

BK -- Spring 2004 Software Design 38


OOA, OOD and OOP
 OO Analysis: uses object concepts to
analyse a particular problem domain or
existing system
 OO Design: uses objects to model static and
dynamic aspects of a proposed application
 OO Programming: uses objects and classes
to organize code

BK -- Spring 2004 Software Design 39


Why object-orientation?
In the beginning…
 First computer languages mixed process and data:
– machine code, assembler language
– difficult to produce – limited in application
 Second generation languages separated data from
process:
– Cobol, Fortran, Pascal, C
programs = data structures + algorithms
 Batch data-processing applications served well:
– large-scale banking applications; scientific calculation

BK -- Spring 2004 Software Design 40


Why object-orientation?
Batch and Interactive Systems
 Batch systems process lots of similar data at once:
– e.g. run all the payroll calculations overnight
– fixed process with little variation from run to tun
 Modern interactive systems do things differently:
– small sets of relevant data processed almost instantly
– event-driven user interfaces with much flexibility
 This needs different organization of software:
– group bits of processing and related data together
– organize software around collaborating objects

BK -- Spring 2004 Software Design 41


Why object-orientation?
 Object-oriented languages emerged in modern
form around 1980:
– Smalltalk and OO window system released by Xerox
– Subsequently C++, Java etc.
 Objects provide a natural and productive way of
developing interactive systems:
– Natural to think of GUIs in terms of different objects
– Objects can be linked to provide complex behaviours
– Objects support code re-use

BK -- Spring 2004 Software Design 42


What is an object?
 Objects are the building blocks of OO systems:
 An object:
– has attributes that define its state
– has operations that define its behaviour
– has an identity distinct from other objects
 A well-designed object:
– Provides a coherent view of something (abstraction)
– Limits access to just what is needed (encapsulation)

BK -- Spring 2004 Software Design 43


State, Behaviour and Identity
 State: all the data that an object encapsulates
(values of attributes)
– what do I know?
 Behaviour: the way in which an object reacts to
messages that it understands –
– what can I do?
 Identity: objects persist; you can refer to object by
name; identity versus equality –
– who am I?

BK -- Spring 2004 Software Design 44


Abstraction
 Object typically represent real-world entities:
– Physical things (buildings, people, peripherals…)
– Conceptual entities (dates, plans…)
 Objects abstract away from inessential details:
– Procedural abstraction:
• don’t need to know how a procedure is implemented, just how
to communicate with it
– Data abstraction:
• collect together relevant data

BK -- Spring 2004 Software Design 45


Example:
Objects and Abstraction
sam:Employee sam:Employee

dob: 17.02.80 dob: 17.02.80


address: 20, Foobar Road address: 20, Foobar Road
salary: 25000 height: 5 feet 8 inches
position: programmer weight: 112lb
eye_colour: blue
hair_colour: brown
shoe_size: 8
…..

BK -- Spring 2004 Software Design 46


Encapsulation
 Details of object’s implementation hidden
– Only way that an object can be manipulated is through
its operations
 Consequently, users don’t need to know:
– State: how data is represented or structured
– Behaviour: how operations are implemented
 Object has a well-defined interface:
– public: provide access to essential data and methods
– private: for internal use only

BK -- Spring 2004 Software Design 47


Example:
Object and Interface
An object has a
public and a private sam:Employee
interface
-dob: 17.02.58
Attributes hidden from -address: 20, Foobar Road
view -salary: 25000
-position: programmer
All interaction with the +get_dob()
object must go through +getAddress()
the operations +setAddress()

BK -- Spring 2004 Software Design 48


Modularity
 Modular systems have discrete units with
– high cohesion – package together relevant/coherent
information (abstraction)
– low coupling – provide clean and limited interface
(encapsulation)
 Modular systems are easier to:
– understand (high cohesion is intuitive)
– modify (low coupling/dependency between modules)
– extend

BK -- Spring 2004 Software Design 49


Class, Instance and Object
 Objects may have much in common:
– e.g. employees of a company share certain properties
and behave in similar ways
 In class-based OO languages:
– Classes describe commonality
– Objects belong to classes (are instances of classes)
– Ensure consistency of behaviour
– Provide for type-checking

BK -- Spring 2004 Software Design 50


Classes and Inheritance

Classes organized
Employee
hierarchically

Manager Technician

Classes lower down inherit


ProjectManager properties of those higher up.

BK -- Spring 2004 Software Design 51


Summary
 Object orientation is an approach to problem
solving
 Object orientation grew from the need for
interactive software systems
 Objects have behaviour, state and identity
– abstraction (high cohesion)
– encapsulation (low coupling)
 Classes capture common properties of objects
– Inheritance hierarchy

BK -- Spring 2004 Software Design 52


Lecture 4:
Requirements and Use Cases
 Requirements capture
 Requirements modelling
 Use-cases
 UML Use-Case Diagrams
– Basic notation
– Use-Case Descriptions
– Other notation: generalizes, includes, extends

BK -- Spring 2004 Software Design 53


Requirements Capture
 Aim to develop system to meet user needs
 Capture user requirements capture through:
– Background reading/research
– Interviews with users/clients
– Observation of current practices
– Sampling of documents
– Questionnaires
 This is hard!

BK -- Spring 2004 Software Design 54


Functional and Non-Functional
Requirements
 Functional requirements:
– What processing system must perform
– Details of inputs and outputs
– Details of data held by system
 Non-functional requirements:
– Performance criteria (time/space)
– Security
 Usability requirements
– HCI issues

BK -- Spring 2004 Software Design 55


ATM Case Study:
Statement of Purpose
The design task is to implement an Automated
Teller Machine (ATM):
“An ATM is an electronic device designed for
automated dispensing of money. A user can withdraw
money quickly and easily after authorization. The
user interacts with the system through a card reader
and a numerical keypad. A small display screen
allows messages and information to be displayed to
the user. Bank members can access special
functions such as ordering a statement”

BK -- Spring 2004 Software Design 56


ATM Case Study:
Requirements Summary
1. To allow card holders to make transactions
1. To view and/or print account balances
2. To make cash withdrawals
2. To allow bank members to access special services
1. To order a statement
2. To change security details
3. To allow access to authorized bank staff
1. To re-stock the machine
4. To keep track of how much money it contains

BK -- Spring 2004 Software Design 57


Use Cases
 Use cases used to model functionality:
– What system does, not how
– Focus on functionality from users’ perspective
– not appropriate for non-functional requirements
 UML use case diagrams:
– Document system functionality
– Useful for communicating with clients/users
– Supported by more detailed descriptions of system
behaviour (e.g. text documents, other UML diagrams)

BK -- Spring 2004 Software Design 58


UML Use Case Diagrams
Communication
association
Withdraw (Sub)system
Cash boundary

Check
CardHolder
Balance

Actor Use case

BK -- Spring 2004 Software Design 59


Basic Notation
 Use case diagrams show:
– Actors: people or other systems
interacting with system being
modelled
– Use cases: represent sequences
Withdraw
of actions carried out by the Cash
system
– Communication: between actors
and use cases

BK -- Spring 2004 Software Design 60


Behaviour Specifications
 Document sequence of actions carried out
by system to realize a use case
– Other UML diagrams: e.g.
• sequence diagrams (lecture 9)
• activity diagrams (lecture 11)
– Textual description:
• use-case descriptions
• use-case scenarios

BK -- Spring 2004 Software Design 61


Simple Use Case Description
 Outline of typical sequence of activities:
– The “primary flow” or “path”
 ATM system example:
Withdraw Cash:
The card holder selects the withdraw cash menu, which
is displayed by the system. The card holder selects an
amount of cash. The system debits the user’s account,
returns the user’s card and issues the requested
money.

BK -- Spring 2004 Software Design 62


Elaborated Use-Case Description
Actor System
1 User selects cash System displays cash
withdrawal option withdrawal menu
2 User selects cash System checks cash is
amount available; returns card
3 User takes card System dispenses cash
4 User takes cash System returns to start
menu

BK -- Spring 2004 Software Design 63


Scenarios
 Use case represents a generic case of interaction
 A particular course that a use-case instance might
take is called as scenario
 For example, there may be many Withdraw Cash
scenarios where no cash is withdrawn!
– Card holder has insufficient funds on account
– ATM cannot connect to bank’s system
– ATM does not contain enough cash
– Customer cancels the transaction for some reason

BK -- Spring 2004 Software Design 64


Example Scenarios

 CardHolder Mary Jones selects the cash


withdrawal menu. She changes her mind,
cancels the transaction and takes her card
 CardHolder Peter Smith selects the cash
withdrawal menu. He selects a cash amount,
but is refused because he has insufficient
funds on his account. His card is returned

BK -- Spring 2004 Software Design 65


Other Types of Relationship
 Generalizes:
– Permits actors/use cases to inherit properties of more
general actors/use cases
 Include:
– Permits use case to include functionality of another use
case
 Extend:
– Allows for optional extensions of use case functionality

BK -- Spring 2004 Software Design 66


Generalizes Relationship
BankMember
specializes Withdraw
CardHolder Cash

CardHolder
Check
Balance

Generalizes
Order
Relation
Statement
BankMember

BK -- Spring 2004 Software Design 67


Include Relationship
Select Account
is included in Withdraw
each of the use Cash «include»
cases
«include»
Check Select
Balance Account

BankMember
Order «include»
Note: include was Statemen
formerly called uses t

BK -- Spring 2004 Software Design 68


Extend Relationship
CardHolder has the option of
printing out a balance when the
Check Balance use case is Print
invoked. Balance
«extend»

Check
Balance
Extend
CardHolder relationship

BK -- Spring 2004 Software Design 69


Summary
 Use case analysis often a first step in system
development:
– provide high-level view of system functionality (what
rather than how) and its users
– Model generic activities
– Particular instances of use-cases are termed scenarios
 UML use case diagrams
– Contain actors, use cases and associations
– supported by behaviour specifications (e.g. use-case
descriptions)

BK -- Spring 2004 Software Design 70


Lecture 5: An Overview of UML
 Background to UML
– A little history
– What UML is, and what it is not
 Models and Diagrams
– Use-case diagram
– Activity diagram
– Class diagram
– Interaction diagram
 UML Tools

BK -- Spring 2004 Software Design 71


A Little History
 Late 1960s:
– Emergence of OO programming languages
– Simula-67, Smalltalk (1970)
 1970s:
– Appearance of first OOA&D methodologies
 1980s and early 1990s:
– Many competing general development methods and
modelling languages (over 50)
– The “methods wars”

BK -- Spring 2004 Software Design 72


Emergence of UML
 By the mid 1990s three key methods had become
prominent:
– Rumbaugh: Object Modelling Technique
– Booch: Booch ’93 “OO Analysis and Design”
– Jacobson: OO Software Engineering
 1995: Rumbaugh, Booch and Jacobson join forces
in Rational:
– Develop the (Rational) Unified Process
– Develop the Unified Modelling Language (UML)

BK -- Spring 2004 Software Design 73


UML is….
 A ready-to use visual modelling language:
– A language, not just a notation
– For OO analysis and design of (software) systems
– UML diagrams provide for various views of systems
 Simple and expressive:
– UML has core set of expressive concepts/notations
 Extensible:
– allows specialization/addition of concepts/notations
 An emerging standard for modelling systems

BK -- Spring 2004 Software Design 74


UML is not…
 A visual programming language
– UML is for modelling/conceptualizing/visualizing
systems, not for implementing them
– Not tied to a particular programming language
 A development process:
– UML is process neutral
– Not tied to a particular process (e.g. Unified Process)
 A development tool
 A guarantee of success

BK -- Spring 2004 Software Design 75


System, Design, Model, Diagram
Important to be clear about terminology:
– System: program or collection of programs meeting
user requirements – end goal of the development
process
– Design: collection of decisions about how to build
system – end product of the design process
– Model: abstract representation of system or design from
a particular viewpoint – a product of some stage of the
design process
– Diagram: visual representation of (part of) model

BK -- Spring 2004 Software Design 76


Models and UML Diagrams
 Use case model: describes the high level
functionality of system from users point of view
– UML use case diagram; UML activity diagram
 Static model: describes the elements of system and
their organization and relationships
– UML class diagram; UML package diagram
 Dynamic model: describes behaviour of system
over time
– UML collaboration diagram; UML sequence diagram;
UML statechart diagram
BK -- Spring 2004 Software Design 77
UML Use Case Diagram

Check «extend»
Balance Print
Balance
CardHolder «include»

Withdraw
Cash Select
«include»
Account
Order
Statemen «include»
BankMember t

BK -- Spring 2004 Software Design 78


UML Activity Diagram
ATM Customer ATM System
Select withdrawal Display menu

[Insufficient funds]
Select amount

[Sufficient funds]
User takes
Return card Notify user
card

Dispense cash

BK -- Spring 2004 Software Design 79


UML Class Diagram
1..3 *
CardHolder Account
holds
1
*
Transaction
Simple ATM class
diagram, showing static
structure for banking
domain
Debit Credit

BK -- Spring 2004 Software Design 80


UML Collaboration Diagram
1:select withdrawal menu
2:select amount 3:withdraw sum

:ATMUI :CardHolder

6:dispense sum 4:debit


:ATMCustomer
account
Collaboration diagram
:CashDispenser :Account
with interactions
realizing the Withdraw 5:add
Cash use case debit
:Debit

BK -- Spring 2004 Software Design 81


UML Sequence Diagram

:ATMUI :ATMControl :CardHolder :Account :CashDispenser

select withdrawal
menu
select amount
withdraw
withdraw :Debit
sum debit add
sum account debit

dispense sum
return
card

BK -- Spring 2004 Software Design 82


UML State Diagram
exit /balance = 0

withdraw(sum) withdraw(sum)
withdraw(sum)
/balance -=sum /balance -=sum
[sum >balance]
/balance -=sum
inCredit inDebit
entry/balance -= pen
deposit(sum)
[sum >= balance]
deposit(sum) deposit(sum)
/balance+=sum /balance += sum /balance+=sum
close close

BK -- Spring 2004 Software Design 83


UML CASE Tools
 Poseidon UML Standard Edition:
– A professional UML Case tool provided on lab PCs
 Poseidon UML Community Edition:
– A cut-down version of the above that is freely downloadable from:
http://www.gentleware.com/
 Rational Rose:
– Can be run from Sun machines. In .login file add the line:
source /local/global/rational_login
– To run, at prompt do: rose
&
 Eclipse + Omohondro plug-in:
– Useful if you like Eclipse, though not fully featured as yet.

BK -- Spring 2004 Software Design 84


UML Drawing Tools
 Some drawing tools incorporate UML diagrams
– e.g. dia: http://dia-installer.sourceforge.net/
 But for small design tasks, any half-way decent
drawing package will probably do:
– All the UML drawing in these lectures were produced
with Windows AutoShapes
 Or you could just use paper and pencil:
– Remember: the goal is good design rather than pretty
pictures!

BK -- Spring 2004 Software Design 85


Summary
 UML is a an expressive and flexible visual modelling
language
– Emerged in the mid 90s,
– Combines ideas from several notations
 Should distinguish between
– System, design, model and diagram
 UML supports modelling from different viewpoints:
– Functional view
– Static view
– Dynamic view

BK -- Spring 2004 Software Design 86


Lecture 6:
Class Models and Diagrams
 Class models
– What makes a good class?
– Developing the class model
 Finding classes and associations (Part 1)
– Noun identification
 Basics of UML Class Diagrams
– Class notation
– Associations
 ATM Case Study: initial class model

BK -- Spring 2004 Software Design 87


What is a Class Model?
 Model of the static structure of a system
– What classes are there?
– How are these classes related?
 Allocation of class responsibilities:
– Management of data within the system
– Behavioural responsibilities of classes
 May not be immediately concerned with:
– functional requirements
– how classes interact to achieve behaviour

BK -- Spring 2004 Software Design 88


What Makes a Good Class Model?
A good class model consists of classes that
1. can provide all of the required system behaviour
2. represent (as far as possible) enduring domain
objects
If 1 is self-evident, 2 is more like an act of faith:
– part of the object oriented design philosophy
– modelling the application domain can provide a
good basis for developing the required software
– in practice, need to compromise between 1 and 2

BK -- Spring 2004 Software Design 89


Developing the Class Model
Class model typically developed in stages:
 Analysis phase:
– Classes in problem domain of primary interest
– Basic relationships between classes
– Little detail about class responsibilities
 Design phase:
– Additional classes provided for implementation
– Class responsibilities (attributes, operations) refined
– Relationships between classes refined

BK -- Spring 2004 Software Design 90


Finding Classes and Associations
 How do we find classes?
– Doesn’t really matter, as long as the resulting class
model is good!
 We’re unlikely to get it right first time:
– Probably shouldn’t even try!
– Finding classes and associations is a process of:
• Evolution
• Revolution

BK -- Spring 2004 Software Design 91


Noun Identification
 A way of finding “enduring domain objects”:
 A “data driven development” (DDD) method
– Useful in early stages of development (analysis)
– Provides “first-cut” set of problem classes
 Useful in analysis of requirements:
1. Pick out all nouns/noun phrases in requirements
documentation
2. Filter out ‘inappropriate’ expressions
3. Use remaining phrases as candidate classes

BK -- Spring 2004 Software Design 92


ATM Case Study:
Finding Candidate Domain Classes
Step 1: underline nouns/noun phrases:
“An ATM is an electronic device designed for automated
dispensing of money. A card holder can get a
balance, or withdraw money from an account after
authorization. Customers interact with the system
through a simple interface consisting of a display
screen, a card reader and a numeric keypad. Cash is
obtained from a dispenser. Bank members are card
holders who can access additional functions such as
ordering a statement from the bank”

BK -- Spring 2004 Software Design 93


ATM Case Study:
Finding Candidate Classes
Stage 2: Discard candidates that are:
– Events: dispensing of money, authorization
– Vague: function, device
– Meta-language terms: system
– Redundant terms: customer same as card holder; cash
same as money
– Outside scope of system: bank
• but retain actors such as card holder?
– Constitute everything: ATM (system)
• Avoid monolithic design!

BK -- Spring 2004 Software Design 94


ATM Case Study:
Finding Candidate Classes
 Remaining nouns represent candidate domain
objects/classes:
– Actor/Role entities: card holder, bank member
– Boundary (interface) objects: interface, card reader,
keypad, display screen, cash dispenser
– Entity (domain) objects: balance, money, account,
statement
 This analysis provides the initial set of classes in
the ATM class model.

BK -- Spring 2004 Software Design 95


Basics of UML Class Diagrams
Notation for documenting class models:
 Notation for classes:
– Rectangle with class name (minimally)
– Details of attributes and operations (additionally)
 Notation for relationships:
– Associations: model dependencies between classes
– Generalizations: model “is a” relationships between
classes
 Model represented by one or more class diagrams

BK -- Spring 2004 Software Design 96


Basics of UML Class Notation
Only class name shown Operations shown

CardHolder CardHolder
authorize()
Both attributes
Attributes shown and operations
CardHolder CardHolder shown, with type
lastName lastName:String information
firstName firstName:String
authorize()

BK -- Spring 2004 Software Design 97


Basics of UML Associations
In the banking domain
each CardHolder has Simple association
an Account between classes

CardHolder Account

holds
CardHolder Account

Named
association

BK -- Spring 2004 Software Design 98


What Do Associations Imply?
 An association implies collaboration between
instances of two classes
– Classes A and B are associated if an instance of A
needs to “know about” an instance of B
 A needs to “know about” B if an instance of A:
– sends a message to an object of class B, or
– has an attribute with a value of class B, or
– creates an object of class B, or
– receives a message with an object of class B as an
argument

BK -- Spring 2004 Software Design 99


ATM Case Study:
Initial Class Model
holds has
CardHolder Account Balance

CashDispenser ATMUI

Initial class diagrams Screen CardReader KeyPad


for the ATM System

BK -- Spring 2004 Software Design 100


Summary
 Class model represents static structure of system
– Classes and their relationships
 Developing class model is a staged process:
– May begin by identifying classes in application domain
– Later add classes required for implementation reasons
 Noun identification is a simple analysis technique
for finding domain classes
 UML class diagrams used to document class
model

BK -- Spring 2004 Software Design 101


Lecture 7:
More About Class Diagrams
 More about associations:
– navigability
– multiplicity
– aggregation and composition
 The generalizes relationship
 More about attributes and operations
– type information and visibility
 ATM Case Study:
– Refining the ATM class model and refactoring

BK -- Spring 2004 Software Design 102


Navigability
 Consider CardHolder and Account again:
CardHolder Account

 The diagram does not specify which way the


association is supposed to be navigated:
– Does CardHolder ‘know about’ Account?
– Does Account ‘know about’ CardHolder?
 In the absence of more specific information:
– Each ‘knows about’ the other

BK -- Spring 2004 Software Design 103


Showing Navigability
 Navigability may be shown with an arrow:
CardHolder Account

CardHolder knows about


Account (not vice-versa)
• Named association usually implies direction
CardHolder Account
holds
Direction given by
arrow head

BK -- Spring 2004 Software Design 104


Multiplicity
 So far, associations tell us nothing about how
many objects are involved
CardHolder Account
holds

 Does a CardHolder hold:


– just one Account ?
– several Accounts ?
 Can one Account belong to many CardHolders?

BK -- Spring 2004 Software Design 105


Adding Multiplicities
 Specify number of objects involved:
– An exact number, such as: 1, 3 or 100
– A range of numbers, such as 1..10
– An arbitrary number: *
Each Account is held by Each CardHolder holds
exactly one CardHolder one or more Account

1 1..*
CardHolder Account
holds

BK -- Spring 2004 Software Design 106


Aggregation and Composition
 Provide detail about the kind of association:
 Aggregation:
– Records whole-part structure
 Composition:
– as aggregation, but
– implies strong ownership

BK -- Spring 2004 Software Design 107


Using Aggregation
Use when there is clear part-whole structure:
The aggregate
Each account Account (‘whole’) end of
consists of or
1 1 the association
includes debits
and credits 0..* 0..* Aggregation
symbol
Debit Credit

Each debit and credit The ‘part’ end of


is part of one account the association

BK -- Spring 2004 Software Design 108


Using Composition
 Used to indicate strong ownership:
– coincident lifetime of objects
– part cannot exist without whole and vice-versa
Notation for
composition
ATMUI

1 1 1
Screen CardReader KeyPad

BK -- Spring 2004 Software Design 109


Generalization
 A conceptual relationship between classes
– the kind-of or is-a relation:
e.g. BankMember is a kind of CardHolder
 Makes a strong claim about behaviour:
– a BankMember can do anything a
CardHolder can do
– the classes conform to the same interface

BK -- Spring 2004 Software Design 110


Notation for Generalization
More general class
(super-class) Any BankMember is a
CardHolder (but not
necessarily vice-versa).
CardHolder
This implies that a
Notation for BankMember object:
generalization • should behave appropriately
BankMember if treated as a CardHolder

More specific • will exhibit additional


class (sub-class) behaviours

BK -- Spring 2004 Software Design 111


Generalization and Inheritance
 In OOP, generalization is implemented as
inheritance:
public class BankMember extends CardHolder {
. . . .
}

 Powerful mechanism for code re-use, but beware:


– may increase dependency between classes
– not always appropriate

BK -- Spring 2004 Software Design 112


More On Attributes and Operations

• Refining details of class responsibilities:

Visibility: Distinguish Type Information:


between private Debit provide type or
and public class information
attributes or -date: String for attributes
operations +getDate()
+getValue()

BK -- Spring 2004 Software Design 113


ATM Case Study:
Refining the Class Model
 Adding navigability, multiplicities, aggregation
and generalization
CardHolder holds has
Account Balance
authorize() 1..3 1..* 1 1

0..* 0..*
Debit Credit
BankMember getDate() getDate()
getValue() getValue()

BK -- Spring 2004 Software Design 114


Design Note: Refactoring

It seems that the Debit and


Credit classes have quite a Account
bit in common.
Is there an alternative way 0..* 0..*
of structuring things?
Debit Credit
Does this lead to better
getDate() getDate()
design and if so, how?
getValue() getValue()

BK -- Spring 2004 Software Design 115


Design Note: Refactoring
The new Transaction Account
class factors out the
common elements of the 1
Debit and Credit classes. 0..*
This is known as Transaction
refactoring. getDate()
Is the refactored design getValue()
better and if so, in what
way?
Debit Credit

BK -- Spring 2004 Software Design 116


Summary
 Development of class model is to some extent a
process of refinement:
– Navigability (direction of association)
– Multiplicities (cardinality of associations)
– Aggregation and composition (part-whole)
 Generalization relationship between classes
– Promotes code-reuse
– Refactoring

BK -- Spring 2004 Software Design 117


Lecture 8:
Collaboration
 Views and Diagrams
 Responsibility-Driven Design (RDD)
– Class-Responsibilities-Collaborators (CRC) Cards
– Using CRC cards
 Collaboration
– What is collaboration
– UML Notation for Objects and Links
– Basics of UML Collaboration Diagrams
 Collaboration and Interaction
– Showing interaction
– Realizing use cases

BK -- Spring 2004 Software Design 118


Views and Diagrams
Different views of software system:
 Functional (user) view:
– use case diagram
 Structural (static) view:
– class diagram
 Behavioural (dynamic) view:
– collaboration diagram
– sequence diagram } interaction diagrams
– state-chart diagram

BK -- Spring 2004 Software Design 119


Responsibility-Driven Design
 Responsibility-Driven Design (RDD):
– Responsibility for data
– Responsibility for behaviour
 Based on examination of
– collaboration between classes
– interaction needed to fulfil some required behaviour
 Develop class model by identifying:
– operational requirements of classes
– collaboration between classes

BK -- Spring 2004 Software Design 120


Class-Responsibility-Collaboration
(CRC) Cards
 A simulation technique:
– enact collaboration between classes
– e.g. “walk-through” a use-case scenario
 Useful technique for allocating responsibilities:
– required attributes and operations
– new classes required for implementation
 May be used at various stages in development:
– early on, to develop initial class diagram
– later, to model object interaction

BK -- Spring 2004 Software Design 121


CRC Card Example
Class name
CardHolder
Responsibilities: Collaborations:
Provide card holder Account provides
information balance details
Meet requests for Account adds debit
balances/withdrawals transactions
Brief list of
responsibilities Brief list of collaborators

BK -- Spring 2004 Software Design 122


Using CRC Cards
Group role-play activity:
1. Brainstorm to identify roles/objects involved in
required behaviour (e.g. a use-case)
2. Create CRC cards for roles/objects
3. Allocate each role/object to a team member
4. Enact the behaviour
5. Identify/record missing responsibilities
6. Go back to 4., if needed

BK -- Spring 2004 Software Design 123


What is Collaboration?

 In object-oriented systems:
– individual objects are responsible for only a bit of
overall functionality
– useful high-level behaviour (use cases) realized by
objects working together
– objects interact by sending messages to each other
 Collaboration is: “working together for the
purpose of providing some useful behaviour”
– documented by collaboration diagrams

BK -- Spring 2004 Software Design 124


ATM Case Study:
Withdrawal Use-Case Realization
Withdraw
Cash

ATMCustomer

Withdraw Cash:
The ATM customer selects the withdrawal menu, which is
displayed by the system. The card holder selects an
amount of cash. The system debits the user’s account,
returns the user’s card and issues the requested money.

BK -- Spring 2004 Software Design 125


ATM Case Study:
Identifying Collaborating Classes
The dashed line indicates Collaboration
that this class participates in icon
the collaboration

Withdraw
cash

ATMUI Debit

CardHolder Account CashDispenser

BK -- Spring 2004 Software Design 126


UML Collaboration Diagrams

 Collaboration diagrams involve:


– Objects: instances of classes
– Links: instances of associations
– Actors: things/people interacting with the system
 A collaboration will also usually show:
– Interactions: the sequence of messages passing
between objects

BK -- Spring 2004 Software Design 127


UML Notation for Objects
An object An anonymous
named object of class
user391 CardHolder

user391 :CardHolder

user391:CardHolder Objects are notated


rather like classes,
An object named but attributes and
user391 of class operations are
CardHolder omitted

BK -- Spring 2004 Software Design 128


UML Notation for Links
Links drawn as for
associations.

:Account user391
Links may have
1
multiplicities
0..* Links are instances of
:Debit associations in the class
model
Links represent message
passing between
collaborating objects

BK -- Spring 2004 Software Design 129


ATM Case Study:
Classes Involved in the Use Case
ATMUI CardHolder Portion of the class
model involved in
realizing the
Withdraw Cash use
case.
CashDispenser Account

Debit

BK -- Spring 2004 Software Design 130


ATM Case Study:
Withdrawal Collaboration Diagram
:ATMUI :CardHolder

:ATMCustomer

Tentative collaboration :CashDispenser :Account


diagram for Withdraw Cash
use.
Note the structural similarity
to the class model shown :Debit
previously.

BK -- Spring 2004 Software Design 131


Collaboration and Interaction
 Individual objects have local responsibilities:
– For data
– For behaviour
 Objects interact to achieve global behaviours:
– Use case realization
 Collaboration diagrams show interaction through:
– Structural relationship: objects and links
– Interaction: messages flowing along links

BK -- Spring 2004 Software Design 132


UML Notation for Interactions
Message number Message name

7: get balance()

:CardHolder :Account

Messages are sent between Message flow has


objects along the links. direction of arrow

BK -- Spring 2004 Software Design 133


ATM Case Study:
Collaboration with Interaction
1:select withdrawal menu
2:select amount 3:withdraw sum

:ATMUI :CardHolder

6:dispense sum 4:debit


:ATMCustomer
account
Collaboration diagram
:CashDispenser :Account
with interactions
realizing the Withdraw 5:add
Cash use case debit
:Debit

BK -- Spring 2004 Software Design 134


Summary
 Individual objects are responsible for small pieces
of behaviour
 High-level functionality is achieved through
object collaboration
 UML Collaboration Diagrams show:
– Participating objects and links between objects
– Interactions (messages sent between objects).
 Stereotypes provide a mechanism for
distinguishing between different sorts of object.

BK -- Spring 2004 Software Design 135


Lecture 9:
Collaborations and Interactions
 Object stereotypes:
– Entity, boundary and control objects
 Basics of Interaction Sequence Diagrams
– Objects and life-lines
– Messages and control
 ATM Case Study: the withdrawal use-case
– Collaboration diagram with interactions
– Interaction sequence diagram

BK -- Spring 2004 Software Design 136


More about UML Objects:
Stereotypes
 Provide a means of indicating that certain objects
have special roles
 UML has three distinct stereotypes:
entity objects: model things in the application domain
that the system needs to keep information about.
boundary objects: mediate communication with the
outside world.
control objects: organize complex behaviours
involving various boundary and entity objects.

BK -- Spring 2004 Software Design 137


Entity and Boundary: Notations
Named entity
object <<entity>>
Account
:Account
Alternative notations
for stereotyped classes
Account

:ATMUI
Boundary object

BK -- Spring 2004 Software Design 138


ATM Case Study:
Entity and Boundary Collaboration
1:select withdrawal menu
2:select amount 3:withdraw sum 6:dispense sum

:ATMCustomer :ATMUI :CardHolder :CashDispenser


4:debit
Withdraw cash use account 5:add debit
case collaboration
showing boundary
and entity objects
:Account :Debit

BK -- Spring 2004 Software Design 139


Design Note:
Responsibility-Driven Design
Do the responsibilities
of the CardHolder class 3:withdraw sum 6:dispense sum
seem coherent and
reasonable?
How do they compare to :ATMUI :CardHolder :CashDispenser
the CRC card we drew
4:debit
earlier?
account
Is there a better way of
sharing out the
behaviour? :Account

BK -- Spring 2004 Software Design 140


Design Note:
Responsibility-Driven Design
CardHolder
CardHolder
collaborates with
Account Responsibilities: Collaborations:
But should it
need to know
Provide card holder Account provides
about the information balance details
CashDispenser? Meet requests for Account adds debit
balances/withdrawal transactions

BK -- Spring 2004 Software Design 141


Design Note:
Responsibility-Driven Design
1:select withdrawal menu
3:withdraw sum 7:dispense sum
2:select amount

8:return
:ATMUI card :ATMControl :CashDispenser
:ATMCustomer
4:withdraw
New ATMControl sum 5:debit
account 6:add debit
object mediates
between boundary
and entity objects
:CardHolder :Account :Debit

BK -- Spring 2004 Software Design 142


Interaction Sequence Diagrams
An alternative to collaboration diagrams
 Show objects involved in a collaboration
– but, not the structural relationships between objects
– underlying collaboration is left implicit
 Show order of interaction graphically
– c.f. textual representation in collaboration diagrams
using message numbering
– Visual representation of time can be clearer

BK -- Spring 2004 Software Design 143


Basics of UML Sequence Diagrams
Interaction sequence diagrams show:
 Objects and actors:
– just as for collaboration diagrams
 Object life-lines:
– represent time as seen from a given object
– time passes as we move from top to bottom of diagram
 Messages and control
– messages flow between object life-lines
– focus of control changes as messages are sent

BK -- Spring 2004 Software Design 144


Notation for Objects and Lifelines
objects
Objects are shown
along the top of the
:ATMUI :CardHolder diagram

time
Object life-lines are
shown as dashed
lines running from
top to bottom of
diagram

BK -- Spring 2004 Software Design 145


Notation for Messages and Control

:ATMUI :CardHolder
debit account Focus of control
Message shown shown as narrow
using an arrow rectangle
from sender to
receiver
Focus of control passes
from one object to
another as messages
flow between them

BK -- Spring 2004 Software Design 146


ATM Case Study:
Sequence Diagram for Withdrawal
:ATMUI :CardHolder :CashDispenser

:ATMControl :Account
select withdrawal
menu
select amount
withdraw
withdraw :Debit
sum debit add
sum account debit

dispense sum
return
card

BK -- Spring 2004 Software Design 147


Withdrawal Use Case:
Entity, Boundary and Control
:ATMUI :ATMControl :CardHolder :Account :CashDispenser

select withdrawal
menu
select amount
withdraw
withdraw :Debit
sum debit add
sum account debit

dispense sum
return
card

BK -- Spring 2004 Software Design 148


ATM Case Study:
Restructuring the Class Model
CardHolder Account
1 1..*
+getBalance +debit
+withdraw +credit
* 1
1 0..*
1 1 Transaction
ATMUI ATMControl
+getDate()
1
+getValue()
1
CashDispenser
Debit Credit

BK -- Spring 2004 Software Design 149


Summary
 Objects interact by passing messages
– Interaction diagrams document behavioural view
 Collaboration diagrams:
– show messages passing between objects along links
– provide textual representation of control flow
 Interaction sequence diagrams:
– Show objects and life-lines
– Provide visual representation of control flow

BK -- Spring 2004 Software Design 150


Lecture 10: Object Behaviour
 The Behavioural view
– state and behaviour
 Basics of UML Statechart Diagrams
– states, transitions and events
– guard conditions
– actions
 ATM Case Study
– State Diagram for the Account Class
 Activity Diagrams

BK -- Spring 2004 Software Design 151


The Behavioural View
The behavioural view describes:
 Interactions between objects to realize high-level
functionality:
– Collaboration diagrams
– Interaction Sequence diagrams
 Behaviour of individual objects in response to
events:
– Statechart diagrams

BK -- Spring 2004 Software Design 152


State and Behaviour
 In lecture 3 we saw that objects have:
– State: all the data that an object encapsulates (values of
attributes)
– Behaviour: the way in which an object reacts to
messages that it understands
 Object behaviour:
– depends on state
– involves changes of state

BK -- Spring 2004 Software Design 153


Some Questions about ‘State’
 What is meant by the ‘state’ of an object?
– Depends on attribute values, but
– State is an abstraction
 Should objects have lots of states, or a few?
– Too many states makes object behaviour difficult to
characterize/understand
 Can consideration of state inform class design?
– Split classes with too many states into simpler classes

BK -- Spring 2004 Software Design 154


Basics of Statechart Diagrams
 Describe the behaviour of individual model
elements:
– mostly used to model behaviour of objects
– but, can be used for other things
 Statechart diagrams consist of:
– States of objects
– Transitions between states
– Events driving transitions
– Actions performed by objects

BK -- Spring 2004 Software Design 155


States and Transitions

Simple states
Start state

inCredit inDebit

Transitions
Basic statechart
diagram for the
End state Account class

BK -- Spring 2004 Software Design 156


Transitions and Events
 transitions are triggered by events:
Name of event
triggering the
open transition
withdraw
Transitions between
inCredit inDebit states depend on events
deposit
close close

BK -- Spring 2004 Software Design 157


Guard Conditions
 Written alongside associated event:
event [guard]
e.g.
withdraw(sum) [sum > balance]

inCredit inDebit
deposit(sum) [sum > -balance]

 Condition must hold for event to trigger transition

BK -- Spring 2004 Software Design 158


Actions
 Events typically bring about actions:
– Events are things that happened to an object
• e.g. receipt of a message
– Actions are things that an object does
• e.g. sending a message
 Actions may be shown either:
– on transitions
essentially equivalent
– on states

BK -- Spring 2004 Software Design 159


Actions on Transitions
 Written alongside event:
event / action
event [guard] / action
e.g.
withdraw(sum)/balance = balance - sum

inCredit inDebit
deposit(sum)/balance = balance + sum

 Use where action depends on the transition

BK -- Spring 2004 Software Design 160


Actions on States
 Written within state:
entry / action
exit / action
e.g.
inDebit
entry / balance = balance - penalty

 Use where action depends on state

BK -- Spring 2004 Software Design 161


ATM Case Study:
State Diagram for Account Class
exit /balance = 0

withdraw(sum) withdraw(sum)
withdraw(sum)
/balance -=sum /balance -=sum
[sum >balance]
/balance -=sum
inCredit inDebit
entry/balance -= pen
deposit(sum)
[sum >= balance]
deposit(sum) deposit(sum)
/balance += sum
/balance+=sum /balance+=sum
close close

BK -- Spring 2004 Software Design 162


Summary
 Objects have state and behaviour
– behaviour depends on state
 Statechart diagrams describe object behaviour
– events trigger transitions between states
– transitions may depend on guard conditions
– events can result in actions
 Activity diagrams
– share much notation with state diagrams
– different purpose

BK -- Spring 2004 Software Design 163


Lecture 11
Other UML Notations
 Activity Diagrams
– Documenting workflows
– Basic Notation
 ATM Case Study: withdrawal use-case
 Packages and Subsystems
 Implementation Diagrams (very briefly)
– Component diagrams
– Deployment diagrams

BK -- Spring 2004 Software Design 164


UML Activity Diagrams
 Used to document workflows:
– Modelling business activities or systems
– Modelling activities within/between use-cases
– Detailed description of operations in classes
 Similar notation to UML statechart diagrams:
– Activities (action states)
– States
– Transitions

BK -- Spring 2004 Software Design 165


Activity Diagrams: Basic Notation

Start state

Insert card
Activities
Transitions

Enter PIN

Simple Activity
Diagram with start
and stop states Final state

BK -- Spring 2004 Software Design 166


Activity Diagrams: Decision Points

Decision points allow


Insert card branching depending on
a condition

Enter PIN Guard condition


Decision
point
[Invalid PIN]
Confiscate card
[Valid PIN]

Display Menu

BK -- Spring 2004 Software Design 167


Activity Diagrams: Swimlanes
ATM Customer ATM System

Insert card Request PIN


Swimlanes
are a useful
Enter PIN
notation for
Validate PIN
indicating
where an
activity
takes place

BK -- Spring 2004 Software Design 168


ATM Case Study:
Workflow for Withdrawal Use-Case
Withdraw
Cash

ATMCustomer

Withdraw Cash:
The card holder selects the cash menu which is
displayed by the system. The card holder selects an
amount of cash. The system returns the user’s card
and issues the requested money.

BK -- Spring 2004 Software Design 169


ATM Case Study:
Elaborated Use-Case Description
Actor System
1 User selects cash System displays cash
withdrawal option withdrawal menu
2 User selects cash System checks cash is
amount available; returns card
3 User takes card System dispenses cash
4 User takes cash System returns to start
menu

BK -- Spring 2004 Software Design 170


ATM Case Study:
Activity Diagram for Withdrawal
ATM Customer ATM System
Select withdrawal Display menu

[Insufficient funds]
Select amount

[Sufficient funds]
User takes
Return card Notify user
card

Dispense cash

BK -- Spring 2004 Software Design 171


Activity Diagrams & State Diagrams
 Notationally, very similar
– Important to distinguish purpose/use
 State diagrams:
– behaviour of individual objects/components
– show state transitions triggered by events
 Activity diagrams:
– behaviour within systems/organizations
– transitions between activities (work flows)

BK -- Spring 2004 Software Design 172


Packages and Subsystems
 Package: a collection of model elements:
– grouping semantically related elements
– analysing system architecture
– hiding irrelevant detail on a diagram
 Subsystem: special sort of package:
– representing units of the physical system
– developing components of the design

BK -- Spring 2004 Software Design 173


ATM Package Example
ATM System

ATM UI
Bank
Server
Account
Manager

BK -- Spring 2004 Software Design 174


UML Component Diagrams
Relationship
between
components
<<communicates>>
ATMUI.java ATMControl.java

Component diagrams
show how physical
units such as files,
Notation for
executables, etc. are
components
related

BK -- Spring 2004 Software Design 175


UML Deployment Diagrams
Communication association

<<TCP/IP>>
:ATMClient :ATMServer
ATM.jar Bank.jar

Deployment diagrams
model configuration of
Nodes hardware elements

BK -- Spring 2004 Software Design 176


Summary
 Activity diagrams:
– Model workflows
– Transitions between activities
– Use-case modelling/business modelling
 Packages
– Group logically related units
 Implementation diagrams:
– Component diagrams document physical elements
– Deployment diagrams document hardware elements

BK -- Spring 2004 Software Design 177


Lecture 12:Design Quality
 What is Quality?
 Quality in Software
 Key design objectives:
– reliability, maintainability, usability, re-usability,
efficiency
 Measurable software attributes:
– Simplicity, modularity, information-hiding
 Product and Process

BK -- Spring 2004 Software Design 178


What is Quality?
 Objective is to produce a high-quality design
solution
– What is meant by quality in the context of software
development?
 Notion of quality is familiar, but distinguish:
– Quality of production
– Quality of design
e.g. what makes a good chair/video-recorder/bridge…

BK -- Spring 2004 Software Design 179


Some Questions
 What constitutes quality in software?
 What are the attributes associated with
software quality?
 How can we quantify quality?
 How can the design process help to meet
quality objectives?

BK -- Spring 2004 Software Design 180


What is Quality Software?
 Answer may depend on the stakeholder you ask:
Customer: cost- User: easy to use and
effective solution to helpful solution to
design task design task
Software
Quality
Developer: easy Development Manager:
to develop and profitable solution to
maintain solution design task
to design task

BK -- Spring 2004 Software Design 181


Software Quality
 To talk about software quality we must:
– Define the quality objectives of interest
– Provide a set of design attributes
– Have some means of representing the design
– Have some means of measuring the attributes

Quality Measurable Evaluation


Objectives Attributes of Design

BK -- Spring 2004 Software Design 182


Example: Ease of Maintenance
Objective: Maintainability
– important to developer, client and user
– predicted by simplicity/complexity of solution?
Measurable Attribute: Complexity
– Might measure complexity in terms of e.g. number of
control paths in code
Evaluation: count if-then, while etc tokens
– Objective measure of code complexity
– Rather crude, though!

BK -- Spring 2004 Software Design 183


Five Key Quality Objectives
 Reliability – is the software:
– complete: handles all possible inputs?
– consistent: behaves as expected?
– robust: behaves well for abnormal cases?
 Maintainability -- how easy will it be to:
– correct errors
– perfect functionality
– adapt to changing user needs

BK -- Spring 2004 Software Design 184


Five Key Quality Objectives
 Efficiency:
– does the software make good use of memory, processor
time, bandwidth….
 Usability – how easy is it to:
– learn how to use the software
– use the software effectively and productively
 Re-usability – how easy is it to:
– adapt software components for other purposes

BK -- Spring 2004 Software Design 185


Other Software Quality Objectives
 Portability: degree of platform independence
 Flexibility: ability to configure system to handle
different circumstances
 Manageability: how well design permits estimation of
effort involved in implementation
 Buildability: how easily the design translates into an
implementation
 Security: degree to which design is secure against attack

BK -- Spring 2004 Software Design 186


Measurable Attributes of Software:
Simplicity
“A solution should be as simple as possible but no simpler” (A. Einstein)
 Held to be a mark of good design in all areas
 In software, relates to:
– Maintainability
– Re-usability
– Testability
 Not easy to measure:
– Complexity of structure, control/information flow.

BK -- Spring 2004 Software Design 187


Measurable Attributes of Software:
Modularity
 Notion of modularity arises in many fields:
– e.g. electronics, furniture, buildings
 Modular structure relies on:
– Clean separation of responsibilities
– Well-defined interfaces between components
– Low coupling and high cohesion
 Benefits include:
– modules easier to re-use and replace
– modules easier to understand

BK -- Spring 2004 Software Design 188


Measurable Attributes of Software:
Coupling and Cohesion
 Coupling – a measure of connectivity:

High
coupling Low
coupling

 Cohesion – a measure of functional relatedness:


– e.g. for methods and data of a class
– ‘singleness of purpose’

BK -- Spring 2004 Software Design 189


Measurable Attributes of Software:
Information Hiding
Keep details of implementation local:
 Conceal detailed design decisions:
– choice of data structures
– choice of algorithm
 Protect against data corruptions
– access procedures
 Simplify interconnections:
– reduce dependency
– provide consistency

BK -- Spring 2004 Software Design 190


Quality of Product and Process
 Software is the product of a design process
 Ensure quality in process:
– well-defined and clear
– effective monitoring
– evaluation and management
 Make good use of resources:
– Domain expertise
– Knowledge of methods
– Technical reviews, exploratory prototyping

BK -- Spring 2004 Software Design 191


Summary
 Software systems must meet competing objectives
– different stakeholders may have different views
 Key objectives include:
– Reliability, maintainability, usability, re-usability and
efficiency
 We can measure certain attributes
– e.g. simplicity
 Important to ensure that the process of design is of
high quality

BK -- Spring 2004 Software Design 192


Lecture 13: Product Quality
 Verification, validation and testing
– Verification: what and how
– Validation: what and how
– Testing
• Kinds of Testing
• How is testing done?
 ATM Case Study:
– unit testing of withdrawal use case

BK -- Spring 2004 Software Design 193


Verification, Validation and Testing
 Verification:
– Does the product meet its stated requirements?
– “Are we building the product right?”
 Validation:
– Is the product fit for its purpose?
– “Are we building the right product?”
 Testing:
– Chief means of verifying and validating the product

BK -- Spring 2004 Software Design 194


What is Verification?
Are we building the product right?
 Involves testing product against specification:
– e.g. test implementation against requirements
– but can also test other products of the design process:
• Verify that use-cases satisfy requirements
• Check that classes are capable of realizing use-cases
• Ensure that code corresponds to classes in class model
 Such checks can be done throughout the design
process (not just at the end)

BK -- Spring 2004 Software Design 195


How is Verification Carried Out?
 May be a more or less formal process:
– Informal: by inspection Formal or informal, should be
– Formal: construct proof systematic and thorough

 Sanity checks:
– Use CASE tools to ensure correctness/consistency
– Use compiler to ensure code is legal
 Correspondence checks:
– Inspect product and specification for correspondence
– Make use of some kind of technical review

BK -- Spring 2004 Software Design 196


What is Validation?
Have we built the right product?
 Is the product as useful as it should be?
– not as ‘objective’ as verification
 Really requires customer involvement:
– user-centred design
– At the start of the project (requirements capture)
– At regular intervals throughout the project

BK -- Spring 2004 Software Design 197


How is Validation Done?
 Customer Involvement
– To ‘sign-off’ documentation during project
 Prototyping:
– In early stages to elicit customer requirements
– To remove misunderstandings at later stages
 Usability testing:
– Getting users to carry out tasks with system
– Observing what problems users encounter
BK -- Spring 2004 Software Design 198
Usability Studies
 Usability is concerned with ‘ease of use’:
– Users can find out easily how to carry out a task
– Users can carry out tasks quickly
– Users can recover readily from errors
 Hard for developers to foresee users’ problems:
– Hard to imagine someone who does not understand the
software!
– Software developers are not ‘typical’ software users

BK -- Spring 2004 Software Design 199


Testing
 Testing contributes to
– verification (mainly)
– But also validation
 Purpose of testing is to:
– Help you find the bugs
– Convince customers that there are no bugs
– To gather information (e.g. about performance
or future requirements).

BK -- Spring 2004 Software Design 200


Kinds of Testing
 Usability testing: is whole or part of system easy to use?
 Unit (module) testing: are individual modules bug-free? (in OO
modules usually means classes)
 Integration testing: do various parts of system work together OK (e.g.
collaborations)?
 System testing: does system meet its requirements (both functional and
non-functional)
 Acceptance testing: is the system fit for purpose? (Usually carried out
by the customer or an independent body.)
 Performance testing: test system, modules (etc.) for satisfactory
performance
 Stress testing: ensure that system doesn’t fail catastrophically under
abnormal conditions
 Regression testing: are features still OK after modifications?

BK -- Spring 2004 Software Design 201


How is Testing Done?
 black box testing:
– Treat thing to be tested as a ‘black box’
– choose tests according to specification
 white (glass) box testing:
– Treat thing to be tested as ‘white/glass box’
– choose test according to structure:
• Logical structure
• Dynamic structure

BK -- Spring 2004 Software Design 202


ATM Case Study: Unit Testing
Activity Diagram for Withdrawal
ATM Customer ATM System
Select withdrawal Display menu

[Insufficient funds]
Select amount

[Sufficient funds]
User takes
Return card Notify user
card

Dispense cash

BK -- Spring 2004 Software Design 203


ATM Case Study: Unit Testing
Sequence Diagram for Withdrawal
:ATMUI :ATMControl :CardHolder :Account :CashDispenser

select withdrawal
menu
select amount
withdraw
withdraw :Debit
sum debit add
sum account debit

dispense sum
return
card

BK -- Spring 2004 Software Design 204


ATM Case Study: Unit Testing
State Diagram for Account
exit /balance = 0

withdraw(sum) withdraw(sum)
withdraw(sum)
/balance -=sum /balance -=sum
[sum >balance]
/balance -=sum
inCredit inDebit
entry/balance -= pen
deposit(sum)
[sum >= balance]
deposit(sum) deposit(sum)
/balance += sum
/balance+=sum /balance+=sum
close close

BK -- Spring 2004 Software Design 205


ATM Case Study: Unit Testing
Withdrawal Test Plan
Use Case name: Withdraw cash
Test Number: 1 Objective: Test the primary path
Set up: Account details for cardholder must be set up, with start balance of
£500. Interface components must be available and tested
Test:
1. Select cash withdrawal menu from main menu
2. Select set amount of £100 from cash withdrawal menu
Expected results:
1. The user’s card should be returned and the requested cash dispensed
2. A debit transaction should be recorded on the cardholder’s account, and
the new balance should set to £400

BK -- Spring 2004 Software Design 206


ATM Case Study:Unit Testing
Withdrawal Test Plan
Use Case name: Withdraw cash
Test Number: 2 Objective: Test alternative where cardholder is overdrawn
Set up: Account details for cardholder must be set up, with overdraft of £100 .
Interface components must be available and tested
Test:
1. Select cash withdrawal menu from main menu
2. Select set amount of £100 from cash withdrawal menu
Expected results:
1. The user’s should be notified that the account is overdrawn.
2. The cardholder’s account should not be debited; the balance should stay at
£100 overdrawn

BK -- Spring 2004 Software Design 207


Summary
 Verification: are we building the product right
 Validation: are we building the right product?
 Testing
– Supports both verification and validation
– Important to be systematic
– Black box test plans should be developed at an early
state from specifications (e.g. use cases).

BK -- Spring 2004 Software Design 208


Lecture 14: Software Patterns
 What are Patterns?
– Idioms,
– Design Patterns
– Architectural Patterns
– Frameworks
 Design patterns:
– Structural, creational and behavioural patterns
 Using Design Patterns:
– The Singleton pattern (creational)
– The Façade pattern (structural)

BK -- Spring 2004 Software Design 209


What are Design Patterns?
 Well-understood, proven techniques for solving
particular types of design problem:
– discovered, not invented
– tried and trusted solutions, not clever tricks
 Occur in all areas of design/construction
– e.g. architecture (Alexander 1979)
 Software design patterns have been catalogued:
– Gamma, E., Helm, R., Johnson, R. and J. Vlissides.
(1995) Design Patterns: Elements of Reusable Object
Oriented Software.

BK -- Spring 2004 Software Design 210


Programming Idioms
 Characteristic solutions to programming problems
in particular programming languages:
 e.g. iteration operations for accessing elements of
a collection in Java:
for (Iterator i = a.iterator(); i.hasNext(); ) {
.. ..
/* do something with i.next() */
.. ..
}

BK -- Spring 2004 Software Design 211


Design Patterns
 Standard solutions to software design problems at the level
of objects/components
– Independent of programming language
– Apply to collaborating groups of classes/objects/components
– Patterns are abstract/general representations of solutions
– Based on principles of good design (e.g. low coupling, high
cohesion, etc.)
 Using design patterns:
– Design patterns are not themselves solutions
– Patterns are used to structure a particular solution, and many
variations are possible.

BK -- Spring 2004 Software Design 212


Architectural Patterns
 Characteristic patterns or styles also occur at the
level of computer architecture:
– layered architecture
– client-server architecture
– Model-View-Controller (MVC) architecture:

View update
User interface split into
Controller View and Controller. View
renders objects/data in
notify Model. Controller accepts
modify user input events
Model

BK -- Spring 2004 Software Design 213


Software Frameworks
 Partial solutions to complete applications or types of
application:
– less abstract than design patterns
– a framework has an implementation (unlike a pattern)
– frameworks are higher level than patterns
• frameworks may involve patterns, but not vice-versa
 Examples of frameworks:
– partially completed sales order processing application
that may be tailored to particular organizations
– J2EE for internet applications in Java
– event/listener mechanism used in Java Swing

BK -- Spring 2004 Software Design 214


Types of Design Pattern
Gamma et. al. catalogue 23 design patterns of
different types:
 creational:
– concerned with the construction of objects
 structural:
– concerned organization of classes/objects
 behavioural:
– concerned with behavioural responsibilities and
communication between objects/classes

BK -- Spring 2004 Software Design 215


Example: The Singleton Pattern
 Context. In many software systems there are classes for
which only one instance should be created.
 Problem: how do you ensure that it is never possible to
create more than one instance of a class?
 Forces: constructor cannot be public, but singleton
instance must be public
 Solution:
• private class variable theInstance to store the single instance
• public class method getInstance() creates the instance on the first
call and stores it in theInstance; subsequent calls return
theInstance
• private constructor

BK -- Spring 2004 Software Design 216


ATM Case Study: Singleton
 The ATM system may require a unique class providing information
about the bank to which it belongs:

Bank if ( bankInstance == null )


bankInstance = new Bank();
return bankInstance
-bankInstance
-bankName NB: getInstance() is a static method
-bankAddress
-Bank()
+getInstance()
+getBankdetails()

BK -- Spring 2004 Software Design 217


Example: Facade
 Context: applications may have complex packages with
complicated interfaces
 Problem: how do you simplify the view that clients have
of a complex package?
 Forces: hard to understand/use a complex sub-system/want
to reduce coupling
 Solution: create a special class called a <<Façade>>
which will provide a simpler interface to the package,
thereby making it easier to use and reducing dependencies
with other packages.

BK -- Spring 2004 Software Design 218


ATM Case Study: Facade
 ATM System has many classes and methods. Overall
interface is complex, and clients risk being exposed to any
changes to the system:
ATM System
Customer

Administration

Servicing

BK -- Spring 2004 Software Design 219


ATM Case Study: Facade
 The <<Façade>> class ATM provides a
simpler interface and reduces
ATM Systemclients’
Customer
dependencies on the ATM sub-system
Administration
<<Façade>>
ATM

Servicing

BK -- Spring 2004 Software Design 220


Summary
 Patterns occur in various aspects of software:
– low-level idioms to high-level frameworks
 Design patterns represent tried and trusted
solutions to design problems:
– abstract and general
– creational, structural and behavioural
 Using design patterns can help achieve design
objectives:
– low coupling and high cohesion

BK -- Spring 2004 Software Design 221