0% found this document useful (1 vote)
356 views2,358 pages

Rajib Mall Pose

Uploaded by

Shagun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (1 vote)
356 views2,358 pages

Rajib Mall Pose

Uploaded by

Shagun
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2358

Introduction

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.

12/30/2021 1
About The Instructor
 RAJIB MALL

 B.E. , M.E., Ph.D from


Indian Institute of Science, Bangalore

 Worked with Motorola (India)

 Shifted to IIT, Kharagpur in 1994


 Currently Professor
and HOD 2
Review Questions
 What is the difference between
abstraction and decomposition?

 How are these two concepts useful in


software engineering?

3
What is Software Engineering?
 Engineering approach to develop
software.
 Building Construction Analogy.
 Systematic collection of past
experience:
 Techniques,

 Methodologies,

 Guidelines. 4
Techniques versus Methodology…
 Many times used interchangeably…
 Dictionary:
 Technique: a systematic procedure, formula,
or a routine by which a task is accomplished.
 Method: A habitual, logical, or prescribed
practice or a preordained sequence of achieving
certain end results with accuracy and
efficiency.
 However, when a method is systematic and based
5
upon logic, it is referred to as a scientific method.
Jobs versus Projects?
Uncertainty
Routine of outcome

Jobs Projects Exploration

Jobs – repetition of very well-defined and well


understood tasks with very little uncertainty
Exploration – The outcome is very uncertain, e.g.
finding a cure for cancer.
Projects – in the middle! Has challenge as well as
6

routine…
IEEE Definition
 “Software engineering is the
application of a systematic,
disciplined, quantifiable approach
to the development, operation, and
maintenance of software; that is,
the application of engineering to
software.”
7
Technology Development Pattern
Programming an Art
or Engineering? Engineering
Esoteric Past
Experience
Technology

Craft Systematic Use of Past


Experience and Scientific Basis

Unorganized Use of
Art Past Experience

Time 8
Programming an Art or Engineering?
 Heavy use of past experience:

 Pastexperience is systematically
arranged.
 Theoretical basis and quantitative
techniques provided.
 Many are just thumb rules.
 Tradeoff between alternatives.
 Pragmatic approach to cost-
effectiveness. 9
What is Exploratory Development?
 Early programmers used an

exploratory (also called build and fix)


style.
A `dirty' program is quickly developed.
 The bugs are fixed as and when they
are noticed.
 Similarto a junior student
develops programs… 10
Exploratory Style

Fix

Initial
Test
Coding Do Until
Done

Does not work for nontrivial projects…


Why?...
11
What is Wrong with the Exploratory Style?
 Can successfully be used for developing
very small (toy) programs.
Software
Exploratory Engineering
Effort, time,

Machine
cost

Program Size 12
Dilbert: Scott Adams 13
Our Project Manager: Ponty Haired Boss

Hopelessly
incompetent at
management. He
does not understand
technical issues but
always tries to
disguise this, usually
by using buzzwords
that he does not
understand himself.
Often lacks Ethics…

14
15
Dogbert
Consultant ---
Low on ethics--- Loves
conning and insulting
people---
When hired as a consultant
to create a new company
logo, Dogbert proposed
using a piece of paper with
Dilbert a circular stain from his
coffee cup as the Brown
Competent --- Ring of Quality.
Bit arrogant – Low on Ethics 16
17
18
19
Asok graduated from the Indian
Institute of Technology (IIT). Asok's
test scores (a perfect 1600 on the old
SAT) and the fact his IQ is 240, show
that he is the smartest member of the
engineering team. He is often called
upon by the Boss to do odd jobs and
his ideas are usually left hanging in the
meetings. There are a few jokes about
him having psychic powers which he
learned at the IIT. Yet despite his
intelligence, ethics and mystical
powers, Asok sometimes takes advice
from Wally in the arts of laziness, and
20
Dilbert in surviving the office.
21
22
What is Wrong with the Exploratory Style?
Cont…

 Besides the exponential growth of


effort, cost, and time with problem
size:
 Exploratory
style usually results in
unmaintenable code.

 It becomes very difficult to use the


exploratory style in a team development
environment… 23
What is Wrong with the Exploratory Style?
Cont…

 Why does the effort required to


develop a software grow exponentially
with size?
 Why does the approach completely
Software
breaks down Exploratory Engineering
Effort, time, cost
when the Machine

size of required
software
becomes large?
24
Program Size
An Interpretation Based on Human
Cognition Mechanism
 Human memory can be thought to
be made up of two distinct parts
[Miller 56]:
 Short term memory and

 Long term memory.


25
Human Cognition Mechanism
 Suppose I ask: “If it is 10:10AM now,
how many hours are remaining today?"
 10AM would be stored in the short-term
memory.

 “A day is 24 hours long.”


would be fetched from the long
term memory into short term memory.

 The mental manipulation unit would compute


the difference (24-10). 26
Schematic Representation of Brain

Short Term Memory

Processing Center

Long Term Memory

Brain 27
Short Term Memory
 An item stored in the short term
memory can get lost:
 Either due to decay with time or
 Displacement by newer information.
 This restricts the time for which an
item is stored in short term memory:
 Typically few tens of seconds.
 However, an item can be retained longer
28
in the short term memory by recycling.
What is an Item?
 An item is any set of related information.
 A character such as `a' or a digit such as `5'.
 A word, a sentence, a story, or even a picture.
 Each item normally occupies one place in
memory.
 When you are able to relate several
different items together (chunking):
 The information that should normally occupy
several places, takes only one place in memory.
29
Chunking
 If you are given the binary number
110010101001
 It
may prove very hard for you to
understand and remember.
 But,the octal form of 6251
(110)(010)(101)(001) would be easier.
 Youhave managed to create chunks of
three items each. 30
Evidence of Short Term Memory
 In many of our day-to-day experiences:
 Short term memory is evident.
 Suppose, you look up a number from the
telephone directory and start dialling it.
 If you find the number is busy, you can dial
the number again after a few seconds without
having to look up the directory.
 But, after several days:
 You may not remember the number at all
 Would need to consult the directory again. 31
The Magical Number 7
 If a person deals with seven or less
number of items:
 These would be accommodated in the
short term memory.
 So, he can easily understand it.
 As the number of new information
increases beyond seven:
 It
becomes exceedingly difficult to
understand it.
32
What is the Implication in Program
Development?
 A small program having just a few variables:
 Is within easy grasp of an individual.

 As the number of independent variables in


the program increases:
 It quickly exceeds the grasping power of an
individual…

 Requires an unduly large effort to master


the problem. 33
Implication in Program Development
 Instead of a human, if a machine could be
writing (generating) a program,
 The slope of the curve would be linear.

 But, how does use of software engineering


principles helps hold down the effort-size
curve to be almost linear?
 Software engineering principles extensively
use techniques specifically targeted to
overcome the human cognitive limitations.34
Which Principles Deployed by Software
Engineering Techniques to Overcome Human
Cognitive Limitations?

 Two important principles are


profusely used:
 Abstraction

 Decomposition
35
What is Abstraction?
 Simplify a problem by omitting
unnecessary details.
 Focus attention on only one
aspect of the problem and
ignore other aspects and
irrelevant details.
 Also called model building. 36
Questions
 What is a model?

 Why develop a model? That


is, how does a model help?

 Give some examples of


models. 37
Abstraction Example
 Suppose you are asked to develop an

overall understanding of some


country.
 Would you:
 Meet all the citizens of the country,
visit every house, and examine every
tree of the country?
 Youwould possibly refer to various
types of maps for that country only. 38
You would study an Abstraction…
 A map is:

 An abstract representation of a country.


 Various types of maps (abstractions) possible.

39
Does a Problem have a single Abstraction?

 Several abstractions of the


same problem can be created:
 Focuson some specific aspect
and ignore the rest.
 Differenttypes of models help
understand different aspects of
the problem. 40
Abstractions of Complex Problems
 For complex problems:
A single level of abstraction is inadequate.
A hierarchy of abstractions may have to
be constructed.
 Hierarchy of models:
A model in one layer is an abstraction of
the lower layer model.
 Animplementation of the model at the
higher layer. 41
Complex Problem Abstraction Example
 Suppose you are asked to understand

all life forms that inhabit the earth.


 Would you start examining each living
organism?
 You will almost never complete it.
 Also, get thoroughly confused.

 Solution: You can try to build an


abstraction hierarchy. 42
Living Organisms
Animalia Plantae Fungae Kingdom

Mollusca Chordata Ascomycota Zygomycota


Phyllum

Species
Homo Solanum Coprinus
Sapien Tuberosum Comatus
43
Decomposition
 Decompose a problem into many small
independent parts.
 Thesmall parts are then taken up one
by one and solved separately.
 The idea is that each small part would
be easy to grasp and therefore can be
easily solved.
 Thefull problem is solved when all the
parts are solved. 44
Decomposition
 A popular use of decomposition
principle:
 Try to break a bunch of sticks tied
together versus breaking them
individually.
 Any arbitrary decomposition
of a problem may not help.
 The decomposed parts must be more or
45
less independent of each other.
Decomposition Example
 Example use of decomposition
principle:
 You understand a book better
when the contents are organized
into independent chapters.
 Compared to when everything is
mixed up. 46
Why Study Software
Engineering? (1)‫‏‬
 To acquire skills to develop large
programs.
 Handlingexponential growth in
complexity with size.
 Systematic techniques based on
abstraction (modelling) and
decomposition. 47
Why Study Software Engineering? (2)‫‏‬

 Learn systematic techniques of:

 Specification, design, user interface


development, testing, project
management, etc.

 Appreciate issues that arise in team


development.
48
Why Study Software Engineering? (3)‫‏‬

 To acquire skills to be a
better programmer:
 Higher Productivity

 Better Quality Programs

49
Software Crisis
 It is often the case that software
products:
 Fail to meet user requirements.
 Expensive.

 Difficult to alter, debug, and enhance.


 Often delivered late.
 Use resources non-optimally. 50
Software Crisis (cont.)‫‏‬

Laptop or Desktop = Rs.45,000/-


Rational rose node locked =
Rs.314,600/-
Hw cost Rational rose floating license=
Sw cost Rs.603,200/-

1960 Year 2014

Relative Cost of Hardware and Software 51


Standish Group Report

28% Successful

49% Delayed or
cost overrun

23% Cancelled

52
Then why not have entirely
hardware systems?
 A virtue of software:
 Relatively easy to change
 Otherwise it might as well be hardware
 The more the complexity of a
software (Entropy), the harder it is to
change--why?
 Further, the more the changes made
to a program, the greater is the
increase in its entropy.
53
Which Factors are Contributing to the
Software Crisis?
 Larger problems,

 Poor project management

 Lack of adequate training in software


engineering,

 Increasing skill shortage,

 Low productivity improvements. 54


Programs versus Software Products
 Usually small in size  Large

 Author himself is sole  Large number of


user users

 Single developer  Team of developers

 Lacks proper user  Well-designed


interface interface

 Lacks proper  Well documented &


documentation user-manual prepared

 Ad hoc development.  Systematic


55
development
Types of Software Projects
 Two types of software projects:
 Products (Generic software)‫‏‬

 Services (custom software)‫‏‬

 Total business – appx. $1 Trillion


 Half in products and half services

 Services segment is growing fast!


56
Types of Software
Horizontal market
software—meets
needs of many
companies
Packaged software—prewritten
software available for purchase
Vertical market
software—designed
for particular
industry
Custom software—software
developed at user’s request

Custom software-Developer
tailors his generic solution
57
Types of Software Projects

 Software product development


projects

 Software services projects

58
Software Services
 Software service is an umbrella
term, includes:
 Software customization
 Software maintenance CP

 Software testing
 Alsocontract programmers
who carry out coding or any
other assigned activities. 59
Scenario of Indian Software
Companies

 Indian companies have focused


on the services segment ---
Why?

60
A Few Changes in Software Project
Characteristics over Last 40 Years
 40 years back, very few software existed
 Every project started from scratch
 Projects were multi year long
 The programming languages that were used
hardly provided any scope for reuse:
 FORTRAN, PASCAL, COBOL, BASIC
 No application was GUI-based:
 Mostly command selection from displayed text
menu items.
61
Traditional versus Modern Projects
 Projects are increasingly becoming services:
 Either tailoring some existing software or reusing
certain pre-built libraries.
 Facilitation and accommodation of client
feedbacks
 Facilitation of customer participation in project
development work
 Incremental software delivery with evolving
functionalities.
 No software being developed from scratch --
62
- Significant reuse
Computer Systems Engineering
 Computer systems engineering:
 encompasses software engineering.
 Many products require development of
software as well as specific hardware
to run it:
 a coffee vending machine,
a sophisticated toy,
A new smart phone, etc. 63
Computer Systems Engineering

 The high-level problem:


 Deciding
which tasks are to be solved
by software.
 Which ones by hardware.

64
Computer Systems Engineering (CONT.)

 Typically, hardware and software are


developed together:

 Hardware simulator is used during


software development.

 Integration of hardware and software.

 Final system testing


65
Computer Systems Engineering
(CONT.)

Feasibility
Study

Requirements
Analysis and
Specification Hardware
Development
Hardware
Software
Partitioning Software
Development
Integration
and Testing

Project Management

66
Emergence of Software Engineering

 Early Computer Programming


(1950s):
 Programswere being written in
assembly language…
 Sizes
limited to about a few
hundreds of lines of assembly
code… 67
Early Computer Programming (50s)‫‏‬

 Every programmer developed


his/her own style of writing
programs:

 According to his intuition


(exploratory programming).
68
High-Level Language Programming
(Early 60s)‫‏‬

 High-level languages such as


FORTRAN, ALGOL, and COBOL
were introduced:

 Thisreduced software
development efforts greatly.

 Why reduces?
69
High-Level Language Programming
(Early 60s)‫‏‬

 Software development style was


still exploratory.

 Typical program sizes were limited


to a few thousands of lines of source
code.

70
Control Flow-Based Design (late 60s)‫‏‬

 Size and complexity of programs


increased further:
 Exploratoryprogramming style
proved to be insufficient.

 Programmers found:
 Verydifficult to write cost-effective
and correct programs. 71
Control Flow-Based Design (late 60s)‫‏‬

 Programmers found it very difficult:

 To understand and maintain programs


written by others.

 To cope up with this problem,


experienced programmers advised--
-”Pay particular attention to the design
of the program's control structure.'’ 72
Control Flow-Based Design (late 60s)
 A program's control structure

indicates:
 The sequence in which the program's
instructions are executed.
 To help design programs having good
control structure:
 Flow charting technique was
developed. 73
Control Flow-Based Design (late 60s)

 Using flow charting technique:


 Onecan represent and design a
program's control structure.
 Usually
one understands a
program:
 By mentally simulating the
program's execution sequence. 74
Control Flow-Based Design
(Late 60s)‫‏‬

 A program having a messy flow


chart representation:
 Difficult to understand and debug.

75
Control Flow-Based Design (Late 60s)‫‏‬

 It was found:
 GO TO statements makes control
structure of a program messy.

 GO TO statements alter the flow of


control arbitrarily.

 The need to restrict use of GO TO


statements was recognized. 76
Control Flow-Based Design (Late 60s)

 Many programmers had extensively


used assembly languages.

 JUMP instructions are frequently


used for program branching in
assembly languages.

 Programmers considered use of GO


TO statements inevitable. 77
Spaghetti Code Structure

78
Control-flow Based Design (Late 60s)‫‏‬

 At that time, Dijkstra published


his article:
 “Goto
Statement Considered
Harmful” Comm. of ACM, 1969.

 Many programmers were


unhappy to read his article.
79
Control Flow-Based Design (Late 60s)

 They published several counter


articles:
 Highlighted the advantages and
inevitability of GO TO statements.

80
Control Flow-Based Design (Late 60s)
 It soon was conclusively proved:

 Only three programming constructs


are sufficient to express any
programming logic:
 sequence (a=0;b=5;)‫‏‬
 selection (if(c==true) k=5 else m=5;)‫‏‬
 iteration (e.g. while(k>0) k=j-k;)‫‏‬
81
Control-flow Based Design (Late 60s)‫‏‬

 Everyone accepted:
 It is possible to solve any
programming problem without using
GO TO statements.
 This formed the basis of Structured
Programming methodology.
82
Structured Programming
 A program is called structured:
 When it uses only the following
types of constructs:
 sequence,
 selection,
 iteration
83
Structured Programs
 Unstructured control flows are
avoided.
 Consist of modules.
 Use single-entry, single-exit
program constructs.

84
Structured Programs
 However, violations to this
feature are permitted:
 Dueto practical considerations
such as:

 Prematureloop exit (break) to


support exception handling.
85
Structured programs
 Structured programs are:
 Easier to read and understand,
 Easier to maintain,
 Require
less effort and time for
development.

86
Structured Programming
 Research experience shows:
 Programmers commit less number
of errors:
 While using structured if-then-else
and do-while statements.
 Compared to test-and-branch
constructs. 87
Data Structure-Oriented Design
(Early 70s)‫‏‬

 Soon it was discovered:

 Itis important to pay more


attention to the design of data
structures of a program

 Than to the design of its control


structure.
88
Data Structure-Oriented Design
(Early 70s)‫‏‬

 Techniques which emphasize


designing the data structure:
 Derive program structure from it:

 Are called data structure-


oriented design techniques.
89
Data Structure Oriented Design (Early
70s)‫‏‬

 Example of data structure-


oriented design technique:

 Jackson's Structured
Programming(JSP) methodology

 Developed by Michael Jackson in


1970s.
90
Data Structure Oriented Design (Early 70s)‫‏‬

 JSP technique:

 Program code structure


should correspond to the data
structure.

91
Data Structure Oriented Design
(Early 70s)‫‏‬

 JSP methodology:

A program's data structures are first


designed using notations for

 sequence, selection, and iteration.

 Then data structure design is used :

 To derive the program structure.


92
Data Structure Oriented Design
(Early 70s)‫‏‬

 Several other data structure-


oriented Methodologies also exist:

 e.g., Warnier-Orr Methodology.

93
Data Flow-Oriented Design
(Late 70s)

 Data flow-oriented techniques


advocate:
 The data items input to a system must
first be identified,

 Processingrequired on the data items to


produce the required outputs should be
determined. 94
Data Flow-Oriented Design (Late 70s)‫‏‬
 Data flow technique identifies:
 Differentprocessing stations
(functions) in a system.

 Theitems (data) that flow


between processing stations.

95
Data Flow-Oriented Design (Late 70s)‫‏‬

 Data flow technique is a generic


technique:
 Canbe used to model the working of any
system.
 not just software systems.

 A major advantage of the data flow


technique is its simplicity. 96
Data Flow Model of a Car
Assembly Unit
Engine Store Door Store

Partly
Assembled
Chassis with Car
Engine

Fit Fit Paint and Car


Fit
Engine Doors Wheels Assembled Test
Car

Chassis Store Wheel Store

97
Object-Oriented Design (80s)‫‏‬

 Object-oriented technique:
 An intuitively appealing design
approach:

 Natural objects (such as employees,


pay-roll-register, etc.) occurring in a
problem are first identified.
98
Object-Oriented Design (80s)‫‏‬

 Relationships among objects:


 Such as composition, reference, and
inheritance are determined.

 Each object essentially acts as:


A data hiding (or data abstraction)
entity. 99
Object-Oriented Design (80s)‫‏‬
 Object-Oriented Techniques have gained
wide acceptance:

 Simplicity

 Increased Reuse possibilities

 Lower development time and cost

 More robust code

 Easy maintenance
100
Evolution of Design Techniques
Aspect- Component- Service-
oriented based oriented

Object-Oriented
Object-Oriented

Data flow-based

Data structure-
based

Control flow-
based

Ad hoc
101
Evolution of Other Software
Engineering Techniques
 The improvements to the software
design methodologies
 are indeed very conspicuous.

 In additions to the software


design techniques:
 Several other techniques evolved. 102
Evolution of Other Software Engineering
Techniques
 Life cycle models,

 Specification techniques,
 Project management techniques,
 Testing techniques,
 Debugging techniques,
 Quality assurance techniques,
 Metrics,
 CASE tools, etc. 103
Differences between the exploratory style
and modern software development practices

 Use of Life Cycle Models

 Software is developed through


several well-defined stages:
 Requirements analysis and specification,
 Design,

 Coding,

 Testing, etc. 104


Differences between the exploratory style
and modern software development practices

 Emphasis has shifted


 from error correction to error
prevention.

 Modern practices emphasize:


 detection of errors as close to their
point of introduction as possible.
105
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 In exploratory style,
 errors are detected only during
testing,

 Now:
 Focus is on detecting as many errors
as possible in each phase of
development.
106
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 In exploratory style:
 codingis synonymous with program
development.

 Now:
 codingis considered only a small
part of program development
107
effort.
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 A lot of effort and attention is now


being paid to:
 Requirements specification.

 Also, now there is a distinct design


phase:
 Standard design techniques are being
used. 108
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 During all stages of development


process:
 Periodic reviews are being carried
out
 Software testing has become
systematic:
 Standard testing techniques are
109
available.
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 There is better visibility of design and code:

 Visibility means production of good quality,


consistent and standard documents.

 In the past, very little attention was being given


to producing good quality and consistent
documents.

 We will see later that increased visibility makes


software project management easier. 110
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 Because of good documentation:


 faultdiagnosis and maintenance are
smoother now.

 Several metrics are being used:


 help in software project management,
quality assurance, etc.
111
Differences between the exploratory style
and modern software development practices
(CONT.)‫‏‬

 Projects are being prperly


planned:
 estimation,

 scheduling,

 monitoring mechanisms.

 Use of CASE tools. 112


Review Questions
 Graphically represent the
important activities carried out in
the build and fix style of program
development.

 What are the advantages and


disadvantages of the build and fix
style of software development?
113
Review Questions
 When using exploratory style, why
does the development time and effort
increase exponentially with linear
increase in software size?

 What are the two basic mechanisms


deployed by software engineering
techniques to handle problem
complexity?
114
Review Questions
 What is software crisis? What are its
symptoms and cure?

 What is the difference between a


programming job and assignment?

 What are the different types of


software projects undertaken by
software development companies?
115
Review Questions
 What is structured
programming?
 What problems may appear if a
large program is being developed
without using structured
programming techniques?
116
Life Cycle Models
(Lect 2)

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
12/30/2021 1
Quiz
 Give one example project situation for which
waterfall model is suitable.
 Give one example project situation for which
waterfall model is not suitable.
 What is a milestone? Give one example of a
milestone.
 In what way are milestones useful?
 How frequently should milestones be placed?
 What problems may be encountered if a project
manager recommends use of the iterative
waterfall model for a customization project? 2
Quiz
 Suppose the sales manager of your company
informs the top management of your
company that he sees tremendous potential
for a wearable health monitor:
 The wearable health monitor would measure
vital body parameters such as heart rate,
temperature, blood pressure, etc and maintain
a log.

 How would you perform feasibility study? 3


Human Life Cycle

4
Software Life Cycle
Conceptualize

Specify
Retire

Design
Maintain

Deliver Code

Test 5
Life Cycle Model
 A software life cycle model (also
process model or SDLC):
A descriptive and diagrammatic model of
software life cycle:
 Identifies all the activities undertaken during
product development,
 Establishes a precedence ordering among the
different activities,
 Divides life cycle into phases. 6
Life Cycle Model (CONT.)‫‏‬

 Each life cycle phase (activity)


consists subactivities.
 Forexample, the design stage
might consist of:
 structured analysis
 structured design
7
Why Model Life Cycle?
 A graphical and written description:
 Helps
common understanding of activities
among the software developers.
 Helpsto identify inconsistencies,
redundancies, and omissions in the
development process.
 Helpsin tailoring a process model for
specific projects.
8
Life Cycle Model (CONT.)‫‏‬

 The development team must


identify a suitable life cycle model:
 and then adhere to it.
 Primary advantage of adhering to a
life cycle model:
 Helps development of software in a
systematic and disciplined manner.
9
Life Cycle Model (CONT.)

 When a program is developed by a single


programmer ---
 The problem is within the grasp of an
individual.

 He has the freedom to decide his exact steps


and still succeed Exploratory model

 CodeTest Design

 CodeDesign Test  Code


Specify code Design Test etc.
10

Life Cycle Model (CONT.)‫‏‬

 When software is being developed


by a team:
 There must be a precise
understanding among team members
as to when to do what,

 Otherwise, it would lead to chaos


and project failure.
11
Life Cycle Model (CONT.)‫‏‬

 A software project will never


succeed if:
 one engineer starts writing code,
 another
concentrates on writing the test
document first,
 yet another engineer first defines the
file structure
 another defines the I/O for his portion
first. 12
Entry and Exit Criteria
 A life cycle model:
 definesentry and exit criteria
for every phase.
A phase is considered to be
complete:
 only when all its exit criteria are
satisfied. 13
Life Cycle Model (CONT.)‫‏‬

 What is the phase exit criteria for the


software requirements specification
phase?
 SoftwareRequirements Specification
(SRS) document is complete, reviewed,
and approved by the customer.

 A phase can start:


 Onlyif its phase-entry criteria have
been satisfied. 14
Life Cycle Model (CONT.)‫‏‬

 Milestones help software


project managers:
 Trackthe progress of the
project.
 Phaseentry and exit are
important milestones.
15
Life Cycle and Project
Management
 When a life cycle model is
followed:

 The project manager can at any time


fairly accurately tell,

 At which stage (e.g., design, code,


test, etc.) the project is.
16
Project Management Without Life
Cycle Model

 It becomes very difficult to track the


progress of the project?
 Theproject manager would have to
depend on the guesses of the team
members.

 This usually leads to a problem:


 known as the 99% complete syndrome.
17
Myth: Deliverables and Milestones
Myth:
“The only deliverable for a successful
project is the working program.”

Reality:
Documentation of all aspects of
software development are needed to
help in operation and maintenance.
18
Life Cycle Model (CONT.)‫‏‬

 Many life cycle models have been proposed.


 We confine our attention to a few important
and commonly used models.
 Classical and Iterative waterfall models
 V model,
 Evolutionary,
 Prototyping
 Spiral model, and
19
 Agile models
Software Life Cycle
 Software life cycle (or software
process):
 Series of identifiable stages that a
software product undergoes during its
life time:
 Feasibility study

 Requirements analysis and specification,

 Design,

 Coding,

 Testing
20
 Maintenance.
Classical Waterfall Model
 Classical waterfall model divides life
cycle into following phases:
 Feasibility study,
 Requirements analysis and specification,
 Design,
Conceptualize

Retire Specify

 Coding and unit testing, Design


Maintain
 Integration and system
testing, Deliver Code

Test 21
 Maintenance.
Classical Waterfall Model
Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
22
Relative Effort for Phases
 Phases between feasibility
study and testing 60
 Called development phases. 50
40

Relative Effort
 Among all life cycle phases
30
 Maintenance phase 20
consumes maximum effort. 10
 Among development 0

Maintnce
Design

Test
Coding
Req. Sp
phases,
 Testing phase consumes the
maximum effort. 23
Classical Waterfall Model (CONT.)‫‏‬

 Most organizations usually define:


 Standards on the outputs (deliverables)
produced at the end of every phase
 Entry and exit criteria for every phase.
 They also prescribe methodologies for:
 Specification,
 Design,
 Testing,
 Project management, etc. 24
Classical Waterfall Model (CONT.)‫‏‬

 The guidelines and methodologies of


an organization:
 Called the organization's software
development methodology.

 Software development organizations:


 Expect fresh engineers to master
the organization's software
development methodology. 25
Feasibility Study
 Main aim of feasibility study: determine
whether developing the product
 Financially worthwhile
 Technically feasible.
 Roughly understand what customer wants:
 Data which would be input to the system,
 Processing needed on these data,
 Output data to be produced by the system,
 Various constraints on the behavior of the
system. 26
The business case
 Benefits of delivered
project must
Benefits
outweigh costs
Costs  Costs include:
- Development
Rs - Operation
Rs
• Benefits:
– Quantifiable
– Non-quantifiable 27
Case Study
 SPF Scheme for CIL
 CIL has a large number of employees,
exceeding 50,000.
 Majority of these are casual labourers
 Mining being a risky profession:
 Casualties are high
 Though there is a PF:
 But settlement time is high
 There is a need of SPF:
28

 For faster disbursement of benefits


Activities During Feasibility Study
 Work out an overall understanding of
the problem.
 Formulate different solution
strategies.
 Examine alternate solution strategies
in terms of:
 resources required,
 cost of development, and
 development time. 29
Feasibility Study
Operational
feasibility

Measure of how
suitable system
Four feasibility
development will
tests:
be to the
company Schedule
feasibility

Economic
feasibility
(also called Technical
cost/benefit feasibility
feasibility)
30
Feasibility Study Activities

Assesses
feasibility
of each
alternative
solution

Presented to
Recommends steering
the most committee,
feasible which decides
solution for how system will
the project be developed

31
Activities during Feasibility Study
 Perform a cost/benefit analysis:
 Determine which solution is the best.
 May also find that none of the
solutions is feasible due to:
 high cost,
 resource constraints,
 technical reasons.
32
Cost benefit analysis (CBA)
 Need to identify all costs --- these
could be:
 Development costs
 Set-up

 Operational costs
 Identify the value of benefits

 Check benefits are greater than costs


33
Classical Waterfall Model
Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
34
Requirements Analysis and Specification
 Aim of this phase:
 Understand the exact requirements
of the customer,
 Document them properly.

 Consists of two distinct activities:


 Requirements gathering and analysis
 Requirements specification. 35
Goals of Requirements Analysis
 Collect all related data from the
customer:
 Analyzethe collected data to clearly
understand what customer wants,
 Findout any inconsistencies and
incompleteness in the requirements,
 Resolveall inconsistencies and
incompleteness. 36
Requirements Gathering
 Gathering relevant data:
 Usually
collected from the end-users
through interviews and discussions.
 Example: for a business accounting
software:
 Interview all the accountants of the
organization to find out their
requirements. 37
Requirements Analysis (Cont...)‫‏‬

 The data you initially collect from


the users:
 Usually contain several contradictions
and ambiguities.

 Why?

 Each user typically has only a partial


and incomplete view of the system. 38
Requirements Analysis
(Cont...)‫‏‬
 Ambiguities and contradictions:
 must be identified
 resolved by discussions with the
customers.

 Next, requirements are organized:


 into a Software Requirements
Specification (SRS) document. 39
Dilbert: Scott Adams 40
Classical Waterfall Model
Feasibility Study

Req. Analysis

Design
Design

Coding

Testing

Maintenance
41
Design
 During design phase requirements
specification is transformed into :
 A form suitable for implementation
in some programming language.

42
Design
 In technical terms:
 Duringdesign phase, software
architecture is defined.
 Two commonly used design
approaches:
 Traditional approach,
 Object oriented approach. 43
Traditional Design Approach

 Consists of two activities:


 Structured analysis
 Structured design

44
Structured Analysis (CONT.)‫‏‬

 Carried out using Data flow


diagrams (DFDs).
 After structured analysis, carry
out structured design:
 architectural design (or high-level
design)‫‏‬
 detailed design (or low-level design).
45
Structured Design
 High-level design:
 decompose the system into modules,
 representinvocation relationships among
the modules.
 Detailed design:
 different modules designed in greater
detail:
 data structures and algorithms for each
module are designed. 46
Object-Oriented Design
 First identify various objects (real
world entities) occurring in the
problem:
 Identify the relationships among objects.
 Forexample, the objects in a pay-roll
software may be:
 employees,
 managers,

 pay-roll register,
47
 Departments, etc.
Object Oriented Design (CONT.)‫‏‬

 Object structure
 Further refined to obtain the
detailed design.
 OOD has several advantages:
 Lower development effort,
 Lower development time,
 Better maintainability. 48
Classical Waterfall Model
Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
49
Coding and Unit Testing
 During this phase:

 Each module of the design is coded,

 Each module is unit tested

 That is, tested independently as a stand


alone unit, and debugged.

 Each module is documented.


50
Classical Waterfall Model
Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
51
Integration and System Testing
 Different modules are integrated in a
planned manner:
 Modulesare usually integrated through
a number of steps.
 During each integration step,
 thepartially integrated system is
tested.
M1 M2 M5 M7

M3 M4 M6 M8
52
System Testing
 After all the modules have been
successfully integrated and tested:

 System testing is carried out.

 Goal of system testing:


 Ensure that the developed system functions
according to its requirements as specified
in the SRS document.
53
Classical Waterfall Model

Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
54
Maintenance
 Maintenance of any software:

 Requiresmuch more effort than


the effort to develop the product
itself.
 Developmenteffort to
maintenance effort is typically
40:60. 55
Dilbert: Scott Adams 56
Types of Maintenance?
 Corrective maintenance:
 Correct errors which were not discovered during
the product development phases.
 Perfective maintenance:
 Improve implementation of the system
 enhance functionalities of the system.
 Adaptive maintenance:
 Port software to a new environment,
 e.g. to a new computer or to a new operating system.
57
58
Dilbert: Scott Adams 59
Iterative Waterfall Model
 Classical waterfall model is
idealistic:
 Assumes that no defect is
introduced during any development
activity.
 In practice:
 Defects do get introduced in almost
every phase of the life cycle. 60
Iterative Waterfall Model (CONT.)‫‏‬

 Defects usually get detected much


later in the life cycle:
 For example, a design defect might go
unnoticed till the coding or testing
phase.
 The later the phase in which the
defect gets detected, the more
expensive is its removal --- why? 61
Iterative Waterfall Model (CONT.)‫‏‬

 Once a defect is detected:

 The phase in which it occurred needs to


be reworked.

 Redo some of the work done during that


and all subsequent phases.

 Therefore need feedback paths in the


classical waterfall model. 62
Iterative Waterfall Model
(CONT.)‫‏‬
Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
63
Phase Containment of Errors
 Errors should be detected: (Cont...)‫‏‬

 In the same phase in which they are


introduced.
 For example:
 If a design problem is detected in the
design phase itself,
 The problem can be taken care of much
more easily
 Than say if it is identified at the end of the
integration and system testing phase. 64
Cartoonist’s View…

Grows over Lifecycle…

65
Phase Containment of Errors
 Reason: rework must be carried out not only
to the design but also to code and test
phases.
 The principle of detecting errors as close
to its point of introduction as possible:
 is known as phase containment of errors.
 Iterative waterfall model is by far the most
widely used model.
 Almost every other model is derived from the
waterfall model. 66
Waterfall Strengths
 Easy to understand, easy to use
 Provides a reference to inexperienced
staff
 Milestones are well understood by the
team
 Provides requirements stability
 Facilitates strong management control
67
(plan, staff, track)
Waterfall Deficiencies
 All requirements must be known
upfront
 Deliverables created for each phase
are considered frozen – inhibits
flexibility
 Can give a false impression of progress
 Integration is one big bang at the end
 Little opportunity for customer to pre-
68
view the system.
When to use the Waterfall Model?
 Requirements are well known and
stable

 Technology is understood

 Experienced Development team

69
Classical Waterfall Model
(CONT.)‫‏‬

 Irrespective of the life cycle


model actually followed:
 The documents should reflect a
classical waterfall model of
development,
 Comprehension of the documents
is facilitated.
70
Classical Waterfall Model
(CONT.)‫‏‬

 Metaphor of mathematical
theorem proving:
A mathematician presents a proof
as a single chain of deductions,
 Even though the proof might have
come from a convoluted set of partial
attempts, blind alleys and backtracks.
71
Quiz
 What problems may be encountered if a project
manager recommends use of the iterative
waterfall model for a customization project?
 Give one example project situation for which
waterfall model is suitable.
 Give one example project situation for which
waterfall model is not suitable.
 What is a milestone? Give one example of a
milestone.
 In what way are milestones useful?
 How frequently should milestones be placed? 72
Quiz
 Suppose the sales manager of your company
informs the top management of your
company that he sees tremendous potential
for a wearable health monitor:
 The wearable health monitor would measure
vital body parameters such as heart rate,
temperature, blood pressure, etc and maintain
a log.

 How would you perform feasibility study? 73


V Model

12/30/2021 74
V Model
 It is a variant of the Waterfall
 emphasizes verification and validation
 V&V activities are spread over the
entire life cycle.

 In every phase of development:


 Testing activities are planned in
parallel with development. 75
Project& Production,
Requirements Operation &
Planning Maintenance

Product System&
Requirements& Acceptance
Specification Testing
Analysis

Architecture Integration&
High Level Testing
Design

Detailed Unit
Design testing

Coding 76
V Model Steps
 Planning

 Requirements  System and acceptance


Specification and testing
Analysis

 Design  Integration and Testing

 Coding  Unit testing


77
V Model: Strengths
 Starting from early stages of
software development:

 Emphasize planning for verification


and validation of the software

 Each deliverable is made testable

 Easy to use 78
V Model Weaknesses
 Does not support overlapping of
phases

 Does not handle iterations or phases

 Does not easily handle later changes


in requirements

 Does not support risk analysis


activities 79
When to use V Model
 Natural choice for systems
requiring high reliability:

 Embedded control applications

 All requirements are known up-


front

 Solution and technology are known 80


Prototyping
Model

12/30/2021 81
Prototyping Model
 A derivative of waterfall model.
 Before starting actual development,
A working prototype of the system
should first be built.
 A prototype is a toy implementation of
a system:
 Limited functional capabilities,
 Low reliability,
82
 Inefficient performance.
Reasons for prototyping
 learning by doing: useful where
requirements are only partially known
 improved communication
 improved user involvement
 reduces the need for documentation
 reduces maintenance costs i.e. changes
after the application goes live 83
Reasons for Developing a Prototype
 Illustrate to the customer:
 inputdata formats, messages, reports, or
interactive dialogs.

 Examine technical issues associated


with product development:
 Often major design decisions depend on
issues like:
 Response time of a hardware controller,
84
 Efficiency of a sorting algorithm, etc.
Prototyping Model (CONT.)‫‏‬
 Another reason for developing a

prototype:
 It
is impossible to “get it right”
the first time,
 We must plan to throw away the
first version:
 If we want to develop a good
software.
85
Prototyping Model (CONT.)‫‏‬

 Start with approximate requirements.


 Carry out a quick design.
 Prototype model is built using several
short-cuts:
 Short-cuts might involve:
 Using inefficient, inaccurate, or dummy
functions.
 A table look-up rather than performing the
86
actual computations.
Prototyping Model (CONT.)‫‏‬

 The developed prototype is submitted


to the customer for his evaluation:
 Based on the user feedback, the
prototype is refined.
 This cycle continues until the user
approves the prototype.

 The actual system is developed using


the waterfall approach. 87
Prototyping Model (CONT.)‫‏‬

Build Prototype

Requirements Customer Customer


Evaluation of Design
Gathering Quick Design Prototype satisfied

Refine
Requirements Implement

Test

Maintain88
Prototyping Model (CONT.)‫‏‬

 Requirements analysis and specification


phase becomes redundant:
 Final working prototype (incorporating all user
feedbacks) serves as an animated
requirements specification.
 Design and code for the prototype is
usually thrown away:
 However, experience gathered from developing
the prototype helps a great deal while
developing the actual software. 89
Prototyping Model (CONT.)‫‏‬

 Even though construction of a working


prototype model involves additional cost ---
overall development cost might be lower for:
 Systems with unclear user requirements,
 Systems with unresolved technical issues.
 Many user requirements get properly
defined and technical issues get resolved:
 These would have appeared later as change
requests and resulted in incurring massive
redesign costs. 90
Prototyping: advantages
 The resulting software: more usable
 User needs are better accommodated
 The design is of higher quality
 The resulting software is easier to
maintain
 Overall, the development incurs less
effort
91

SE, Software Lifecycle, Hans van Vliet, ©2008 91


Prototyping: disadvantages
 Sometimes expensive

 Susceptible to over-engineering:

 Designers start to incorporate


sophistications that they could not
incorporate in the prototype.

92

SE, Software Lifecycle, Hans van Vliet, ©2008 92


Major difficulties of Waterfall-Based
Models
1. Difficulty in accommodating change
requests during development.
 40% of requirements change during
development

2. High cost incurred in developing


custom applications.
3. “Heavy weight processes.” 93
Documentation.

94
Source: Robert Martin
Major difficulties of Waterfall-Based Life
Cycle Models

 Requirements for the system are


determined at the start:

 Are assumed to be fixed from that


point on.

 Long term planning is made based on


this. 95
“… the assumption that one can specify a
satisfactory system in advance, get bids
for its construction, have it built, and
install it. …this assumption is
fundamentally wrong and many software
acquisition problems spring from this…”
Frederick Brooks

96
Evolutionary
Model

12/30/2021 97
Evolutionary Model
 Evolutionary model (aka successive versions
or incremental model):
 The system is broken down into several modules
which can be incrementally implemented and
delivered.
 First develop the core modules of the
software.
 The initial skeletal software is refined into
increasing levels of capability:
 By adding new functionalities in successive 98
versions.
Biological Systems

99
Biological Systems
The waterfall model did not apply to
biological systems --- these evolved instead
of being designed.

A complex system that works


is invariably found to have
evolved from a simple system
that worked.

100
12/30/2021 © 2009 Bahill
Evolutionary Model
 “A complex system will be most successful
if implemented in small steps… “retreat”
to a previous successful step on failure…
opportunity to receive some feedback
from the real world before throwing in all
resources… and you can correct possible
errors…” Tom Glib in Software Metrics

101
Evolutionary Model (CONT.)‫‏‬

 Successive version of the product:

 functioning
systems capable of
performing some useful work.
A new release may include new
functionality:
 Also existing functionality in the
current release might have been
enhanced.
102
Evolutionary Model
 Evolves an initial implementation with user
feedback:
 Multiple versions until the final version.

Initial
Specification version
Outline
Intermediate
description
Development versions

Final
Validation version
12/30/2021 103
Advantages of Evolutionary Model (1)
 Users get a chance to experiment with a
partially developed system:
 Much before the full working version is
released,

 Helps finding exact user requirements:


 Much before fully working system is
developed.

 Core modules get tested thoroughly:


 Reduces chances of errors in final product.104
Advantages of Evolutionary
Model (2)
 Customers involved in the process:

 Therefore more likely to meet the


user requirement.

 Early and frequent testing:

 More likely to identify problems.


105
Evolutionary Model: Problems
 The process is intangible:
 No regular, well-defined deliverables.
 The process is unpredictable:
 Hard to manage, e.g., scheduling, workforce
allocation, etc.
 Systems are poorly structured:
 Continual, unpredictable changes tend to
degrade the software structure.
 Systems may not even converge to a final
106
version.
Incremental
Model

12/30/2021 107
Customer’s Perspective‫‏‬

A AB A

B B

108
Incremental Model
 Combines the ideas from Waterfall and
Evolutionary Model.

Requirements Split into


Outline Requirements Design

Develop Validate Integrate Validate


Increment Increment Increment System

Final
System
109
Slice
Slice
Slice
Slice
Slice
Slice
Slice
Slice
Slice
High Level Analysis
Incremental Model

Slice
Slice
110

Slice
Incremental Model
 Waterfall: single release
 Iterative: many releases (increments)
 First increment: core functionality
 Successive increments: add/fix functionality
 Final increment: the complete product

 Each iteration: a short mini-project with


a separate lifecycle
 e.g., waterfall 111
Incremental delivery
delivered
system

design build install evaluate increment


1
first incremental delivery

design build install evaluate increment


2
second incremental delivery
increment
design build install evaluate 3
third incremental delivery

112
The incremental process

Planned Identify System Objectives


incremental
Plan increments
delivery
Incremental delivery plan

Design increment

Build the increment


Repeat for
Feedback
each
Implement the increment
increment

Evaluate the results

113
R Waterfall
D
C
T

One Iteration
R
R
D Evolutionary
R
C
D Model With
R Iteration
D
T C
D
C
T
C
T
T
Time
R:Requirement Analysis
D:Design
114
C:Coding, Unit Testing
Which step first?
 Some steps will be pre-requisite because of
physical dependencies
 Others may be in any order
 Value to cost ratios may be used
 V/C where

 V is a score 1-10 representing value to


customer

 C is a score 0-10 representing cost to


115
developers
V/C ratios: an example
step value cost ratio
profit reports 9 1 9 2nd
online database 1 9 0.11 5th
ad hoc enquiry 5 5 1 4th
purchasing plans 9 4 2.25 3rd
profit- based pay 9 0 inf 1st
for managers

116
Incremental and
Iterative
Development (IID)
Model

12/30/2021 117
 “The basic idea… take advantage of what was
being learned during the development of
earlier, incremental, deliverable versions of
the system. Learning comes from both the
development and use of the system… Start
with a simple implementation of a subset of
the software requirements and iteratively
enhance the evolving sequence of versions. At
each version design modifications are made
along with adding new functional capabilities. “
Victor Basili
118
Incremental and Iterative
Development (IID)
 Key characteristics
 Consists of a planned number of iterations
 Each iteration produces a working program

 Builds system incrementally


 Monolithic approach of waterfall model
 Benefits
 Facilitates and manages changes
 Foundation of agile techniques
 Rational Unified Process (RUP)
 Extreme Programming (XP) 119
Evolutionary Model with Iteration
 Outcome of each iteration: tested,
integrated, executable system
 Iteration length is short and fixed
 e.g. 2 weeks, 4 weeks, 6 weeks
 Takes many iterations (e.g. 10-15)
 Does not “freeze” the requirements and
then speculatively design :
 Opportunity exists to modify requirements as
well as the design…
 Later iterations become stable 120
Advantages of evolutionary model
with iteration?
 Can better manage complexity by
developing one increment at a time.
 Can better manage changing requirements.
 Can provide partial solutions throughout the
development process.
 Can get customer feedback and incorporate
them much more efficiently:
 As compared when customer feedbacks come
only after all development is complete. 121
Advantages of Evolutionary Model
with Iteration
 Training can start on an earlier release
 customer feedback taken into account

 Markets can be created:


 Forfunctionality that has never been
offered by other vendors.

 Frequent releases allow developers to


fix unanticipated problems quickly. 122
Incremental versus Evolutionary
 Evolutionary iterative development implies
that the requirements, plan, estimates, and
solution evolve or are refined over the
course of the iterations, rather than fully
defined and “frozen” in a major up-front
specification effort before the development
iterations begin. Evolutionary methods are
consistent with the pattern of unpredictable
discovery and change in new product
development.” Craig Larman 123
RAD Model

12/30/2021 124
Rapid Application Development
(RAD) Model
 Sometimes referred to as the rapid
prototyping model.
 Major aims:
 Decrease the time taken and the cost incurred
to develop software systems.
 Facilitate accommodating change requests as
early as possible:
 Before large investments have been made in
development and testing. 125
Important Underlying Principle
• A way to reduce development time
and cost, and yet have flexibility
to incorporate changes:

• Make only short term plans and


make heavy reuse of existing
code.
126
Methodology
•Plans are made for one increment at
a time.
• The time planned for each iteration
is called a time box.
•Each iteration (increment):
• Enhances the implemented
functionality of the application a
little. 127
Methodology
• During each iteration,
• A quick-and-dirty prototype-style
software for some functionality is
developed.
• The customer evaluates the prototype
and gives his feedback.
• The prototype is refined based on the
customer feedback. 128
How Does RAD Facilitate Faster
Development?
 RAD achieves fast creation of working
prototypes.
 Through use of specialized tools.
 These specialized tools usually support
the following features:
 Visual style of development.
 Use of reusable components.
 Useof standard APIs (Application Program
129

Interfaces).
Applications for Which RAD is
Suitable
•Customized product developed for
one or two customers only

•Performance and reliability are not


critical.

•The system can be split into several


independent modules. 130
Application Characteristics that
Render RAD Unsuitable

• Few plug-in components are available

• High performance or reliability


required

• No precedence for similar products


exists

• The system cannot be modularized.


131
Prototyping versus RAD
•In prototyping model:
•The developed prototype is
primarily used to gain insights into
the solution
•Choose between alternatives
•Elicit customer feedback.
•The developed prototype:
•Usually thrown away. 132
Prototyping versus RAD
• In contrast:
• In RAD the developed prototype
evolves into deliverable software.

• RAD leads to faster development


compared to traditional models:
• However, the quality and reliability
would possibly be poorer.
133
RAD versus Iterative Waterfall Model
 In the iterative waterfall model,
 All product functionalities are developed
together.

 In the RAD model on the other hand,


 Product functionalities are developed
incrementally through heavy code and design
reuse.
 Customer feedback is obtained on the developed
prototype after each iteration:
134
 Based on this the prototype is refined.
RAD versus Iterative Waterfall
Model
 The iterative waterfall model:
 Does not facilitate accommodating requirement
change requests.
 Iterative waterfall model does have some
important advantages:
 Use of the iterative waterfall model leads to
production of good documentation.
 Also, the developed software usually has
better quality and reliability than that
135
developed using RAD.
RAD versus Evolutionary Model
 Incremental development:
 Occurs in both evolutionary and RAD models.
 However, in RAD:
 Each increment is a quick and dirty prototype,
 Whereas in the evolutionary model each
increment is systematically developed using the
iterative waterfall model.
 Also, RAD develops software in shorter
increments:
 Compared to the evolutionary model
 The incremental functionalities are fairly large
136
in the evolutionary model.
Agile Models

12/30/2021 137
What is Agile Software Development?

 Agile: Easily moved, light, nimble,


active software processes

 How agility achieved?

 Fitting the process to the project

 Avoidance of things that waste time


138
Cartoonist’s View: Agile Model

139
Agile Model
 To overcome the shortcomings of the
waterfall model of development.
 Proposed in mid-1990s

 The agile model was primarily designed:


 To help a project to adapt to change requests

 In the agile model:


 The requirements are decomposed into many
small incremental parts that can be developed
over one to four weeks each. 140
141
What is Agile Software Development?

 Agile: Easily moved, light, nimble,


active software processes

 How agility achieved?


 Fitting the process to the project

 Avoidance of things that waste


time 142
Dilbert: Scott Adams 143
Ideology: Agile Manifesto
 Individuals and interactions over
 process and tools
 Working Software over
 comprehensive documentation
 Customer collaboration over
 contract negotiation
 Responding to change over
http://www.agilemanifesto.org
 following a plan 144
Dilbert: Scott Adams 145
Agile Methodologies
 XP
 Scrum
 Unified process
 Crystal
 DSDM
 Lean 146
Agile Model: Principal Techniques
 User stories:
 Simpler than use cases.
 Metaphors:
 Based on user stories, developers propose a
common vision of what is required.
 Spike:
 A very simple program to explore potential
solutions should be considered.
 Refactor:
 Restructure code without affecting behavior,
147
improve efficiency, structure, etc.
Agile Model: Nitty Gritty
 At a time, only one increment is planned,
developed, deployed at the customer site.
 No long-term plans are made.

 An iteration may not add significant


functionality,
 but still a new release is invariably made at
the end of each iteration

 Delivered to the customer for regular use. 148


Methodology
 Face-to-face communication favoured over
written documents.

 To facilitate face-to-face communication,


 development team to share a single office
space.

 Team size is deliberately kept small (5-9


people)

 This makes the agile model most suited to the


149
development of small projects.
Effectiveness of Face-to-face
at whiteboard

Communication Modes Face-to-face


conversation
Communication Effectiveness

Video
conversation
Modeling
Phone Options
conversation

Videotape
Email
conversation

Audiotape
Documentation
Options
Paper

Cold Hot
Richness of Communication Channel
Copyright 2002-2005 Scott W. Ambler 150
Original Diagram Copyright 2002 Alistair Cockburn
Agile Model: Principles
 The primary measure of progress:
 Incremental release of working software
 Important principles behind agile model:
 Frequent delivery of versions every few weeks.
 All change requests to the requirements are
accommodated easily.
 Close cooperation between customers and
developers.
 Face-to-face communication among the
development team members. 151
Agile Documentation
 Travel light:
 You need far less documentation than you think.
 Agile documents:
 Are concise
 Describe information that is less likely to change
 Describe “good things to know”
 Are sufficiently accurate, consistent, and detailed
 Valid reasons to document:
 Your project stakeholders require it
 To define a contract model
 To support communication with an external group
 To think something through 152
Agile Software Requirements Management
High
{ Each iteration implement the highest-
Priority priority requirements

Each new requirement is


prioritized and added to
the stack

Requirements may be
reprioritized at any time

Requirements may be
removed at any time

Low
Priority 153
Requirements Copyright 2004 Scott W. Ambler
Adoption Detractors
 Lack of theoretical grounding
 Inconsistent and diverse definitions
 High quality people skills required
 Short iterations inhibit long-term
perspective
 Higher risks:
 Harderto manage feature creep and
customer expectations
 Difficult to quantify cost, time, quality.
154
Agile Model Shortcomings
 Derive agility through developing
tacit knowledge in the team, rather
than any formal document:
 Can be misinterpreted…
 External review difficult to get…
 When project is complete, and team
disperses, maintenance becomes
difficult…
155
Agile vs. Plan-Driven Processes
1. Small products and 1. Large products and
teams: teams;
 Scalability limited  hard to scale down
2. Untested on safety- 2. Proven for highly critical
critical products products;
3. Good for dynamic, 3. Good for stable:
but expensive for  But expensive for dynamic
stable environments. environments
4. Require experienced 4. Require only few
personnel throughout experienced personnel
5. Personnel thrive on 5. Personnel thrive on
freedom and chaos
structure and order 156
Agile Model versus Iterative Waterfall
Model
 The waterfall model steps through in a planned
sequence over
 Requirements-capture, analysis, design, coding, and
testing stages:
 Progress is measured in terms of delivered
artifacts:
 Requirement specifications, design documents, test
plans, code reviews, etc.
 In contrast agile model sequences:
 Delivery of working versions of a product in several
157
increments.
Agile Model versus
Iterative Waterfall Model
 As regards to similarity:
 We can say that Agile teams
use the waterfall model on a
small scale.

158
Agile versus RAD Model
 Agile model does not recommend developing
prototypes:
 Systematic development of each incremental
feature is emphasized.
 In contrast:
 RAD is based on designing quick-and-dirty
prototypes, which are then refined into
production quality code.
 Agile projects logically break down the
solution into a number of features:
 These are incrementally developed and 159

delivered.
Agile versus exploratory programming
 Similarity:

 Frequent re-evaluation of plans,


 Emphasis on face-to-face communication,
 Relatively sparse use of documents.
 Agile teams, however, do follow defined
and disciplined processes and carry out
rigorous designs:
 Thisis in contrast to chaotic coding in
160
exploratory programming.
Extreme Programming
and Unified Process

12/30/2021 161
Extreme Programming

Dilbert: Scott Adams 162


Extreme Programming

Dilbert: Scott Adams 163


Extremely Programming: Con

Dilbert: Scott Adams 164


Extreme Programming Model
 Extreme programming (XP) was
proposed by Kent Beck in 1999.
 The methodology got its name from
the fact that:
 Recommends taking the best
practices to extreme levels.
 Ifsomething is good, why not do it all
165
the time.
Cartoonist’s View

Dilbert: Scott Adams 166


4 Values
 Communication:
 Enhance communication among team members
and with the customers.
 Simplicity:
 Build something simple that will work today
rather than something that takes time and yet
never used
 May not pay attention for tomorrow
 Feedback:
 System staying out of users is trouble waiting
to happen
 Courage: 167
 Don’t hesitate to discard code
Taking Good Practices to Extreme
 If code review is good:
 Always review --- pair programming
 If testing is good:
 Continually
write and execute test cases ---
test-driven development
 If incremental development is good:
 Come up with new increments every few
days
 If simplicity is good:
 Createthe simplest design that will support
168
only the currently required functionality.
Taking to Extreme
 If design is good,
 everybody will design daily (refactoring)

 If architecture is important,
 everybody will work at defining and
refining the architecture (metaphor)

 If integration testing is important,


 buildand integrate test several times a
day (continuous integration) 169
Best Practices
 Coding:
 without code it is not possible to have a
working system.
 Utmost attention needs to be placed on
coding.
 Testing:
 Testing is the primary means for developing a
fault-free product.
 Listening:
 Careful listening to the customers is essential
170
to develop a good quality product.
Best Practices
 Designing:
 Withoutproper design, a system
implementation becomes too complex
 Thedependencies within the system
become too numerous to comprehend.
 Feedback:
 Feedbackis important in learning
customer requirements. 171
Extreme Programming Activities
 XP Planning
• Begins with the creation of “user stories”
• Agile team assesses each story and assigns a cost
• Stories are grouped to for a deliverable increment
• A commitment is made on delivery date
 XP Design
• Follows the KIS principle
• Encourage the use of CRC cards
• For difficult design problems, suggests the creation of
“spike solutions”—a design prototype
• Encourages “refactoring”—an iterative refinement of the
internal program design 172
172
Extreme Programming Activities
 XP Coding
• Recommends the construction of a unit test
for a store before coding commences
• Encourages “pair programming”
 XP Testing
• All unit tests are executed daily
• “Acceptance tests” are defined by the
customer and executed to assess customer
visible functionality 173
173
Full List of XP Practices
1. Planning – determine scope of the next release by
combining business priorities and technical
estimates

2. Small releases – put a simple system into


production, then release new versions in very short
cycle

3. Metaphor – all development is guided by a simple


shared story of how the whole system works

4. Simple design – system is designed as simply as


possible (extra complexity removed as soon as
found 174
Full List of XP Practices
7. Refactoring – programmers continuously
restructure the system without changing its
behavior to remove duplication and simplify

8. Pair-programming -- all production code is


written with two programmers at one machine

9. Collective ownership – anyone can change any


code anywhere in the system at any time.

10. Continuous integration – integrate and build


the system many times a day – every time a
task is completed. 175
Full List of XP Practices
11.40-hour week – work no more than 40
hours a week as a rule

12.On-site customer – a user is on the team


and available full-time to answer
questions

13.Coding standards – programmers write all


code in accordance with rules emphasizing
communication through the code
176
Emphasizes Test-Driven Development
(TDD)
 Based on user story develop test cases
 Implement a quick and dirty feature
every couple of days:
 Get customer feedback
 Alter if necessary
 Refactor

 Take up next feature 177


Project Characteristics that Suggest
Suitability of Extreme Programming
 Projects involving new technology or
research projects.
 Inthis case, the requirements change
rapidly and unforeseen technical problems
need to be resolved.
 Small projects:
 Theseare easily developed using extreme
programming. 178
Rational Unified Process
 Originally developed by Rational Software:
 Acquired by IBM in February 2003.
 Based on six best practices:
 Develop iteratively, with risk as the primary
iteration driver
 Manage requirements
 Employ a component-based architecture
 Model software visually
 Continuously verify quality
 Control changes 179
An Evolutionary and Iterative
Development Process...
 Recognizes the reality of changing requirements
 Capers Jones’s research on 8000 projects
 40% of final requirements arrived after
development had already begun
 Promotes early risk mitigation:
 Breaks down the system into mini-projects and focuses on the
riskier elements first.
 Allows you to:
 “plan a little, design a little, and code a little”
 Encourages all development participants to be involved
earlier on,:
180
 Testers, integrators, and technical writers
Goals and Features of Each Iteration
 Primary goal of each iteration:
 Chip away the project risks.
 Addresses following risks:
 Performance risks
 Integration risks (different vendors,
tools, etc.)
 Conceptual risks (ferret out analysis
and design flaws) 181
Activities in an Iteration
 Perform a project of “mini
waterfalls”.
 The result of a single iteration:
 Ends with delivery of some tangible
code
 An incremental improvement to the
software --- leads to evolutionary
development
182
Four Phases --- and iterative
Development at Every phase

 Inception Phase
 Elaboration Phase
 Construction Phase
 Transition Phase

183
RUP Iterations in Phases
The duration of and iteration may vary from
two weeks or less.
Iterations Iterations Iterations Iterations

Inception Elaboration Construction Transition

184
Unified process
software
increment
Communication inception

Deployment Planning

transition elaboration

Construction Modeling

construction
185
Unified process work products

Inception phase Elaboration phase Construction phase Transition phase


vision document use-case model design model SW increment
initial use-case model requirements SW components beta test reports
initial business case analysis model test plan user feedback
initial risk list preliminary model test procedure ...
project plan revised risk list test cases
prototype(s) preliminary manual user manual
... ... installation manual
...

186
Structure of RUP Process
 Two dimensions.
 Horizontal axis:
 Represents time and shows the
lifecycle aspects of the process as it
unfolds.

 Vertical axis:
 Represents core process workflows. 187
Two dimensions of RUP

188
Inception activities
 Formulate scope of project

 Evaluate alternatives for risk


management, staffing, project
plan

 Synthesize a candidate
architecture. 189
Outcome of Inception Phase
 Initial requirements capture

 Cost Benefit Analysis

 Initial Risk Analysis

 Project scope definition

 Defining a candidate architecture

 Development of a disposable prototype

 Initial Use Case Model (10% - 20% complete)

 First pass at a Domain Model 190


Elaboration Phase
 Requirements Analysis and Capture
 Use Case Analysis
 Use Case Model (80% done)
 Other models:
 Sequence and Collaboration Diagrams
 Class, Activity, Component, State Diagrams
 Glossary (users and developers can speak common
vocabulary)
 Domain Model
 Model the system’s requirements as they exist within the
context of the problem domain
 Risk Assessment Plan revised
191
 Architecture Document
Construction Phase
 Focus is on implementation of the
design:
 The focus is on implementation.
 Mostof the coding is done in this phase,
and the architecture and design are fully
developed.
 Greater stability begins to appear
 Analysiscontinues, but design and
coding predominate 192
Transition Phase
• Beta testing

• The users and maintainers of the system


are trained on the application.

• The tested baseline of the application is


transitioned to the user community and
deployed for use.

193
Transition Phase
 The transition phase consists of the transfer
of the system to the user community
 Includes shipping, installation, training, technical
support and maintenance

 Development team begins to shrink

 Control is moved to maintenance team

 Alpha, Beta, and final releases

 Integration with existing systems (legacy,


existing versions, etc.) 194
Transition Phase Activities
 Beta testing to validate the new system against use
expectations.

 Parallel operation with the legacy system that the


project is replacing

 Conversion of operational databases.

 Training of users and maintainers.

 Rollout of the product to the marketing, distribution


and sales teams.

 It concludes when the deployment baseline has


achieved the completed vision. 195
Comparison of Different Life
Cycle Models
 Iterative waterfall model
 Most widely used model.
 But,
suitable only for well-understood
problems.
 Prototype model is suitable for projects
not well understood:
 user requirements
 technical aspects 196
Comparison of Different Life Cycle Models
(CONT.)‫‏‬

 Evolutionary model is suitable for large


problems:
 Can be decomposed into a set of modules that
can be incrementally implemented,
 Incremental delivery of the system is
acceptable to the customer.

 The spiral model:


 Suitable for development of technically
challenging software products that are subject
197
to several kinds of risks.
Practice Questions
 What are the stages of iterative
waterfall model?
 What are the disadvantages of the
iterative waterfall model?
 Why has agile model become so
popular?
 What difficulties might occur if no life
cycle model is followed? 198
Suggest Suitable Life Cycle Model
 A software for an academic institution to
automate its:
 Course registration and grading
 Fee collection
 Staff salary
 Purchase and store inventory
 The software would be developed by tailoring a
similar software that was developed for
another educational institution:
 70% reuse
 10% new code and 20% modification 199
Practice Questions
 Which types of risks can be better
handled using the spiral model
compared to the prototyping model?
 Which type of process model is
suitable for the following projects:
A customization software
A payroll software for contract
employees that would be add on to an
200

existing payroll software


Practice Questions
 Which lifecycle model would you select for
the following project which has been
awarded to us by a mobile phone vendor:
 A new mobile operating system
 Needs to work well efficiently with 4G systems
 Power usage minimization
 Directly upload backup data on a cloud
infrastructure maintained by the mobile phone
vendor
 Provides sensing many health parameters of 201the
user and alerting on any abnormality.
Scrum

202
Scrum: Characteristics
 Self-organizing teams
 Product progresses in a series of month-
long “sprints”
 Requirements are captured as items in a
list of “product backlog”
 No specific engineering practices
prescribed
 Uses generative rules to create an agile
environment for delivering projects
One of the “agile processes”
203

How Scrum Works?

204
Sprints
 Scrum projects make progress in a series
of “sprints”
 Analogous to XP iterations

 Target duration is one month


 +/- a week or two
 But, a constant duration leads to a better
rhythm

 Product is designed, coded, and tested


during the sprint
205
Sequential vs. Overlapping Dev.

Requirements Design Code Test

206
207
No changes during the sprint

Change

Inputs Sprint Tested Code

 Plan sprint durations around how long you can


commit to keeping change out of the sprint
208
Scrum Framework
 Roles : Product Owner, ScrumMaster,
Team

 Ceremonies : Sprint Planning, Sprint


Review, Sprint Retrospective, & Daily
Scrum Meeting

 Artifacts : Product Backlog, Sprint


Backlog, and Burndown Chart

209
Key Roles and Responsibilities in Scrum Process
 Product Owner
 Acts on behalf of customers to represent
their interests.
 Development Team
 Team of five-nine people with cross-functional
skill sets.
 Scrum Master (aka Project Manager)
 Facilitates scrum process and resolves
impediments at the team and organization level
by acting as a buffer between the team and
outside interference. 210
Product Owner
 Define the features of the product
 Decide on release date and content
 Responsible for the profitability of the
product (ROI)
 Prioritize features according to market
value
 Adjust features and priority every
iteration, as needed
211
 Accept or reject work results.
The Scrum Master
 Represents management to the project

 Responsible for enacting Scrum


values and practices

 Removes impediments
 Ensure that the team is fully functional and
productive
 Enable close cooperation across all roles and
functions
 Shield the team from external interferences212
Scrum Team
 Typically 5-10 people
 Cross-functional
 QA, Programmers, UI Designers, etc.

 Members should be full-time


 May be exceptions (e.g., System Admin, etc.)

 Teams are self-organizing


 What to do if a team self-organizes someone off the
team??
 Ideally, no titles but rarely a possibility

 Membership can change only between sprints 213


Ceremonies
 Sprint Planning Meeting

 Sprint

 Daily Scrum

 Sprint Review Meeting

214
Spring Planning Meeting

Product Backlog

Team Capabilities
Sprint Goal
Sprint Planning
Business Conditions
Meeting Sprint Backlog
Technology

Current Product

215
Parts of Sprint Planning Meeting
 1st Part:
 Creating Product Backlog
 Determining the Sprint Goal.

 Participants: Product Owner, Scrum


Master, Scrum Team

 2nd Part:
 Participants: Scrum Master, Scrum Team
 Creating Sprint Backlog 216
Pre-Project/Kickoff Meeting
 A special form of Sprint Planning
Meeting

 Meeting before the begin of the


Project

217
Sprint
• Fundamental process flow of Scrum
• A short, fixed-length period of time
• Goal is to produce Backlog Items into renewable
products that Stakeholders can provide feedback
on
• Sprint Planning allows the PO to work with the
Team to negotiate what Backlog Items the Team
will work on in order to meet Release Goals
• Scrum Master ensures Team agrees to realistic
goals 218
Sprint
 A month-long iteration, during which is
incremented a product functionality

 NO outside influence can interfere with


the Scrum team during the Sprint

 Each Sprint begins with the Daily Scrum


Meeting
219
 Parameters Daily Scrum
 Daily

 15-minutes

 Stand-up

 Not for problem solving

 Three questions:
1. What did you do yesterday

2. What will you do today?

3. What obstacles are in your way?

 Chickens and pigs are invited


220
 Help avoid other unnecessary meetings
Daily Scrum
 Is NOT a problem solving session
 Is NOT a way to collect information
about WHO is behind the schedule
 Is a meeting in which team members
make commitments to each other and to
the Scrum Master
 Is a good way for a Scrum Master to
track the progress of the Team
221
Scrum FAQs
 Why daily?
 “How does a project get to be a year late?”
 “One day at a time.”
 Fred Brooks, The Mythical Man-Month.
 Can Scrum meetings be replaced by emailed
status reports?
 No
 Entire team sees the whole picture every day
 Create peer pressure to do what you say
you’ll do
222
Sprint Review Meeting
 Team presents what it accomplished during the sprint

 Typically takes the form of a demo of new features or


underlying architecture

 Informal
 2-hour prep time rule

 Participants
 Customers

 Management

 Product Owner
223
 Other engineers
Sprint Retrospective Meeting
 Scrum Team only
 Feedback meeting
 Three questions
 Start

 Stop
 Continue

 Don’t skip for the first 5-6 sprints!!!


224
Product Backlog
 A list of all desired work on the project

 Usually a combination of

 story-based work (“let user search and replace”)

 task-based work (“improve exception handling”)

 List is prioritized by the Product Owner

 Typically a Product Manager, Marketing,


Internal Customer, etc. 225
Product Backlog
 Requirements for a system, expressed as a
prioritized list of Backlog Items
 Is managed and owned by a Product Owner
 Spreadsheet (typically)
 Usually is created during the Sprint
Planning Meeting
 Can be changed and re-prioritized before
each PM 226
Sample Product Backlog

227
From Sprint Goal to Sprint Backlog
 Scrum team takes the Sprint Goal and
decides what tasks are necessary
 Team self-organizes around how they’ll
meet the Sprint Goal
 Manager doesn’t assign tasks to individuals

 Managers don’t make decisions for the


team
 Sprint Backlog is created 228
Sprint Backlog during the Sprint
 Changes
 Team adds new tasks whenever they need
to in order to meet the Sprint Goal
 Team can remove unnecessary tasks
 But:Sprint Backlog can only be updated
by the team

 Estimates are updated whenever


there’s new information 229
Sprint Backlog
 A subset of Product Backlog Items, which
define the work for a Sprint

 Is created ONLY by Team members

 Each Item has it’s own status

 Should be updated every day

230
Sprint Backlog
 No more than 300 tasks in the list

 If a task requires more than 16 hours, it


should be broken down

 Team can add or subtract items from the


list. Product Owner is not allowed to do it

231
Sample Sprint Backlog

232
Burn down Charts
 Are used to represent “work done”.
 Are wonderful Information Radiators
 3 Types:
 Sprint Burn down Chart (progress of the
Sprint)

 Release Burn down Chart (progress of


release)

Product Burn down chart (progress of the


233
JASS 2006
Product)
Sprint Burn down Chart
 Depicts the total Sprint Backlog hours
remaining per day

 Shows the estimated amount of time to


release

 Ideally should burn down to zero to the end


of the Sprint

 Actually is not a straight line


234
Remaining Effort in Hours

5/
3/
2

0
100
200
300
400
500
600
700
800
900
5/ 00
5/ 2
2
5/ 002
7/
2
752

5/ 00
9/ 2
5/ 200
11 2
5 / /2 0
762

13 02
/
5/ 200
664

15 2
/
5/ 200
17 2
5 / /2 0
Progress

619

19 02
/
5/ 200

Date
21 2
304

5 / /2 0
23 02
/
5/ 200
25 2
5 / /2 0
264

27 02
/
5/ 200
180

29 2
5 / /2 0
31 02
/2
00
2
104
20
Sprint Burndown Chart

235
Release Burndown Chart
 Will the release be done on right
time?

 X-axis: sprints

 Y-axis: amount of hours remaining

 The estimated work remaining can


also burn up
236
Product Burndown Chart
 Is a “big picture” view of project’s
progress (all the releases)

237
Scalability of Scrum
 A typical Scrum team is 6-10 people

 Jeff Sutherland - up to over 800 people

 "Scrum of Scrums" or what called


"Meta-Scrum“

 Frequency of meetings is based on the


degree of coupling between packets
238
Scalability of Scrum

239
Scalability of Scrum

240
Thanks

241
Feasibility Analysis and Bidding

242
243
244
245
Requirements Analysis
and Specification

Prof. R. Mall
Dept. of CSE, IIT, Kharagpur

1
Requirements Analysis and Specification

● Many projects have failed:

– Becausethey started to implement


the software.

– Without ever determining whether


they are building what the customer
really wanted.
2
What are Requirements?
● A Requirement is:
– A capability or condition required from the
system.
● What is involved in requirements analysis
and specification?
– Determine what is expected by the client
from the system.
– Document them in the form that is clear to
the client as well as to the development team
members. 3
Understand and specifying requirements
 A problem of scale:

 For small scale: understanding and specifying


requirements is easy

 For large scale: very hard; probably the hardest,


most problematic and error prone development task

 The requirements specification task:


 Input: User needs in minds of people (hopefully)!

 Output: precise statement of what the future


system will do 4
Requirements for Products

● When a company plans to develop a


generic product:

– Who gives the requirements?

● The sales personnel

5
6
Dilbert: Scott Adams
Dilbert: Scott Adams 7
Activities in Requirements
Analysis and Specification

Requirements Gathering

Requirements Analysis

Requirements Specification
8
Requirements Engineering Process

Feasibility
Study Requirements
gathering
Requirements
analysis
Feasibility Requirements
report specification

SRS Document

9
Dilbert: Scott Adams 10
Requirements Analysis and Specification

● Requirements Gathering:
– Fully understand the user requirements.
● Requirements Analysis:
– Removeinconsistencies, anomalies, etc.
from requirements.
● Requirements Specification:
– Documentrequirements properly in an
SRS document. 11
Dilbert: Scott Adams 12
Need for SRS…
● Good SRS reduces development cost
– Req. errors are expensive to fix later
– Req. changes cost a lot (typically 40%)
– Good SRS can minimize changes and errors
– Substantial savings --- effort spent during
req. saves multiple times that effort

Cost
● An Example:
– Cost of fixing errors in req. , design , coding ,
acceptance testing and operation are 2 , 5 , 15
, 50 , 150 person-months 13
Uses of SRS Document
● Establish the basis for agreement
between the customers and the suppliers
● Provides starting point for development.
● Provide a basis for estimating costs and
schedules.
● Provide a baseline for validation and
verification.
● Facilitates transfer.
● Serves as a basis for enhancement. 14
Forms Basis for User Manual
● The SRS can serve as the basis for
writing User Manual for the software:

– User Manual: Describes the


functionality from the perspective of a
user --- An important document for
users.

– Typically also describes how to carry out


the required tasks with examples. 15
SRS Document: Stakeholders
● SRS intended for a diverse audience:
– Customers and users for validation, contract, ...
– Systems (requirements) analysts
– Developers, programmers to implement the system
– Testers to check that the requirements have been
met
– Project Managers to measure and control the project
● Different levels of detail and formality is needed
for each audience
● Different templates for requirements
specifications:
16
– Often variations of IEEE 830
Requirement process..
needs ● Specification itself
may lead to more
Gathering analysis

Analysis ● Validation can show


gaps that can lead to
Specification further analysis and
specification .
Validation

SRS Document 17
Dilbert: Scott Adams
18
How to Gather Requirements?
● Observe existing (manual) systems,
● Study existing procedures,
● Discuss with customer and end-
users,
● Analyse what needs to be done
● Input and Output analysis
19
Requirements Gathering Activities

● 1. Study existing documentation

● 2. Interview

● 3. Task analysis
● 4. Scenario analysis
● 5. Form analysis
20
Dilbert: Scott Adams 21
Requirements Gathering (CONT.)
● In the absence of a working
system,
– Lotof imagination and creativity
are required.
● Interacting with the customer to
gather relevant data:
– Requires a lot of experience.
22
Requirements Gathering (CONT.)

● Some desirable attributes of a


good system analyst:
– Good interaction skills,
– Imagination and creativity,
– Experience…

23
Dilbert: Scott Adams 24
Case Study: Automation of
Office Work at CSE Dept.
● The academic, inventory, and financial
information at the CSE department:
– Being carried though manual processing by two
office clerks, a store keeper, and two
attendants.
● Considering the low budget he had at his
disposal:
– The HoD entrusted the work to a team of
student volunteers. 25
Case Study: Automation of Office
Work at CSE Dept.
● The team was first briefed by the HoD:
– Concerning the specific activities to be
automated.
● The analysts first discussed with the two
office clerks: Interview

– Regarding their specific responsibilities (tasks)


that were to be automated.
● The analyst also interviewed student and
faculty representatives who would also use
the software.
26
Case Study: Automation of Office
Work at CSE Dept.
● For each task that a user needs the
software to perform, they asked:
– The steps through which these are to be
performed. Task and Scenario Analysis
– The various scenarios that might arise for
each task.
● The analyst also collected the different
types of forms that were being used.
Form Analysis 27
Case Study: Automation of Office
Work at CSE Dept.
● The analysts understood the requirements for
the system from various user groups:
– Identified inconsistencies, ambiguities,
incompleteness.
Requirements Analysis
● Resolved the requirements problems through
discussions with users:
– Resolved a few issues which the users were unable to
resolve through discussion with the HoD.

● Documented the requirements in the form of an


SRS document. Requirements Specification 28
Analysis of Gathered Requirements
● Main purpose of req. analysis:
● Clearly understand user requirements,
● Detect inconsistencies, ambiguities,
and incompleteness.

● Incompleteness and inconsistencies:


– Resolvedthrough further discussions
with the end-users and the customers.
29
Ambiguity
“All customers must have the same control
field.”

Do you notice any problems?


Multiple interpretations possible
1. All customers have the same value in
their control field.
2. All control fields have the same format.

3. One control field is issued for all


customers. 30
Inconsistent Requirement
● Some part of the requirement:
– contradicts with some other part.
● Example:
– One customer says turn off heater and
open water shower when temperature >
100°C
– Another customer says turn off heater
and turn ON cooler when temperature >
100°C 31
Incomplete Requirement
● Some requirements not included:
– Possibly due to oversight.
● Example:
– Theanalyst has not recorded:
when temperature falls below 90° C
● heater should be turned ON
● water shower turned OFF.
32
Analysis of the Gathered
Requirements (CONT.)
● Requirements analysis involves:
– Obtaininga clear, in-depth
understanding of the software to be
developed,
– Remove all ambiguities and
inconsistencies from the initial
customer perception of the problem.
33
Analysis of the Gathered
Requirements (CONT.)

● It is quite difficult to obtain:


–A clear, in-depth understanding
of the problem:
● Especially if there is no working
model of the problem.

34
Analysis of the Gathered
Requirements (CONT.)

● Experienced analysts take


considerable time:

– Clearly understand the exact


requirements the customer has in his
mind.
35
Analysis of the Gathered
Requirements (CONT.)

● Experienced systems analysts


know - often as a result of painful
experiences ---
– “Without a clear understanding of
the problem, it is impossible to
develop a satisfactory system.”
36
Analysis of the Gathered
Requirements (CONT.)
● Several things about the project should
be clearly understood by the analyst:
– What is the problem?
– Why is it important to solve the problem?
– What are the possible solutions to the
problem?
– What complexities might arise while
solving the problem? 37
Analysis of the Gathered
Requirements (CONT.)

● Some anomalies and inconsistencies


can be very subtle:
– Escape even most experienced eyes.
– Ifa formal model of the system is
constructed,
● Many of the subtle anomalies and
inconsistencies get detected. 38
Analysis of the Gathered
Requirements (CONT.)

● After collecting all data regarding


the system to be developed,
– Remove all inconsistencies and
anomalies from the requirements,
– Systematicallyorganize requirements
into a Software Requirements
Specification (SRS) document.
39
Software Requirements Specification
● Main aim of requirements
specification:
– Systematically
organize the
requirements arrived during
requirements analysis.
– Document requirements properly.
40
SRS Document

● As already pointed out---


useful in various contexts:
– Statement of user needs
– Contract document
– Reference document
– Definition for implementation
41
SRS Document (CONT.)

● The SRS document is known as


black-box specification:
– Thesystem is considered as a black box
whose internal details are not known.
– Onlyits visible external (i.e.
input/output) behavior is documented.

Input
Data S Output
Data
42
SRS Document (CONT.)

● SRS document concentrates on:


– What needs to be done in terms of
input-output behaviour
– Carefully avoids the solution (“how to
do”) aspects.

43
SRS Document (CONT.)

● The requirements at this stage:


– Writtenusing end-user
terminology.
● If necessary:
– Latera formal requirement
specification may be developed
from it.
44
Properties of a Good SRS Document
● It should be concise
– and at the same time should not be ambiguous.

● It should specify what the system must do


– and not say how to do it.

● Easy to change.,
– i.e. it should be well-structured.

● It should be consistent.
● It should be complete. 45
Properties of a Good SRS Document
(cont...)

● It should be traceable
– Youshould be able to trace which
part of the specification
corresponds to which part of the
design, code, etc and vice versa.
● It should be verifiable
– e.g.
“system should be user friendly” is
not verifiable 46
SRS should not include...
● Project development plans
– E.g. cost, staffing, schedules, methods, tools, etc
● Lifetime of SRS is until the software is made obsolete
● Lifetime of development plans is much shorter

● Product assurance plans


– Configuration Management, Verification & Validation,
test plans, Quality Assurance, etc
● Different audiences
● Different lifetimes

● Designs
– Requirements and designs have different audiences
47
– Analysis and design are different areas of expertise
A Badly Written Gigantic Document is a Pain to Users

Dilbert: Scott Adams 48


SRS Document (CONT.)

● Following are possibly the most


important parts:
– Functional requirements,
– External Interfaces
– Non-functional requirements,
– Constraints
49
Functional Requirements
● Specifies all the functionality that the
system should support
– Heart of the SRS document:

– Forms the bulk of the Document

● Outputs for the given inputs and the


relationship between them
● Must specify behavior for invalid inputs
too! 50
Functional Requirement Documentation
● Overview
– describe
purpose of the function and the
approaches and techniques employed
● Inputs and Outputs
– sources of inputs and destination of
outputs
– quantities,units of measure, ranges of
valid inputs and outputs
51
– timing
Functional Requirement Documentation
● Processing
– validation of input data
– exact sequence of operations
– responses to abnormal situations
– any methods (eg. equations,
algorithms) to be used to transform
inputs to outputs 52
Nonfunctional Requirements
● Characteristics of the system which
can not be expressed as functions:
● Maintainability,
● Portability,
● Usability,
● Security,
● Safety, etc.
53
Nonfunctional Requirements
● Reliability issues
● Performance issues:
– Example:How fast the system can
produce results
● so that it does not overload another
system to which it supplies data, etc.
● Needs to be measurable (verifiability)
● Eg resp time should be xx 90% of the
time 54
Constraints
● Hardware to be used,
● Operating system
– or DBMS to be used
● Capabilities of I/O devices
● Standards compliance
● Data representations
– by the interfaced system 55
External Interface Requirements
● User interfaces

● Hardware interfaces

● Software interfaces

● Communications interfaces with


other systems

● File export formats 56


Goals of Implementation
● Goals describe things that are
desirable of the system:
– But,
would not be checked for
compliance.
– For example,
● Reusability issues
● Functionalities to be developed in
future 57
IEEE 830-1998 Standard for SRS
● Title
•Describe purpose of this SRS
● Table of Contents •Describe intended audience

● 1. Introduction •Identify the software product


– 1.1 Purpose •Enumerate what the system will and will not do
•Describe user classes and benefits for each

– 1.2 Scope
– 1.3 Definitions. Acronyms, and Abbreviations
•Define the vocabulary of the
– 1.4 References SRS (may reference appendix)

– 1.5 Overview •List all referenced documents including sources


(e.g., Use Case Model and Problem Statement;
● 2. Overall Description Experts in the field)

● 3. Specific Requirements •Describe the content of the rest of the


SRS

● Appendices •Describe how the SRS is organized

● Index 58
IEEE 830-1998 Standard – Section 2 of SRS
● Title •Present the business case and operational concept of the system
•Describe how the proposed system fits into the business context

● Table of Contents
•Describe external interfaces: system, user, hardware, software, communication
•Describe constraints: memory, operational, site adaptation

● 1. Introduction
•Summarize the major functional capabilities
● 2. Overall Description •Include the Use Case Diagram and supporting narrative
(identify actors and use cases)
– 2.1 Product Perspective •Include Data Flow Diagram if appropriate

– 2.2 Product Functions •Describe and justify technical skills


and capabilities of each user class
– 2.3 User Characteristics
– 2.4 Constraints
– 2.5 Assumptions and Dependencies
•Describe other constraints that will limit developer’s
● 3. Specific Requirements options; e.g., regulatory policies; target platform,
database, network software and protocols, development
● 4. Appendices standards requirements

● 5. Index 59
IEEE 830-1998 Standard – Section 3 of SRS (1)
● …
● 1. Introduction Specify software requirements in sufficient

● 2. Overall Description those requirements and testers to verify


detail to enable designers to design a system to satisfy

requirements
● 3. Specific Requirements
State requirements that are externally perceivable by
– 3.1 External Interfaces users, operators, or externally connected systems
Requirements should include, at a minimum, a description
– 3.2 Functions of every input (stimulus) into the system, every output
(response) from the system, and all functions performed

– 3.3 Performance Requirements by the system in response to an input or in support of


an output

– 3.4 Logical Database Requirements


(a) Requirements should have characteristics of
high quality requirements
(b) Requirements should be cross-referenced to
– 3.5 Design Constraints their source.
(c) Requirements should be uniquely identifiable
– 3.6 Software System Quality Attributes
(d) Requirements should be organized to
maximize readability

– 3.7 Object Oriented Models


● 4. Appendices
60
● 5. Index
IEEE 830-1998 Standard – Section 3 of SRS (2)
● …
•Detail all inputs and outputs
● 1. Introduction (complement, not duplicate, information presented in section 2)
•Examples: GUI screens, file formats
● 2. Overall Description

● 3. Specific Requirements
•Include detailed specifications of each
– 3.1 External Interfaces use case, including collaboration and
other diagrams useful for this purpose

– 3.2 Functions
•Include:
– 3.3 Performance Requirements a) Types of information used
b) Data entities and their relationships

– 3.4 Logical Database Requirements


– 3.5 Design Constraints •Should include:
a) Standards compliance
b) Accounting & Auditing procedures
– 3.6 Software System Quality Attributes
– 3.7 Object Oriented Models
•The main body of requirements organized in a variety of
possible ways:

● 4. Appendices a) Architecture Specification


b) Class Diagram 61
c) State and Collaboration Diagrams
d) Activity Diagram (concurrent/distributed)‫‏‬
IEEE 830-1998 Standard – Templates

● Section 3 (Specific Requirements) may


be organized in many different ways
based on
– Modes
– User classes
– Concepts (object/class)
– Features
– Stimuli
– Organizations 62
SRS explained
● 1.0 INTRODUCTION
This document specifies all the requirements for
● 1.1 Purpose
The purpose of the …is to ….
The system should assist ….
The intended audience for this document is …
This specification describes …..
● 1.2 Scope
This document applies only to …...
This specification is not concerned with ….. 63
SRS explained
2.0 GENERAL DESCRIPTION

2.1 Product Perspective

This system allows stakeholders to…..

The system will display…..

The system will help ……

The system provides information about ….

2.2 Product Functions

The system provides the following functions: 64


SRS explained
● 2.3 User Characteristics
The users of the system are:
o Level of Users’ Computer Knowledge
o Level of Users’ Business Knowledge
o Frequency of Use
● 2.4 General Constraints
The system will support ….
The system will not allow ……
● 2.5 Assumption and Dependencies
This system relies on ……
The system must have a satisfactory interface and ……
65
65
Section 3 of SRS
● SPECIFIC REQUIREMENTS
3.1 Functional Requirements
3.1.1 Subject Registration
– The subject registration requirements are concerned with
functions regarding subject registration which includes
students selecting, adding, dropping, and changing a subject.
● F-001 (3.1.1.1):
– The system shall allow the user to register a subject.
● F-002 (3.1.1.2):
– ARS shall allow the user to delete a subject if the user has
chosen to drop that unit.
● F-003 (3.1.1.3):
– ARS shall check if a unit has been filled by enough registered
66
students.
SRS functional Reqs
● F-004 (3.1.1.4):
– ARS shall allow the user to add his/her name to the
unit waiting list if the user wants to register in a
subject which has been filled already with enough
registered students.
● F-005 (3.1.1.5):
– ARS shall automatically register the subject for the
user who is the first one on the waiting list if a
vacancy appears for that subject.
● F-006 (3.1.1.6):
– ARS shall allow the user to change practical
session(s), if available. 67
67
Design Constraints (3.2)
● 3.2 Design Constraints
● C-001 (3.2.1):
– ARS shall provide user interface through
standard web browsers.
● C-002 (3.2.2):
– ARS shall support PC and/or UNIX platforms.
● C-003 (3.2.3):
– ARS shall be developed using the JAVA
programming language 68
68
Non-functional requirements
● 3.3 Non-Functional Requirements
● N-001 (3.3.1):
– ARS shall respond to any retrieval in less than 5
seconds.
● N-002 (3.3.2):
– ARS shall generate a report within 1 minute.
● N-003 (3.3.3):
– ARS shall allow the user to remotely connect to the
system.
● N-004 (3.3.8):
– The system will be accompanied by a well-written69
user manual.
Structure of an SRS
● Introduction
– Purpose , the basic objective of the system
– Scope of what the system is to do , not to do
● Overall description
– Product perspective
– Product functions
– User characteristics
– Assumptions
– Constraints 70
Structure of an SRS…
 Specific requirements
 External interfaces
 Functional requirements
 Performance requirements
 Design constraints
 Acceptance criteria
 desirable to specify this up front.
 Based on IEEE 830.
71
Partitioning
Partitioning decomposes a problem and Establishes a hierarchical representation
of information (or function):
- exposing increasing detail by moving vertically in the hierarchy
- decomposing the problem by moving horizontally in the hierarchy.

SafeHome Software

Configure system Monitor sensors Interact with user

Poll for sensor event Activate alarm functions

Activate audible alarm Dial phone number


72
Functional Requirements
● It is desirable to consider every system
as:
– Performing a set of functions {fi}.
● Each function fi considered as:
– Transforminga set of input data to
corresponding output data.
Input Data Output Data
fi
73
Example: Functional Requirement
● F1: Search Book
– Input:

● an author’s name:
– Output:

● details of the author’s books and the


locations of these books in the library.
Author Name Book Details
f1
74
Functional Requirements
● Functional requirements describe:
–A set of high-level requirements
– Each high-level requirement:
● takes in some data from the user
● outputs some data to the user
– Each high-level requirement:
● might consist of a set of identifiable
functions 75
Functional Requirements

● For each high-level requirement:


–A function is described in terms of:
● Input data set
● Output data set
● Processing required to obtain the
output data set from the input data
set.
76
Dilbert: Scott Adams 77
Functional Requirements
● A high-level function is one:
– Using which the user can get some useful piece of
work done.

● Can the receipt printing work during withdrawal


of money from an ATM:
– Be called a high level function?

● A high-level requirement typically involves:


– Accepting some data from the user,
– Transforming it to the required response, and then
– Outputting the system response to the user. 78
Use Cases
● A use case is a term in UML:
– Represents a high level functional
requirement.

● Use case representation is more well-


defined and has agreed documentation:
– Compared to a high-level functional requirement
and its documentation

– Therefore many organizations document the


functional requirements in terms of use cases
79
Example Functional Requirements
● Req. 1:
– Once user selects the “search” option,
● he is asked to enter the key words.
– Thesystem should output details of all
books
● whose title or author name matches any of
the key words entered.
● Details include: Title, Author Name,
Publisher name, Year of Publication, ISBN
Number, Catalog Number, Location in the
80
Library.
Example Functional Requirements
● Req. 2:
– When the “renew” option is selected,
● The user is asked to enter his membership
number and password.
– After password validation,
● The list of the books borrowed by him are
displayed.
– The user can renew any of the books:
● By clicking in the corresponding renew box.
81
High-Level Function: A Closer View
● A high-level function:
– Usually
involves a series of interactions
between the system and one or more
users.
● Even for the same high-level function,
– Therecan be different interaction
sequences (or scenarios)
– Dueto users selecting different options
82
or entering different data items.
Req. 1:
● R.1.1:
– Input: “search” option,
– Output: user prompted to enter the key words.

● R1.2:
– Input: key words
– Output: Details of all books whose title or author
name matches any of the key words.
● Details include: Title, Author Name, Publisher name, Year
of Publication, ISBN Number, Catalog Number, Location
in the Library.

– Processing: Search the book list for the keywords83


Req. 2:
● R2.1:
– Input: “renew” option selected,

– Output: user prompted to enter his membership number and


password.

● R2.2:
– Input: membership number and password
– Output:
● list of the books borrowed by user are displayed. User prompted to enter
books to be renewed or
● user informed about bad password

– Processing: Password validation, search books issued to the user


from borrower list and display. 84
Req. 2:
● R2.3:
– Input:user choice for renewal of the
books issued to him through mouse clicks
in the corresponding renew box.
– Output: Confirmation of the books
renewed
– Processing:Renew the books selected by
the in the borrower list. 85
Examples of Bad SRS Documents
● Unstructured Specifications:
– Narrativeessay --- one of the worst
types of specification document:
● Difficult to change,
● Difficult to be precise,
● Difficult to be unambiguous,
● Scope for contradictions, etc.
86
Examples of Bad SRS
Documents
● Noise:
– Presenceof text containing
information irrelevant to the
problem.
● Silence:
– Aspects important to proper
solution of the problem are omitted.
87
Examples of Bad SRS Documents
● Overspecification:
– Addressing “how to” aspects
– For example, “Library member names should
be stored in a sorted descending order”
– Overspecification restricts the solution space
for the designer.

● Contradictions:
– Contradictions might arise
● if the same thing described at several places in88
different ways.
Examples of Bad SRS
● Ambiguity:
Documents
– Literary expressions
– Unquantifiable aspects, e.g. “good user
interface”
● Forward References:
– References to aspects of problem
● defined only later on in the text.

● Wishful Thinking:
– Descriptions of aspects
89

● for which realistic solutions will be hard to find.


Suggestions for Writing Quality
Requirements
● Keep sentences and paragraphs short.
● Use active voice.
● Use proper grammar, spelling, and
punctuation.
● Use terms consistently and define them in
a glossary.
● To see if a requirement statement is
sufficiently well defined,
Read it from the developer’s perspective
90

Suggestions for Writing Quality
Requirements cont…
● Avoid stating requirements redundantly in
the SRS.
– Including the same requirement in multiple
places may make the document easier to read,
– But, it makes the document more difficult to
maintain.
– The multiple instances of the requirement all
have to be updated at the same time,
● Lest an inconsistency would creep in. 91
Suggestions for Writing Quality
Requirements
● Split a requirement into multiple
sub-requirements:
– Because each will require separate test cases
and because each should be separately
traceable.
– If several requirements are strung together in
a paragraph, it is easy to overlook one during
construction or testing.
92
Reviewing Requirements for Quality:
An Example
● The product shall provide status messages
at regular intervals not less than every 60
seconds.
– What is wrong with this requirement?
● This requirement is incomplete:
– What are the status messages and how are
they supposed to be displayed to the user?
● The requirement contains ambiguities.
– Is the interval between status messages really
supposed to be at least 60 seconds, so showing
93
a new message every 10 years is okay?
A Better Requirement
● 1. Status Messages.

● 1.1. The Background Task Manager shall display status


messages in a designated area of the user interface at
intervals of 60 plus or minus 10 seconds.

● 1.2. If background task processing is progressing


normally, the percentage of the background task
processing that has been completed shall be displayed.

● 1.3. A message shall be displayed when the background


task is completed.

● 1.4. An error message shall be displayed if the


background task has stalled. 94
SRS Review
● Review done by the Developers along with the
user representatives.

● To verify that SRS confirms to the actual user


requirements

● To detect defects early and correct them.

● Review typically done using standard inspection


process:

– Checklists. 95
What is the difference between a System
Specification and a Software Specification?

● System specification concerns full


functionality of the system.
– Some of the functionalities may be performed
in hardware and some in software.
● Example, if the system is required to move
an object to a particular position within an
accuracy of ± 1 millimeter:
– This requirement would be met partly by each
of mechanical hardware, servo amplifier and
electronics, and the software. 97
System Specification
● System specification needs to address the
following issues:
– Define the functions of the system
– Define the Hardware / Software Functional
Partitioning
– Define the Performance Specification
– Define the Hardware / Software Performance
Partitioning
– Define Safety Requirements
– Define the User Interface
– Develop Installation Drawings/Instructions. 98
Video Rental Store Software
● A video rental store has a large collection of video CDs and DVDs in VHS and
MP4 format as well as music CDs.
● A person can become member a member by depositing Rs. 1000 and filling up
details such as name, address, and telephone number. A member can cancel his
membership and take back his deposit, if he has no dues outstanding against him.
● Whenever the store purchases a new item, details such as price and date of
procurement are entered. The daily rental charge is also entered by the
manager. After passage of a year, the daily rental charge is automatically halved.
● A member can, at a time, take on loan at most two video CDs and one music CD.
The details are entered by a store clerk and a receipt indicating the daily rental
charge should be printed by the software.
● Whenever a member returns his loaned item(s), the due amount to be paid is
displayed. After the amount is paid, the items are marked returned.
● If a customer loses or damages any item, the full price of the item is charged to
him and the item is removed from the inventory.
● If an item is not lent out by anyone for even once over a year, the item is sold
at 10% of the purchase price and is removed from the inventory. 99

● The manager can, at any time, check the profit/loss account.


IIT Security Software
● The staff and students of IIT register their vehicle by filling up a form which
a security staff would enter into the system.
● Each time a vehicle enters or leaves the campus, a camera reads the
registration number of the car, and the model of the car. If the car is
registered, the check gate should lift automatically to let in (or out) the vehicle.
The details regarding the entry and exit of the vehicle are registered in the
database. For outside vehicles, the driver needs to enter the purpose of entry,
the model number, the registration number, and a photograph of the vehicle is
stored in the database.
● When an outside vehicle leaves the campus, the details are automatically
registered in the database. For any external vehicle that is inside the campus for
more than 8 hours, the driver is stopped by the security personnel manning the
gate, queried to satisfaction, and the response are recorded. Considering that
there have been several incidence of speeding and rough driving, the security
personnel are empowered to telephone the registration number of errant
vehicles to the main gate. For outside vehicles, the driver is quizzed at the check
gate and his future entry is barred if the response is not satisfactory. For inside
vehicles, a letter is issued to the dean to deal with the employee or student as
the case might be.
● The security officer can check the data regarding the number of vehicles
going in and coming out of the campus (over a day, month or year), the total
number of vehicles currently inside the campus. 100
Personal Library System
● The software is required to manage the collection of books by individuals.
● A person can have a few hundreds of books. The details of all the books such as
name of the book, year of publication, date of purchase, price, and publisher
must be entered. A book is to be given a unique serial number by the computer
which would be written by the owner using a pen on the book. Before a friend can
be lent a book, he must be registered. The registration data would include name
of the friend, address, land line number, and mobile number. Before a friend is
issued a book, the various books outstanding against him also with the date
borrowed are displayed. The date of issue and the title of the book are stored.
When a friend returns a book, the date of return is stored and the book is
removed from his borrowing list. Up on query, the software should display the
name, address, and telephone numbers of each friend against whom books are
outstanding along with the titles of the outstanding books and the date on which
those were issued.
● The owner of the library software, when he borrows books from his friends,
would enter the details regarding the title of books borrowed, and the date
borrowed. Similarly, the return details of books would be entered. The software
should be able display all the books borrowed from various friends. The owner
should be able to query about the availability of a particular book, the total
101

number of books in the personal library,


Travel Agency Automation Software
● The company owns a number of vehicles (cars and SUVs) of various make and intends to
deploy a web-based software. A customer can become regular customer by depositing Rs.
5,000/-.
● When a customer requests for a car, he is displayed the types of vehicles are available,
and their charges. For every vehicle, there is a per hour charge, and a per kilometer
charge. A vehicle can be rented for a minimum of 4 hours. An AC vehicle of a particular
category is charged 50% more than a non-AC vehicle of the same category. There is a
charge of Rs 300 for every night of halt regardless of the type of the vehicle.
● A customer can book a vehicle, only if he has at least Rs. 2000/- advance. The customer
needs to enter when he expects to return the car.
● When the car is returned, depending on the usage, if possible the amount is fully adjusted
from the advance, or he has to pay additional amount to cover the cost incurred.
● The company can acquire new vehicles and add them to the fleet of its vehicles. Cars may
be condemned and sold off. A car which is currently with the company can be in one of
three states: it may have gone for repair, it may be available, it may be rented out. If it is
rented out, the company records the date and time when it has been rented out, and the
mile-meter reading of the car at that time.
● The company also wants to maintain the maintenance and running expense for each vehicle.
● The manager of the company should be able to query statistics about various types of
vehicles, their prices, average expense on repairs for the car, average demand, revenue
102
earned, and fuel consumption of the car.
Students’ Auditorium Management Software
● Various types of social and cultural events are conducted in the
student auditorium. The auditorium secretary should have the
overall authority of scheduling the shows, selecting and authorizing
the show managers, as well as sales agents.
● There are two categories of seats: balcony and ordinary seats.
Normally balcony seats are more expensive in any show.
● The show manager fixes the prices of these two categories of
seats for a specific show, depending on the popularity of a show.
The show manager also determines the number of balcony and
ordinary seats that can be put on sale. For each show, some seats
are offered as complimentary gifts to important functionaries of
the students' society and to VIPs which need to be entered into
the system.
● The show manager also enters the show dates, the number of shows
on any particular date and the show timings. It is expected that
the software would support a functionality to let the show manager
103
configure the different show parameters.
● The auditorium secretary appoints a set of sales agents. A sales agent gets a
commission of 1% of the total sales he makes for any show.
● The system should let the spectators query the availability of different
classes of seats for a show on-line. For the convenience of the spectators,
two ways of seat booking are supported. If a spectator pays Rs. 1000/-, a
unique 10 digit id is generated and given to him.
● He can use this id to book seats for the shows on-line by using a web browser.
For each seat booked for a show using the unique id, he would get a 10%
discount. A spectator can also book a seat for a single show only through
regular payment.
● For an on-line booking, a spectator would indicate for the type of the seat
required by him, the requested seat should be booked if available,
● and the software should support printing out the ticket showing the seat
numbers allocated. A spectator should be able to cancel his booking before 3
clear days of the show.
– In this case, the ticket price is refunded to him after deducting Rs.5/- as the
booking charge per ticket.
– If a ticket is returned at least before 1 day of a show, a booking charge of Rs.10/-
is deducted for ordinary tickets and Rs.15/- is deducted for balcony tickets.104
When
a cancellation is made on the day of the show, there is a 50% deduction.
Representation of complex
processing logic:

● Decision trees
● Decision tables

105
Decision Trees
● Decision trees:
– Edges of a decision tree represent
conditions
– Leafnodes represent actions to be
performed.
● A decision tree gives a graphic view of:
– Logic involved in decision making
– Corresponding actions taken. 106
Example: LMS

● A Library Membership automation


Software (LMS) should support
the following three options:
– New member,
– Renewal,

– Cancel membership.

107
Example: LMS

● When the new member option is


selected,
– The
software asks details about the
member:
● name,
● address,
● phone number, etc.

108
Example(cont.)
● If proper information is entered,
–A membership record for the member is
created
–A bill is printed for the annual
membership charge plus the security
deposit payable.

109
Example(cont.)
● If the renewal option is chosen,
– LMSasks the member's name and his
membership number
● checks whether he is a valid member.
– If the name represents a valid member,
● the membership expiry date is updated and
the annual membership bill is printed,
● otherwise an error message is displayed.
110
Example(cont.)
● If the cancel membership option is
selected and the name of a valid
member is entered,
– The membership is cancelled,
–A cheque for the balance amount due to
the member is printed
– The membership record is deleted.
111
Decision Tree
- Get details
- Create record
- Print bills
New member

- Get Details
User Renewal - Update record
input - Print bills
Cancel
- Get Details
- Print Cheque
- Delete record
Invalid option

- Print error message


112
Decision Table
● Decision tables specify:
– Which variables are to be tested
– What actions are to be taken if the
conditions are true,
– The order in which decision making
is performed.
113
Decision Table
● A decision table shows in a tabular form:
– Processing logic and corresponding actions

● Upper rows of the table specify:


– The variables or conditions to be evaluated

● Lower rows specify:


– The actions to be taken when the
corresponding conditions are satisfied.
114
Decision Table
● In technical terminology,
–A column of the table is called a
rule.
–A rule implies:
● If a condition is true, then
execute the corresponding action.

115
Example
● Conditions
Valid selection NO YES YES YES
New member -- YES NO NO
Renewal -- NO YES NO
Cancellation -- NO NO YES

● Actions
Display error message -- -- --

Ask member's name etc.


Build customer record -- -- --
Generate bill -- --
Ask membership details --
Update expiry date -- -- --
Print cheque -- -- --
Delete record -- -- -- 116
Comparison
● Both decision tables and decision
trees
– Can represent complex program logic.
● Decision trees are easier to read and
understand
– When the number of conditions are
small.
● Decision tables help to look at every
possible combination of conditions. 117
Formal Specification
● A formal specification technique
is a mathematical method to:
– Accurately specify a system.
– Verifythat implementation
satisfies specification.
– Proveproperties of the
specification.
118
Formal Specification
● Mathematical techniques used
include:
– Logic-based

– set theoretic
– algebraic specification
– finite state machines, etc.
119
Formal Specification

● Advantages:
– Well-defined semantics, no scope
for ambiguity
– Automated tools can check
properties of specifications
– Executable specification
120
Formal Specification

● Disadvantages of formal
specification techniques:
– Difficult to learn and use
– Notable to handle complex
systems

121
Semiformal Specification
● Structured specification languages
– SADT (Structured Analysis and Design
Technique)
– PSL/PSA (Problem Statement
Language/Problem Statement Analyzer)
● PSL is a semi-formal specification
language
● PSA can analyze the specifications
expressed in PSL 122
Executable Specification Language
● If specification is expressed in formal
language:
– it
becomes possible to execute the
specification to provide a system
prototype.

● However, executable specifications


are usually slow and inefficient.
123
Executable Specification Language

● Executable specifications only


test functional requirements:
– If non-functional requirements are
important for some product,
● The utility of an executable
specification prototype is limited.
124
4GLs
● 4GLs (Fourth Generation
Languages) are examples of
– executable specification languages.
● 4GLs are successful
– because there is a lot of
commonality across data processing
applications.
125
4GLs
● 4GLs rely on software reuse
– Where common abstractions have been
identified and parameterized.
● Rewriting 4GL programs in higher level
languages:
– Result in upto 50% lower memory
requirements
– Also the programs run upto 10 times faster.
126
Summary
● Requirements analysis and specification
– An important phase of software
development:
– Any error in this phase would affect all
subsequent phases of development.
● Consists of two different activities:
– Requirements gathering and analysis
– Requirements specification
127
Summary
● The aims of requirements analysis:
– Gather all user requirements
– Clearly understand exact user requirements
– Remove inconsistencies and incompleteness.
● The goal of specification:
– Systematically organize requirements
– Document the requirements in an SRS
document.
128
Summary
● Main components of SRS document:
– Functional requirements
– Non-functional requirements
– Constraints

● Techniques to express complex logic:


– Decision tree
– Decision table
129
Summary
● Formal requirements
specifications have several
advantages.
– Butthe major shortcoming is
that these are hard to use.

130
Assignment
● A public library is considering the
implementation of a computer-based
system to help administer book loans at
libraries.

● Identify the stakeholders in such a


project.

● What might be the objectives of such a


project and how might the success of the
project be measured in practical terms? 131
Stake holders
● Representatives of the local authority
who own and pay for the library
● Library staff at various levels
● Technical support staff
● Software and hardware suppliers
● Library users
132
● Objectives
● ‘To have in place an operational computer-
based loans management system by
dd/mm/yy which meets the requirements
specified in Annex at a development cost of
not more than e.g. Rs.10,00,000.’
● Measures of effectiveness
● Was the application actually working by
dd/mm/yy?
● Were costs under £xxxx?
● Can users etc certify that delivered system
meets the documented requirements? 133
Software Design

Prof. R. Mall
Dept. of CSE, IIT, Kharagpur
What does designer do during
design phase?
• Transform SRS document to
Design document:
 A form easily implementable in some
programming language.

SRS Design
Document Design Documents
Activities
Items Designed During Design
Phase
• Module structure,
• Control relationship among the modules
 call relationship or invocation relationship
• Interface among different modules,
 data items exchanged among different
modules,
• Data structures of individual modules,
• algorithms for individual modules.
Module
• A module consists of:
 several functions
 associated data structures.
D1 ..
D2
D3
..
..
Data
F1 ..
F2 .. Functions
F3 ..
F4 ..
F5 ..
Module Structure
Iterative Nature of Design

• Good software designs:


 seldom arrived through a
single step procedure:
 but through a series of steps
and iterations.
Stages in Design
• Design activities are usually classified
into two stages:
 preliminary (or high-level) design
 detailed design.
• Meaning and scope of the two stages:
 vary considerably from one methodology
to another.
High-level design

• Identify:
 modules
 control relationships among modules
 interfaces among modules.

d1 d2

d3 d1 d4
High-level design

• The outcome of high-level


design:
 program structure, also called
software architecture.
High-level Design
• Several notations are available to
represent high-level design:
 Usually a tree-like diagram called
structure chart is used.
 Other notations:
Jackson diagram or Warnier-
Orr diagram can also be used.
Detailed design

• For each module, design:


 data structure
 algorithms
• Outcome of detailed design:
 module specification.
A fundamental question

• How to distinguish between good


and bad designs?
 Unless we know what a good
software design is:
we can not possibly design
one.
Good and bad designs
• There is no unique way to design a
software.
• Even while using the same design
methodology:
 different engineers can arrive at very
different design solutions.
• We need to distinguish between
good and bad designs.
What Is Good Software Design?

• Should implement all functionalities


of the system correctly.
• Should be easily understandable.
• Should be efficient.
• Should be easily amenable to change,
 i.e. easily maintainable.
Dilbert: Scott Adams
What Is Good Software
Design?

• Understandability of a design is a
major issue:
 Largely determines goodness of
design:
 a design that is easy to understand:
also easy to maintain and change.
What Is Good Software
Design?

• Unless a design is easy to understand,


 Tremendous effort needed to maintain it
 We already know that about 60% effort
is spent in maintenance.
• If the software is not easy to
understand:
 maintenance effort would increase many
times.
How to Improve Understandability?
• Use consistent and meaningful names
 for various design components,
• Design solution should consist of:
 A set of well decomposed modules
(modularity),
• Different modules should be neatly
arranged in a hierarchy:
 in a tree-like diagram.
 Called Layering
Modularity
• Modularity is a fundamental
attributes of any good design.
 Decomposition of a problem into a clean
set of modules:
 Modules are almost independent of each
other
 Based on divide and conquer principle.
Modularity
• If modules are independent:
 modules can be understood
separately,
reduces the complexity greatly.
 To understand why this is so,
remember that it is very difficult to
break a bunch of sticks but very easy
to break the sticks individually.
Layering

Superior
Inferior
urce
3-layer architectures of
applications

Presentation layer

Application processing
layer

Data management
layer
Modularity
• In technical terms, modules
should display:
 high cohesion
 low coupling.
• We nexts discuss:
 cohesion and coupling.
Modularity
• Arrangement of modules in a
hierarchy means:
 low fan-out
 abstraction
Coupling: Degree of dependence
among components

No dependencies Loosely coupled-some dependencies

High coupling makes


modifying parts of the
Highly coupled-many dependencies
system difficult, e.g.,
modifying a component
affects all the components
Source:
to which the component is
Pfleeger, S., Software Engineering
Theory and Practice. Prentice Hall, 2001.
connected.
Cohesion and Coupling
• Cohesion is a measure of:
 functional strength of a module.
 A cohesive module performs a single
task or function.
• Coupling between two modules:
 A measure of the degree of
interdependence or interaction
between the two modules.
Cohesion and Coupling

• A module having high cohesion and


low coupling:
 Called functionally independent of
other modules:
A functionally independent module
needs very little help from other
modules and therefore has minimal
interaction with other modules.
Advantages of Functional
Independence

• Better understandability and good


design:
• Complexity of design is reduced,
• Different modules easily
understood in isolation:
 modules are independent
Why Functional Independence is
Advantageous

• Functional independence reduces


error propagation.
 degree of interaction between
modules is low.
 an error existing in one module does
not directly affect other modules.
• Reuse of modules is possible.
Advantages of Functional
Independence
• A functionally independent
module:
 can be easily taken out and reused in
a different program.
each module does some well-defined
and precise function
the interfaces of a module with other
modules is simple and minimal.
Functional Independence

• Unfortunately, there are no ways:


 to quantitatively measure the
degree of cohesion and coupling:
 At least classification of different
kinds of cohesion and coupling:
will give us some idea regarding the
degree of cohesiveness of a module.
Classification of Cohesiveness

• Classification can have scope for


ambiguity:
 yet gives us some idea about cohesiveness
of a module.
• By examining the type of cohesion
exhibited by a module:
 we can roughly tell whether it displays
high cohesion or low cohesion.
Classification of Cohesiveness

functional
sequential
communicational
Degree of
procedural cohesion
temporal
logical
coincidental
Coincidental cohesion

• The module performs a set of tasks:


 which relate to each other very loosely, if
at all.
That is, the module contains a random
collection of functions.
functions have been put in the module out of
pure coincidence without any thought or
design.
Coincidental Cohesion - example
Module AAA{

Print-inventory();

Register-Student();

Issue-Book();
};
Logical cohesion
• All elements of the module perform
similar operations:
 e.g. error handling, data input, data
output, etc.
• An example of logical cohesion:
 a set of print functions to generate an
output report arranged into a single
module.
Logical Cohesion

Module print{
void print-grades(student-file){ …}

void print-certificates(student-file){…}

void print-salary(teacher-file){…}
}
Temporal cohesion
• The module contains tasks so that:
 all the tasks must be executed in the
same time span.
• Example:
 The set of functions responsible for
initialization,
start-up, shut-down of some process,
etc.
Temporal Cohesion – Example

init() {

Check-memory();

Check-Hard-disk();

Initialize-Ports();

Display-Login-Screen();

}
Procedural cohesion

• The set of functions of the


module:
 all part of a procedure (algorithm)
 certain sequence of steps have to be
carried out in a certain order for
achieving an objective,
e.g. the algorithm for decoding a message.
Communicational cohesion

• All functions of the module:


 reference or update the same data
structure,
• Example:
 the set of functions defined on an
array or a stack.
Communicational Cohesion

handle-Student- Data() {
Static Struct Student-data[10000];
Store-student-data();
Search-Student-data(); Function A

Print-all-students(); Function B

}; Function C

Communicational
Access same data
Sequential cohesion

• Elements of a module form


different parts of a sequence,
 output from one element of the
sequence is input to the next.
 Example: sort

search

display
Functional cohesion
• Different elements of a module
cooperate:
 to achieve a single function,
 e.g. managing an employee's pay-roll.
• When a module displays functional
cohesion,
 we can describe the function using
a single sentence.
Determining Cohesiveness

• Write down a sentence to describe the


function of the module
 If the sentence is compound,
it has a sequential or communicational
cohesion.
 If it has words like “first”, “next”,
“after”, “then”, etc.
it has sequential or temporal cohesion.
 If it has words like initialize,
it probably has temporal cohesion.
Coupling

• Coupling indicates:
 how closely two modules interact
or how interdependent they are.
 The degree of coupling between
two modules depends on their
interface complexity.
Coupling
• There are no ways to precisely measure
coupling between two modules:
 classification of different types of coupling
will help us to approximately estimate the
degree of coupling between two modules.

• Five types of coupling can exist between


any two modules.
Classes of coupling

data
stamp
control Degree of
coupling
common
content
Data coupling

• Two modules are data coupled,


 if they communicate via a parameter:
 an elementary data item,
e.g an integer, a float, a character, etc.

 The data item should be problem related:


not used for control purpose.
Stamp coupling

• Two modules are stamp


coupled,
 if they communicate via a
composite data item

or an array or structure in C.


Control coupling

• Data from one module is used to


direct
 order of instruction execution in
another.
• Example of control coupling:
 a flag set in one module and tested
in another module.
Common Coupling

• Two modules are common


coupled,
 if they share some global data.
Content coupling
• Content coupling exists between two
modules:
 if they share code,
 e.g, branching from one module into
another module.

• The degree of coupling increases


 from data coupling to content coupling.
Hierarchical Design
• Control hierarchy represents:
 organization of modules.
 control hierarchy is also called program
structure.

• Most common notation:


 a tree-like diagram called structure
chart.
Good Hierachical Arrangement
of modules

• Essentially means:
low fan-out
abstraction
Characteristics of Module
Structure
• Depth:
 number of levels of control
• Width:
 overall span of control.
• Fan-out:
 a measure of the number of modules
directly controlled by given module.
Characteristics of Module
Structure
• Fan-in:
 indicates how many modules
directly invoke a given module.
 High fan-in represents code
reuse and is in general
encouraged.
Module Structure
Fan out=2

Fan out=1
Fan in=1

Fan in=2
Fan out=0
Goodness of Design

• A design having modules:


 with high fan-out numbers is not a
good design:

 a module having high fan-out lacks


cohesion.
Large Fan Out

• A module that invokes a large


number of other modules:
 likely to implement several
different functions:
 not likely to perform a single
cohesive function.
Control Relationships

• A module that controls another


module:
 said to be superordinate to it.

• Conversely, a module controlled


by another module:
 said to be subordinate to it.
Visibility and Layering

• A module A is said to be visible by


another module B,
 if A directly or indirectly calls B.

• The layering principle requires

 modules at a layer can call only the


modules immediately below it.
Bad Design
Abstraction

• Lower-level modules:
 do input/output and other low-
level functions.
• Upper-level modules:
 do more managerial functions.
Abstraction

• The principle of abstraction


requires:
 lower-level modules do not invoke
functions of higher level modules.

 Also known as layered design.


High-level Design

• High-level design maps functions into


modules {fi}  {mj} such that:
 Each module has high cohesion
 Coupling among modules is as low as
possible
 Modules are organized in a neat
hierarchy
High-level Design

f1
f2 d1 d2
f3

• d3 d4
• d1

fn
Design Approaches

• Two fundamentally different


software design approaches:
 Function-oriented design
 Object-oriented design
Design Approaches

• These two design approaches are


radically different.
 However, are complementary
rather than competing techniques.

 Each technique is applicable at


different stages of the design process.
Function-Oriented Design

• A system is looked upon as something


 that performs a set of functions.
• Starting at this high-level view of the
system:
 each function is successively refined
into more detailed functions (top-down
decomposition).
 Functions are mapped to a module
structure.
Example

• The function create-new-library-


member:
 creates the record for a new
member,
 assigns a unique membership number
 prints a bill towards the membership
Function-Oriented Design

• The system state is centralized:


 accessible to different functions,
 member-records:
available for reference and updation to
several functions:
create-new-member
delete-member
update-member-record
Function-Oriented Design

• Several function-oriented design


approaches have been developed:
 Structured design (Constantine and
Yourdon, 1979)
 Jackson's structured design (Jackson,
1975)
 Warnier-Orr methodology
 Wirth's step-wise refinement
 Hatley and Pirbhai's Methodology
Example
• Create-library-member function
consists of the following sub-
functions:
 assign-membership-number
 create-member-record
 print-bill
• Split these into further subfunctions,
etc.
Object-Oriented Design

• System is viewed as a collection


of objects (i.e. entities).
• System state is decentralized
among the objects:
 each object manages its own state
information.
Object-Oriented Design
Example

• Library Automation Software:


 each library member is a separate
object
with its own data and functions.
 Functions defined for one object:
cannot directly refer to or change
data of other objects.
Object-Oriented Design

• Objects have their own internal data:


 defines their state.
• Similar objects constitute a class.
 each object is a member of some class.
• Classes may inherit features
 from a super class.
• Conceptually, objects communicate by
message passing.
Object-Oriented versus Function-
Oriented Design

• Unlike function-oriented design,


 in OOD the basic abstraction is not
functions such as “sort”, “display”,
“track”, etc.,
 but real-world entities such as
“employee”, “picture”, “machine”,
“radar system”, etc.
Object-Oriented versus Function-
Oriented Design
• In OOD:
 software is not developed by
designing functions such as:
update-employee-record,
get-employee-address, etc.
 but by designing objects such as:
employees,
departments, etc.
Object-Oriented versus Function-
Oriented Design

• Grady Booch sums up this


fundamental difference saying:
 “Identify verbs if you are after
procedural design and nouns if
you are after object-oriented
design.”
Object-Oriented versus Function-
Oriented Design

• In OOD:
 state information is not shared
in a centralized data.
 but is distributed among the
objects of the system.
Example:
• In an employee pay-roll system, the
following can be global data:
 names of the employees,
 their code numbers,
 basic salaries, etc.
• Whereas, in object oriented systems:
 data is distributed among different
employee objects of the system.
Object-Oriented versus Function-
Oriented Design

• Objects communicate by message


passing.
 one object may discover the state
information of another object by
interrogating it.
Object-Oriented versus Function-
Oriented Design

• Of course, somewhere or other the


functions must be implemented:
 the functions are usually associated
with specific real-world entities
(objects)
 directly access only part of the
system state information.
Object-Oriented versus Function-
Oriented Design

• Function-oriented techniques group


functions together if:
 as a group, they constitute a higher
level function.
• On the other hand, object-oriented
techniques group functions together:
 on the basis of the data they operate
on.
Object-Oriented versus Function-
Oriented Design

• To illustrate the differences


between object-oriented and
function-oriented design
approaches,
 let us consider an example ---
 An automated fire-alarm system for
a large building.
Fire-Alarm System:
• We need to develop a
computerized fire alarm
system for a large multi
-storied building:

 There are 80 floors and 1000 rooms


in the building.
Fire-Alarm System:

• Different rooms of the building:


 fitted with smoke detectors and fire
alarms.
• The fire alarm system would
monitor:
 status of the smoke detectors.
Fire-Alarm System

• Whenever a fire condition is


reported by any smoke detector:
 the fire alarm system should:
determine the location from which
the fire condition was reported
sound the alarms in the neighboring
locations.
Fire-Alarm System

• The fire alarm system should:


 flash an alarm message on the
computer console:
fire fighting personnel man the
console round the clock.
Fire-Alarm System

• After a fire condition has


been successfully handled,
 the fire alarm system should
let fire fighting personnel
reset the alarms.
Function-Oriented Approach:

• /* Global data (system state) accessible by various


functions */
BOOL detector_status[1000];
int detector_locs[1000];
BOOL alarm-status[1000]; /* alarm activated when set */
int alarm_locs[1000]; /* room number where alarm is located */
int neighbor-alarms[1000][10];/*each detector has at most*/
/* 10 neighboring alarm locations */
interrogate_detectors();
get_detector_location();
determine_neighbor();
ring_alarm();
reset_alarm();
report_fire_location();
Object-Oriented Approach:

• class detector
• attributes: status, location, neighbors
• operations: create, sense-status, get-location,
• find-neighbors
• class alarm
• attributes: location, status
• operations: create, ring-alarm, get_location,
• reset-alarm

 Appropriate number of instances of the class


detector and alarm are created.
Object-Oriented versus Function-
Oriented Design

• In a function-oriented program :
 the system state is centralized
 several functions accessing these
data are defined.
• In the object oriented program,
 the state information is distributed
among various sensor and alarm
objects.
Object-Oriented versus Function-
Oriented Design

• Use OOD to design the classes:


 then applies top-down function
oriented techniques
to design the internal methods of
classes.
Object-Oriented versus Function-
Oriented Design

• Though outwardly a system may


appear to have been developed in
an object oriented fashion,
 but inside each class there is a small
hierarchy of functions designed in a
top-down manner.
Summary
• We started with an overview of:
 activities undertaken during the
software design phase.
• We identified:
 the information need to be produced
at the end of design:
so that the design can be easily
implemented using a programming
language.
Summary
• We characterized the features
of a good software design by
introducing the concepts of:
 fan-in, fan-out,
 cohesion, coupling,
 abstraction, etc.
Summary

• We classified different types


of cohesion and coupling:
 enables us to approximately
determine the cohesion and
coupling existing in a design.
Summary

• Two fundamentally different


approaches to software
design:
 function-oriented approach
 object-oriented approach
Summary

• We examined the essential


philosophy behind these two
approaches
 these two approaches are not really
competing but complementary
approaches.
Structured Analysis
and Design

Prof. R. Mall
Dept. of CSE, IIT, Kharagpur

1
Introduction
● Structured analysis is a modelling technique:
– DFD (Data Flow Diagram) is the modelling
technique used

– Functional requirements are modelled.

● Why model functionalities?


– Used for functional requirements exploration
and validation

– A starting point for design.


2
Introduction
● Two distinct style of design:
– Function-oriented or Procedural
● Top-down approach
● Carried out using Structured analysis and
structured design
● Coded using languages such as C
– Object-oriented
● Bottom-up approach
● Carried out using UML
● Coded using languages such as Java, C++, C#
3
Structured analysis and Structured Design

● During Structured analysis:


– High-levelfunctions are
successively decomposed:
● Into more detailed functions.

● During Structured design


– The
detailed functions are mapped to a
module structure. 4
Structured Analysis
● Successive decomposition of
high-level functions:
– Into more detailed functions.

– Technically
known as top-down
decomposition.

5
SA/SD (Structured
Analysis/Structured Design)
● SA/SD technique draws heavily from the
following methodologies:
– Constantine and Yourdon's methodology
– Hatley and Pirbhai's methodology
– Gane and Sarson's methodology
– DeMarco and Yourdon's methodology
● SA/SD technique can be used to perform
– high-level design. 6
Functional Decomposition
● Each function is analyzed:
– Hierarchically
decomposed into
more detailed functions.
– Simultaneous decomposition of
high-level data
● Into more detailed data.
7
Structured Analysis
● Textual problem description
converted into a graphic model.

– Done using data flow diagrams


(DFDs).

– DFD graphically represents the


results of structured analysis.
8
Structured Analysis
● The results of structured analysis can be easily
understood even by ordinary customers:
– Does not require computer knowledge.

– Directly represents customer’s perception of the


problem.

– Uses customer’s terminology for naming different


functions and data.

● The results of structured analysis can be


reviewed by customers:
– To check whether it captures all their requirements.
9
Structured Design
● The functions represented in the
DFD:

– Mapped to a module structure.

● Module structure:

– Also called software architecture


10
Structured Analysis vs.
Structured Design
● Purpose of structured analysis:
– Capturethe detailed structure of
the system as the user views it.
● Purpose of structured design:
– Arriveat a form that is suitable for
implementation in some programming
language. 11
Structured Analysis: Recap
● Based on principles of:
– Top-down decomposition approach.
– Divide and conquer principle:
● Each function is considered individually (i.e.
isolated from other functions).
● Decompose functions totally disregarding
what happens in other functions.
– Graphical representation of results using
● Data flow diagrams (or bubble charts). 12
Data Flow Diagram
● DFD is a hierarchical graphical
model:
– Showsthe different functions (or
processes) of the system and
game
Display
– Data
interchange move -board
0.1 result

among the processes. Validate


-move
0.2
board
Check-
winner
0.4

Play-
move
0.3 13
DFD Concepts
● It is useful to consider each
function as a processing
station:
– Each function consumes some
input data.
– Produces some output data.
14
Data Flow Model of a Car
Assembly Unit

Engine Store Door Store

Partly
Assembled
Car
Fit Paint
Fit Fit and
Engine Doors Wheels
Chassis Assembled Test
with Car Car
Engine

Chassis Store Wheel Store

15
Data Flow Diagrams (DFDs)

● A DFD model:

– Uses limited types of symbols.

– Simple set of rules

– Easy to understand --- a hierarchical


model.
16
Hierarchical Model
● As pointed out earlier:
– Human cognitive restrictions are
overcome through use of a
hierarchical model:
– In a hierarchical model:
● We start with a very simple and
abstract model of a system,
● Details are slowly introduced through
the hierarchies. 17
A Hierarchical Model

18
Data Flow Diagrams (DFDs)
● Primitive Symbols Used for Constructing DFDs:

19
External Entity Symbol
● Represented by a rectangle

● External entities are either


Librarian
users or external systems:
– input data to the system or

– consume data produced by the system.

– Sometimes external entities are called


terminator, source, or sink. 20
Function Symbol
● A function such as “search-book” is
represented using a circle:
search
– Thissymbol is called a -book
process or bubble or transform.

– Bubblesare annotated with


corresponding function names.

–A function represents some activity:


● Function names should be verbs. 21
Data Flow Symbol

● A directed arc or line. book-name

– Represents data flow in the


direction of the arrow.
– Dataflow symbols are
annotated with names of data
they carry.
22
Data Store Symbol
● Represents a logical file:
–A logical file can be:
book-details
● a data structure

● a physical file on disk.

– Eachdata store is connected to a


process:
● By means of a data flow symbol. 23
Data Store Symbol
● Direction of data flow arrow:
find-book
– Shows whether data is being
read from or written into it.
Books

● An arrow into or out of a data store:


– Implicitly
represents the entire data of
the data store
– Arrows connecting to a data store need
not be annotated with any data name. 24
Output Symbol
● Output produced by the system

25
Synchronous Operation
● If two bubbles are directly
connected by a data flow arrow:
– They are synchronous

Read- number Validate-


numbers numbers
0.1 0.2 Valid
Data- number
items

26
Asynchronous Operation
● If two bubbles are connected via a
data store:
– They are not synchronous.

Read- Validate-
numbers numbers
0.1 0.2
Valid
numbers number
Data-items

27
Yourdon's vs. Gane Sarson Notations
● The notations that we are following:
– Are closer to the Yourdon's notations

● You may sometimes find notations in


books and tools that are slightly
different:
– For example, the data store may look like
a box with one end closed
28
DFD Shapes from Visio
Visio 5.x Visio 2000
From Flow Chart /
From Software Diagram / Data Flow Diagram
From Flow Chart / Gane-Sarson DFD
Data Flow Diagram
ID #
Process
Process Process

Data Store

Data Store 1 Data Store

ID
# External
External Entity External
Entity
Entity 29
How is Structured Analysis Performed?
● Initially represent the software at
the most abstract level:

– Called the context diagram.

– The entire system is represented as a


single bubble,

– This bubble is labelled according to the


main function of the system. 30
Tic-tac-toe: Context Diagram

Tic-tac-toe
display software

move
Human Player

31
Context Diagram
● A context diagram shows:
– External entities.

– Data input to the system by them,

– Output data generated by the system.

● The context diagram is also called the


level 0 DFD. 32
Context Diagram
● Establishes the context
of the system, i.e.
–Represents

● Data sources
● Data sinks. 33
Level 1 DFD Construction Display
game
move -board
0.1 result
● Examine the SRS
Check-
document: Validate
-move board
winner
0.4
0.2

– Represent each high-level


Play-
function as a bubble. move
0.3

– Represent data input to


every high-level function.
– Represent data output from
every high-level function. 34
Higher Level DFDs
● Each high-level function is separately
decomposed into subfunctions:
– Identify the subfunctions of the function
– Identifythe data input to each
subfunction
– Identifythe data output from each
subfunction
● These are represented as DFDs.
35
Decomposition
● Decomposition of a bubble:

– Also called factoring or


exploding.

● Each bubble is decomposed into

– Between 3 to 7 bubbles. 36
Decomposition
● Too few bubbles make
decomposition superfluous:
– Ifa bubble is decomposed to
just one or two bubbles:
● Then this decomposition is
redundant. 37
Decomposition
● Too many bubbles:
– More than 7 bubbles at any
level of a DFD.
– Make the DFD model hard
to understand.
38
Decompose How Long?
● Decomposition of a bubble
should be carried on until:
–A level at which the function
of the bubble can be
described using a simple
algorithm. 39
Example 1: RMS Calculating Software

● Consider a software called RMS


calculating software:
– Reads three integers in the range
of -1000 and +1000

– Finds out the root mean square


(rms) of the three input numbers

– Displays the result. 40


Example 1: RMS Calculating Software

● The context diagram is


simple to develop:
– The system accepts 3
integers from the user
– Returns the result to him.
41
Example 1: RMS Calculating
Software

Data-
items Compute-
RMS
0

User result

Context Diagram
42
Example 1: RMS Calculating
Software

● From a cursory analysis of


the problem description:
– We can see that the system
needs to perform several
things.
43
Example 1: RMS Calculating
Software
● Accept input numbers from the
user:
– Validate the numbers,
– Calculatethe root mean square
of the input numbers
– Display the result. 44
Example 1: RMS Calculating
Software
numbers

Read- Validate-
numbers numbers
0.1 0.2
Valid -
Data-items numbers
error

Display Compute-
0.4 rms
0.3

result RMS
45
Example 1: RMS Calculating
Software
Squared-
Calculate- sum
squared-sum Calculate-
0.3.1 mean
0.3.2

Valid - Mean-
numbers square
Calculate-
root
0.3.3

46
RMS
Example: RMS Calculating
Software
b
c
Square Square Square
0.3.1.1 0.3.1.2 0.3.1.3

bsq
asq csq
Sum
0.3.1.4

Squared-sum

47
Example: RMS Calculating
Software
● Decomposition is never carried
on up to basic instruction level:
–A bubble is not decomposed any
further:
● If it can be represented by a
simple set of instructions.
48
Data Dictionary
● A DFD is always accompanied by a data
dictionary.
● A data dictionary lists all data items appearing
in a DFD:
– Definition of all composite data items in terms of
their component data items.
– All data names along with the purpose of the data
items.
● For example, a data dictionary entry may be:
– grossPay = regularPay+overtimePay
49
Importance of Data Dictionary
● Provides all engineers in a project with
standard terminology for all data:
–A consistent vocabulary for data is very
important

– Differentengineers tend to use different


terms to refer to the same data,
● Causes unnecessary confusion.
50
Importance of Data Dictionary
● Data dictionary provides the definition of
different data:
– In terms of their component elements.

● For large systems,


– The data dictionary grows rapidly in size and
complexity.
– Typical projects can have thousands of data
dictionary entries.
– It is extremely difficult to maintain such a
51
dictionary manually.
Data Dictionary
● CASE (Computer Aided
Software Engineering) tools
come handy:
– CASE tools capture the data
items appearing in a DFD
automatically to generate the
data dictionary. 52
Data Dictionary
● CASE tools support queries:
– About definition and usage of data items.

● For example, queries may be made to find:


– Which data item affects which processes,
– A process affects which data items,
– The definition and usage of specific data items, etc.

● Query handling is facilitated:


– If data dictionary is stored in a relational database
management system (RDBMS). 53
Data Definition
● Composite data are defined in terms of
primitive data items using following
operators:

● +: denotes composition of data items, e.g


– a+b represents data a and b.
● [,,,]: represents selection,
– i.e. any one of the data items listed inside the
square bracket can occur.
– For example, [a,b] represents either a occurs54 or
b occurs.
Data Definition
● ( ): contents inside the bracket
represent optional data

– which may or may not appear.

– a+(b) represents either a or a+b occurs.

● {}: represents iterative data definition,

– e.g. {name}5 represents five name data. 55


Data Definition
● {name}* represents
– zero or more instances of name data.

● = represents equivalence,
– e.g. a=b+c means that a represents b
and c.

● * *: Anything appearing within * *


is considered as comment.
56
Data Dictionary for RMS Software
● numbers=valid-numbers=a+b+c
● a:integer * input number *
● b:integer * input number *
● c:integer * input number *
● asq:integer
● bsq:integer
● csq:integer
● squared-sum: integer
● Result=[RMS,error]
● RMS: integer * root mean square value*
57
● error:string * error message*
Balancing a DFD
● Data flowing into or out of a bubble:
– Must match the data flows at the next level
of DFD.
● In the level 1 of the DFD,
– Data item c flows into the bubble P3 and the
data item d and e flow out.
● In the next level, bubble P3 is decomposed.
– The decomposition is balanced as data item c
flows into the level 2 diagram and d and e flow
58

out.
Balancing a DFD
c
b c

c1
d1

a d
e
Level 1 d e1
e
Level 2
59
Numbering of Bubbles
● Number the bubbles in a DFD:
– Numbers help in uniquely identifying any bubble
from its bubble number.

● The bubble at context level:


– Assigned number 0.

● Bubbles at level 1:
– Numbered 0.1, 0.2, 0.3, etc

● When a bubble numbered x is decomposed,


60
– Its children bubble are numbered x.1, x.2, x.3, etc.
Example 2: Tic-Tac-Toe
Computer Game
● A human player and the computer make alternate
moves on a 3 X 3 square.

● A move consists of marking a


previously unmarked square.
● The user inputs a number between 1 and 9 to mark
a square
● Whoever is first to place three consecutive marks
along a straight line (i.e., along a row, column, or
diagonal) on the square wins. 61
Example: Tic-Tac-Toe Computer Game
● As soon as either of the human player or
the computer wins,
– A message announcing the
winner should be displayed.

● If neither player manages to get three


consecutive marks along a straight line,
– And all the squares on the board are filled up,
– Then the game is drawn.

● The computer always tries to win a game. 62


Context Diagram for Example

Tic-tac-toe
display software
0

move
Human Player
63
Level 1 DFD
game
Display-
move board
0.1 result

Validate- Check-
move winner
0.2 board 0.4

Play-
move
0.3 64
Data Dictionary
● Display=game + result
● move = integer
● board = {integer}9
● game = {integer}9
● result=string
65
Example 3: Trading-House
Automation System (TAS)
● A large trading house wants us to
develop a software:
– To automate book keeping activities
associated with its business.

● It has many regular customers:


– Who place orders for various kinds of
commodities. 66
Example 3: Trading-House
Automation System (TAS)
● The trading house maintains names and
addresses of its regular customers.
● Each customer is assigned a unique
customer identification number (CIN).
● As per current practice when a customer
places order:
– The accounts department first checks the
credit-worthiness of the customer. 67
Example: Trading-House
Automation System (TAS)
● The credit worthiness of a customer is
determined:
– By analyzing the history of his payments to
the bills sent to him in the past.
● If a customer is not credit-worthy:
– His orders are not processed any further
– An appropriate order rejection message is
generated for the customer. 68
Example: Trading-House
Automation System (TAS)
● If a customer is credit-worthy:
– Items he/she has ordered are checked
against the list of items the trading house
deals with.

● The items that the trading house does not


deal with:
– Are not processed any further
– An appropriate message for the customer for
these items is generated. 69
Example: Trading-House
Automation System (TAS)
● The items in a customer's order that the
trading house deals with:
– Are checked for availability in inventory.

● If the items are available in the


inventory in desired quantities:
– A bill with the forwarding address of the
customer is printed.
– A material issue slip is printed. 70
Example: Trading-House
Automation System (TAS)
● The customer can produce the
material issue slip at the store
house:
– Take delivery of the items.

– Inventory data adjusted to reflect


the sale to the customer. 71
Example: Trading-House
Automation System (TAS)
● If an ordered item is not available in
the inventory in sufficient quantity:
– Tobe able to fullfill pending orders
store details in a "pending-order" file :
● out-of-stock items along with quantity
ordered.
● customer identification number
72
Example: Trading-House
Automation System (TAS)
● The purchase department:
– would periodically issue commands to
generate indents.
● When generate indents command is
issued:
– The system should examine the "pending-
order" file
– Determine the orders that are pending
– Total quantity required for each of the items.
73
Example: Trading-House
Automation System (TAS)
● TAS should find out the addresses
of the vendors who supply the
required items:
– Examine the file containing vendor
details (their address, items they supply etc.)

– Print out indents to those vendors.


74
Example: Trading-House
Automation System (TAS)
● TAS should also answers
managerial queries:
– Statisticsof different items sold
over any given period of time
– Corresponding quantity sold and the
price realized.
75
Context Diagram
indent
query
Trading-
House-
Automation-
Manager
statistics System
0

order Generate-
response indent

Customer Purchase-
Department
76
Level 1 DFD
Customer-history Item-file
query

Accept inventory statistics


Customer-file -order
0.1 Handle-
query
0.3
order Process
Accepted-
orders -order
Vendor-list 0.2

Handle-
indent- Sales-statistics
Indent-
request request
0.4
Indents Material-issue-
pending-order slip + bill
77
Example: Data Dictionary
● response: [bill + material-issue-slip, reject-message]
● query: period /* query from manager regarding sales statistics*/

● period: [date+date,month,year,day]
● date: year + month + day
● year: integer
● month: integer
● day: integer
● order: customer-id + {items + quantity}*
● accepted-order: order /* ordered items available in inventory */

● reject-message: order + message /* rejection message */


● pending-orders: customer-id + {items+quantity}*
● customer-address: name+house#+street#+city+pin 78
Example: Data Dictionary
● item-name: string
● house#: string
● street#: string
● city: string
● pin: integer
● customer-id: integer
● bill: {item + quantity + price}* + total-amount + customer-address
● material-issue-slip: message + item + quantity + customer-address
● message: string
● statistics: {item + quantity + price }*
● sales-statistics: {statistics}*
● quantity: integer 79
Observation
● From the examples,
– Observe that DFDs help
create:
● Data model
● Function model

80
Observation
● As a DFD is refined into greater
levels of detail:
– The analyst performs an implicit
functional decomposition.

– At the same time, refinements of


data takes place.
81
Guidelines For Constructing
DFDs
● Context diagram should represent
the system as a single bubble:

– Many beginners commit the mistake


of drawing more than one bubble in
the context diagram.
82
Guidelines For Constructing DFDs
● All external entities should be represented
in the context diagram:
– External entities should not appear at any
other level of DFD.

● Only 3 to 7 bubbles per diagram should be


allowed:
– Each bubble should be decomposed to between
3 and 7 bubbles.
83
Guidelines For Constructing DFDs
● A common mistake committed by
many beginners:
– Attempting to represent control
information in a DFD.

– e.g. trying to represent the order in


which different functions are
executed. 84
Guidelines For Constructing DFDs
● A DFD model does not represent control
information:
– When or in what order different functions
(processes) are invoked
– The conditions under which different functions
are invoked are not represented.
– For example, a function might invoke one
function or another depending on some condition.
– Many beginners try to represent this aspect by
drawing an arrow between the corresponding 85
Find Error Example-1
● Functionality: Check the input value:
– If the input value is less than -1000 or greater than
+1000 generate an error message
– otherwise search for the number

Generate
Error message
Check
number number
number
[found,not-found]
Search
86
Find 4 Errors
item query

inventory statistics
Item-file Handle-
query
0.3
Process-
order
0.2
statistics
Handle-
indent-
request Sales-statistics
0.4
Material-issue-slip87+
pending-order bill
Common Mistakes in Constructing DFDs

● If a bubble A invokes either bubble B


or bubble C depending on some
conditions:

– Represent the data that flows from


bubble A to bubble B and bubbles A to C

– Not the conditions depending on which a


process is invoked. 88
Find Error Example-2
● A function accepts the book name to be searched
from the user
● If the entered book name is not a valid book name
– Generates an error message,

● If the book name is valid,


– Searches the book name in database.
Search-
Get- Good-book- book
name
book- Book-
name details
Print- Error-
err- message
Book-name message 89
Guidelines For Constructing DFDs
● All functions of the system must be
captured in the DFD model:
– No function specified in the SRS document
should be overlooked.

● Only those functions specified in the SRS


document should be represented:
– Do not assume extra functionality of the
system not specified by the SRS document.
90
Commonly Made Errors
● Unbalanced DFDs
● Forgetting to name the data flows
● Unrepresented functions or data
● External entities appearing at higher level DFDs
● Trying to represent control aspects
● Context diagram having more than one bubble
● A bubble decomposed into too many bubbles in
the next level
● Terminating decomposition too early
91
● Nouns used in naming bubbles
Shortcomings of the DFD Model
● DFD models suffer from several
shortcomings:
● DFDs leave ample scope to be
imprecise.
– Ina DFD model, we infer about the
function performed by a bubble from its
label.
–A label may not capture all the
92
functionality of a bubble.
Shortcomings of the DFD Model
● For example, a bubble named find-book-
position has only intuitive meaning:
– Does not specify several things:
● What happens when some input information is
missing or is incorrect.
● Does not convey anything regarding what
happens when book is not found
● or what happens if there are books by
different authors with the same book title.
93
Shortcomings of the DFD Model
● Control information is not represented:
– For instance, order in which inputs are consumed
and outputs are produced is not specified.
Customer-history Item-file

inventory
Customer-file Accept-
order

order Process-
Accepted-orders
order
94
Shortcomings of the DFD Technique
● A DFD does not specify
synchronization aspects:
– Forinstance, the DFD in TAS example
does not specify:
● Whether process-order may wait until the
accept-order produces data
● Whether accept-order and handle-order
may proceed simultaneously with some
buffering mechanism between them.
95
Shortcomings of the DFD Model
● Decomposition is carried out to arrive at the
successive levels of a DFD is subjective.
● The ultimate level to which decomposition is
carried out is subjective:
– Depends on the judgement of the analyst.
● Even for the same problem,
– Several alternative DFD representations are
possible:
– Many times it is not possible to say which DFD
representation is superior or preferable. 96
Shortcomings of the DFD Model
● DFD technique does not provide:
– Any clear guidance as to how exactly one should
go about decomposing a function:
– One has to use subjective judgement to carry
out decomposition.
● Structured analysis techniques do not
specify when to stop a decomposition
process:
– To what length decomposition needs to be
carried out. 97
DFD Tools
● Several commercial and free tools
available.
● Commercial:
– Visio
– Smartdraw (30 day free trial)
– Edraw
– Creately
– Visual analyst
● Free:
– Dia (GNU open source) 98
Word of Caution
● Tools can be easily learned and used.

● Too much focus on SA/SD case tools


does not make you any more a good
designer:

– Than an expert knowledge of the


Word Package making you a famous
writer of thriller stories. 99
Structured Design
● The aim of structured design
– Transform the results of structured analysis
(DFD representation) into a structure chart.
● A structure chart represents the software
architecture:
– Various modules making up the system,
– Module dependency (i.e. which module calls
which other modules),
– Parameters passed among different modules.
100
Structure Chart
● Structure chart representation
– Easily implementable using programming
languages.
● Main focus of a structure chart:
– Define the module structure of a software,
– Interaction among different modules,
– Procedural aspects (e.g, how a
particular functionality is achieved) are
not represented. 101
Basic Building Blocks of Structure
Chart
● Rectangular box:
–A rectangular box represents a module.
– Annotated with the name of the module
it represents.

Process-order

102
Arrows
● An arrow between two modules
implies:
– During execution control is passed
from one module to the other in the
direction of the arrow.
root

Process-order Handle-indent Handle-query


103
Data Flow Arrows
● Data flow arrows represent:
– Datapassing from one module to
another in the direction of the arrow.
root

order

Process-order
104
Library Modules
● Library modules represent frequently
called modules:
– A rectangle with double side edges.
– Simplifies drawing when a module is
called by several modules.

Quick-sort
105
Selection
● The diamond symbol represents:
– One module of several modules
connected to the diamond symbol is
invoked depending on some condition.
root

Process-order Handle-indent Handle-query


106
Repetition
● A loop around control flow arrows
denotes that the concerned modules
are invoked repeatedly.
root

Process-order Handle-indent Handle-query


107
Structure Chart
● There is only one module at the top:
– the root module.
● There is at most one control relationship
between any two modules:
– if module A invokes module B,
– Module B cannot invoke module A.
● The main reason behind this restriction:
– Modules in a structure chart should be
arranged in layers or levels. 108
Structure Chart
● The principle of abstraction:

– does not allow lower-level modules


to invoke higher-level modules:

– But,two higher-level modules can


invoke the same lower-level
module. 109
Example
root

rms
rms
Valid-numbers
Valid-numbers

Get-good-data Compute-solution Display-solution

Get-data Validate-
data

110
Bad Design

111
Shortcomings of Structure Chart
● By looking at a structure chart:
– wecan not say whether a module calls
another module just once or many
times.

● Also, by looking at a structure chart:


– wecan not tell the order in which the
different modules are invoked. 112
Flow Chart (Aside)
● We are all familiar with the flow chart
representations:
– Flow chart is a convenient technique to represent the
flow of control in a system.
● A=B A=B

● if(c == 100) yes no

● P=20 P=20 P=80

● else p= 80 dummy

● while(p>20) yes no

● print(student mark) Print


113
Flow Chart versus Structure Chart
● A structure chart differs from a flow
chart in three principal ways:
1. It is difficult to identify modules of a
software from its flow chart
representation.
2. Data interchange among the modules is
not represented in a flow chart.
3. Sequential ordering of tasks inherent in
a flow chart is suppressed in a
114
structure chart.
Transformation of a DFD
Model into Structure Chart
● Two strategies exist to guide
transformation of a DFD into a
structure chart:
– Transform Analysis
– Transaction Analysis

115
Transform Analysis
● The first step in transform
analysis:
– Divide the DFD into 3 parts:
● input,
● logical processing,
● output. 116
Transform Analysis
● Input portion in the DFD:
– processes which convert input data from
physical to logical form.
– e.g.
read characters from the terminal
and store in internal tables or lists.
● Each input portion:
– called an afferent branch.
– Possible
to have more than one afferent
117
branch in a DFD.
Transform Analysis
● Output portion of a DFD:
– transforms output data from logical form
to physical form.
● e.g., from list or array into output characters.
– Each output portion:
● called an efferent branch.

● The remaining portions of a DFD


– called central transform
118
Transform Analysis
● Derive structure chart by

drawing one functional


component for:
– the central transform,

– each afferent branch,

– each efferent branch. 119


Transform Analysis
● Identifying the highest level input and
output transforms:
– requires experience and skill.
● Some guidelines:
– Trace inputs until a bubble is found whose
output cannot be deduced from the inputs
alone.
– Processes which validate input are not central
transforms.
– Processes which sort input or filter data from
it are. 120
Transform Analysis
● First level of structure chart:
– Draw a box for each input and output units
–A box for the central transform.
● Next, refine the structure chart:
– Add subfunctions required by each high-
level module.
– Manylevels of modules may required to be
added. 121
Factoring
● The process of breaking functional
components into subcomponents.
● Factoring includes adding:
– Read and write modules,
– Error-handling modules,
– Initialization and termination modules,etc.

● Finally check:
– Whether all bubbles have been mapped to
modules. 122
Example 1: RMS Calculating
Software
Data-items
Compute-
RMS
0

User result

Context Diagram
123
Example 1: RMS Calculating
Software
● From a cursory analysis of the problem
description,
– easyto see that the system needs to
perform:
● accept the input numbers from the user,
● validate the numbers,
● calculate the root mean square of the input
numbers,
124
● display the result.
Example 1: RMS Calculating Software
numbers
Read- Validate-
numbers numbers
0.1 0.2
Valid -
Data- numbers
items error

Compute-
Display rms
0.4 0.3

result RMS

125
Example 1: RMS Calculating
Software
● By observing the level 1 DFD:
– Identifyread-number and
validate-number bubbles as the
afferent branch
– Display as the efferent branch.
126
Example 1: RMS Calculating
Software
root

rms
rms
Valid-numbers
Valid-numbers

Get-good-data Compute-solution Display-solution

Data
Valid-numbers
Data

Get-data Validate-
data

127
Example 2: Tic-Tac-Toe Computer
Game
● As soon as either of the human player or
the computer wins,
– A message congratulating the winner should
be displayed.
● If neither player manages to get three
consecutive marks along a straight line,
– And all the squares on the board are filled up,
– Then the game is drawn.
● The computer always tries to win a game. 128
Context Diagram for
Example 2

Tic-tac-toe
display software
0

move
Human Player

129
Level 1 DFD
game
Display-
move board
result

Validate- Check-
move board winner

Play-
move
130
Structure Chart
root

Get-valid-data Play-move Display

Validate- Check-
move winner

131
Transaction Analysis
● Useful for designing transaction
processing programs.
– Transform-centered systems:
● Characterized by similar processing steps for
every data item processed by input, process,
and output bubbles.
– Transaction-driven systems,
● One of several possible paths through the
DFD is traversed depending upon the input
132
data value.
Transaction Analysis
● Transaction:
– Any input data value that triggers an
action:
– Forexample, selected menu options might
trigger different functions.
– Represented by a tag identifying its type.
● Transaction analysis uses this tag to
divide the system into:
– Several transaction modules
133
– One transaction-center module.
Transaction analysis
Transaction-
center
trans 3
trans 1
trans 2

type 1 type 2 type 3

134
Level 1 DFD for TAS
Customer-history Item-file
query

Accept- inventory statistics


Customer-file order
Handle-
query
order Process
Accepted-orders
-order
Vendor-list

Handle-
indent- Sales-statistics
Indent- request
request
Indents
pending-order 135
Structure Chart
root

order query
indent

Handle-order Handle-indent Handle-query

Accept- Process-
Get-order order
order
136
Summary
● We discussed a sample function-oriented
software design methodology:
– Structured Analysis/Structured
Design(SA/SD)
– Incorporates features from some important
design methodologies.

● SA/SD consists of two parts:


– Structured analysis
– Structured design. 137
Summary
● The goal of structured analysis:
– functional decomposition of the system.

● Results of structured analysis:


– represented using Data Flow Diagrams (DFDs).

● We examined why any hierarchical model is


easy to understand.
– Number 7 is called the magic number.
138
Summary
● During structured design,
– The DFD representation is
transformed to a structure chart
representation.

● DFDs are very popular:


– Because it is a very simple technique.
139
Summary
● A DFD model:
– Difficult
to implement using a
programming language:
– Structure chart representation can
be easily implemented using a
programming language.
140
Summary
● Several CASE tools are available:
– Support structured analysis and
design.
– Maintain the data dictionary,
– Check whether DFDs are balanced or
not.
141
Structured Design

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
1
Structured Analysis: Recap
 Based on principles of:
 Top-down decomposition approach.
 Divide and conquer principle:
 Each function is considered individually
 Decompose disregarding other functions.

 Graphical representation of results


 Data flow diagrams (or bubble charts).2
Context Diagram
indent
query
Trading-
House-
Automation-
Manager
statistics System
0

order Generate-
response indent

Customer Purchase-
Department
3
Level 1 DFD
Customer-history Item-file
query

Accept inventory statistics


Customer-file -order
0.1 Handle-
query
0.3
order Process
Accepted-
orders -order
Vendor-list 0.2

Handle-
indent- Sales-statistics
Indent-
request request
0.4
Indents Material-issue-
pending-order slip + bill
4
Partial Data Dictionary
 response: [bill + material-issue-slip, reject-message]
 query: period /* query from manager regarding sales statistics*/

 period: [date+date,month,year,day]
 date: year + month + day
 year: integer
 month: integer
 day: integer
 order: customer-id + {items + quantity}*
 accepted-order: order /* ordered items available in inventory */

 reject-message: order + message /* rejection message */


 pending-orders: customer-id + {items+quantity}*
 customer-address: name+house#+street#+city+pin 5
Structured Design
 The aim of structured design:
 Transform the results of structured analysis
(DFD representation) into a structure chart.

 A structure chart represents the software


architecture:
 Various modules making up the system,
 Module dependency (i.e. which module calls
which other modules),
 Parameters passed among different modules.6
Structure Chart
 Structure chart representation
 Easily implementable using a programming
language.

 Main focus of a structure chart:


 Define the module structure of a software,
 Interaction among different modules,
 Procedural aspects (algorithms etc.) are
not represented.
7
Basic Building Blocks of Structure Chart

 Rectangular box:
A rectangular box represents a
module.
 Annotated with the name of the
module it represents.

Process-order
8
Arrows
 An arrow between two modules implies:
 During execution control is passed from
one module to the other in the direction
of the arrow. root

Process-order Handle-indent Handle-query


9
Data Flow Arrows
 Data flow arrows represent:

 Datapassing from one module to


another in the direction of the
arrow.
root

order

Process-order 10
Library Modules
 Library modules are the frequently
called modules:
 A rectangle with double side edges.
 Simplifies repeated drawing when a
module is called by several modules.

Quick-sort
11
Selection
 The diamond symbol represents:
 One module of several modules
connected to the diamond symbol is
invoked depending on some
condition. root

Process-order Handle-indent Handle-query


12
Repetition
 A loop around control flow arrows
denotes that the concerned modules
are invoked repeatedly.
root

Process-order Handle-indent Handle-query


13
Structure Chart
 There is only one module at the top:
 the root module.
 There is at most one control relationship
between any two modules:
 if module A invokes module B,
 Module B cannot invoke module A.
 The main reason behind this restriction:
 Modulesin a structure chart should be
arranged in layers or levels. 14
Structure Chart
 The principle of abstraction
(layering):

 does not allow lower-level modules


to invoke higher-level modules:

 But,two higher-level modules can


invoke the same lower-level
15
module.
Example
root

rms
rms
Valid-numbers
Valid-numbers

Get-good-data Compute-solution Display-solution

Get-data Validate-
data
16
Bad Design

17
Shortcomings of Structure Chart
 By looking at a structure chart:

 we can not say whether a module calls


a module just once or many times.

 By looking at a structure chart:

 we can not tell the order in which the


different modules are invoked.
18
Flow Chart (Aside)
 We are all familiar with the flow chart
representations:
 Flow chart is a convenient technique to
represent the flow of control in a system.
A=B A=B

yes no
if(c == 100) C==100

P=20 P=80
P=20
dummy
else p= 80 yes no
P>20
while(p>20)
Print
19

print(student mark)
Flow Chart versus Structure Chart
 A structure chart differs from a flow
chart in three principal ways:
1. It is difficult to identify modules of a
software from its flow chart
representation.
2. Data interchange among the modules is
not represented in a flow chart.
3. Sequential ordering of tasks inherent in
a flow chart is suppressed in a
20
structure chart.
Transformation of a DFD Model
into Structure Chart

 Two strategies exist to guide


transformation of a DFD into a
structure chart:
 Transform Analysis

 Transaction Analysis
21
Transform Analysis

 The first step in transform


analysis:
 Divide the DFD into 3 parts:
 input,
 logical processing,
 output. 22
Transform Analysis
 Input portion in the DFD:
 processes which convert input data from
physical to logical form.
 e.g.
read characters from the terminal
and store in internal tables or lists.
 Each input portion:
 called an afferent branch.
 Possible
to have more than one afferent
branch in a DFD. 23
Transform Analysis
 Output portion of a DFD:
 transformsoutput data from logical
form to physical form.
 e.g., from list or array into output
characters.
 Each output portion:
 called an efferent branch.
 The remaining portions of a DFD
 called central transform 24
Transform Analysis
 Derive structure chart by
drawing one module each for:
 central transform,

 afferent branch,

 efferent branch.
25
Transform Analysis
 Identifying the highest level input and
output transforms:
 requires experience and skill.
 Some guidelines:
 Trace inputs until a bubble is found whose
output cannot be deduced from the inputs
alone.
 Processes which validate input are not central
transforms.
 Processes which sort input or filter data from
26
it are.
Transform Analysis
root
 First level of structure chart:
 Drawa box for input and
output units input transform
Output

A box for the central transform.


 Next, refine the structure chart:
 Add subfunctions required by each high-
level module.
 Manylevels of modules may required to be
added. 27
Factoring
 The process of breaking functional
components into subcomponents.
 Factoring includes adding:
 Read and write modules,
 Error-handling modules,
 Initialization and termination modules,etc.
 Finally check:
 Whether all bubbles have been mapped to
28
modules.
Example 1: RMS Calculating
Software

Data-items Compute-
RMS
0

User result

Context Diagram
29
Example 1: RMS Calculating Software
 From a cursory analysis of the
problem description,
 easyto see that the system needs to
perform:
 accept the input numbers from the user,
 validate the numbers,
 calculate the root mean square of the
input numbers,
 display the result. 30
Example 1: RMS Calculating Software
numbers
Read- Validate-
numbers numbers
0.1 0.2
Valid -
Data- numbers
items error

Compute-
Display rms
0.4 0.3

result RMS

31
Example 1: RMS Calculating
Software

 Observe the level 1 DFD:


 Identifyread-number and
validate-number bubbles as the
afferent branch
 Display as the efferent branch.
32
Example 1: RMS Calculating Software
root

rms
rms
Valid-numbers
Valid-numbers

Get-good-data Compute- Display-


solution solution

Get-data Validate-
data 33
Example 2: Tic-Tac-Toe Computer Game
 As soon as either of the human player or
the computer wins,
 A message congratulating the winner should
be displayed.
 If neither player manages to get three
consecutive marks along a straight line,
 And all the squares on the board are filled up,
 Then the game is drawn.
 The computer always tries to win a game. 34
Context Diagram for Example 2

Tic-tac-toe
display software
0

move
Human Player

35
Level 1 DFD
game
Display-
move board
result

Validate- Check-
move board winner

Play-
move
36
Structure Chart
root

Get-good-move Compute-game Display

Get-move Validate- play- Check-


move move winner
37
Transaction Analysis
 Useful for designing transaction
processing programs.
 Transform-centered systems:
 Characterized by similar processing steps for
every data item processed by input, process,
and output bubbles.

 Transaction-driven systems,
 One of several possible paths through the
DFD is traversed depending upon the input
38
data value.
Transaction Analysis
 Transaction:
 Any input data value that triggers an
action:
 Forexample, a menu option selection
might trigger a set of functions.
 Represented by a tag identifying its type.
 Transaction analysis uses this tag to
divide the system into:
 Several transaction modules
39
 One transaction-center module.
Transaction analysis
Transaction-
center
trans 3
trans 1
trans 2

type 1 type 2 type 3

40
Level 1 DFD for TAS
Customer-history Item-file
query

Accept- inventory statistics


Customer-file order
Handle-
query
order Process
Accepted-orders
-order
Vendor-list

Handle-
indent- Sales-statistics
Indent- request
request
Indents
pending-order 41
Structure Chart

root
order query
indent
Handle-order Handle-indent Handle-query

Get- Accept- Process-


order order
order
42
Object-Oriented
Software Design

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
43
Introduction
 Object-oriented design (OOD)
techniques are now extremely popular:
 Inception in early 1980’s and nearing
maturity.
 Widespread acceptance in industry and
academics.
 Unified
Modelling Language (UML) became
an ISO standard (ISO/IEC 19501) in 2004. 44
Schematic Object-Oriented Solution

reference-
books

issue-books
members register
45
Objects
 A system is designed as a set of interacting
objects.
 Objects are often real-world entities:
 Examples: an employee, a book etc.
 Can also be conceptual objects :
 Controller, manager, etc.

 An object consists of data (attributes) and


functions (methods) that operate on data.
 Hides organization of internal information
46
(information hiding).
What is a Data Type?
 A data type (or simply type)
determines:
 Representation: The way values of
variables of that type can be stored.
 Value Space: The possible values
for a variable of that type;
 Behavior:The operations that can
be applied on variables of that type;
47
What is a Type System?

 A type system associates types


with each computed value.

 Seeks to guarantee that operations


expecting a certain kind of value
are not used with operations in
which it does not make sense.
48
Strongly vs. Weakly Typed Languages
 Liskov and Zilles (1974):
 A strong-typed language is one in which whenever an object
is passed from a calling function to a called function, its
type must be compatible with the type declared in the called
function.
 Absence of static type checking:
 A variable may be assigned float, int, string, etc.: Symptom
of Weakly typed,
 But, Is there any problem with weakly typed languages?
 Unpredictable result: x = "5" + 6 may be 56 or 11
 Dynamic type checking:
 Prevents unchecked runtime type error using a type system.
49
Are Classes ADTs?
m8 m7
mi are methods
of the class

m1 m6
Data
m2 m5
Class

m3 m4 50
Encapsulation
 James Rumbaugh et al., 1991
 “Amechanism by which external aspects
of a class that are visible to or accessible
by other objects are separated from the
internal or implementation details of
these aspects.”
 Grady Booch, 1994
 “…Serves to separate the contractual
interface of an abstraction and its
implementation.” 51
Information Hiding

“…encapsulation is most often


achieved through information
hiding, which is the process of
hiding all of the secrets of object
that do not contribute to its
essential characteristics. “ Grady
Booch
52
Let us now formalize our concept…
 Encapsulation

 Encapsulationallows the programmer to


group data and the subroutines that
operate on them together in one place,
and to hide irrelevant details from the
user.
 Information Hiding
 Making objects and code parts
(algorithms) invisible to portions of the
53

system that do not need them.


What is Encapsulation Then?
• An Object communicates with other
objects through messages:

―Data of an object encapsulated within


its methods and can be accessed only
through its methods. m4

m3
m5

―Realized by data hiding


m2 Data
―One use of the separation m6

m1

of concerns principle. Methods


54
Encapsulation
cont…

m4

m3
m5

m2 Data
m6

m1

Methods

Concept of encapsulation 55
Encapsulation Vs Information Hiding
 Encapsulation is a concept

 Information hiding (how to) is


concretization of encapsulation
(what):

 Encapsulation
is implemented by
Information hiding.
56
Class
 Template for object creation:
 Instantiated into objects
 An abstract data type (ADT)‫‏‬
 Examples: Employees, Books, etc.
 Sometimes not intended to produce
instances:
 Abstract classes 57
UML Class Representation
 A class represents a set of objects having
similar attributes, operations, relationships and
behavior.

Class Name

Window
A class can
size: Size implicitly
Inline Attributes have a few
visibility: boolean association
attributes
display()
Operations
hide()
58
Example UML Classes
LibraryMember LibraryMember LibraryMember

Member Name issueBook( );


Membership Number findPendingBooks( );
Address findOverdueBooks( );
Phone Number returnBook( );
E-Mail Address findMembershipDetails( );
Membership Admission Date
Membership Expiry Date
Books Issued

issueBook( );
findPendingBooks( );
findOverdueBooks( );
returnBook( );
findMembershipDetails( );

59
Different representations of the LibraryMember class
Active Class
 The nature of objects as self-
contained entities make them suitable
for concurrent implementation.
 An active class is just like any other
class:
 Except that behavior of its objects is
concurrent with other objects.
 Indicates implementation as one or more
processes or threads. 60
Active Class
 Represented as a class with
double lines on the left and right.

EventManager

suspend()
flush()

61
Class Attribute Examples
Java Syntax UML Syntax

Date birthday Birthday:Date

Public int duration = 100 +duration:int = 100

Private Student
-Students[0..MAX_Size]:Student
students[0..MAX_Size]
62
Visibility Syntax in UML

Visibilty Java Syntax UML Syntax

public public +

protected protected #

package ~

private private -
63
Methods vs. Messages?
 Methods are the operations
supported by an object:
 Means for manipulating the data of
an object.
 Invokedby sending a message
(method call).
 Examples:
calculate_salary, issue-
book, member_details, etc. 64
Method Examples

Java Syntax UML Syntax


void move(int dx, int dy) ~move(int dx,int dy)

public int getSize() +int getSize()

65
Are Methods and Messages
Synonyms?
 No
 Message was the original
concept in object-orientation…
 Methods are the later
simplifications…
 Sometimes used as synonyms 66
Are Methods and Operations
Synonyms?
 No

 An operation can be implemented


by multiple methods.
 Known as polymorphism

 Inthe absence of polymorphism --


are used as synonyms. 67
What are the Different Types of
Relationships Among Classes?
 Four types of relationships:
Inheritance

Association

Aggregation/Composition

Dependency 68
Inheritance
 Allows to define a new class LibraryMember Base Class

(derived class) by extending an


existing class (base class). Faculty Students Staff

 Represents generalization-
UnderGrad PostGrad Research

specialization relationship.
 Allows redefinition of the existing
methods (method overriding). 69
Inheritance

Animal

“A Dog ISA Animal”

Dog

70
Hmmm… not really…

71
Source: Robert Martin
Inheritance
 Lets a subclass inherit attributes
and methods from a base class.
LibraryMember Base Class

Derived
Faculty Students Staff
Classes

UnderGrad PostGrad Research 72


Inheritance Implementation in Java
Inheritance is declared using the "extends" keyword
If no inheritance defined, the class implicitly extends a class
called Object
class Person{
Person
private String name; - name: String
private Date dob; - dob: Date
...
}
class Employee extends Person{
private int employeeID;
Employee
private int salary; - employeeID: int
private Date startDate; - salary: int
... - startDate: Date
}

73
Employee anEmployee = new Employee();
Objects myRectangle and myBox
Rectangle myRectangle = new Rectangle(5, 3);
Box myBox = new Box(6, 5, 4);

length 5.0 length 6.0


myRectangle
myBox

width 3.0 width 5.0

height 4.0

74
A Generalization Example
Mammal Quadruped

Feline Lizard

Tiger Lion Puma


75
Poor Generalization Example
(violates “is a” or “is a kind of” heuristic)

Person
attributes
operations

Arm Leg Head


attributes attributes attributes
operations operations operations

Any problems?
76

76
Inheritance Example
Library
Book

issuable reference

Issuable Reference
Issuable Reference
Single Volume Single Volume
BookSet BookSet
Book Book

Discriminator: allows one to group subclasses into


77
clusters that correspond to a semantic category.
GeneralizationDiscriminator
- Multiple Classification
Doctor

Female #3
role
<<abstract>>
Person Nurse
Gender
Male #1 patient
#2 Physical-
therapist
Impractical
Patient
78
#2 78
Multiple Inheritance
cont…
LibraryMember Base Class LibraryMember Base Class

Derived
Faculty Students Staff Faculty Students Staff
Classes

Multiple
Inheritance

UnderGrad PostGrad Research UnderGrad PostGrad Research


79
Inheritance Pitfalls
 Inheritance certainly promotes
reuse.
 Indiscriminate use can result in
poor quality programs.
 Base class attributes and methods
visible in derived class
 Leads to tight coupling 80
Association Relationship
 How implemented in program?
 Enables objects to communicate
with each other:
 One object must “know” the ID of
the corresponding object in the
association.
 Usually binary:
 But in general can be n-ary. 81
Association – example
 In a home theatre system,
A TV object has an association with a
VCR object
 It may receive a signal from the VCR
 VCR may be associated with remote
 It may receive a signal (command) to
record
1 1 1 1
Remote commands VCR Connected to TV 82
1-1 Association – example
tax_file
Rakesh Shukla
760901-1234

V. Ramesh
691205-5678

People Tax_files

1 1
People Associated with Tax_files
83
Multiple Association – example
motherOf

Bhim
motherOf
Kunti Yudhistir

motherOf
Arjun
Women People

1 *
Women Mother of People
84
Association UML Syntax
role B
Class A Class B
role A

 A Person works for a Company.


Role

employee
Person employer
Company
works for

85
Association Name
Association - More Examples

1 borrowed by *..5
Library Member Book

* eats * Human
Lion

86
Navigability

opens 0..5
Key * Door

87
Association – Multiplicity
 A teacher teaches 1 to 3 courses (subjects)
 Each course is taught by only one teacher.
 A student can take between 1 to 5 courses.
 A course can have 10 to 300 students.

1 teaches 1..3
Teacher Course
1..5

takes
Students
10..300 88
Quiz: Draw Class Diagram
 A Student can take up to five Courses.

 A student has to enroll in at least one


course.

 Up to 300 students can enroll in a


course.

 A class should have at least 10


students. 89
Student credits hasEnrolmentOf Course
10..300 Enrols in 1..5

90
Student credits hasEnrolmentOf
Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5 91
Quiz: Read the Two Diagrams.

1..2 teaches 0..3


Teacher Course

* opens 0..5
Key Door

92
Association and Link
 A link:
 An instance of an association
 Exists between two or more objects
 Dynamically created and destroyed as
the run of a system proceeds
 For example:
 An employee joins an organization.
 Leavesthat organization and joins a new
93
organization etc.
Association Relationship
 A class can be associated with itself
(recursive association).
 Give an example?

 An arrowhead used along with name:


 Indicates direction of association.

 Multiplicity indicates # of instances


taking part in the association. 94
Self Association: Example 0

Person Friend of

95
Self Association: Example 0
Computer Network

Connects to

Computer *

96
Computer Network: Object
Diagram

Node1 Node2 Node3

Node4

Node5

Node6 Node7 Node8


97
Self Association: Example 1

next

LinkedListNode
previous

98
Reflexive Association: Example 2

Course
*

*
has pre-requisite of
99
Implementing Association
Relationship: Example 1
• To implement in Java:
– Use a reference variable of one class as
an attribute of another class
Bookname: OOSD
abook Author: Gamaa
ISBN: 12234434

Book Reference Book instance


1 1
Borrowed
Bookname: abook Member Book
memberName: AKK
Member Number: 412323 by

100
public class Member{
private Book book;
public issueBook(Book abook){
setBook(abook);
abook.setLender(this);
}
setBook(Book abook){
book=abook;
} 1 1
Borrowed
… Member Book
by
}
101
public class Book{
private Member member;
setLender(Member aLender){
member=aLender;
}
… 1 1
Borrowed Book
} Member
by

102
Association Implementation:
Example 2
Student credits hasEnrolmentOf
Course
1..300 enrols 1..5

Class Student { Observe the


Course credits[5]; Navigation

}
Class Course {
Student hasEnrolmentOf[300];

103
}
Association Example 2
 A Person works for a Company.
Role Implicit attribute of Company

Implicit attribute of Person

employee
Person employer
Company
works for

Association Name

Observe: Implicit bidirectional navigation


Implementation? 104
Example 2 Implementation
public class Company {
private Person employee;
public void setCompany(Person p){ employee=p;}
}
public class Person {
private Company employer;
public Company getWorksFor() {
return employer;
}
public void setWorksFor(Company c) {
employer=c;
} 105

}
Code for Association Multiplicity
class Customer{
private ArrayList <Account> accounts =
new ArrayList<Account>();
public Customer() {
Account defaultAccount = new Account();
accounts.add(defaultAccount);
}
} has
Customer 1 1..* Account106
1-1 Association Example 3

1 has 1
Advertiser Account

public class Advertiser {


private Account account;
public Advertiser() {
account = new Account(this);
}
public Account getAccount() {
return account; Now,
} Write
} code for
Account 107
1-1 Association
Advertiser 1 1 Account

public class Advertiser {


public class Account {
private Account account;
private Advertiser owner;
public Advertiser() {
publicAccount(Advertiser
account = new owner) {
Account(this); this.owner = owner;
} }
public Account getAccount() public Advertiser getOwner() {
{ return owner;
return account; }
} } 108

}
Quiz: Read and understand
UML class diagram
has
CPU 1 Controller
0..2

1..4 1
DiskDrive controls SCSIController

• 1 CPU has 0 to two Controllers


• 1-4 DiskDrives controlled by 1 SCSIController
• SCSIController is a (specialized) Controller 109
Java Code?
has
class CPU { CPU 1 * Controller
Controller [ ] myCtlrs;
}
1..4 1
class Controller { DiskDrive controls SCSIController

CPU myCPU;
}
class SCSIController extends Controller {
DiskDrive [ ] myDrives = new DiskDrive[4];
}
Class DiskDrive {
SCSIController mySCSI;
}
110
Quiz: Banking System

Bank
has 1

*
Account
Audit() :void

Checking Saving MoneyMarket


Audit() :void Audit() :void Audit() :void

• 1 Bank associated with 0 or more Accounts


• Checking, Savings, MoneyMarket are Account types 111
More Association
Relationships

1 borrowed by *
Library Member Book

employed by 1
Employee * Company

112
Object-Oriented
Software Design

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
1
Introduction
 Object-oriented design (OOD)
techniques are now extremely popular:
 Inception in early 1980’s and nearing
maturity.

 Widespread acceptance in industry and


academics.

 Unified Modelling Language (UML)


became an ISO standard (ISO/IEC
2

19501) in 2004.
Schematic Object-Oriented Solution

reference-
books

issue-books
members register
3
Objects
 A system is designed as a set of interacting
objects.
 Objects are often real-world entities:
 Examples: an employee, a book etc.

 Can also be conceptual objects :


 Controller, manager, etc.

 An object consists of data (attributes) and


functions (methods) that operate on data.
 Encapsulation. 4
What is a Data Type?
 A data type (or simply type)
determines:
 Representation: The way values of
variables of that type can be stored.
 Value Space: The possible values
for a variable of that type;
 Behavior:The operations that can
be applied on variables of that type;
5
What is a Type System?

 A type system associates types


with each computed value.

 Seeks to guarantee that operations


expecting a certain kind of value
are not used with operations in
which it does not make sense.
6
Strongly vs. Weakly Typed Languages
 Liskov and Zilles (1974):
 A strong-typed language is one in which whenever an
object is passed from a calling function to a called
function, its type must be compatible with the type
declared in the called function.

 Absence of static type checking:


 A variable may be assigned float, int, string, etc.: Symptom
of Weakly typed,

 But, Is there any problem with weakly typed languages?

 Unpredictable result: x = "5" + 6 may be 56 or 11

 Dynamic type checking:


7
 Prevents unchecked runtime type error using a type system.
Are Classes ADTs?
m8 m7
mi are methods
of the class

m1 m6
Data
m2 m5
Class

m3 m4 8
Encapsulation
 James Rumbaugh et al., 1991
 “Amechanism by which external aspects
of a class that are visible to or accessible
by other objects are separated from the
internal or implementation details of
these aspects.”
 Grady Booch, 1994
 “…Serves to separate the contractual
interface of an abstraction and its
implementation.” 9
Information Hiding

“…encapsulation is most often


achieved through information
hiding, which is the process of
hiding all of the secrets of object
that do not contribute to its
essential characteristics. “ Grady
Booch
10
Let us now formalize our concept…
 Encapsulation

 Encapsulationallows the programmer to


group data and the subroutines that
operate on them together in one place,
and to hide irrelevant details from the
user.
 Information Hiding
 Making objects and code parts
(algorithms) invisible to portions of the
11

system that do not need them.


What is Encapsulation Then?
• An Object communicates with other
objects through messages:

―Data of an object encapsulated within


its methods and can be accessed only
through its methods. m4

m3
m5

―Realized by data hiding


m2 Data
m6

―One use of the separation m1

Methods
of concerns principle. 12
Encapsulation
cont…

m4

m3
m5

m2 Data
m6

m1

Methods

Concept of encapsulation 13
Encapsulation Vs Information Hiding

 Encapsulation is a concept

 Information hiding (how to) is


concretization of encapsulation
(what):

 Encapsulation is implemented by
Information hiding. 14
Class
 Template for object creation:
 Instantiated into objects
 An abstract data type (ADT)‫‏‬
 Examples: Employees, Books, etc.
 Sometimes not intended to produce
instances:
 Abstract classes 15
UML Class Representation
 A class represents a set of objects having
similar attributes, operations, relationships
and behavior.

Class Name
Window
A class can
size: Size implicitly
Attributes have a few
visibility: boolean association
attributes
display()
Operations hide()
16
Example UML Classes
LibraryMember LibraryMember LibraryMember

Member Name issueBook( );


Membership Number findPendingBooks( );
Address findOverdueBooks( );
Phone Number returnBook( );
E-Mail Address findMembershipDetails( );
Membership Admission Date
Membership Expiry Date
Books Issued

issueBook( );
findPendingBooks( );
findOverdueBooks( );
returnBook( );
findMembershipDetails( );

17
Different representations of the LibraryMember class
Active Class
 The nature of objects as self-
contained entities make them suitable
for concurrent implementation.
 An active class is just like any other
class:
 Except that behavior of its objects is
concurrent with other objects.
 Indicates implementation as one or more
processes or threads. 18
Active Class
 Represented as a class with double
lines on the left and right.

EventManager

suspend()
flush()

19
Servers and active objects
 Servers:
 Implemented as a parallel process with entry
points corresponding to object operations.
 If no calls are made to it, the object
suspends itself and waits for further
requests for service.
 Active objects:
 Objects are implemented as parallel
processes and the internal object state may
be changed by the object itself and not
simply by external calls. 20
Class Attribute Examples
Java Syntax UML Syntax

Date birthday Birthday:Date

Public int duration = 100 +duration:int = 100

Private Student
-Students[0..MAX_Size]:Student
students[0..MAX_Size]
21
Visibility Syntax in UML

Visibilty Java Syntax UML Syntax

public public +

protected protected #

package ~

private private -
22
Methods vs. Messages?
 Methods are the operations
supported by an object:
 Means for manipulating the data of
an object.
 Invokedby sending a message
(method call).
 Examples:
calculate_salary, issue-
book, member_details, etc. 23
Method Examples

Java Syntax UML Syntax


void move(int dx, int dy) ~move(int dx,int dy)

public int getSize() +int getSize()

24
Are Methods and Messages
Synonyms?
 No
 Message was the original
concept in object-orientation…
 Methods are the later
simplifications…
 Sometimes used as synonyms 25
Are Methods and Operations
Synonyms?
 No

 An operation can be implemented


by multiple methods.
 Known as polymorphism

 Inthe absence of polymorphism --


are used as synonyms. 26
What are the Different Types of
Relationships Among Classes?
 Four types of relationships:
 Inheritance

 Association

 Aggregation/Composition

 Dependency 27
Inheritance
 Allows to define a new class LibraryMember Base Class

(derived class) by extending an


existing class (base class). Faculty Students Staff
Derived
Classes

 Represents generalization-
specialization relationship.
UnderGrad PostGrad Research

 Allows redefinition of the existing


methods (method overriding). 28
Inheritance Example

Animal

“A Dog ISA Animal”

Dog

29
Hmmm… not really…

30
Inheritance
 Lets a subclass inherit attributes
and methods from a base class.
LibraryMember Base Class

Derived
Faculty Students Staff
Classes

UnderGrad PostGrad Research 31


Multiple Inheritance
cont…
LibraryMember Base Class LibraryMember Base Class

Derived
Faculty Students Staff Faculty Students Staff
Classes

Multiple
Inheritance

UnderGrad PostGrad Research UnderGrad PostGrad Research


32
Inheritance Implementation in Java
Inheritance is declared using the "extends" keyword
Even when no inheritance defined, the class implicitly extends a
class called Object.
class Person{
Person
private String name; - name: String
private Date dob; - dob: Date
...
}
class Employee extends Person{
private int employeeID;
Employee
private int salary; - employeeID: int
private Date startDate; - salary: int
... - startDate: Date
}

33
Employee anEmployee = new Employee();
Objects myRectangle and myBox Rectangle

Rectangle myRectangle = new Rectangle(5, 3); Box


Box myBox = new Box(6, 5, 4);

length 5.0 length 6.0


myRectangle
myBox

width 3.0 width 5.0

Object height 4.0


Reference
34
More Generalization Examples…

Mammal Quadruped

Feline Lizard

Tiger Lion Puma


35
Poor Generalization Example
(violates “is a” or “is a kind of” heuristic)

Person
attributes
operations

Arm Leg Head


attributes attributes attributes
operations operations operations

Any problems?
36

36
Inheritance Example
Library
Book

issuable reference

Issuable Reference
Issuable Reference
Single Volume Single Volume
BookSet BookSet
Book Book

Discriminator: allows one to group subclasses into


37
clusters that correspond to a semantic category.
GeneralizationDiscriminator
- Multiple Classification
Doctor

Female #3
role
<<abstract>>
Person Nurse
Gender
Male #1 patient
#2 Physical-
therapist
Patient
Poor Model 38
#2 38
Inheritance Pitfalls
 Inheritance certainly promotes
reuse.
 Indiscriminate use can result in
poor quality programs.
 Base class attributes and methods
visible in derived class…
 Leads to tight coupling 39
Association Relationship
 How implemented in program?

 Enables objects to communicate


with each other:
 One object must “know” the ID of
the corresponding object in the
association.
 Usually binary:
 But in general can be n-ary.
40
Association – example
 In a home theatre system,
A TV object has an association with a
VCR object
 It may receive a signal from the VCR
 VCR may be associated with remote
 It may receive a signal (command) to
record
1 1 1 1
Remote commands VCR Connected to TV 41
1-1 Association – example
tax_file
Rakesh Shukla 760901-1234

V. Ramesh
691205-5678
Keshab Parhi

People Tax_files

1 1
People Associated with Tax_files
42
Multiple Association – example
motherOf

Bhim
motherOf
Kunti Yudhistir

motherOf
Arjun
Women People

1 *
Woman Mother of People
43
Association UML Syntax
role B
Class A Class B
role A

 A Person works for a Company.


Role

Person employee employer Company


works for

44
Association Name
Association - More Examples

1 borrowed by *..5
Library Member Book

* eats * Human
Lion

Multiplicity: The number of objects from one


class that relate with a single object in an
associated class. 45
Navigability

opens 0..5
Key * Door

46
Association – Multiplicity
 A teacher teaches 1 to 3 courses (subjects)
 Each course is taught by only one teacher.
 A student can take between 1 to 5 courses.
 A course can have 10 to 300 students.

1 teaches 1..3
Teacher Course
1..5

takes
Students
10..300
47
Quiz: Draw Class Diagram
 A Student can take up to five Courses.

 A student needs to enroll in at least one


course.

 Up to 300 students can enroll in a


course.

 An offered subject in a semester should


have at least 10 registered students. 48
Student credits hasEnrolmentOf Course
10..300 Enrols in 1..5

49
Identify as Correct or Wrong

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course
10..300 Enrols in 1..5

Student credits hasEnrolmentOf


Course 50
10..300 Enrols in 1..5
Quiz: Read the Diagram

1..2 teaches 0..3


Teacher Course

opens 0..5
* Door
Key

51
Association and Link
 A link:
 An instance of an association
 Exists between two or more objects
 Dynamicallycreated and destroyed as
the run of a system proceeds
 For example:
 An employee joins an organization.
 Leavesthat organization and joins a new
52
organization etc.
Association Relationship
 A class can be associated with itself
(recursive association).
 Give an example?

 An arrowhead used along with name:


 Indicates direction of association.

 Multiplicity indicates # of instances


taking part in the association. 53
Self Association: Example 0

*
Person *
Friend of

54
Self Association: Example 0
Computer Network

Connects to

Computer *

55
Computer Network: Object
Diagram

Node1 Node2 Node3

Node4

Node5

Node6 Node7 Node8


56
Self Association: Example 1

next

LinkedListNode
previous

57
Reflexive Association: Example 2

Course
*

*
has pre-requisite of
58
Implementing Association
Relationship: Example 1
• To implement in Java:
– Use a reference variable of one class as
an attribute of another class
Bookname: OOSD
abook Author: Gamaa
ISBN: 12234434

Book Reference Book instance

1 Borrowed by 1
Bookname: abook Member Book
memberName: AKK
Member Number: 412323
59
public class Member{
private Book book;
public issueBook(Book abook){
setBook(abook);
abook.setLender(this);
}
setBook(Book abook){
book=abook;
} 1 1
Borrowed
… Member Book
by
}
60
public class Book{
private Member member;
setLender(Member aLender){
member=aLender;
}
… 1 1
Borrowed Book
} Member
by

61
Association Implementation:
Example 2
Student credits hasEnrolmentOf
Course
1..300 enrols 1..5

Class Student { Observe the


Course credits[5]; Navigation

}
Class Course {
Student hasEnrolmentOf[300];

62
}
Association Exercise 1
 A Person works for a Company.

Role Implicit attribute of type Company

Implicit attribute of type Person

Person employee employer Company


works for

Association Name

Observe: Implicit bidirectional navigation


Implementation? 63
Exercise 1: Solution
public class Company {
private Person employee;
public void setCompany(Person p){ employee=p;}
}
public class Person {
private Company employer;
public Company getWorksFor() {
return employer;
}
public void setWorksFor(Company c) {
employer=c;
} 64

}
Code for Association Multiplicity
class Customer{
private ArrayList <Account> accounts =
new ArrayList<Account>();
public Customer() {
Account defaultAccount = new Account();
accounts.add(defaultAccount);
}
} has
Customer 1 1..* Account 65
1-1 Association Example 3

1 has 1
Advertiser Account

public class Advertiser {


private Account account;
public Advertiser() {
account = new Account(this);
}
public Account getAccount() {
return account; Now,
} Write
} code for
Account 66
1-1 Association
Advertiser 1 1 Account

public class Advertiser {


public class Account {
private Account account;
private Advertiser owner;
public Advertiser() {
publicAccount(Advertiser
account = new owner) {
Account(this); this.owner = owner;
} }
public Account getAccount() public Advertiser getOwner() {
{ return owner;
return account; }
} } 67

}
Quiz: Read and understand
UML class diagram
has
CPU 1 Controller
0..2

1..4 1
DiskDrive controls SCSIController

• 1 CPU has 0 to two Controllers


• 1-4 DiskDrives controlled by 1 SCSIController
• SCSIController is a (specialized) Controller 68
Java Code?
has
class CPU { CPU 1 * Controller
Controller [ ] myCtlrs;
}
1..4 1
class Controller { DiskDrive controls SCSIController

CPU myCPU;
}
class SCSIController extends Controller {
DiskDrive [ ] myDrives = new DiskDrive[4];
}
Class DiskDrive {
SCSIController mySCSI;
}
69
Quiz: Banking System

Bank
has 1

*
Account
Audit() :void

Checking Saving MoneyMarket


Audit() :void Audit() :void Audit() :void

• 1 Bank associated with 0 or more Accounts


• Checking, Savings, MoneyMarket are Account types 70
More Association
Relationships

1 borrowed by *
Library Member Book

employed by 1
Employee * Company

71
Quiz 1: Write Java Code

1 issues 1
Book Member

Source code? ? ?

72
Quiz 2: Draw UML Class Diagram
public class TreeMap {
TreeMapNode topNode = null;
public void add(Comparable key, Object value) {…}
public Object get(Comparable key) {…}
}

class TreeMapNode {
private Comparable itsKey;
private Object itsValue;
private TreeMapNode nodes[] = new TreeMapNode[2];

public TreeMapNode(Comparable key, Object value) {…}

public Object find(Comparable key) {…}


public void add(Comparable key, Object value) {…}
73
}
Quiz 1: Write Java Code
1 issues 1
Book Member

Source code? ? ?
public class Book {
private Member member;
public issue(Member m) {
member = m; }
public Member issuedTo() {
return member; }
} 74
Quiz 2: UML Class Diagram Solution

2 nodes
TreeMap TreeMapNode
topNode
+ add(key,value) + add(key,value)
+ get(key) + find(key)

itsKey <<interface>>
Comparable

<<interface>>
itsValue
Object
75
public class Company {
Recapture:
private Person employee;
public void setCompany(Person p){ Association
employee=p; Implementation
p.setWorksFor(this);}
} Do you see any problems
public class Person { with this code?
private Company employer;
public Company getWorksFor() {
return employer; Company 1 works 1
Person
} employer employee

public void setWorksFor(Company c) {


employer=c; Caveat: Previous employee
} may still have link to company. 76
public class A{
A 1 1
B
private B b;
public boolean setB (B value ){
if ( this.b == value ) return false ;
B oldValue = this.b ;
this.b = value ; a1 b1
if ( oldValue != null )
oldValue.setA ( null ) ;
if ( value != null)
value.setA ( this ) ; a2 b2
return true ;
}
public B getB () { return this.b ; } Corrected Code77
Association Class
 An association can have its own attributes
and methods:
 Example 1: A person works for a company
 The date he joined a company
 The pay scale and the grade at which joined and so
on
 Remember he may join a company multiple times
 Example 2: A teacher teaches a subject:
 A teacher may teach the same subject multiple
times over many semesters
 Each time the students may be different 78
Association Class
 An association class is shown as a

class symbol:
 Attached to the association symbol by
a dashed line.
 An association class:
 Samename as the association
because...
 It represents the same thing! 79
Association Class: Example 1
Server 1 Connection * Client

Connection
baudRate
protocol
total Cost
• These attributes don’t belong
Disconnect
reportUsage to either the Client or Server
rerouteLink class.
• They are attributes of the
connection itself.

• An association class can have methods as well as attributes.


80
Association Class: Example 2
* *
Person Skill

How many association


class objects?
An association
class is a Competency
“normal” class, For every
level
and may include date acquired person-skill
attributes, link, there a
methods, competency
relations, object
inheritance etc. 81
Implementing Association Class
*
Module Student Module Student
1
Registration * Registration

Class
Mark: Integer Mark: Integer
Class
Diagram
Diagram

:Module :Student
:Module :Student
:Registration :Registration

Mark = 76 Mark = 76

:Student
:Student
:Registration :Registration
Object Object
Diagram Mark = 89 Diagram
Mark = 89

82
Pass the
Java Code Student to
public class Module { Registration.
private Vector <Registration> reg=new Vector<Registration>();
public void enrol(Student st) {
reg.addElement( new Registration(st) );
}
... Maintain the link
to Registration
}
class Registration { Module Student
private Student student; 1
* Registration
private int mark; Mark: Integer

Registration(Student st) {
student = st; mark = 0; Keep track of
the Student
} reference.
...
} 83
Association Class: Example 4

RealEstate 1 *
Developer Client

An association Contract
class is a
“normal” class,
Amount
and may include
Contract #
relations,
Date
inheritance etc.

84
public class RealEstateDeveloper{
private Vector <Contract> contracts= new Vector
<Contract>();
public void buy(Client c){contracts.add(new Contract(c))};
}
public class Client{
private Address address;
public Address getCurrentAddress(){}
}
public class Contract{
private Client client;
private int contractNo;
public Contract(Client c){ client=c;} 85
Ternary Association
 An object of an association class:

 Stores the details of one link for two or


more associated class.

 Some times three (or more) classes


may be associated:
 Inthis case an association end represents
the potential number of values at that end
when the values at the other end is kept
86
fixed.
Ternary Association

Man Woman
1 1

marry
1..3
Priest

and we can add more classes to the diamond…


87
Implementation of Ternary Association
 There are several ways in which ternary
association can be implemented.
 One is to decompose it into a set of binary
associations.

Man 1
Marriage 1 1 Woman
1
Participates
Participates
in
in
*
Performed by
1..3
Priest
88
Record
Goals against
Goals for

Player 11 1
Team

*
Season

89
Association Quiz

Book Editor
title: String * 1 name: String
Edited by
editor: String myBooks: Book

What is the problem?

1. Association denoted by symbol not attributes.

 Implementation (pointers, arrays, vectors, ids etc) is


left to the detailed design phase.

2. Wrong arrow type 90


“Or” Association
 Used when all association combinations in
a class model are not valid.
 Example:
 A person can have an insurance contract with
an insurance company
 A company can have an insurance contract with
an insurance company
 A person and a company CANNOT have the
same insurance contract with an insurance
company. 91
“Or” Association Example

1
Insurance Company * Insurance Contract
* *

{or}

1..* 1..*

Person Company

92
Qualified Association
 A qualified association allows us to restrict the
objects referred in an association.
 Modelled by associative arrays, maps, and
dictionaries.
1
GradeCard Roll
0..1
Student
Read
1
0..1
Directory file
name File

 How to read?
 There exists upto one file for each instance of93
filename in the directory .
What does it Mean?
 There is at most one Product for each
instance of Order Line in the Order.
1
0..1 Product
Order Order Line
Refers to

1 * Product
Order Refers to

 A qualifier selects at most one among the


target objects:
 Reduces the effective multiplicity from ‘many’
to ‘one’.
94
Qualified Association…
* *
League Player
nickName

1 0..1
League nickName Player

•The second is the preferred way…


•Hint on implementation…
•Effectively reduces multiplicity… 95
Qualified Association
1
0..1
League nickName Player
public class League { public class Player {
private Map players; private Map leagues;

public void addPlayer public void addLeague


(String nickName, Player p) {
(String nickName, League l) {
if(!players.containsKey(nickNam
e)) { if (!leagues.containsKey(l)) {
players.put(nickName, p); leagues.put(l, nickName);
p.addLeague(nickName, this); l.addPlayer(nickName, this);
} }
} }
} } 96
Converting to Qualified Association
Role

Person employee employer Company


* works for 1

Association Name

Give qualified association?

employer
Person employee
works for empId Company
0..1
1 97
Qualified Association
1
0..1
Bank accno Account

 The purpose of a qualifier is usually


to indicate efficient access to linked
objects:
 For example, access accounts based
only on the account number;

 Also to avoid a linear search through all


accounts.
98
Implementing Qualifier
 The run-time structure involves some
kind of index to accounts:
:Account
:Bank
:Account
Using
Acc As 41
index :Account
53
99

99
Code Example
 Hash Table is another choice to implement the index, it
provides synchronized access.:
public class Bank{
private HashTable theAccounts;

public void addAccount (Account a) {


theAccounts.put(new Integer(a.getNumber()), a);
}

public void removeAccount(int number) {


theAccounts.remove(new Integer(number));
}

public Account lookupAccount(int number) {


return (Account) theAccounts.get(new Integer(number));
}
} 100
Types of Class Relationships
Relation

Generalization Association Dependency

Binary Association N-ary Association

Aggregation

Composition 101
Overdoing Associations
 Avoid unnecessary Associations

PersonInfo PersonInfo
Person 1 1 Address Name
Name E-Mail Address
Birthday E-Mail
Birthday

Avoid This… Do This


102
Recollect: Implementing Association
Multiplicities
 Fixed multiplicity: Member
1 Borrowed
Book
by 0..10

 The reference field can be


Book [10] book; // with a reference being
null if there is no related object for this association.

 When the upper end is *:


 Java collections can be used
 Collections facility was added to Java as a
part of JDK 1.2 103
Java Collections framework?
 Collections framework provides two
things:
 Implementations of common high-level
data structures: e.g. Maps, Sets, Lists,
etc.
 An organized class hierarchy with
rules/formality for adding new
implementations
 The latter point is the reason why
104
Collections is a framework.
Bit of History…
 Pre Java SDK1.2, Java provided a handful
of data structures:
 Hashtable
 Vector
 Bitset
 These were for the most part good and
easy to use:
 But were not organized into a general
framework.
 In SDK1.2 legacy data structures
105
retrofitted to new model.
Java Collections

106
«interface» «interface»
Collection Map

«interface»
«interface» «interface» «interface» SortedMap
Set List Queue

HashSet «interface» Vector ArrayList LinkedList TreeMap HashMap


SortedSet

Linked TreeSet
HashSet

107
Java Collections: What is it?

“The Collections Framework


provides a well-designed set of
interfaces and classes for storing
and manipulating groups of data as
a single unit, a collection.”
-java.sun.com
108
Java Collections

Implementations
Hash Resizable Balanced Linked
Table Array Tree List
Set HashSet TreeSet
Interfa
ces List ArrayList LinkedList

Map HashMap TreeMap

109
Three Basic Java Collections
 List : Sequences
 Ordering is implicit
 it is legitimate to ask questions like “what is the first
object in the sequence?”
 Add book as first book etc.
 Sets: Unordered collection
 Maps: Qualified associations
 Each entry involves a pair of objects.
 A map is also called as a dictionary.
 it is legitimate to ask questions like “what value - if any
- is associated with the following key?” or
 “does this map contain the following key?”.
 For all types of Collections:
 Can create an Iterator object to access each item110in
the collection once.
Which List to Use?
 LinkedList:
 Goodif the list changes size (grows or
shrinks) frequently
 Good for accessing either end of the list,
but slower when accessing items in the
middle of the list
 ArrayList:
 Good if accessing elements by specific
position, but slow for adds and removes.
111
Vector class
 In what ways different from
ArrayList?
 Similar to an ArrayList, but
synchronized for multithreaded
programming.
 Mainly for backward-compatibility
with old java.
 Used also as base class for Stack
implementation. 112
Which Sets to Use?
 HashSet:
 Good efficiency in most cases

 TreeSet:
 Useful when an iterator will access
the elements of the set in a specific
order based on their value (e.g.
Strings would be kept in alphabetical
order.)
113
Which Map to Use?
 HashMap:

 Efficient in most cases

 TreeMap:

 An iterator obtained from the key


set will access the elements of
the map in key order. 114
Collection: Basic operations
int size( );

boolean isEmpty( );

boolean contains(Object element);

boolean add(Object element); // Optional

boolean remove(Object element); // Optional

Iterator iterator( ); 115


Collection: Iterator
public interface Iterator {
boolean hasNext( );
// true if there is another element
Object next( );
// returns the next element (advances the
iterator)

void remove( ); // Optional


// removes the element returned by next
}
116
One-to-many Association
1 *
Advertiser Account

public class Advertiser { public class Account {


private Set accounts; private Advertiser owner;
public Advertiser() { public void setOwner(Advertiser
newOwner) {
accounts = new HashSet();
if (owner != newOwner) {
}
Advertiser old = owner;
public void addAccount(Account a) {
owner = newOwner;
accounts.add(a);
if (newOwner != null)
a.setOwner(this);
} newOwner.addAccount(this);
public void removeAccount(Account a) { if (oldOwner != null)
accounts.remove(a); old.removeAccount(this);
a.setOwner(null); }
} } 117

}
Ordered Association
* {ordered} *
Tournament Player

public class Tournament { public class Player {


private List players; private List tournaments;
public Tournament() { public Player() {
players = new ArrayList(); tournaments = new ArrayList();
} }
public void addPlayer(Player p) { public void
addTournament(Tournament t) {
if (!players.contains(p)) {
if (!tournaments.contains(t)) {
players.add(p);
tournaments.add(t);
p.addTournament(this);
t.addPlayer(this);
}
}
}
} 118
}
}
Summary of Implementation of
Association
 1-to-1 association:
 Role names become attributes

 1-to-many association:
 Translate into a Vector

 Qualified association:
 Translate into a Hash table 119
Which sentences are true?
a) CheckingAccount implements BankAccount
b) CheckingAccount and SavingAccount are BankAccount
c) CheckingAccount and SavingAccount are associated
d) BankAccount is associated to CheckingAccount
e) SavingAccount can processCheck
120
f) CheckingAccount has a balance
Aggregation Relationship
 Represents whole-part relationship
 Represented by a diamond symbol at
the composite end.
 Usually creates the components:
 Butoften indistinguishable from plain
association.
 Except,aggregate usually invokes the
same operations of all its components.
 Usually owner of the components:
121
 But can share with other classes
Aggregation Relationship

1
Document * Paragraph 1
* Line

1 1
Company
employs
* Person * memberOf
Club

122
Aggregation cont…

 An aggregate object contains


other objects.

 Aggregation limited to tree


hierarchy: Paragraph
1
Line

*
 No circular inclusion relation.
123
Aggregation vs. Inheritance
Cont…
 Inheritance:
 Different object types with similar
features.
 Necessary semantics for similarity of
behavior is in place.
 Aggregation:
 Containmentallows construction of
complex objects.
124
Aggregation vs. Inheritance

Aggregation Inheritance
Instances of distinct Instances of a single
classes class
“a-part-of” (APO) “a-kind-of” or “is-a”
(AKO)
Propagated only if Inheritance
specified
Aggregate + parts Superclass + subclass
25
125
Composition
 A stronger form of aggregation
 The whole is the sole owner of its part.
 A component can belong to only one whole
 Thelife time of the part is dependent
upon the whole.
 The composite must manage the creation and
destruction of its parts.
1 Circle
Circle Point
3..* Point
Polygon 126
Composition Relationship

 Life of item is same as that of order

1
Order * Item

127
Composition: Alternate Notation

Car
4 1
Wheel Engine

2 1
Door Chassis

1 1
Axle Steering
128
Composition
• An object may be a part of ONLY one
composite at a time.
Whole is responsible for the disposition of its
parts. whole
Window

*
Frame part 129
Aggregation vs. Composition
 Composition:
 Composite and components have the same
life line.
 Aggregation:
 Lifelines are different.
 Consider an order object:
 Aggregation:If order items can be
changed or deleted after placing order.
130

 Composition: Otherwise.
Composition versus Aggregation
1
* Composition
Order Item

1
* Aggregation
Order Item

131
Implementing Composition
public class Car{
private Wheel wheels[4];
1 4 Wheel
public Car (){ Car
wheels[0] = new Wheel();
wheels[1] = new Wheel();;
wheels[2] = new Wheel();;
wheels[3] = new Wheel();;
}
} 132
Representing Aggregation in Classes
An aggregation relationship is usually represented
as a data field in the aggregated class.

public class Name { public class Person { public class


/** Data fields */ Address {
/* Data fields */
private Name name; /* Data fields */
/*Constructors */ private Address address;

/* Methods */ /*Constructors*/
/** Constructors */
} /** Methods */ /** Methods */
} }

133
Inner Classes Translation

If house is used public class Person {


private Name name;
only in the Person
private House house;
class:
...
 Itcan be
declared as an class House {
inner class in ...
Person. }

} 134
Implementing Aggregation: Ex 1
import java.util.ArrayList;
public class CarShop{
private ArrayList<SalesPerson> people = new
ArrayList<SalesPerson>();
private ArrayList<Car> cars = new
ArrayList<Car>();
public Dealership(String company, Manager
manager) {
this.company = company;
this.manager = manager;
}
1
* Car
Car Shop
* Salesman
135
Implementing Aggregation: Ex 2
Class Aggregator{
Public class sentence{
Char [] text; public static void main() {
} BufferedReader br=new
BufferedReader(new
Public class paragraph{
InputStreamReader(System.in));
private ArrayList <Sentence>
sentList=new Paragraph p= new Paragraph();
ArrayList<Sentence>(); do{
public addSentence(Sentence s){ String line=br.readLine();
sentList.add(s);
p.addSentence(line);
}
}
}
1 }
Pragraph * Sentence 136
}
How to identify
aggregation/composition?
 Lifetime of part is bound within lifetime of
composite
 There is a create-delete dependency

 There is an obvious whole-part physical or


logical assembly
 Some properties of composite propagate to
parts (e.g., location)
 Operations applied to composite propagate to
parts (e.g., destruction, movement, recording)137
Class Dependency

Dependent Class Independent Class

138
Dependency
 Dependency relationship can arise due to a variety
of reasons:
 Stereotypes are used to show the precise nature of
the dependency.
Type of Stereotype Description
dependency
Abstraction «abstraction» Relates two model elements, that
represent the same concept at
different levels of abstraction
Binding «bind» Connects template arguments to
template parameters to create
model elements from templates.
Realization «realize» Indicates that the client model
element is an implementation of the
supplier model element
Substitution «substitute» Indicates that the client model
139
element takes place of the supplier.
Dependency
 Commonly Dependence may be caused by:
 Local variable
 Parameter
 Return value
 Example
Class A { Class B {
B Foo(B x) { …
B y = new B(); …
return y; …
}
140
} }
Dependence – Possible Implementations
class MyDependentClass{

void myFunction1(
MyClass
MyReferencedClass r ) {
att: int .. }
myFunction()
MyreferencedClass
dependence myFunction2( .. ) { .. }
arrow
void myFunction3( .. ){
MyReferencedClass MyReferencedClass m .. }

}
141
Association Vs. Aggregation

 Is aggregation an association?

 Is composition an aggregation?

142
Association Types
 aggregation: "is part of" Car

1
 Symbolized by a white diamond aggregation
1
 composition: is made of Engine

 Stronger version of
Book
aggregation composition

 The parts live and die with the 1


* Page
whole
 Symbolized by a black diamond
dependency
 dependency: Depends on
Lottery Random
 Repres. by dotted arrow. Ticket 143
UML Class Relation Notation
Summary
Class
Generalization dependency
Relationship

Object Object
Aggregation Composition
Object Association Association Association

1..* 1
n n
0..* 0..*

Will always be “1” 144


Aggregation Composition

Faculty SalesOrder

(team- 1..5 1
teaching is
possible) 0..* 1..*
CourseTeaching SalesOrderLineItem

145
Multiplicity Quiz #1
Whole

Draw Class
diagram 3
1
5 2
Part1 PartN

•One Whole is associated with 5 Part1 •One Whole is associated with 2 PartN
•One Part1 is associated with 1 Whole •One PartN is associated with 3 Whole

P1
Object diagram W
P1
Pn
W P1 Pn W
P1 W Pn
P1
W
W 146
P1
Class Relation Hints
 Composition
 B is a permanent part of A
 A contains B
 A is a permanent collection of Bs

 Subclass / Superclass
 A is a kind of B
 A is a specialization of B
 A behaves like B

 Association (Collaboration)
 A delegates to B
 A needs help from B
147
 A and B are peers.
Class Diagram Inference Based on Text Analysis
(based on Dennis, 2002)
 A common or improper noun implies a class e.g.
Book
 A proper noun implies an object (instance of a
class): CSE Dept, OOSD, etsc.
 An adjective implies an attribute e.g. price of book
 A “doing” verb implies an operation
 Can also imply a relationship e.g. student issues Book
 A “having” verb implies an aggregation relationship
 A predicate or descriptive verb phrase elaborates
an operation e.g. ISBN numbers are integers
 An adverb implies an attribute of an operation e.g.
fast loading of image…
148
Identify Class Relations
 Faculty & student
 Hospital & doctor
 Door & Car
 Member & Organization
 People & student
 Department & Faculty
 Employee & Faculty
 Computer Peripheral & Printer
149
 Account & Savings account
Identify Classes & Relations
 A square is a polygon
 Shyam is a student
 Every student has a name
 100 paisa is one rupee
 Students live in hostels
 Every student is a member of the library
 A student can renew his borrowed books
 The Department has many students 150
Identify Classes & Relations
 A country has a capital city
 A dining philosopher uses a fork
 A file is an ordinary file or a directory file
 Files contain records
 A class can have several attributes
 A relation can be association or
generalization
 A polygon is composed of an ordered set of
points
 A person uses a computer language on a
project 151
Exercise: Draw UML Diagrams

1. Some persons keep animals as


pets.

2.A company has many employees


and undertakes many projects.
Each project is carried out by a
team of employees.
152
153
154
Exercise
 Develop UML Class diagram for a software that we have
been assigned to develop to manage a library.
 Each member has a name, date of birth, address, phone
number and email
 Each journal has a name, the ISBN code, the subject
areas, the shelf where it is located and the editor. Each
editor has a name and a nationality.
 A journal may cover issues in several subject areas. It is
important to store the order of appearance of areas,
since these indicate their relative importance for the
journal.
 It is important to keep track of the date on which each
journal has been borrowed, returned, disappeared, and
155
the user carrying out the operation.
AreaOrder
-orderOfApperarance

1..* 1..*
Editor publishes Journal Area
Addressed in
-editorName -journalName -areaName
-nationality 1 0..* 1 -areaDetails
-ISBN
-shelf

has

0..* Member
Operation 0..* 1 -userName
performs
-address
-date -birthDate
-operationType
-phone
-email
156
Elevator System

157
Identify Classes and Relations
 Controller program for an elevator is to be developed.
 Each elevator has a set of m buttons, one for each floor.
 These illuminate when pressed and cause the elevator to visit
the corresponding floor.
 The illumination is canceled when the elevator reaches the
corresponding floor.
 Each floor, except the first floor and top floor has two
buttons:
 One to request and up-elevator and one to request a down-
elevator.
 These buttons illuminate when pressed. The illumination is
canceled when an elevator visits the floor. The door opens as
soon as it stops at a floor.
 When an elevator has no requests, it remains at its
158
current floor with its doors closed.
Elevator Elevator_Controller control Door
control

Preliminary
only: Please *
Button
refine
yourself

Elevator_Button Floor_Button

159
Interface
 An interface in UML is a named set of operations.
 Interfaces are used to characterize the behaviour
of some classes.
 Shown as a stereotyped class.

<<interface>>
List

Add( )
isEmpty( )

 Generalization can be defined between


interfaces. 160
Interface Example
 An interface specifies the set of services
to be offered by a class.

<<interface>> Cylinder
Shape
Draw
Move
Scale
Pyramid
Rotate

Cube
Realization relationship
161
Realizing an Interface
 A class realizes an interface if it provides
implementations of all the operations.
 Similar to the implements keyword in Java.
 UML provides two equivalent ways of denoting this
relationship:
CircularLinkedList <<interface>>
List

CircularLinkedList
List

Both represent: “CircularLinkedList implements all


the operations defined by the List interface”.
12/30/20 162 162
Interface Dependency
 A class can be dependent on an interface.

 This means that it makes use of the operations


defined in that interface.

 E.g., the Restaurant class makes use of the List


interface:
Restaurant

<<use>>

List 163
Collection List
<<interface>> <<interface>>

Java Provides a List


interface for several
AbstractList implementations
<<abstract>>

ArrayList Vector AbstractSequentialList


<<abstract>>

Stack
LinkedList 164
Interface Representations
Tube

Alternate
Representations Pyramid

Cube
Shape

Implementors
Tube

Service <<interface>>
description Shape
Pyramid
Draw
Move
Scale Cube
Rotate 165
Interface Diagram Example
Storable
Class A Class B
Runnable

<<interface>> <<interface>>
Runnable Storable
Class C Runnable
run() {} load() {}

save() {}

Class A implements the interfaces Runnable and


Storable. Class C implements the interface Runnable.
Class B uses the interface Runnable and Storable
from A, and Runnable from C. 166
UML Packages
 A package is a general purpose grouping
mechanism.

 Can be used to group any UML element (e.g. use case,


actors, classes, components and other packages.)

 Commonly used for specifying the logical


grouping of classes.

 A package does not necessarily translate into a


physical sub-system. Name

167
Packages
 Model elements in a package are taken
to be related semantically (group).
 Packages can be related to each other:
 By dependencies or generalizations

 A modelling element can be located in


only one package:
 Also, Packages cannot share model
elements
168
Java Global Namespace
How come package name is
org.afox.financial.inventory.stock?
The designers of Java have proposed an Internet-wide unique
package naming scheme
It includes the Internet domain name of the organization within
which the package was developed.
The domain is reversed and the subdomains become packages
afox.org becomes org.afox

The domain portion is prepended to any packages


developed within afox.org
financial.inventory.Stock becomes org.afox.financial.inventory.Stock

This standard guarantees that no name conflicts 169


with classes developed with afox.org.
Mapping to Code

MyPackage package MyPackage;


abstract class
MyAbstractClass{}
MyAbstractClass

class MyDerivedClass extends


MyAbstractClass{
MyDerivedClass
int att;
att: int
void myFunction() { .. }
myFunction()
}
170
Exercise
 The B.Tech program of IIT Computer
Science Department:
 comprises of many B.Tech batches.
 Each B.Tech batch consists of many B.Tech
students.
 CSE Department has many listed courses.
 A course is either listed as an elective course or
a core course.
 Each B.Tech student credits between 30 to
171
32 course offering.
Aggregation vs. Composition
• Aggregation: BTech Program
*
BTech Batch
1
1
•A special form of Association *
Student
•Models “part of” relationship

credits
•Part may belong to several whole
Course Course
List
* 30..32
1
•Composition: Core Elective Course offering

• stronger version of Aggregation


• “part(s)” may belong to only ONE whole
• part(s) usually “live” and “die” with the whole
172
172
Constraints on Objects
A constraint restricts the values that
objects can take.

Example: No employee’s salary can


not exceed the salary of his boss.

{salary <=boss.salary}
Employee Employer
Salary reports to Salary
173
Constraints and Notes
 Can be used to annotate:
 Associations, attributes, operations,
classes, etc.
 Constraints are expressed in OCL:
 Semantic restrictions noted as Boolean
expressions.
Customer 1 Place *
Order
may be
{ total < $50 } cancelled
id: long { value > 0 }

Constraint Note 174


Relationships Between Classes
 Association OR
 Permanent, structural, “has a”
 Solid line (arrowhead optional)
 Aggregation/Composition
 A whole created from parts
 Solid line with empty or filled diamond from whole
 Dependency
 Temporary, “uses a”
 Dotted line with arrowhead
 Generalization
 Inheritance, “is a”
 Solid line with open (triangular) arrowhead
 Implementation 175
 Dotted line with open (triangular) arrowhead
Abstraction
 Consider aspects relevant for
certain purpose.

 Suppress non-relevant aspects

 Types of abstraction:

 Data abstraction

 Behaviour abstraction
176
Abstract Classes

 Not allowed to have objects


instantiated from it.

 Used only for inheritance purposes

 Describes common attributes and


behavior for other classes.
177
Abstract Class
Video
<<abstract>>

- Rental fee()

VHS DVD

178
Abstract Class
cont…

 Why use abstract class?

 Reduces complexity of design


 Enhances understandability
 Increases productivity

 It has been observed that:


 Productivity is inversely proportional
to complexity.
179
Another Abstract Class Hierarchy
Diagram

Figure {abstract}
Figures
*
# position: Pos

+draw () {abstract}

Group Polygon

draw () draw ()
180
Abstract public class Figure {
abstract public void draw();
protected Pos position; Java
} Implementation
public class Group extends Figure {
private Vector <Figure> figures = new Vector
<Figure> ();
public void draw () {
}
}
public class Polygon extends Figure {
public void draw () { // draw polygon
code
181
}
What is Polymorphism?
 Denotes poly (many) morphism

(forms).
 Under different situations:
 Same message to the same object can
result in different actions:

 Two types:
 Static
182
 Dynamic
An Example of Static Binding
Class Circle{
private float x, y, radius;
private int fillType;

public create ();


public create (float x,float y, float centre);
public create (float x, float y, float centre,
int fillType);
}

183
An Example of Static Binding
cont…
 Assume a class named Circle has three
definitions for create operation
 Without any parameter, default
 Centre and radius as parameter
 Centre, radius and fillType as parameter
 Depending upon parameters, method will be
invoked

 Method create is said to be overloaded 184


What is Dynamic Binding?
 A method call to an object of an
ancestor class:
 Resultsin the invocation of the method of
an appropriate object of the derived class.
LibraryMember
 Which principles are involved?
 Inheritance hierarchy
Faculty Students Staff
 Method overriding
 Assignment to compatible types
185
UnderGrad PostGrad Research
Compatible Types
 Principle of substitutability (Liskov’s
substitutability principle):
 Anobject can be either assigned to or
used in place of an object of its
ancestor class, but not vice versa.

A A a; B b;
a=b; (OK)‫‏‬
B b=a; (not OK)‫‏‬ 186
Liskov Substitution Principle
(Barbara Liskov, 1988)
 If for an object o1 of type A there
is an object o2 of type B such that A
is a subtype of B:
 Then it is possible to use o1 for o2.

A A a; B b;
a=b; (OK)‫‏‬
B b=a; (not OK)‫‏‬
187
Or in Plain English
 Any subclass object should be
usable in place of its parent class
object.
 Corollary:
 All derived classes must honour the
contracts of their base classes

 IS A = same public behavior


188
Dynamic Binding
Cont …

 Exact method to be bound on


a method call:
 Notpossible to determine at
compile time.
 Dynamically decided at runtime.
189
An Example of Dynamic Binding
• Consider a class hierarchy of
different geometric objects:
—Display method is declared in the
shape class and overridden in each
derived class.
—A single call to the display method
would take care of displaying the
appropriate element. 190
An Example of Dynamic Binding
cont…
Shape

Circle Rectangle Line

Ellipse Square

Cube

Class hierarchy of geometric objects 191


An Example
cont…
Traditional code Object-oriented code
Shape s[1000];
For(i=0;i<1000;i++){ Shape s[]=newShape[1000];
If (s[i] == Circle) For(i=0;i<1000;i++)‫‏‬
s[i].draw();
draw_circle();
else if (s[i]== Rectangle) -
draw_rectangle(); -
-
-
-
}
Traditional code and OO code using dynamic binding

192
Genericity
 Generic programming = programming with
classes and methods parameterized with
types.
 Example: class stack of different types of
elements:
 Integer stack
 Character stack
 Floating point stack
 Define generic class stack only once:
193
 Later instantiate as required
Genericity
T
Set

insert(T)‫‏‬
remove(T)‫‏‬

Refinement

EmployeeSet

194
Java Generics
 A generic class is recompiled with different types as
needed.
 The bad news:
 Instead of: List words = new ArrayList();
 Write: List<String> words = new ArrayList<String>();
 The good news:
 Replaces runtime type checks with compile-time checks
 No casting; instead of String title = (String) words.get(i);
use: String title = words.get(i);
 Some classes and interfaces that have been “genericized”
are: Vector, ArrayList, LinkedList, Hashtable,
HashMap, Stack, Queue, PriorityQueue, Dictionary,
Prasad cs884
TreeMap and TreeSet 195 195
import java.util.ArrayList;
.....
ArrayList class
(generic)
ArrayList<String> L = new ArrayList<String>(8);
L.add("Li");
L.add("Robinson");
L.set(0,"Good");


L L
Li Li
Good
Size=1 Size=2 Robinson
L
Size=0

Capacity Capacity
Capacity=8 =8 =8

196
How do you Define your Own Generic Class?
public class GenericClass<T> {
private T obj;
public void setObj(T t) {obj = t;}
public T getObj() {return obj;}
public void print() {
System.out.println(obj);
}
}
Main:
GenericClass<Integer> g = new GenericClass<Integer>();
g.setObj(5); // auto-boxing
int i = g.getObj(); // auto-unboxing
g.print(); 197
Type Wrapper
 Why does Java distinguish between primitive
types and objects?
 Should n’t everything be objects?
 Java uses primitive types such as int, double or
float to hold the basic data types :
 For the sake of performance.
 However, there are situations when you will need
object representations.
 For example, when operation involving objects is
required, you cannot use primitive types.
 To handle these situations Java provides type
Wrappers which provide classes that encapsulate a198
primitive type within an object.
Auto Boxing and Unboxing
 Autoboxing is a process by which primitive type
is automatically encapsulated(boxed) into its
equivalent type wrapper

 Auto-Unboxing is a process by which the value of


object is automatically extracted from a type
wrapper.

 Example:
public static void main(String[] args) {
Integer iob = 100; //Autoboxing of int
int i = iob; //unboxing of Integer
199
}
Advantages of Object-Oriented
Development
 Code and design reuse
 Increased productivity
 Ease of testing (?) and maintenance
 Better understandability
 Elegant design:
 Loosely coupled, highly cohesive objects:
 Essential for solving large problems. 200
Experience Report
 Initially incurs higher costs

 Aftercompletion of some projects


reduction in cost become possible

 Using well-established OO methodology


and environment:

 Projects can be managed with 20% --


50% of traditional cost of development.
201
Disadvantages?
 Non-locality of memory access:
 Data distributed across objects
 Also,
objects tend to have complex
associations:
 Leads to poor memory access times.
 Higher overheads:
 Object creation, destruction
 Overhead due to encapsulation, etc. 202
End

203
Example

has 0..1
School Department
1 1..n 1..n
1..n 1..n

assignedTo
member
-chairperson
n 1..n 1..n 0..1
Student attends Course teaches Instructor
n n n 1..n

204
Qualified Association
 Represent the following using UML

class diagram:
A library member can issue a book
 Date issued and returned must be
kept track of
Member Book

Member
*
Book
1
IssueRecord
IssueReord
*
borrowDate: Date
issueDate:Date Returndate: Date
205
returnDate:Date
Association - Multiplicity
 A cricket team has 11 players. One of them is the
captain.
 A player can play only for one Team.
 The captain leads the team members.

Captain
Team
Memb 1
er Player 0..1
Team
10
11 member of 1

Captain
1

Leads 206
Book
Solution Q.1
*
Part

*
Chapter

*
Section 207
Marking Guide
 Four Classes are represented with rectangles.
[1]

 The attribute and operations compartment should


have been omitted. [0]

 Class names start with a capital letter and are


singular. [1]

 Three Aggregation relationships are correctly


represented with diamonds and with proper
cardinality. [3]
208
Class Hierarchy Diagram

Vehicle {abstract}

Person drives * -color: Int

drive () {abstract}

Car Boat Scooter

drive () drive () drive ()

209
Java Implementation
Abstract public class Person {
private ArrayList<Vehicle> drives = new
ArrayList<Vehicle>();
}
Abstract public class Vehicle{
private int color;
abstract public void drive ();
}
public class Scooter extends Vehicle{
public void drive () {}
}

….. 210
Quiz
 Convert qualified association into normal
association…
StockExchange * 1 Company
tickerSymbol SX_ID

Lists

StockExchange
* * Company
Lists tickerSymbol
SX_ID
211
Unified Modelling
Language

12/30/2021 1
Object Modelling Using UML
 UML is a modelling language.
 Not a system design or
development methodology

 Used to document object-oriented


analysis and design results.
 Independent of any specific
design methodology. 2
UML Origin
 OOD in late 1980s and early 1990s:
 Different software development
houses were using different notations.
 Methodologies were tied to notations.
 UML developed in early 1990s:
 To standardize the large number of
object-oriented modelling notations
that existed. 3
UML Lineology
 Based Principally on:
 OMT [Rumbaugh 1991]
 Booch’s methodology[Booch
1991]
 OOSE [Jacobson 1992]
 Odell’s methodology[Odell 1992]
 Shlaer and Mellor [Shlaer 1992]
4
Different Object Modeling
Techniques in UML

OMT

UML
Booch’s
OOSE
Methodology
5
UML as A Standard
 Adopted by Object Management
Group (OMG) in 1997.
 OMG is an association of industries
 Promotes consensus notations and
techniques
 UML also being used outside software
development area:
 Example car manufacturing 6
History of UML
UML 2.0
Industrialization

UML 1.1 Standardization

public
feedback UML
UML 0.9
0.9 && 0.91
0.91
Unification

Unified method 0.8

Booch'93 OMT-2

Fragmentation 7
Other methods Booch'91 OMT-1 OOSE
Developments to UML
UML 2.0 2003
 UML continues
Application
to develop: to embedded
systems
 Refinements UML 1.X
 Making it
applicable to new
contexts UML 1.0 1997

8
Why are UML Models Required?
 Modelling is an abstraction mechanism:
 Capture only important aspects and
ignores the rest.
 Differentmodels result when different
aspects are ignored.
 Aneffective mechanism to handle
complexity.
 UML is a graphical modelling tool
 Easy to understand and construct 9
Modeling a House

10
UML Diagrams
 Nine diagrams in UML1.x :
 Used to capture 5 different views of a
system.
 Views:
 Providedifferent perspectives of a
software system.
 Diagrams can be refined to get the
actual implementation of a system. 11
UML Model Views
 Views of a system:
 User’s view
 Structural view
 Behavioral view
 Implementation view
 Environmental view 12
Diagrams and views in UML

Behavioural View
Structural View - Sequence Diagram
- Class Diagram - Collaboration Diagram
- Object Diagram - State-chart Diagram
- Activity Diagram
User’s View
-Use Case
Diagram

Implementation View Environmental View


- Component Diagram - Deployment Diagram

13
Diagrams in the UML 2.0 -- 13 Diagrams

14
UML 2.0 Diagrams
Class
Diagram
Component
Diagram
Structure Composite
Diagram Structure Diagram
Deployment
Diagram
Object
Diagram
Package
UML 2.0 Diagram
Diagram

Sequence
Use Case Diagram
Diagram
Behavior Communication
Activity Diagram
Diagram Diagram
Interaction
Interaction Overview
Diagram Diagram
State Machine Timing
Diagram Diagram
15
Structural Diagrams
 Class Diagram
 set of classes and their relationships.
 Object Diagram
 set of objects (class instances) and their
relationships
 Component Diagram
 logical groupings of elements and their
relationships
 Deployment Diagram
 set of computational resources (nodes) that host
each component. 16
Behavioral Diagrams
 Use Case Diagram
 high-level behaviors of the system, user goals,
external entities: actors
 Sequence Diagram
 focus on time ordering of messages
 Collaboration Diagram
 focus on structural organization of objects and
messages
 State Chart Diagram
 event driven state changes of system
 Activity Diagram
 flow of control between activities 17
Quotable Quotes on Using UML
 “UML is a large and growing beast, but you
don’t need all of it in every problem you
solve…”
– Martin Fowler
 “…when learning the UML, you need to be
aware that certain constructs and
notations are only helpful in detailed design
while others are useful in requirements
analysis …”
– Brian Henderson-Sellers 18
Are All Views Required for Developing
A Typical System?
 NO
 For a simple system:
 Use case diagram, class diagram and one of
the interaction diagrams only.
 State chart diagram:
 when class has significant states.
 When states are only one or two, state chart
model becomes trivial
 Deployment diagram:
 In case several hardware components used to
develop the system. 19
Key Diagrams in UML

Use Case Diagrams


Requirements

System Class Diagrams


Structure Collaboration Diagrams

System Interaction Diagrams


Behaviour Activity Diagrams
State Charts
20
Use Case Modelling

12/30/2021 21
Use Case Model
 Consists of a set of “use cases”

 It is the central model:


 Other models must conform to this
model

 Not really an object-oriented model

A functional model of the system 22


A Use Case
 A way in which a system can be used by
the users to achieve specific goals

 Corresponds to a high-level requirement.

 Defines external behavior without


revealing internal structure of system

 Set of related scenarios tied together


by a common goal. 23
Use Cases Cont…

 Normally, use cases are independent of


each other

 Implicit dependencies may exist

 Example: In Library Automation System,


renew-book and reserve-book are
independent use cases.
 But in actual implementation of renew-book---
A check is made to see if any book has been
reserved using reserve-book. 24
Example Use Cases
 Library information system
 issue-book

 query-book

 return-book

 create-member

 add-book, etc. 25
Representation of Use Cases
 Represented in a use case diagram
 A use case is represented by an ellipse
 System boundary is represented by a
rectangle
 Users are represented by Play Move

stick person icons (actor)‫‏‬ Tic-tac-toe game

 Communication relationship between actor


and use case by a line
 External system by a stereotype 26
What is a Connection?
 A connection is an association between
an actor and a use case.

 Depicts a usage relationship

 Connection does not indicate data flow

Play Move

Tic-tac-toe game

27
Use Case Modelling
(Lecture 6) 19-08-2015

28
Exercise1: Video Store Information System
 Video Store Information System supports the
following business functions:
 Recording information about videos the store owns
 This database is searchable by staff and all customers

 Information about a customer’s borrowed videos


 Access by staff and also the customer. It involves video
database searching.

 Staff can record video rentals and returns by


customers. It involves video database searching.
 Staff can maintain customer, video and staff
information.
 Managers of the store can generate various reports.
29
Exercise 1: Solution
Video Store Information System

Rent/Return
Videos
«include» Customer
Staff

Search for
Videos
Maintain
Customers
«include»

Maintain
Videos

Manager Generate
Reports

30
Effective Use Case Modelling
 Use cases should be named and organized
from the perspective of the actor.

 Use cases should start off simple and at


as much high view as possible.
 Can be refined and detailed further.

 Use case diagrams represent


functionality:
 Should focus on the "what" and not the
31

"how".
An Example Use Case Diagram

Play Move

Tic-tac-toe game
Player

Use case model

32
Relationships between Use Cases
and Actors
 Actors may be connected to a use
case by association relation:
 Indicating that the actor and the use
case communicate with one another.

update
grades

faculty 33
Another Example Use Case Diagram

Video Store
Information System

Rent
Videos
Clerk <<external system>>
Credit Authorization
. . . Service

34
Yet Another Use Case Example

Telephone Catalog

Check
Status Salesperson

Place
Order

Fill Orders Shipping


Customer Clerk

Establish
credit

Supervisor
35
Why Develop A Use Case Diagram?
 Serves as requirements specification
 How are actor identification useful in
software development?
 Identifies different categories of users:
 Helps in implementing appropriate interfaces
for each category of users.

 Helps in preparing appropriate documents


(e.g. user’s manual). 36
Use Case Description: Change Flight
 Actors: traveler
 Preconditions:
 Traveler has logged on to the system and selected ‘change
flight itinerary’ option
 Basic course
1. System retrieves traveler’s account and flight itinerary
from client account database
2. System asks traveler to select itinerary segment she
wants to change; traveler selects itinerary segment.
3. System asks traveler for new departure and destination
information; traveler provides information.
4. If flights are available then
5. …
6. System displays transaction summary.
 Alternative courses
4. If no flights are available then … 37
ATM Money Withdraw Example
 Actors: Customer
 Pre Condition:
 ATM must be in a state ready to accept transactions
 ATM must have at least some cash it can dispense
 ATM must have enough paper to print a receipt

 Post Condition:
 The current amount of cash in the user account is the
amount before withdraw minus withdraw amount
 A receipt was printed on the withdraw amount 38
ATM Money Withdraw Mainline Scenario
Actor Actions System Actions
1. Begins when a Customer arrives
at ATM
2. Customer inserts a Credit card 3. System verifies the customer ID
into ATM and status
5. Customer chooses “Withdraw” 4. System asks for an operation type
operation
7. Customer enters the cash 6. System asks for the withdraw
amount amount
8. System checks if withdraw amount
is legal
9. System dispenses the cash
10. System deduces the withdraw
amount from account

11. System prints a receipt


13. Customer takes the cash and 12. System ejects the cash card
the receipt 39
ATM Money Withdraw (cont.)
 Alternative flow of events:
 Step 3: Customer authorization failed. Display an
error message, cancel the transaction and eject the
card.
 Step 8: Customer has insufficient funds in its account.
Display an error message, and go to step 6.
 Step 8: Customer exceeds its legal amount. Display an
error message, and go to step 6.

 Exceptional flow of events:


 Power failure in the process of the transaction before
40
step 9, cancel the transaction and eject the card.
Guidelines for Effective Use Case Writing
 Use simple sentence

 Do not have both system and


actor doing something in a System Actor
Actor asks for money
single step
System asks for amount

 Bad: “Get the amount from the Actor gives the amount

user and give him the receipt.” System produce the money

 Any step should lead to some


progress:
Bad: “User clicks a key”
41

Identification of Use Cases
1. Actor-based:
- Identify the actors related to a system or
organization.
- For each actor, identify the processes they
initiate or participate in.

2. Event-based
- Identify the external events that the system
must respond to.
- Relate the events to actors and use cases. 42
Factoring Use Cases
 Two main reasons for factoring:
 Complex use cases need to be factored
into simpler use cases
 To represent common behavior across
different use cases
 Three ways of factoring:
 Generalization

 Include

 Extend 43
Generalization
 The child use case inherits the

behavior of the parent use case.


 The child may add to or override
some of the behavior of its parent
parent.

child
44
Generalization Example 1

Registration

Under-graduate Graduate
registration registration
45
Factoring Use Cases Using
Generalization

Pay membership fee

Pay through credit card Pay through library pay card

46
Factoring Use Cases Using Include

<<include>> Common
Base use case
use case

Base use case 2 Base use case 1

<<include>> <<include>>

<<include>> <<include>>

Common use case 1 Common use case 2 Common use case 3

48
Example of Factoring Use Cases
Using Includes

Issue Book Renew Book

<<include>>
<<include>>

Check Reservation
49
Factoring Use Cases Using
Extends

Base <<extend>> Common


use case use case

51
Factoring Use Cases Using
Extends

Order <<extend>> Show


Item Catalog

52
Extension Point
 The base use case may include/extend
other use cases:
 At certain points, called extension
points.

 Note the direction of the arrow

<<extend>>
Perform Sale Product is a gift
Gift wrap
After checkout Product

53
Use Case Relationships

Order
Supply
Product
Customer Arrange
Data Payment
<<include>>
<<include>>
<<include>>
Place Order
Cash Credit
Payment Payment
Sales Person
<<extend>>
Salesperson asks for
catalog

Request
Catalog
54
Exercise 2: Use Case Model for Course Management Software
 At the beginning of each semester,
 Each professor shall register the courses that he is going to
teach.
 A student can select up to four-course offerings.
 During registration a students can request a course catalogue
showing course offerings for the semester.
 Information about each course such as professor, department
and prerequisites would be displayed.
 The registration system sends information to the billing
system so the students can be billed for the semester.
 For each semester, there is a period of time during
which dropping of courses is permitted.
 Professors must be able to access the system to see
which students signed up for each of their course
55
offerings.
Exercise 2: Answer
Course Management Software

Register
offering
See
Course
Professor Show List
registration
<<Extend>>

<<External>>
Register
Billing System
course
Student

Drop
Course

Calendar
56
Hierarchical Organization of Use
Cases
use case 1 use case 3 External users

use case 2

use case 3.1 use case 3.3

Subsystems
use case 3. 2

use case 1 use case 3

Methods
use case 2
57
Too many use cases
at any level should
be avoided!

58
Use Case Packaging

Accounts

Print
Query balance
Balance sheet

Receive Make
grant payments

59
Use-Case Model using Packaging

60
Use Cases of Order Entry Subsystem

61
Use Case Description

Name
Actors
Trigger
Preconditions
Post conditions

Success Scenario
Alistair Cockburn
“Writing
Effective Use
Cases”
Alternatives flows
62
Triggers
 What starts a use-case?
 Examples:
 Customer initiates a claim report by
clicking a button on a web page
 Customer inserts ATM card
 System clock is 10:00
 etc. 63
Preconditions
 What the system needs to be true
before running the use-case.
 Examples:
 The use has logged on
 Requested Book is issued out
 User account has been created
 The membership has expired
64
Post-Conditions
 A post-condition is the outcome of a use-case.
 Examples:
 Money is transferred to the user account
 User is logged in
 The file is saved to the hard-disk
 Minimal guarantee:
 The things that a system can promise, holding even
when the use case execution ended in failure
 Example: Money is not transferred unless
authorization is granted by the user
 Success guarantee:
 What happens after a successful conclusion of the use-
case.
65
 Example: Transaction logged; Money is transferred
Success Scenario
 The success scenario is the main story-line of
the use-case:
 Under the assumption that everything is okay, no
errors or problems occur
 Typically, it is composed of a sequence of action
steps Interaction
step

1. Administrator enters course name, code and description


Validation
2. System validates course code Step
3. System adds the course to the db and shows a confirmation message
Interaction
Step
Internal Change
66
Step
67
68
69
Example: Online HR System

Online HR System

Recruit
Employee
Manager
Update
Employee
Profile

Update
Benefits
Employee Healthcare
Plan System
Access Pay
Records

Access
Travel
System
Insurance
Plan System
70
Online HR System: Use Case
Relationships
Update
Update Dental Plan Update
Medical Plan Insurance
Plan
<<include>>

<<include>> <<include>>
Update Benefits
Extension points Extension point
benefit options : name and location
After required enrollments
Employee
<<extend>>
Employee requests stock
<<extend>> purchase options
Employee requests
reimbursement options
Select stock
option
Select
Reimbursement
Extension
for health care condition
71
Online HR System: Update Benefits Use Case
Actors : employee, employee account db, healthcare plan system,
insurance plan system
Preconditions:

Employee has logged on to the system and selected ‘update


benefits’ option
Basic course
 System retrieves employee account from employee account db
 System asks employee to select medical plan type; include

Update Medical Plan.


 System asks employee to select dental plan type; include

Update Dental Plan.


 …

Alternative courses
If health plan is not available in the employee’s area the
employee is informed and asked to select another plan... 72
Style Notes (Ambler, 2005)
 Use case name should begin with a verb.
 While use cases do not explicitly imply timing:
 Order use cases from top to bottom to imply timing -- it
improves readability.

 The primary actors should appear in the left.


 Actors are associated with one or more use cases.
 Do not use arrows on the actor-use case relationship.
 To initiate scheduled events include an actor called
“time”
 Do not show actors interacting with each other.
73
 <<include>> should rarely nest more than 2 deep.
Interaction Diagrams
Lecture 8

74
Quiz: Home Assignment System - Use Case Model
 HAS will be used by the instructor to:
 Distribute the homework assignments,
 Review the students’ solutions,
 Distribute suggested solution,
 Assign grade to each assignment.
 Students can:
 Download assignments
 Submit assignment solutions
 System:
 Automatically reminds the students a day before an
75
assignment is due.
Quiz: Solution 1 (Inferior)
Remind
Student

Calendar Distribute Get


Assignments Assignment

Submit
<<Extends>>
Post Solutions Assignment

Student
Distribute Get
Grade Solution
Instructor

Get Grade
76
Quiz: Alternate (Better) Solution

Distribute
Assignments

Post Solutions

Student
Distribute
Grade
Instructor
Submit
Assignment

Remind
Student
Calendar
77
Class Diagram: Already Discussed!!
 Describes static structure of a
system
 Main constituents are classes and
their relationships:
 Generalization

 Aggregation

 Association

 Various kinds of dependencies 78


Class Diagram
 Classes:
 Entities with common features, i.e. attributes
and operations.
 Represented as solid outline rectangle with
compartments.
 Compartments for name, attributes, and
operations.
 Attribute and operation compartments are
optional depending on the purpose of a
diagram. 79
Summary of Relationships Between
Classes
 Association
 Permanent, structural, “has a”
OR
 Solid line (arrowhead optional)
 Aggregation
 Permanent, structural, a whole created from parts
 Solid line with diamond from whole
 Dependency
 Temporary, “uses a”
 Dotted line with arrowhead
 Generalization
 Inheritance, “is a”
 Solid line with open (triangular) arrowhead
 Implementation
 Dotted line with open (triangular) arrowhead
80
Object Diagram
LibraryMember

Mritunjay LibraryMember
LibraryMember
B10028
C-108, Laksmikant Hall Mritunjay
1119 B10028
Mrituj@cse C-108, Laksmikant Hall
25-02-04 1119
25-03-06 Mrituj@cse
NIL 25-02-04
25-03-06
IssueBook( ); NIL
findPendingBooks( );
findOverdueBooks( );
returnBook( );
findMembershipDetails( );

Different representations of the LibraryMember object


81
Interaction Diagram
 Can model the way a group of objects
collaborate to realize some behaviour.

 How many interaction diagrams to


draw?
 Typically each interaction diagram
realizes behaviour of a single use case

 Draw one sequence diagram for each


use case. 82
Interaction Diagrams
 Three kinds:
 Interaction overview diagram
 Sequence and Collaboration (now communication
in UML 2.0) diagrams.
 Sequence and Collaboration diagrams are
equivalent:
 Portray different perspectives
 As we shall see:
 These diagrams play a very important role in
83
the design process.
Interaction Overview Diagram
 Focuses on the overview of the flow
of control of the interactions.

 It is a variant of the Activity Diagram:

 Nodes are the interactions or interaction


occurrences.

 Describes the interactions where messages


and lifelines are hidden. 84
85
A First Look at Sequence Diagrams
 Captures how objects interact with
each other:
 To realize some behavior.
 Emphasizes time ordering of
messages.
 Can model:
 Simple sequential flow, branching,
86 86
iteration, recursion, and concurrency.
Develop One Sequence diagram
for every use case

Return
Book member: book:Book :Book
LibraryMember Copy

Use ok = canBorrow()

Case borrow(book)

Borrow
Book [ok] borrow(member)

setTaken(member)
Search
Book

87
87
Sequence Diagram
 Shows interaction among objects as a two-
dimensional chart

 Objects are shown as boxes at top


 If object created during execution:
 Then shown at appropriate place in time line

 Object existence is shown as dashed


lines (lifeline)‫‏‬
 Object activeness, shown as a rectangle
88
on lifeline
Sequence Diagram Cont…

 Messages are shown as arrows.


 Each message labelled with
corresponding message name.
 Each message can be labelled with some
control information.
 Two types of control information:
 condition ([])‫‏‬
89
 iteration (*)‫‏‬
Gist of Syntax
 iteration marker *[for all objects]
 [condition]
 themessage is sent only if the condition is
true
 self-delegation
a message that an object sends to itself
 Loops and conditionals:
 UML2 uses a new notation called
interaction frames to support these 90
Control logic in Interaction Diagrams
 Conditional Message
[ variable = value ] message()
 Message is sent only if clause evaluates
to true
 Iteration (Looping)
* [ i := 1..N ] message()
 “*” is required; [ ... ] clause is optional
 The message is sent many times to
91

possibly multiple receiver objects.


Elements of A Sequence Diagram
X-Axis (objects)

member: book:Book :Book


LibraryMember Copy

borrow(book) Life Line


Object
ok = canBorrow()
Y-Axis (time)

message
Activation
[ok] borrow(member) box
setTaken(member)

condition

How do you show Mutually exclusive conditional message?


92 92
Sequence Diagrams
How to represent Mutually exclusive conditional
messages? Eg. msg2 to ClassB or msg3 to classC,

:ClassA :ClassB :ClassC

msg1( )

[flag = true] msg2( )

[flag = false] msg3( )

93
Representing an object
 Class name, optionally preceded by object
name and colon:
 write object's name if it clarifies the diagram
 object's "life line" represented by dashed
vertical line Anonymous object Object of
Object
unknown Class

Smith :
:Patient Smith
Patient

Active object Object


LifeLine

94
Name syntax: <object name>:<class name>
Messages between objects
 Message (method call) indicated by a horizontal
arrow to other object:

[registered] Admit (pateintID, room type)


: Hospital
 Dashed arrow back indicates return
 different arrowheads
Sync/Async calls
:Controller

:Controller :Controller

95
asynchronous
return
95
Message Arrows for Communication
 Message arrows represent communications
between two objects in a sequence diagram
 Synchronous message :
 Sending object suspends action and waits for the
response to the message
(filled head)
 Asynchronous message:
 Sending object continues with its operations without
waiting for the response
(open head)

 A return of control from the synchronous


message 96

 A creation of a new entity


Asynchronous Messages
 An example of this is a Timer in Java:
 An object that implements ActionListener may
register itself as a listener for a Timer object

 The Timer object will store a handle to the object,

 Later, when the Timer expires, an event will be issued


to the object's 'actionPerformed' method

 Obviously, if the object had to wait for the timer


to expire:
 It could have missed a long period of potential
computation time. 97
Asynchronous Messages Example

:ActionListener inv:Inventory

addActionListener(self:ActionListener)
Time

…continue operation…

The eventual
response is
actionPerformed(e: ActionEvent) called a callback

98
Return Values
 Optionally indicated using a dashed
arrow:
 Label indicates the return value.
 Don’t
need when it is obvious what is being
returned, e.g. getTotal()
 Model a return value only when you
need to refer to it elsewhere:
 Example:A parameter passed to another
message. 99 99
Summary of Kinds of Arrows
Procedure call or other kind of nested
flow of control
(The sender losses control until the
receiver finishes handling the message)

Flat flow of control(The sender does


not expect a reply)

Explicit asynchronous flow of control


(The sender does not expect a reply, stays
active and may send further messages)

Return
(Unblocks a synchronous send) 100
Synchronous Messages
 Flow of control, typically implemented as a
method call.
 The routine that handles the message is
completed before the caller resumes execution.

:A :B
doYouUnderstand()

return
Caller (optional)
Blocked yes

101 101
Lifetime of objects
 creation: arrow with
'new' or create written
above it
 Notice that an object
created, appears at point
of call.
 deletion: an X at bottom
of object's lifeline
 Java doesn't explicitly
delete objects; they fall
out of scope and are
garbage-collected 102
102
Method calls
 Activation: thick box over object's life line; drawn
when object's method is on the stack
 Either that object is running its code, or it is on
the stack waiting for another object's method to
finish
 Nest to indicate recursion
Activation
:Controller

Nesting

Activation 103
Elements of a Sequence Diagram
: Customer : Order : Pay ment : Produc t : Supplier

object
plac e an order

process
Activation lifetime
validate

if ( payment ok )
if ( not i n stock )
deli ver
back order

get address

mail to address
message
104
Example
Cont…
: Customer : Order : Pay ment : Produc t : Supplier

plac e an order

process

validate
Sequence of message sending

if ( payment ok )
if ( not in stock )
deliver
back order

get address

mail to address

105
An Example of A Sequence Diagram
:Library
:Library
:Library Book :Library
Book :Book
Boundary Renewal Member
Register
Controller

renewBook find MemberBorrowing


displayBorrowing
selectBooks bookSelected
* find
[reserved]
[reserved] apology
update
apology

confirm

confirm
updateMemberBorrowing

106
Sequence Diagram for the renew book use case
Method Population in Classes
 Methods of a class are determined
from the interaction diagrams…
:Registration :Registration
form manager

RegistrationManager
add course
(joe, math 01)
addCourse(Student,Course)

107
Example Sequence Diagram:
Borrow Book Use Case

member: book:Book :Book


LibraryMember Copy

borrow(book)
ok = canBorrow()

[ok] borrow(member)
setTaken(member)

108
Object Creation
 An object may create another object
via a <<create>> message.

:A
<<create>>
:B

109
Object Destruction
 An object may destroy another object via a
<<destroy>> message.
 An object may also destroy itself.
 But, how do you destroy an object in Java?
 Avoid modeling object destruction unless memory
management is critical.

:A :B
<<destroy>>

110
Control Information
 Iteration example UML 1.x:

:CompoundShape :Shape
draw()
*draw()

111
Exercise 0
 A user can use a travel portal to plan a
travel
 When the user presses the plan button, a
travel agent applet appears in his window
 Once the user enters the source and
destination,
 The travel agent applet computes the route and
displays the itinerary.
 The travel agent widget gets destroyed and
112
disappears
Exercise 0: Solution

:client

plan
<<create>> :travelAgent

setItinerary
calculateRoute

<<destroy>>

113 113
Exercise 1
 A clerk in the RTO office uses a traffic violation
application to find the details of any traffic
violation by entering the violation id.
 The clerk first presses the view button in the
dialog box of the application.
 This request is conveyed to the controller object
 The controller object asks for the violation id

 Once the clerk enters the violation id, the


controller queries the DBproxy object using the id
 Based on the response received from the DBProxy, the
controller creates a violation object and passes it to
114
the dialog box for display by calling its display method.
Exercise 1: Lookup Traffic
Violation
:Violations :Violations :Violations
Dialog Controller DBProxy
Clerk
lookup
viewButton()

id=getID()

getViolation(id)
<<create>>
v:Traffic
May be a Violation
pseudo-
method
v DB is
display(v) queried and
the result is
returned as
an object

115 115
Exercise 2: Print Server
 A print server is an active object

 Client applications send jobs to the print


server

 The print server enqueues the object by


calling a queue object

 The job server takes up jobs one by one


from the queue and prints them by sending
them to the printer proxy 116
Exercise 2: Solution
Printing A
Document

Active :Printer
object :PrintServer :Queue Proxy
Client
Application
print(doc,client) enqueue(job)

loop queue-not-empty()
job=dequeue()

[job]print(job.doc)

status
[job] done(status)

117 117
Guards in Communication Diagrams

Conditional Message with Test

message

[color = red] calculate


:Foo :Bar

118
Sequence Diagram: Frames
 A frame consists
of:
1) Diagram identifier order process
2) Participants in a
rectangle depicting :client :order :inventory
the participating
objects: create
Locate item
 A dotted line that
extends for the time
period of the
interaction
3) Messages to
communicate among
119
the participants
Example Sequence Diagram
order
:StoreFront :Cart :Inventory

loop
AddItem
ReserveItem

Need not show:


Implicit Return
Checkout
ConfirmOrder ProcessOrder

PlaceItemInOrder

120
Interaction Frame
op (operator):
applied to the enclosed interaction(s)
(some operators require arguments, such as diagrams names,
parameters, constants and guards)

[guard]:
a boolean expression
op [:arguments] [ [guard] ] the interaction is executed according
to the guard’s value

diagram name | interaction Interaction frame:


a (fragment of a) sequence diagram

diagram name:
needed if we want to refer to a diagram defined elsewhere
121
Depicting a Fragment Graphically
sd sample

client order inventory


Interaction
Fragment

create

operator op1
Interaction
Fragment
Operation
Name: Interaction
(e.g. loop) Fragment
Operand

Locate item

122
Interaction Frame Example
op [guard_1]

interaction_1


[guard_n]
interaction_n

 Divided into a set of interactions by dotted


lines
 interaction_i is executed if guard_i is true
123
Frame Operators
Frame Meaning
Operator

Alt Alternative fragment for conditional logic


expressed in the guards

Loop Loop fragment while guard is true. Can also


write loop(n) to indicate looping n times.

Opt Optional fragment that executes if guard is


true
Par Parallel fragments that execute in parallel

Region Critical region within which only one thread


can run
124
Fragment Operators: Full List
 Conditional: operator “opt”
 Loop: operator “loop”
 Branching: operator “alt”
 Reference: operator “ref”
 Parallel: operator “par”
 Critical Region: operator “critical”
 Interrupt: operator “break”
Assertion: operator ‘’assert’’
125

Repeating Message

126
Sequence Diagram for Telephone Order
Scenario

127
Alternative Fragment
sd sample

Interaction
Interaction client order inventory Fragment
Fragment
Operation
Name:
(Alternative)
Alt [new_cust=yes]

cr_custinfo()

Interaction [new_cust= no]


Fragment
guard
get_custinfo()

Cr_order( )

Interaction
Fragment
128
Operands
Loop Fragment
sd
sample order inventory
n_it = check_items()
checking
Interaction create
Fragment iterator for
more
Operation more = has_item items
Name: (n_it)
Loop (min,max)
Loop [more]

Process_item()

The guard
expression of
[ more] more =
has_item(n_it)

129
Interaction Frames for Indicating selection and loops
 Frame: box around part of a sequence diagram to
indicate selection or loop
 if -> (opt) [condition]
 if/else -> (alt) [condition], separated by horiz. dashed line
 loop -> (loop) [condition or items to loop over]

opt [balance
<> 0] alt [balance
< 100.00]

[balance
>= 100.00]

loop [balance
< 0]

130
130
Linking Sequence Diagrams
 If one sequence diagram is too large or refers to
another diagram, indicate it with either:
 an unfinished arrow and comment
 a "ref" frame that names the other diagram

Customer Info ref

Verify customer credit

Approved?

131
Logic in sequence diagrams: Which notation do you prefer?

:Foo :Bar
xx
opt [color = red] calculate

yy

:Foo :Bar
xx
[color = red] calculate
yy 132
Nesting Frames
:Foo :Bar
xx

opt
[colour : red]
Loop(n)

calculate

133
:Employee :EmployeeDB

Emp=getEmployee(empId)

Public class EmployeeDB{


public Employee getEmployee(String empId){

}
} 134
:ShapeFactory

makeSquare
new
:Square

Public class ShapeFactory{


public Shape makeSquare(){
return new Square(); }
} 135
Exercise 3

:TreeMap :TreeNode
clear
destroy

Public class TreeMap{


private TreeNode t;
Write
Java Code public void clear(){
t=null;
}
136
}
PurchaseItem Use Case: Sequence Diagram
:Controller
Write
purchase
Java Code
new :Purchase

public Class Controller buyGrocery


{
private Purchase myPurchase; create(cashTender) :Payment

private Payment myPayment;


public void purchase() {
myPurchase = new Purchase();
myPurchase.buyGrocery();
myPayment = new Payment( cashTender );
}
// . .
137 137
}
create

138
139
Sequence Diagram : Enroll Student

u:URSDatabase stu:Student

procCmd(cmd)
parseCommand(cmd)

new a:AssgSubCmd

execute()

getStudent(id)

return stu

getSubject(subId)
[if stu != NULL and sub !=
return sub NULL]
addSubject(sub)
140
Exercise 6
class AssgSubCmd{ Write
Java Code
private URSDatabase u;
public execute(){
Student stu = u.getStudent(id);
Subject sub = u.getSubject(subId);
if (stu != null && sub != null){
stu.addSubject(sub);
}
}
} 141
Exercise 7: Java Code for Sequence Diagram

:Account :Order :ShoppingBasket

alt
ref
[ValidUser]

placeOrder(Order: iOrderNo)

return()

return()

142
public void newTransaction(){
// behavior is an Interaction
if (ValidUser) // Alt combined fragment
{
placeOrder(101); //Interaction Occurrence
}
else
{
return;
}
}
143
Exercise 8: Sequence Diagram
 “Compute Price” use case is invoked in
the context of a specific order to
calculate the price of the order.

 Al the line items are examined to determine


their prices, which are based on the pricing
rules of the order line’s products.

 Then the overall discount is computed, which


144
is based on rules tied to the customer.
Solution : First Identify Classes
 “Compute Price” use case is invoked in
the context of a specific order to
calculate the price of the order.

 Al the line items are examined to determine


their prices, which are based on the pricing
rules of the order line’s products.

 Then the overall discount is computed, which


145
is based on rules tied to the customer.
Exercise 8: Example Answer

:Customer :Order :OrderLine :Product


calculatePrice
Loop
getQuantity

getProduct

getPricingDetails

getDiscountInfo

calculateDiscounts

146
Exercise 9: Consider the following Java code.
Draw a sequence diagram to represent the
message exchanges that occur among objects
when the printGameMoney() method of the
Game class is invoked.
class Ticket {
int gameID;
double price;
int seatnumber;
public int getPriceOfTick();
}
Class Game{
private List <Ticket> tickets=new Arraylist<Ticket>();
public static int printGameMoney(){
double total = 0;
for (final Ticket ticket : tickets) {
final double tickMoney = ticket.getPriceOfTick();
total = total + tickMoney;
}
} 147

}
Exercise 9: Solution
Ex.9

client Game Ticket

Print
Game
Money
Loop For all
Tckets
Get
Ticket
Price

148
 Exercise 10: Draw a sequence diagram to
represent the following interactions between a
video store clerk and objects in a video rental
system. The scenario is name is rent video:
 Clerk creates new a Rental object named
aRental.The message includes arguments for
memberID and videoID.
 aRental sends addMemberToRental message to
Member object based on memberID, named
aMember, which returns member details.
 aRental sends rentVideo message to a Video
object based on the videoID, named aVideo,
which returns video details.
149
 aRental returns all rental details to the actor.
Video
Clerk aMember aVideo

aRental
create(memberID,videoID)

addMembertoRental()

Member details

rentVideo()

Video details

Rentaldetails

150
Exercise 11: Change Flight Itinerary
 Actors: traveler, client account db, airline
reservation system
 Basic course:
 Traveler selects ‘change flight itinerary’ option
 System retrieves traveler’s account and flight itinerary from
client account database
 System asks traveler to select itinerary segment she wants to
change; traveler selects itinerary segment.
 System asks traveler for new departure and destination
information; traveler provides information.
 If flights are available then …
 …
 System displays transaction summary.
 Alternative course: 151
 If no flights are available then…
Example Answer: Change Flight Itinerary

Traveler : Booking System Client Account DBMS Airline Reservation System


change flight itinerary
get customer account

get itinerary
present itinerary

select segment

present detailed info

update information
available flight

:
:

152
Sequence diagram exercise 12
 Use Case: Add Calendar Appointment: Scenario
begins when the user chooses to add a new
appointment in the UI.
 The UI notices which part of the calendar is active
and pops up an Add Appointment window for that date
and time.
 The user enters the necessary information about
the appointment's name, location, start and end
times.
 The Appointment window will prevent the user from
entering an appointment that has invalid information,
such as an empty name or negative duration.
 The calendar records the new appointment in the 153
user's list of appointments. 153
Sequence diagram exercise 12
Use Case: Add Calendar Appointment:
Alternate scenario: If the user has an appointment at that
time, the user is shown a warning message and asked to
choose an available time or replace the previous
appointment. If the user enters an appointment with the
same name and duration as an existing group meeting, the
calendar asks the user whether he/she intended to join
that group meeting instead. If so, the user is added to
that group meeting's list of participants.

154
154
Activity Diagrams
Lecture 9

155
Collaboration Diagram
 Known as Communication Diagram in UML 2

 Shows both structural and behavioural


aspects:
 Objects are collaborator, shown as boxes
3 : notify()
 Messages between objects 4 : update() s1 :StockQuote
Subscriber
1 : attach(s1)
6 : getState()

shown as labelled arrow p : Stock


QuotePublisher 5 : update()

placed near links 2 : attach(s2)


7 : getState()
s2 :StockQuote
Subscriber

 Messages are prefixed with sequence


numbers to show relative sequencing 156
Interaction Diagram: sequence vs communication
objects

p : StockQuotePublisher s1 : StockQuoteSubscriber s2 : StockQuoteSubscriber

attach(s1)
attach(s2) Procedure call, RMI, JDBC, …

Observer
Time notify() design
pattern
update()
{update < 1 minutes}
getState()
update()
getState()

3 : notify() 4 : update()
s1 :StockQuoteSubscriber
1 : attach(s1)
6 : getState()
p : StockQuotePublisher 5 : update()

2 : attach(s2) s2 :StockQuoteSubscriber
157 157
7 : getState()
Another Example Collaboration Diagram
6: * find
:Library
Book :Book
[reserved] Register
9: update
8: apology 5: book 10:
Selected confirm

1: renewBook :Library [reserved]


:Library Book 7: apology
Boundary 3: display Renewal
Borrowing Controller

4: selectBooks
2: findMemberBorrowing

12: confirm
:Library
Member

updateMemberBorrowing

Collaboration Diagram for the renew book use case 158


Quiz: Write Code for class B

a:A

m1
create
:B
flag=doA(this)
create
doB(c) c:C

159
Quiz: Ans
public class B {

int doA(A a) {
int flag;
C c = new C();
a.doB(c); …
return flag; }
}
160
Activity Diagram
 Not present in earlier modelling techniques:
 Possibly based on event diagram of Odell [1992]

 Often used to represent processing steps


in a single or a group of use cases:
 May not correspond to methods

 An activity is a state with an internal


action and has one or more outgoing
transitions, e.g. fillOrder.
 Vaguely similar to a flowchart 161
Activity Diagram
 Normally employed in business
process modelling.
 Spans one or more use cases

 Carried out during requirements


analysis and specification stage.
 Useful in developing interaction
diagrams and test cases. 162
Activity diagram Example
[order reject]

Receive Fill Close


Ship
Order Order Order
Order
[order
accepted]

Send
Invoice Make Accept
Invoice Payment Payment

163
Activity Diagram Elements
 Initial node
 Activity final node
 Action
 Flow/edge
 Fork
 Join
 Decision
 Merge
 Synch 164
Activities, Actions, Events
 Activities are operations that take time and
can be interrupted:
 Accessing a web page.
 Writing to a disk.
 Often modeled as nested states.
 Actions are of very short duration and cannot
be interrupted:
 Beep.
 Display a menu.
 Set a flag.
 Events cause changes in state:
 State transitions can trigger actions.
165
 Transitions are essentially instantaneous.
Actions
 The fundamental unit for execution
or behavior.
 Represents some transformations or
processing in the modeled system
 Examples: creating objects, setting
attribute values, linking objects together,
invoking user-defined behaviour, etc.
Receive
order Description of
the action
166

behaviour
Basic Elements—Action
 A rounded rectangle represents an
action.
 Example: Customer calls ticket
office

Customer Calls
Ticket Office

167
Activity Diagram (continued)
 Transitions in an activity diagram do
not have labels:
 They indicate the completion of an
action

 An activity diagram may describe a


use case, an operation or a message
 Purpose: to describe details that may be
useful in implementation. 168
Controlling Steps
 Inherited from state machines

 Initial state

 Final state

 Fork and join

169
 Decision point and merge ( ):
 Inherited from state machines.

Calculate [cost < 50] Charge


Cost Account

[cost >= 50]

Get
Authorization

170
Decision
• A diamond with one flow entering and
several leaving.
[Drink contains
alcohol]
[Customer Is
less than 21
Years Old]

Customer
Orders Drink
[else]
[Customer Is
At least 21
Years Old] Get Drink For
Customer

171
Activity Diagram Nodes
 Three type of nodes:
Receive
 Action nodes: executable activity order

 Control nodes: coordinate flows in an


activity diagram between nodes

 Object nodes: indicate an instance of a


particular object, may be available at a
particular point in the activity 172
Basic Elements--Initial state
 The filled circle is the initial state:
 The staring point of the diagram.

First Action To
DO

173
Basic Elements—Final node
 The filled circle with a border as
the ending point.
An activity diagram can have zero
or more activity final nodes

First Action
To DO

174
Fork
 Denotes the beginning of parallel
actions.
Verify Order
Products Are In
Stock

Receive
Order
Verify Customer
Has Available
Credit

175
Join
 Models Synch with several flows entering and
one leaving.
 All incoming flows must reach it before
processing may continue.
 This denotes the end of parallel processing.
Verify Order
Products Are In
Stock

Accept Order

Verify Customer
Has Available
Credit
176
Customer Sales Stockroom

Request
service

Take
Order
Pay
Fill Order

Deliver
Collect order
order

C-S 546 177 177


Object Flow
Order
Take Order Fill Order
[Taken]

 Take Order must have an output parameter


giving an order, or one of its subtypes.

 Fill Order must have an input parameter


taking an order, or one of its supertypes.

 Dashed lines used with object flow have


the same semantics as normal transition. 178
Customer Sales Stockroom
The transition between an object
parameters and an action state is
Request
service represented with a dashed line,
: Order
[placed]
instead of a solid line
:Order
[entered]
Take Order
Pay
Fill Order
: Order
[filled]

:Order
[delivered]

Collect Deliver
order order
179
Signals
 An Activity diagram can show response
to signals.
 A signal indicates that the activity
receives an event from an outside process.
 The activity listens those signals, and the
diagram defines how the activity reacts.

 A time signal occurs on passage of time


 For example, each month end might trigger a
signal. 180
Signals
 Using signals we can send a message and
then wait for a reply before we can
continue.
 Basically, the signals are flow triggers.

Send signal Time signal Accept signal


181
Process Request Receive Ship
Order Payment Payment
Order

Report
Receive Cancel Meter
Cancel Order
Request Reading
At end of
month

182
Activity Diagram vs Flow Chart
 Can represent parallel activity and
synchronization aspects
 Swim lanes can be used:
 To group activities based on who is
performing them

 Example: Academic department vs.


Hostel 183
Activity Diagram Example: Student
Admission initial

Initialize activity

Add student

fork/spawn

Notify Teacher Notify Billing

Synchronization
[else]
[ count < 10 ]
guard

Close course final


184
Another Example Activity Diagram:
student admission process at IIT
Academic SectionAccounts Section Hostel Office Hospital Department

check
student
records
receive
fees

allot create
hostel hospital
record
register
receive
in
fees
course
conduct
allot medical
room examination

issue
identity card 185
Activity Diagram: Example 3
Finance Order Stock
Processing Manager
Receive
Order Receive
Supply

*[for each line


item on order]
Choose
Check Outstanding
Authorize [failed] Line Item Order Items
Payment
* [for each chosen
Cancel [in stock] order item]
Order

Assign to Assign
[succeeded] Order Goods to
Order

[need to reorder]
Reorder
Item

[stock assigned to all [all outstanding


line items and payment order items filled]
authorized]
Dispatch
Order 186
Activity Diagram Example 4

Customer Telesales Accounting Warehouse

Request
Return
Get Return
Number
Ship Item
Receive
Item
Item
[returned]
Restock
Item

Credit Item
Account [available]

187
Activity Diagram Exercise: Receive Order
 When an order is received, each line item is
checked on the order to see if goods is in stock.
 If in stock, assign the goods to the order.
 If this assignment reduces stock below reorder level,
 Reorder the goods.
 While doing this, it is checked to see if the
payment is OK.
 If the payment is OK and the goods in stock, dispatch
the order.
 If the payment is OK but don’t have the goods, leave
the order waiting.
 If the payment isn’t OK, cancel the order. 188
Activity
Diagram for
Receive Receiving
order
* for each line
Order
item on order

Check line
Authorise item
Payment
[failed] [in stock]
[succeeded] Assign
Cancel to Order
Order
[need to Reorder
reorder] item
[stock assigned
to all line items
and payment
authorised]
Dispatch
Order
189
Activity Diagram Exercise: Receive Supply
 When a supply delivery comes in:
 Outstanding orders are examined to
decide which ones can be fulfilled from
this incoming supply.
 Then assign each o to its appropriate order.

 Doing this may release those orders for


dispatching.

 Put the remaining goods into stock. 190


Activity Receive
Diagram Supply

for
receiving
Choose outstanding
Supply order items
* for each chosen
order item
Assign goods
to order
[all outstanding
order items
filled]

Add remainder
Dispatch
to stock
Order 191
Combined
Receive
Activity
order Diagram Receive
* for each line Supply
item on order
Choose
Check line outstanding
Authorise item
Payment
order items
[failed] [in stock] * for each chosen order item
[succeeded] Assign
Assign goods
Cancel to Order
to order
Order
[need to Reorder
reorder] item
[stock assigned
to all line items [all
and payment outstanding
authorised] order items
Dispatch filled]
Order Add remainder
to stock192
Order Stock
Finance
Processing Manager
Receive
order Receive
* for each line Supply
item on order
Choose
Check line outstanding
Authorise item
Payment
order items
[failed] [in stock] * for each chosen order item
[succeeded] Assign
Assign goods
Cancel to Order
to order
Order
[need to Reorder
reorder] item
[stock assigned
to all line items [all
and payment outstanding
authorised] order items
Dispatch filled]
Order Add remainder
With Swim lanes to stock193
A time signal

Receive Video
Order 30 days since sent last invoice,
and no payment received

Fill Order Send Invoice Resend Invoice What does the Rake
symbol mean?
Deliver
Order

Receive Payment

Accept a signal
Cancel
request

Close Order

Cancel Order

Deliver Order

The "rake" symbol Decision: Any


branch happens.
Mutual exclusion
indicates that the [ else ] [ rush ]

"activity" is complex Merge: Any input leads


to continuation. This is
Deliver Regular Deliver Rush

enough to merit its own in contrast to a join, in


which case all the
194
activity diagram. inputs have to arrive
before it continues.
Decomposing actions
Order
Deliver Order
Receive
order

[Rush order] [else]

Overnight
Regular delivery Receive
delivery
order
Fill order Send invoice

[rush [else] Order


order]
Fill order Send invoice

Overnight Ordinary Receive


delivery delivery payment
subactivity --- rake symbol

Deliver
denoted by action order
Receive
payment

with a “rake”
symbol
Close
order Subactivity has Close
order

input and output


195
parameters
Uses and Abuses of Activity Diagrams
 Activity diagrams are useful to show behavior
that spans over multiple use cases:
 Describe the workflow of the overall process.

 For multiple objects and their high-level


interaction,
 Activity diagrams are particularly helpful for
representing an overview of concurrent processes

 Activity diagrams are not accurate for describing


how an object behaves over its lifetime. Use a
state diagram instead. 196
Quiz 1: Order Processing
 The customer service Department receives order
and sends out invoice to the customer.
 It also passes on the order to the order processing
Department to process the order
 If it is a rush order then the customer service
Department prepares for an overnight delivery by
express mail
 Otherwise it prepares to send by speed post.
 As soon as the payment is received by the finance
Department from the customer:
 The order is dispatched by the customer service
197
Department and it also closes the order.
Customer services
department
Order Processing Receive Finance
department order department

Fill order Send


invoice

[rush order] [Else]

Overnight Ordinary
delivery
delivery Receive
payment

Quiz 1: Close
order
Answer 198
State Machine
Diagrams
Lecture 10

12/30/2021 199
Krishna air travels (KAT) allows its registered customers to book
cars for travel to outstation locations or for drops at the local
Railway station. Before any one can book a car, he/she is required to
register once with KAT by providing name, residential address, phone
number, and identity proof. KAT entertains registration requests
from only the students and faculty members of IIT and rejects
requests received from any other person. Once a request from a
registered student or faculty is received by the KAT reception, the
request is sent to the accounts department who prepare a duty slip
(indicates driver name, Vehicle number, customer name and address,
and the date, time, and other specifics of the travel) and hand it out
to the driver. Whenever, outstation travel is involved, in addition to
duty slip generation, the accounts Department also sends the vehicle
to the maintenance department to make it journey worthy and to fill
up diesel. After the journey is performed, the driver takes the
signature of the customer on the duty slip and hands it over to the
accounts department. The accounts department prepares the bill
that the customer can download online. After the customer pays the
bill online, the records of journey are archived by
the accounts department. Quiz 2 200
1. Develop use case diagram. No text
description is necessary. [8]

2. Develop activity diagram for car booking,


including customer registration process. [10]

3. Design preliminary class diagram [10]

4. Develop a sequence diagram to model


object interactions for booking a car for
station drop [10]
201
Stateless vs. Stateful Objects
 State-independent (modeless):
 Type of objects that always respond the same
way to an event.

 State-dependent (modal):
 Type of objects that react differently to
events depending on its state or mode.

Use state machine diagrams for modeling


state-dependent objects with complex
behavior. 202
Statefull Classes
 Give examples of some classes that have non-
trivial state models:
 Lift controller: Up, down, standstill
 Game software controller: Novice, Moderate,
Advanced…
 Gui: Active, Inactive, clicked once, …
 Robot Game controller: Defensive/Offensive
strategy…
 Controller classes are an important class of
statefull examples:
 A controller may change its mode depending on sensor
inputs and user inputs. 203
Stateful Objects
 The more an object can be regarded as a “pure
server,”
 The more it is likely to be stateless,
 On the other hand, clients are stateful.
 Common stateful objects:
 Controllers:
 A game controller may put the game in expert, novice or
intermediate modes.
 Devices:
 A Modem object could be dialing, sending, receiving, etc.
 Mutators (objects that change state or role)
204
 A RentalVideo is rented, inStore, or overDue
Event-Based Programming
 Traditional programs have single flow of
control
 Represented using flowchart or activity diagram
 Event-driven systems :
 In contrast, depending on an event occurrence,
corresponding handler is activated
 Programming these using traditional approach
often not suitable, and would at the least cause
wasteful computations.
205
 Represented using state machines.
What Kind of Behavior?
 In general, state machines are suitable:
 Fordescribing event-driven, discrete
behavior
 Inappropriate for modeling continuous
behavior

threshold There is no support


currently in UML for
modeling continuous
behavior

206
time
Why Create State Model?
 Tackle complexity
 Document:
 For review, explaining to others,
etc.

 Generate code automatically


 Generate test cases 207
Automata
 A machine whose output behavior is not only
a direct consequence of the current input,
 But past history of its inputs
 Characterized by an internal state which
captures its past history.

ON

OFF

208
Basic State Machine Diagram
 Graphical representation of automata
behavior…
on

Lamp On

on

off
off
Lamp Off
209
Outputs and Actions
 As the automaton changes state, it

generates outputs.
 Alternate representations.
on on
Lamp Lamp On
On display(”on”)

on/display(”on”) on

off off
off off
Lamp Lamp
Off Off

Mealy automaton Moore automaton 210


Event-Driven Behavior
 Event = An observable occurrence of following
 interactions:
 synchronous object operation invocation (call event)
 asynchronous signal reception (signal event)
 occurrence of time instants (time event)
 interval expiry
 calendar/clock time
 change in value of some entity (change event)
 Event Instance = an instance of an event (type)
 occurs at a particular time instant and has no
211
duration
4 Broad Types of Events
 ChangeEvent (i.e.: when(x>y))
 A change event models an explicit boolean expression
becoming true as a result of a change in value of one or
more attributes or associations.
 CallEvent (i.e.: conflictsWith(Appointment))
 A call event represents the reception of a request to
synchronously invoke a specific operation.
 SignalEvent (i.e.: leftButtonDown)
 A signal event represents the reception of a particular
(asynchronous) signal.
 TimeEvent (i.e.: after(1 second))
212
 A TimeEvent models expiration of a specific deadline
Event Examples
Signal event

C ollision
move stop

state transition
state

startAutopilot( normal )
Manual Automatic

Call event

Change event
when( 11:49PM )

Time event

Idle A ctive
after( 2 seconds ) 213
Activities, Actions, Events
 Activities are operations that take time and can
be interrupted:
 Accessing a web page.
 Writing to a disk.
 Can often be modeled as nested state diagrams.
 Actions are of very short duration and cannot
be interrupted:
 Beep.
 Display a menu.
 Set a flag.
 Events cause changes in state:
 State transitions can trigger actions.
214
 Transitions are essentially instantaneous.
Exercise 0: Draw State Machine Diagram
of a Keyboard?
•Press any key: lower case ASCII code is sent
to computer…
•Can press the caps lock key: after which upper
case ASCII code will be sent on a key press…
Any key/
send-lower-
Case-code Caps Lock
Default

CapsLoc
Caps Unlock ked
AnyKey/
Send-upper-
215
Case-code
Exercise 1: State Machine Diagram of a
Library Book
•A library book to start with, is present in a shelf…
•When borrowed out, it is not on shelf…

initial state

state
On shelf

Returned Borrowed transition


discarded
On loan

final state 216


State Machine
Diagrams cont…
Lecture 11

12/30/2021 217
Exercise 2: Construct State Model
 A car is in initial mode when ignition is off:
 it starts in an initial mode when ignition is keyed ON.
 The car accelerates when the acceleration pedal is
pressed. Cruise Controller
 While accelerating, the car goes into a cruise
mode, when cruise switch is set to ON.
 Cruise mode is turned off either when brake is
applied or the cruise switch is turned off
 From the cruise off state, cruise mode can be
resumed by setting cruise switch to ON.
 When ignition is turned off the car goes to idle218
mode.
Cruise Controller

Initial Engine Idle


Idle
On

Acccel Engine
Off

Accelerating
Cruising Break
off Pressed

Cancel
Resume

Resuming Reached Cruising


Cruising

Cruise 219
Exercise 3
 How do you model a keyboard?

 Transmits key code on each key


stroke.

 Breaks down after entering 100,000


key strokes.

220
Solution

keyStroke++/
Transmit code
KeyStroke>100,000
Default

Broken

221
Exercise 4: Draw State Machine: GUI
Accepts only Balanced Parentheses
(

OK Wait
start
end )

* *

 Inputs are the characters of a string


 No nesting of parentheses
 No “output” other than the resultant state 222
Example 5: Draw State Machine: GUI
Accepts only upto 3 Nested parentheses
 The following example tests whether parentheses are
properly nested (up to 3 deep)

( ( (

OK Wait 1 Wait 2 Wait 3


start ) ) ) )
* * * ( *
Error
How can we extend this machine
*

to handle arbitrarily deep


nesting? 223
Modeling Nested parentheses?

( do count++
( do count=1

start OK Wait

) if count==1
) if count>1
do count=0
do count--

 A state machine, but not just a state


machine --- EFSM
224
Extended State Machines
 Addition of variables (“extended state”)

ctr : Integer
Lamp On

on/ctr = ctr + 1

off

Lamp Off

225
A Bit of Theory
 An extended (Mealy) state machine is
defined by:
 a set of input signals (input alphabet)
 a set of output signals (output alphabet)
 a set of states
 a set of transitions
 triggering signals
 actions
 a set of extended state variables
 an initial state designation
226
 a set of final states (if terminating automaton)
State Chart Diagram
 FSMs suffer from a few severe
shortcomings:

 What are the shortcomings of FSM?

 Based on the work of David Harel [1990]

 Overcomes important shortcomings of FSM

¯ Extends finite state machine (FSM) formalism


227
Toy Car: State Model
Wheel
Headlight
Forward
Off power
power off
on
power power
on
off on
off

Stationary Stationary
On

Any thing wrong? power


power on
off

In FSM exponential Backward


rise in number of
states with state 228
variables
State Chart Diagram Cont…
 State chart avoids two problems of

FSM:
 State explosion
 Lackof support for representing
concurrency

 A hierarchical state model:


 Canhave composite states --- OR
229

and AND states.


Features of Statecharts
 Two major features are
introduced : S1
S2
 nested states
 concurrent states Nested State Diagrams

 Many other features have


also been added:
 History state
 broadcast messages
Concurrent State Diagrams
 actions on state entry, exit 230
Nested State Diagrams
 Hierarchical organization is
a classic way to control
complexity:
 of programs superstate

 of documentation
 of objects
 …
 Why not state diagrams?
 superstates
substates
231
 substates
Superstates and Substates
name of superstate substates terminal state

Dialing

LiftReceiver LiftReceiver
Digit(n)
entry/ start dial tone TheNumber: int
exit/ stop dial tone entry/ AddDigit

self-transition
Digit(n)

enclosing superstate

State model for


telephone dialing 232
State Chart Diagram
Cont…
 Elements of state chart diagram
 Initial State: A filled circle
 Final State: A filled circle inside a larger
circle
 State: Rectangle with rounded corners
 Transitions: Arrow between states, also
boolean logic condition (guard)‫‏‬
 UML uses an extended state chart called
state machine 233
Basic UML State Diagram Syntax
 A state is drawn with a
round box, with three
compartments for: Name sometimes
left out when
 name state variables
empty
 state variables actions

 actions performed

 A transition is drawn
with a labeled arrow,
 event causing the
transaction
AnEvent [guard] / SomeAction
 guard condition
 Action to perform 234
Syntax of UML State machine
• State: A condition that holds during the life of
an object or an interaction.
Simple State: rectangle with rounded corners

• The name tab


Typing password
• The action label
Entry/ set echo invisible
 Entry
Exit / set echo normal
 Exit Do / read character

 do 235
Basic UML State chart Diagram
“top” state
State
Initial
pseudostate top
Trigger

Ready
Transition

stop /ctr := 0

Done
Final
Action
state
stop

236
Object Behavior in State Machines

 Direct mapping:
on
Initialize
Object Lamp
On
Wait for
Event on/display(”on”)
Handle off
Event
off
Lamp
Off
Terminate
Object
stop

237
“Do” Activities
 The thread executes until:

 The action completes or


 Thestate is exited through an
outgoing transition

Error “do” activity


entry/printf(“error!”)

do/while (true) alarm.ring();


238
Guards
 Boolean predicates to indicate Conditional
execution of transitions
bid [value < 100] /reject

bid [value >= 200] /sell


Selling Happy

bid [(value >= 100) & (value < 200)] /sell

Unhappy
239
Predefined Action Labels
 “entry/”
 Identifies an action to be performed upon entry to the
state
 “exit/”
 Identifies an action to be performed upon exit from
the state (exit action)
 “do/”
 Identifies an ongoing activity (“do activity”) that is
performed as long as the modeled element is in the
state or until the computation specified by the action
expression is completed
 “include/”
 Is used to identify a submachine invocation. The action
expression contains the name of the submachine that
240
is to be invoked.
Eliminating Duplicated Transitions
 Duplicate transitions
usually exist when some
transition can happen
from every state:
Quit
 “error”
 “quit”
 “abort”

 These duplicates can be


combined into a single
transition:
Quit
 A transition from a
superstate holds for 241
all of its substates!
Hierarchical State Machines
 Graduated attack on complexity
 states decomposed into state machines

LampOff
flash/ LampFlashing
entry/lamp.off()
FlashOn

off/ entry/lamp.on()

1sec/
1sec/
on/ on/
FlashOff
LampOn
on/
entry/lamp.off()
entry/lamp.on()
242
Group Transitions
 Higher-level transitions
Default transition to
the initial pseudostate

LampOff flash/ LampFlashing


entry/lamp.off()
FlashOn
off/ entry/lamp.on()

1sec/
1sec/
on/
FlashOff
LampOn
on/
entry/lamp.off()
entry/lamp.on()

Group transition
243
Completion Transitions
 Triggered by a completion event:

 Generated automatically when an


immediately nested state machine
terminates.
completion
Committing transition (no trigger)
Phase1

CommitDone
Phase2

244
Triggering Rules
 Two or more transitions may have the same
event trigger:
 Innermost transition takes precedence
 Event is discarded whether or not it triggers a
transition
LampFlashing

FlashOn

on/
off/
on/
FlashOff
245
Simple Diagram for A Heart Monitor Application

Start Up
Problem
Switch Detected
ON

Switch
OFF
Startup
Off Complete Alarm

Switch Problem
OFF Detected
Operational
246
The Heart Monitor Revisited

Start Up
Transition to sub-state
Transition from
Super state
Switch
ON

Startup Problem
Off Complete Detected Alarm
Switch
OFF

Operational

247
Full Diagram for Heart Monitor Applications

The number of
states and
transitions StartUp
have grown Battery
quickly

Start Up Mains
Alarm Battery

Off etc
Alarm Mains

Operational
Battery

Operational
mains 248
Introducing Hierarchy
f
g h i j
A B C D E
k k k k
m
Z
super-state S

f
A g B h C i D j E

k
m
Z sub-states
249
Dialling
Composite
Start
entry/start dial tone
State:
exit/stop dial tone OR state
digit(n)

Encode

250
Composite States
 Composite states can have:
– concurrent substates -and- relationship
• each substate separated from others by dotted line
– disjoint substates -or- relationship
• transitions between substates
 Example of concurrent substates

Overhead Projector
On Desk Light Off

On Floor Light On 251


Exercise 1: Develop State Machine
Model

 In a chess game:
 Black and white sides take turn to
play.

 The game ends anytime when:


 Either there is a checkmate, or

 There is a stalemate. 252


White’s
turn

black white
moves moves

Black’s
turn
253
Handling Interrupted States
 Sometimes it is necessary to interrupt a
complicated procedure:
 And then resume where you stopped
 Consider installing a program on your
computer
 “Out of memory: please delete some files and
hit continue”
 In many situations in which a normal course
of events is interrupted and then resumed
 How can this be handled in a nested state
254
diagram?
History
 Return to a previously visited hierarchical
state.

Diagnosing
suspend/
Diagnostic1 Diagnostic2

Step11 Step21

resume/ Step12 Step22


H*

255
Orthogonality
 Multiple simultaneous perspectives on the
same entity.
age financialStatus

Child
Poor
Adult

Rich
Retiree

256
Orthogonal Regions
 Combine multiple simultaneous descriptions
age financialStatus

Child
Poor
Adult
age financialStatus

Child Rich
Retiree
Poor
Adult

Retiree Rich
257
Orthogonal Regions - Semantics
 All mutually orthogonal regions detect the
same events and respond to them
“simultaneously”
 Usually reduces to interleaving of some kind.
legalStatus financialStatus

LawAbiding Poor

robBank/ robBank/

Outlaw Rich
258
Interactions Between Regions
 Typically through shared variables or
awareness of other regions’ state
changes. sane : Boolean
flying : Boolean
Catch22
sanityStatus flightStatus

Crazy Flying
entry/sane := false; entry/flying := true;

(flying)/ (sane)/
request
Grounding/ (~sane)/
Sane Grounded
entry/sane := true; entry/flying := false;
259
Common Misuse of Orthogonality
 Using regions to model independent objects

Person1 Person2

Person1 Person2
Child Child

Adult Adult

Retiree Retiree
260
Full Diagram for Heart Monitor Applications
Convert to
The number of
states and
transitions StartUp OR-State…
have grown Battery
quickly

Start Up Mains
Alarm Battery

Off etc
Alarm Mains

Operational
Why does the Battery
diagram grow
fast?
Operational
mains 261
Heart Monitor as Concurrent State Machine
Monitoring Subsystem

Running

Switch on
Startup
Problem
detected
Off Startup Alarm
Switch off Complete

Operational Dotted line


separates
concurrent state
machines

Power Subsystem

Mains on
Battery Mains
Mains off
262
Another Example of A State Chart
Diagram
order received
Unprocessed
Order
[reject] checked [accept] checked

Rejected Accepted
Order Order
[some items available]
[some items not processed / deliver
available] processed

[all items
Pending available] Fulfilled
Order newsupply Order

Example: State chart diagram for an order object 263


Developing Statecharts from use Cases
 1. Collect the actions, conditions and results
from a use case description.
 2. Develop a preliminary statechart with
those actions and conditions as the events,
the results and the states.
 3. Consider any alternative external events
not in the use case.
 4. Refine into hierarchical and concurrent
statecharts.
264
Exercise 2
 Draw the state chart diagram of an elevator.
 The elevator is by default at the ground floor.
 It moves up when an up button is pressed and
halts when the required floor is reached.
 When a button at a lower floor is pressed:
 It moves down and halts when the required floor is
reached.

 When it is inactive at a floor for more than 10


minutes:
265
 It moves down to the ground floor.
Elevator: State Machine Representation

On First up floor Moving


Floor Up
arrive
at floor
arrive up floor
Moving to at floor
First Floor

arrive at
Moving floor Idle
Down
down floor

time-out 266
Exercise 3
 To withdraw money:

 customer inserts the ATM card.


 Authentication is done by checking an
entered PIN.
 The PIN can be incorrect.
 On three unsuccessful attempts, the card
is seized and account is locked.
 On correct entry amount dispensed and
card ejected. 267
Turnstile: Exercise 4
 A turnstile check gate would be installed
at a railway station.
 When the turnstile is powered on:
 It starts in the locked state.
 When a commutator enters a one rupee coin:
 The gate gets unlocked and a message “Gate Open”
appears.
 Exactly one person is allowed to pass through
before the gate gets locked.
 If more than one person try to pass through, an
alarm is sounded and gate gets locked.
 Also when any one tries to jump over the gate:
 An alarm is started and gate is locked. 268
Turnstile Exercise cont…
 When the alarm is ON:
 A message “Please wait: Gate temporarily blocked”
is displayed.
 If any one still inserts a coin, it return the coin
without unlocking the gate.
 The alarm is reset when an attendant swipes a
card and the gate starts at the locked state.
 When any one inserts a coin when the gate
is already open:
 The coin is returned.
 If there is a power failure any time:
 The gate gets locked and “Power fail: inoperative”
message is displayed and coins are not accepted.
269
pass/ Alarm
coin/ Unlock
Locked

pass/ Lock
Unlocked
coin/ Thank you

270
State Model power
OFF
powerOFF
coin/return
powerON

coin Unlock
Locked ed

cardSwipe pass
jump multiple
Alarm pass||jump
Entry/
display

271
Translate State Machine to Code
 Complicacies:

 Statemachines have many concepts that


are not directly supported in OO
programming languages --- states,
transitions, concurrent states, history,
etc

 Ina state machine, you can have


transitions from any state to any other
state 272

272
How to Encode an FSM?

 Three main approaches:


 Doubly nested switch in loop

 State table

 Patterns

273
3 Principal Ways
 Doubly nested switch in loop:
 Scalar variable stores state
 Used as switch discriminator for first level
switch
 Event type is the descriptor in second switch
 Hard to handle concurrent states, composite
state, history, etc.
 State table
 Patterns:
 States are represented by classes
274
 Transitions as methods in classes
Key Idea of First Approach
 The trick is to make the “state” a variable:
While(TRUE){
switch (state){
Case state1: switch(event){
case event1: state=state2; etc…; break;
case event2:…
default:
}
Case state2:switch(event){…
…. }
275
}
State Table Approach
 From the state machine, we can set up a state
transition table with a column for the actions
associated with each transition

Present Enable Next


Actions
state input state

e1 BTN_off none
BTN_off
e2 BTN_on set red LED flashing

e1 BTN_on none
BTN_on
e2 BTN_off reset red LED flashing
276
Turnstile: State Model power
OFF
powerOFF
coin/return
powerON

coin Unlock
Locked ed

cardSwipe pass
jump multiple
Alarm pass||jump
Entry/
display

277
enum State {Locked, Unlocked, Alarm, PowerOFF};
enum Event {Pass, Coin, multiplePass, jump, cardSwipe};
static State s = Locked;
void Transition(Event e){
switch(s){
case Locked:
switch(e){
case Coin:
s = Unlocked;
Unlock();
break;
Code case Jump:
s=Alarm;
Alarm();
break;
}
cont…
278
break;
case Unlocked:
switch(e){
case Coin: returnCoin();
break;
case Pass: s = Locked;
Lock();
break;
case jump:
case multiplePass: s=Alarm;
Alarm();
break;}
break;
case Alarm: …. … ….
279
Ex. 5: Course Registration Software
 When the software starts, it initializes all
courses.
 If a student registers, and the course is
open, student is registered and count
incremented.
 If a course is cancelled the students are
notified.
 If registered students are 10, the course is
closed, and it is allocated a room and time
280
slot.
State Transition Diagram
Add student[ count < 10 ]

Add Student
Initialization [count = 0]
Open
do: Initialize course
entry: Register student
exit: Increment count

Cancel

Cancel [ count = 10 ]

Canceled
do: Notify registered students
Closed
Cancel
do: Finalize course

281
Exercise 6
 A digital watch has 2 switches M and A
 The watch is in display mode by default
 Pressing A is ignored
 Pressing M once takes to Hour mode:
 Pressing A advances hour
 Pressing M once more takes to Min mode
 Pressing A advances min
 Pressing M once more:
 Takes to display mode 282
Model Answer

A
Display A

Digital
M SetHours M
A A entry/ SetMinutes
display=digital

Analog

Code?
283
Public class State{ Public void M(){
public final int digital_Display = 0; switch (state.value) {
public final int analog_Display = 1; case State.Display :
public final int Set_hours = 2;
LCD.display_digital_time();
public final int Set_minutes = 3;
public int value; LCD.display_blink_hours();
} state.value = State.set_hours;
public class Watch { break;
private State state = new case State.Set_hours :
State(); LCD.display_blink_minutes();
state.value = State.Set_minutes;
private Digital_display LCD =
break;
new Digital_display();
case State.Set_minutes :
public Watch() { LCD.display_digital_time();
state.value = state.value =
State.digital_Display; State.digital_Display;
break;
LCD.display_time(); 284
}
Public void A() {
switch (state.value){
case state.set_hour :
Case state.set_minutes:
break;
case state.analog_display:
LCD.display.digital_time();
break;
case state.digital_display:
LCD.display_analog_time();
break;
}
285
}
Bonus Problem 27-8-14
 How to handle composite AND
and OR states?

 How to handle history state?

 Write up + example + code

286
Package Diagrams
• A package is a grouping
of several classes:
– Java packages are a good Order Capture
AWT
Mailing List
UI UI
example
• Package diagrams show
module dependencies.
• Useful for large projects Order Capture Mailing List
Application Application
with multiple binary files
Dependency
Common
{global}
Oracle Quantity
Interface Money Domain
DateRange

Sybase
Database Orders Customers
Interface
Interface
{abstract}
287
Component Diagram
 Captures physical structure of
the implementation.
 Purpose:
 Organize source code

 Construct an executable release

 Specify dependencies 288


Component Diagram
 What is a component?
A piece of software that can be
independently purchased and upgraded,
and can integrate seamlessly into
customers’ existing software.

Librarian
Librarian

UML 1 notation UML 2 notation

289
Component Diagram
 Captures the physical structure of the
implementation (code components)‫‏‬
UML 1.X
Notation
dependency

Components:
• Executables
• Library
• Table
• File
• Document

290
Ball and Socket notation for Interfaces
 Ball and socket notation is new in UML 2.0.
 Components that consume (require) an interface:
 Display a "socket" labeled with the interface
name .
 Components that provide (implement) an
interface:
 Display a "ball" labeled with the interface name.
 Combining the two:
 A compact way to say that Consumer talks
to the provider via the named interface. 291
Component Diagram: Example

Library

UI Librarian DB

Ports can be named, such as


the Security and Data ports Database

292
Deployment Diagram
 The deployment diagram shows:
 How a software system will be physically
deployed in the hardware environment.
 Its main purpose is:
 Show where the different components of the
system will physically run and
 How they will communicate with each other.
 Since the diagram models the physical
runtime:
 A system's operation staff will make
293
considerable use of this diagram.
Deployment Diagram
 Node:
 Something that can host an artifact.
 A node represents a physical machine.
 To model a node, draw a three-dimensional cube
with the name of the node at the top.
 Physical nodes should be labeled with the
stereotype device
 Artifact:
 Files, assemblies, DLL, or scripts
294
 An artifact is usually a component
Deployment Diagram
 Captures the topology of a system’s
hardware

A piece of
hardware

295
Architectural Modeling Using
Deployment Diagram

Terminal
2 Terminal
Terminal X
1

Branch
Server ATM X
Terminal
1

Branch Hub Central


Server Bank
Terminal
2

ATM 2
ATM 1
Terminal
X
296
New Notations in UML 2
 UML 2 was a major revision of the
UML standard.

 Several new notions and concepts have


been introduced.
 Based on feed back from practitioners

 Can now be applied meaningfully to many


classes of problems such as embedded
software development.
297
UML 2 Diagrams
 UML now defines twelve types of
diagrams, divided into three categories:
 Fourdiagrams represent static application
structure

 Five
represent different aspects of
dynamic behavior

 Threerepresent ways you can organize and


manage your application modules 298
298
UML Structural Diagrams

 Class Diagram

 Object Diagram

 Component Diagram

 Deployment Diagram
299
299
UML Behavior diagrams
 Use Case Diagram

 Sequence Diagram

 Activity Diagram

 Communication Diagram

 State machine Diagram

 Timing diagram 300


300
UML Model Management Diagrams

 Packages
 Component diagram
 Deployment diagram

301
301
UML 2.0 Highlight of Changes
list is not comprehensive

 Introduced new concept of Ports

 Composite Structure Classes & Diagrams

 Class Diagrams – the least changed

 Collaboration Diagram – renamed to


Communication Diagram

 Sequence Diagram – nesting options

 New diagram introduced – Timing Diagram 302


302
UML 2.0 Highlight of Changes
list is not comprehensive

 Activity Diagrams have the greatest


number of changes of any of the UML
diagrams

 Use Case Diagrams – added multiplicity


and changes with extension points.

 Package Diagram now an official UML


diagram. 303
303
UML 2.0 Changes
 Sequence diagrams can be “nested” using
operators:
sd – named sequence diagram
ref – reference to “interaction fragment”
loop – repeat interaction fragment
alt – selection
par – concurrent (parallel) regions
seq – partial ordering (default) (aka “weak”)
strict – strict ordering
assert – required (i.e. causal)
opt – optional “exemplar”
neg – “can’t happen” or a negative specification 304
304
Sequence Diagram - new notation -
Frame

:Foo :Bar

xx

opt [color = red] calculate

305
Classes: Active and Passive
 In UML 2, there can be:
 Passive classes: as usual
 Active classes: classes with defined
behaviour, and that can react to arriving
signals.
 Denoted with double vertical borders.

ClassName ActiveClass
Attributes Attributes
Operations Operations
306
A passive class An active class
Signals and Channels
 Signals can be sent between active classes.
 A signal is defined by a class with the
stereotype <<signal>>.
 Signals can carry parameters.
 Sending and receiving a signal:
 Somewhat analogous to calling a method in another
object.

 The path that a signal takes from sender


to receiver:
307
 specified by channels between objects.
Ports
 A Port is a named interface on a component:
 It defines a set of operations and events that are provided by a
component or that are required from its environment.

 The port has:


 A name.
 An interface specifying the signals that can be received.
 An interface specifying the signals that can be sent.

 Two types of ports:


 Connected to internal communication channels (by default).
 Connected to the state machine for the class instance (a
behaviour port).
In interface
308
Out interface
A behaviour port
Composite Structure Diagram
 A composite structure diagram:
 Shows the relationship among internal components
of a class, in terms of communication paths.
 Class may have one or more communication ports
 through which signals can be sent or received.
 The ports are connected either to:
 Internal components
 Channels connect the ports of the class to the ports of the
internal components.
 Channels can be unidirectional (one direction only) or
bidirectional (both directions).
 The state machine behaviour of the class (a 309
behaviour port).
Object instance reference

instance name
OutPort

Switch2 : Switch

class name
InPort

310
Composite Structure

311
Composite Structure Diagram
 Lets you capture how a class is defined by a
further structure of classes
 and the communication paths between these parts.

312
Tools Supporting UML 2.0
 PlantUML
 Open Source ArgoUML
 ARTiSAN's Real-time Studio
 Borland Together 2006 for Eclipse
 Computas' Metis with UML 2.0 Template
 Embarcadero Describe
 IBM Rational Software Architect and Modeler
 I-Logix Rhapsody
 MetaMatrix MetaBase Modeler
 Mia Software Model-in-Action
313
 No Magic's MagicDraw UML
Tools Supporting UML 2.0 continued……..

 OMONDO EclipseUML Studio


 Pathfinder Solutions' PathMATE 5.2
 Open Source StarUML sponsored by Plastic
Software
 Sparx Systems Enterprise Architect
 Sun Microsystems' Java Studio Enterprise
 Pattern Weaver Ver. 2.0 Technologic Arts Inc.
(Japanese)
 Telelogic's TAU Developer and TAU Architect
 Gentleware's Poseidon for UML
 Visual Paradigm's Smart Development Environment
314
tool series
Word of Caution!
 Tools can be easily learned and used.

 Too much focus on UML case tools


does not make you any more a good
designer:

 Than becoming an expert Word user


makes you a famous writer of thriller
stories. 315
Review Questions
 Why does UML prescribe development
of several models of a system under
construction?
 Would it not be better to have one
comprehensive model?

 Do you agree with the following


statement?
 “Inheritance is an abstraction mechanism.”
316
End

317
OOAD

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
1
A Design Process
 We discuss a design process based to a large
extent on Larman’s approach:
 Also synthesizes features from various other
methodologies.

 From requirements specification, an initial


model is developed (OOA):‫‏‬
 Analysis model is iteratively refined into a
design model

 Design model is implemented using an OO


language. 2
OOAD

Iterative and Incremental

OOA OOD/OOP
Domain
Specification Definition Model Construction
of of Program
Use
the problem case the solution
model

3
OOA versus OOD?
 Analysis:
 An elaboration of requirements.
 Independentof any specific
implementation
 Design:
A refinement of the analysis model.
 Takesimplementation constraints into
account
4
Design Process
OOA OOD
User interface
Use case Interaction
Issues or GUI
prototype diagram diagram

Start

SRS Domain Class


document model diagram
Code

Glossary
5
Two dimensions of RUP

6
Using UML in the OO Process

7
Domain Model Relationships
Conceptual Class Diagram

Domain Model

Define terms
Domain
Use Case Model objects Glossary

Functional Requirements

Interaction Diagrams
Dynamic Behavior
8
Domain Modelling
 Represent concepts or objects

appearing in the problem domain.


 Also capture object relationships.

 Three types of objects are


identified:
 Boundary objects
 Entity objects
 Controller objects 9
Class Stereotypes
Three different stereotypes are used to
represent classes :
<<boundary>>, <<control>>, <<entity>>.
Boundary
Cashier Interface

Control
Withdrawal
manager

Entity
Account 10
Domain model vs.
Design Class Diagram – What difference?

Register Sale
Domain 1 captures *
Model
time
… isComplete:Boolean
total
Conceptual
Perspective

Design Register Sale


Model …
* time
endSale() isComplete:Boolean
captures total
Software enterItem(...)
Implementation makePayment(...)
makeLineItem(...)
perspective 11
Boundary Objects
 Handle interaction with actors:
 User interface objects
 Often implemented as screens,
menus, forms, dialogs etc.
 Do not perform processing:
 Butmay validate input, format
output, etc. 12
Entity Objects
 Hold information over long term:
 e.g. Book, BookRegister

 Normally are dumb servers:


 Responsible for storing data, fetching data etc.

 Elementary operations on data such as


searching, sorting, etc.

 Often appear as nouns in the problem


description... 13
Controller Objects
 Help to realize use case behavior:
 Interface with the boundary objects
 Coordinate the activities of a set of entity
objects

 Embody most of the business logic:


 Involved with use case execution.

 There can be more than one controller


to realize a single use case 14
Controller Classes
 Controller classes coordinate,
sequence, transact, and otherwise
control other objects…

 In Smalltalk MVC mechanism:

 These are called controllers

15
Use Case Realization

Boundary 1 Controller Boundary 2

Entity 1 Entity 2 Entity 3

Realization of use case through the collaboration of


Boundary, controller and entity objects
16
First Cut Sequence Diagram
for Cancel an Order

17
Identification of Boundary Objects
 Need one boundary object :
 For every actor-use case pair

register
Customer customer Clerk

Play Move register


sales
Tic-tac-toe game Sales Clerk
select
Player
winners

Manager Supermarket
Prize scheme 18
Identification of Controller Objects
 Examine the use case diagram:
 Add one controller class for each use case.
 Some controllers may need to be split into two
or more controller classes if they get assigned
too much responsibility.

register
Customer customer Clerk

register
Play Move sales

Sales Clerk
select
Tic-tac-toe game
Player winners

Supermarket
Manager Prize scheme
19
Identification of Entity Objects
 Usually appear as nouns in the problem
description.
 From the list of nouns, need to exclude:
 Users (e.g. accountant, librarian, etc)
 Passive verbs (e.g. Acknowledgment)
 Those with which you can not associate any data to
store
 Those with which you can not associate any methods

 Surrogate users may exist as classes:


20
 Library member
Identify Classes
 A partial requirements document:
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.

 Of course, not all nouns will correspond


to a class or object in the final solution 21
Identify Entity Classes
 A partial requirements document:
The user must be allowed to specify each product by
its primary characteristics, including its name and
product number. If the bar code does not match the
product, then an error should be generated to the
message window and entered into the error log. The
summary report of all transactions must be structured
as specified in section 7.A.

 Of course, not all nouns will correspond


to a class or object in the final solution 22
Identifying Classes and Objects
 Remember that a class represents a group
(classification) of objects with the same
behavior.
 Generally, classes should have names that
are singular nouns
 Examples: Coin, Student, Message

 A class represents the concept of one such


object
 We are free to instantiate as many of each object as
23
needed
Identification of Entity Objects

 Usually:
 Appear as data stores in DFD

 Occur as aggregate objects

 The aggregator corresponds to


registers in physical world
24
Example 2: Initial Domain Model

SalesHistory CustomerRegister
1 1

* *

SalesRecords CustomerRecord

Initial domain model


25
Example 1: Tic-Tac-Toe Computer Game
 A human player and the computer make
alternate moves on a 3X3 square.
 A move consists of marking a previously
unmarked square.
 The user inputs a number between 1 and
9 to mark a square
 Whoever is first to place three
consecutive marks along a straight line
(i.e., along a row, column, or diagonal) on
26
the square wins.
Example 1: Tic-Tac-Toe Computer Game cont…
 As soon as either of the human player or
the computer wins,
 A message announcing the winner should be
displayed.

 If neither player manages to get three


consecutive marks along a straight line,
 And all the squares on the board are filled up,
 Then the game is drawn.

 The computer always tries to win a game. 27


Example 1: Tic-Tac-Tie
Use Case Model

Play Move

Tic-tac-toe game
Player

28
Example 1: Initial and Refined
Domain Model

Board

Initial domain model

PlayMoveBoundary PlayMoveController Board

Refined domain model

29
Example 1: Sequence Diagram
:playMove :playMove
Boundary Controller
:board
acceptMove checkMoveValidity
move
[invalidMove] [invalidMove]
announceInvalidMove
announceInvalidMove checkWinner
[game over]
[game over] announceResult
announceResult
playMove
checkWinner
[game over] [game over]
announceResult announceResult
displayBoardPositions getBoardPositions
[game not over]
promptNextMove

Sequence Diagram for the play move use case 30


CRC Card
 Used to assign responsibilities
(methods) to classes.
 Complex use cases:
 Realized through collaborative
actions of dozens of classes.
 Without CRC cards, it becomes
difficult to determine which class
should have what responsibility. 31
Class-Responsibility-
Collaborator(CRC) Cards
 Pioneered by Ward Cunningham and
Kent Beck.
 Index cards prepared one each per
class.
 Contains columns for:
 Class responsibility
 Collaborating objects 32
CRC Cards Cont…

 Systematize development of
interaction diagram of complex
use cases.

 Team members participate to


determine:
 The responsibility of classes involved
in a use case realization 33
CRC Cards Cont…

 Responsibility:

 Method to be supported by the


class.

 Collaborator:

 Class whose service (method)


would have to be invoked 34
An Example of A CRC Card
Class name

BookRegister
FindBook Book

CreateBook Book

Reserve Book

Responsibility Collaborator

CRC card for the BookRegister class 35


Using CRC Cards
 After developing a set of CRC cards:
 Run simulations
 Also known as structured walkthrough scenarios

 Execute a scenario :
 A class is responsible to perform some
responsibilities
 It may then pass control to a
collaborator -- another class
 You may discover missing responsibilities and36
classes
Example 1: Class Diagram

Board PlayMoveBoundary
int position[9]
checkMove Validity announceInvalidMove
checkResult announceResult
playMove displayBoard

Controller

announceInvalidMove
announceResult
37
Example 2: Supermarket Prize Scheme
 Supermarket needs to develop software
to encourage regular customers.
 Customer needs to supply his:
 Residence address, telephone number, and
the driving licence number.
 Each customer who registers is:
 Assigneda unique customer number (CN)
by the computer. 38
Example 2: Supermarket Prize Scheme
 A customer can present his CN to the
staff when he makes any purchase.

 The value of his purchase is credited


against his CN.

 At the end of each year:

 The supermarket awards surprise gifts to


ten customers who make highest purchase. 39
Example 2: Supermarket Prize Scheme

 It also, awards a 22 carat gold coin


to every customer:
 Whose purchases exceed Rs. 10,000.

 The entries against the CN are


reset:
 Onthe last day of every year after
the prize winner’s lists are generated.
40
Example 2: Use Case Model

register
Customer customer Clerk

register
sales
Sales Clerk
select
winners

Manager Supermarket
Prize scheme 41
Example 2: Initial Domain Model

SalesHistory CustomerRegister
1 1

* *

SalesRecords CustomerRecord

Initial domain model


42
Example 2: Refined Domain Model
SalesHistory CustomerRegister
1 1

* *
SalesRecords CustomerRecord

RegisterCustomerBoundary RegisterCustomerController

RegisterSalesBoundary RegisterSalesController

SelectWinnersBoundary SelectWinnersControllers

Refined Domain Model 43


Example 2: Sequence Diagram for the
Select Winners Use Case

:SelectWinner :SelectWinner :Sales :Sales :Customer :Customer


Boundary Controller History Record Register Record

Select
SelectWinners
Winners
SelectWinners
*computeSales

*browse

[for each winner]


find WinnerDetails [for each winner]
announces
browse

Sequence Diagram for the select winners use case 44


Example 2: Sequence Diagram for the
Register Customer Use Case

:RegisterCustomer :RegisterCustomer :Customer :Customer


Boundary Controller Register Record

register
register
checkDuplicate
*match
[duplicate]
showError
generateCIN
create :Customer
register
Record
displayCIN

Sequence Diagram for the register customer use case 45


Example 2: Sequence Diagram for the
Register Sales Use Case
:Register :Register
:Sales
Sales Sales
History
Boundary Controller

RegisterSales registerSales
registerSales

create :Sales
Record
confirm
confirm

46
Sequence Diagram for the register sales use case
Example 2: Sequence Diagram for the
Register Sales Use Case
:Register
:Sales
Sales
History
Boundary
registerSales
RegisterSales

create :Sales
Record
confirm

Refined Sequence Diagram for the register sales use case 47


Example 2: Class Diagram
SalesHistory CustomerRegister

selectWinners findWinnerDetails
registerSales register

1 1

* *
SalesRecords CustomerRecord

salesDetails name
address
computerSales browse
browse checkDuplicate48
create create
Video Rental Store Software
 A video rental store has a large collection of video CDs and DVDs in VHS and
MP4 format as well as music CDs.
 A person can become member a member by depositing Rs. 1000 and filling up
details such as name, address, and telephone number. A member can cancel his
membership and take back his deposit, if he has no dues outstanding against him.
 Whenever the store purchases a new item, details such as price and date of
procurement are entered. The daily rental charge is also entered by the
manager. After passage of a year, the daily rental charge is automatically halved.
 A member can, at a time, take on loan at most two video CDs and one music CD.
The details are entered by a store clerk and a receipt indicating the daily rental
charge should be printed by the software.
 Whenever a member returns his loaned item(s), the due amount to be paid is
displayed. After the amount is paid, the items are marked returned.
 If a customer loses or damages any item, the full price of the item is charged to
him and the item is removed from the inventory.
 If an item is not lent out by anyone for even once over a year, the item is sold
at 10% of the purchase price and is removed from the inventory.
49
 The manager can, at any time, check the profit/loss account.
Personal Library System
 The software is required to manage the collection of books by individuals.

 A person can have a few hundreds of books. The details of all the books such as
name of the book, year of publication, date of purchase, price, and publisher
must be entered. A book is to be given a unique serial number by the computer
which would be written by the owner using a pen on the book. Before a friend can
be lent a book, he must be registered. The registration data would include name
of the friend, address, land line number, and mobile number. Before a friend is
issued a book, the various books outstanding against him also with the date
borrowed are displayed. The date of issue and the title of the book are stored.
When a friend returns a book, the date of return is stored and the book is
removed from his borrowing list. Up on query, the software should display the
name, address, and telephone numbers of each friend against whom books are
outstanding along with the titles of the outstanding books and the date on which
those were issued.

 The owner of the library software, when he borrows books from his friends,
would enter the details regarding the title of books borrowed, and the date
borrowed. Similarly, the return details of books would be entered. The software
should be able display all the books borrowed from various friends. The owner
should be able to query about the availability of a particular book, the total50
number of books in the personal library,
IIT Security Software
 The staff and students of IIT register their vehicle by filling up a form which
a security staff would enter into the system.
 Each time a vehicle enters or leaves the campus, a camera reads the
registration number of the car, and the model of the car. If the car is
registered, the check gate should lift automatically to let in (or out) the vehicle.
The details regarding the entry and exit of the vehicle are registered in the
database. For outside vehicles, the driver needs to enter the purpose of entry,
the model number, the registration number, and a photograph of the vehicle is
stored in the database.
 When an outside vehicle leaves the campus, the details are automatically
registered in the database. For any external vehicle that is inside the campus for
more than 8 hours, the driver is stopped by the security personnel manning the
gate, queried to satisfaction, and the response are recorded. Considering that
there have been several incidence of speeding and rough driving, the security
personnel are empowered to telephone the registration number of errant
vehicles to the main gate. For outside vehicles, the driver is quizzed at the check
gate and his future entry is barred if the response is not satisfactory. For inside
vehicles, a letter is issued to the dean to deal with the employee or student as
the case might be.
 The security officer can check the data regarding the number of vehicles
going in and coming out of the campus (over a day, month or year), the total 51
number of vehicles currently inside the campus.
Students’ Auditorium Management Software
 Various types of social and cultural events are conducted in the
student auditorium. There are two categories of seats: balcony and
ordinary seats. The maximum number of balcony seats that can be
booked per ticket is 2.

 The show manager fixes the prices of the two categories of seats
for a specific show, depending on the popularity of a show.

 The show manager also enters the show dates, the number of shows
on any particular date and the show timings. It is expected that
the software would support a functionality to let the show manager
configure the different show parameters.

 The system should let the spectators query the availability of


different classes of seats for a show on-line. A spectator can book
a seat for a single show only through regular cash payment and the
software should print out the ticket showing the seat numbers
allocated. A spectator should be able to cancel his booking before
52
3
clear days of the show.
Travel Agency Automation Software
 The company owns a number of vehicles (cars and SUVs) of various make and intends to
deploy a web-based software. A customer can become regular customer by depositing Rs.
5,000/- and supplying his name address, and mobile phone number.
 When a customer requests for a car, he is displayed the types of vehicles are available,
and their charges. For every vehicle, there is a per hour charge, and a per kilometer
charge. A vehicle can be rented for a minimum of 4 hours. An AC vehicle of a particular
category is charged 50% more than a non-AC vehicle of the same category. There is a
charge of Rs 300 for every night of halt regardless of the type of the vehicle.
 A customer can book a vehicle, only if he has at least Rs. 2000/- advance. The customer
needs to enter when he expects to return the car.
 When the car is returned, depending on the usage, if possible the amount is fully adjusted
from the advance, or he has to pay additional amount to cover the cost incurred.
 The company can acquire new vehicles and add them to the fleet of its vehicles. Cars may
be condemned and sold off. A car which is currently with the company can be in one of
three states: it may have gone for repair, it may be available, it may be rented out. If it is
rented out, the company records the date and time when it has been rented out, and the
mile-meter reading of the car at that time.
 The company also wants to maintain the maintenance and running expense for each vehicle.
 The manager of the company should be able to query statistics about various types of
vehicles, their prices, average expense on repairs for the car, average demand, revenue
53
earned, and fuel consumption of the car.
Newspaper Delivery Automation System
 The local newspaper and magazine delivery agency has asked us to
develop a software for him to automate various clerical activities
associated with his business.
 The customers usually subscribe one or more news papers and
magazines. Customers should be able to initiate new subscriptions
and suspend subscription for a particular item either temporarily or
permanently through a web browser•
 The customers may ask for stopping the deliveries to them for
certain periods when they go out of station.
 For each delivery person, the system must print each day the
publications to be delivered to each address. The system should
also print for the news agent the information regarding who
received what and a summary information of the current month.
 At the beginning of every month bills are printed by the system to
be delivered to the customers. These bills should be computed by
the system automatically.
 The manager must be able to view the total receipts every month.
54
Restaurant Automation Software
 The computer should maintain the prices of all the items:
 Also support changing the prices by the manager.
 Whenever any item is sold:
 The sales clerk would enter the item code and the quantity sold.
 The computer should generate bills and register the payments.
 Whenever ingredients are issued for preparation of food items,
the data is to be entered into the computer.
 Purchase orders are generated on a daily basis, for all ingredients
whose stock falls below a threshold value.
 The threshold value for each item is computed based on the average
consumption for the past three days and assuming that two days stock must
be maintained.
 Whenever the ordered ingredients arrive, the invoice data
regarding the quantity and price is entered.
 If sufficient cash balance is available, the computer should print cheques
against invoice.
 Monthly sales receipt and expenses data should be generated
55
whenever the manger would request to see them.
City Road Maintenance System
 A city corporation has branch offices at different suburbs of the city. Residents would
raise repair requests for different roads of the city on line.
 The supervisor at each branch office should be able to view all new repair requests
pertaining to his area.
 The supervisor visits the road and studies the severity of road condition and the raw material requirement for
carrying out the repair work, the types and number of machines required, and the number and types of
personnel required.
 The supervisor enters this information through a special login in the web site.

 Based on this data, the system should schedule the repair of the road depending on the
priority of the repair work and subject to the availability of raw material, machines, and
personnel.
 This schedule report is used by the supervisor to direct different repair work.
 The manpower and machine that are available are entered by the city corporation
administrator. He can change these data any time.
 The progress of the work is entered periodically by the supervisor which can be seen by
the citizens in the web site.
 The mayor of the city can request for various road repair statistics such as the number
and type of repairs carried out over a period of time and the repair work outstanding at
any point of time and the utilization statistics of the repair manpower and machine over
any given period of time. 56
Bookshop Automation Software
 BAS should help the customers query whether a book is in stock. The users can
query the availability of a book either by using the book title or by using the
name of the author.
 If the book is not currently being sold by the book-shop, then the customer is
asked to enter full details of the book for procurement of the book in future.
The customer can also provide his e-mail address, so that he can be intimated
automatically by the software as and when the book copies are received.
 If a book is in stock, the exact number of copies available and the rack number
in which the book is located should be displayed. If a book is not in stock, the
query for the book is used to increment a request field for the book.
 BAS should maintain the price of various books.
 As soon as a customer selects his books for purchase, the sales clerk would
enter the ISBN numbers of the books. BAS should update the stock, and
generate the sales receipt for the book.
 BAS should allow employees to update the inventory whenever new supply
arrives.
 Upon request by the owner of the book shop, BAS should generate sales
statistics (viz., book name, publisher, ISBN number, number of copies sold,57and
the sales revenue) for any period.
Program Testing

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.

03/08/10 1
Name Any Four Defect Reduction
Techniques…
• Review

• Testing

• Formal specification and


verification

• Use of development process


Why Test?

• Ariane 5 rocket self-destructed 37 seconds after launch


• Reason: A software exception bug went undetected…
– Conversion from 64-bit floating point to 16-bit signed integer
value had caused an exception
• The floating point number was larger than 32767
• Efficiency considerations had led to the disabling of the exception
handler.

• Total Cost: over $1 billion


How Do You Test a Program?
• Input test data to the program.
• Observe the output:
 Check if the program behaved as
expected.
Examine Test Result…
• If the program does not
behave as expected:

Note the conditions under


which it failed (Test report).

Later debug and correct.


Ack www.zelger.org
Ack www.dstb.dk
What’s So Hard About Testing?
• Consider int check-equal(int x, int y)
• Assuming a 64 bit computer
 Input space = 2128

• Assuming it takes 10secs to key-in an integer


pair:

 It would take about a billion years to enter all


possible values!

Automatic testing has its own problems!


The Test Results are In…

08/10/1003/08/10
Dilbert: Scott Adams
Error Tit-Bits
• Experienced programmers on the
average make:
 50 errors per 1000 lines of source code

• Extensively tested software contains:


 About 1 error per 1000 lines of source
Bug Source
code.

• Error distribution: Design


code

 60% spec/design, 40% implementation.


Testing Facts
• Consumes the largest effort among
all development phases:
 Largest manpower among all roles
 Implies more job opportunities

• About 50% development effort


 But 10% of development time?
 How?
Testing Facts
• Testing is getting more complex
and sophisticated every year.

 Larger and more complex


programs

 Newer programming paradigms

 Test automation
Ack www.dstb.dk
Testing Perception
• Testing often viewed as not very
challenging --- less preferred by
novices, but:
 Over the years testing has taken a center
stage in all types of software development.
 Large number of innovations have taken
place in testing area --- requiring tester to
have good knowledge of test techniques.
 Challenges of test automation
Testing Activities
Error, Faults, and Failures
• A failure is observed during
testing:

A manifestation of an error
(also called defect or bug).

Mere presence of an error may


not lead to a failure.
Test How Long?
One way:
Number
# Bugs

Time

• Another way:
 Seed bugs… run test cases
 See if all (or most) are getting
detected
When You Ask Testers to Hurry Up…

Dilbert: Scott Adams


Verification versus Validation
• Verification is the process of
determining:
 Whether output of one phase of
development conforms to its previous phase.

• Validation is the process of


determining:
 Whether a fully developed system
conforms to its SRS document..
Verification versus Validation
• Verification is concerned
with phase containment of
errors:
Whereas the aim of validation
is that the final product be
error free.
Verification Validation
Are you building it Have you built the right
right? thing?
Checks whether an Checks the final product
artifact conforms to against the specification.
its previous artifact.
Done by developers. Done by Testers.

Static activities: Dynamic activities:


reviews, walkthroughs, Execute software and
and inspections. check against
08/10/1003/08/10 requirements.
Dilbert: Scott Adams
Test Level

12/30/2021
Testing Levels
• Software tested at three
levels:
Unit testing
Integration testing
System testing
Test Levels
• Unit testing
 Test each module (unit, or component)
independently
 Mostly done by developers of the modules
• Integration and system testing
 Test the system as a whole
 Often done by separate testing or QA team
• Acceptance testing
 Validation of system functions by the
28
customer
Overview of Activities During System
and Integration Testing
• Test Suite Design
• Run test cases Tester
• Check results to detect failures.
• Prepare failure list
• Debug to locate errors
Developer
• Correct errors.
Quiz 1
• As testing proceeds more and more bugs
are discovered.
 How to know when to stop testing?

• What are the types of bugs detected


during:
 Unit testing?

 Integration testing?

 System testing?
Unit testing
• During unit testing, functions (or
modules) are tested in isolation:
 What if all modules were to be tested
together (system testing)?

•It would become difficult to


determine which module has the
error.
Integration Testing
• After modules of a system have
been coded and unit tested:

 Modules are integrated in


steps according to an integration plan

 The partially integrated system is


tested at each integration step.
Integration Problems…

Dilbert: Scott Adams


System Testing
• While Integration test evaluates a group
of functions or classes:
 Identifies interface compatibility, unexpected
parameter values or state interaction, and
run-time exceptions

 System test tests working of the entire


system

• Build and smoke test:


 System test performed daily or several times
a week
Types of System Testing
• Based on types test:
 Functionality test
 Performance test
• Based on who performs testing:
 Alpha
 Beta
 Acceptance test
Performance test
• Determines whether a system or
subsystem meets its non-functional
requirements:
• Response times
• Throughput
• Usability
• Stress
• Recovery
• Configuration, etc.
User Acceptance Testing
• User determines whether the
system fulfills his requirements

 Accepts or rejects delivered


system based on the test
results.
Who Tests Software?
• Programmers:
 Unit testing
 Test their own or other’s programmer’s code
• Users:
 Usability and acceptance testing
 Volunteers are frequently used to test beta
versions
• Quality assurance personnel:
 All types of testing except unit and acceptance
 Develop test plans and strategy
Who Tests the Software?
Ack www.zelger.org

developer independent tester


Understands the system Must learn about the system,
but, will test "gently" but, will attempt to break it
and, is driven by "delivery" and, is driven by quality
V&V
Pesticide Effect
• Errors that escape a fault detection
technique:
 Can not be detected by further
applications of that technique.
Capers Jones Rule of Thumb

• Each of software review,


inspection, and test step will
find 30% of the bugs present.

In IEEE Computer, 1996


Pesticide Effect
• Assume we use 4 fault detection
techniques and 1000 bugs:

 Each detects only 70% bugs

 How many bugs would remain?

 1000*(0.3)4=81 bugs
Quiz 2
• Certain testing carried out over 5 testing stages
• Each stage can detect 60% of the defects present
at that time.
• Immediately after each testing stage, and before
the next testing stage starts:
 Bug fixes are carried out.
 Each bug fix has a 15% chance of creating a new bug.

• Assume initially number of bugs in a program 1000


 How many bugs would remain after all the five
testing stages are complete?
Dilbert: Scott Adams
Quiz 3:
When are verification undertaken in waterfall model?
When is testing undertaken in waterfall model?
When is validation undertaken in waterfall model?

Feasibility Study

Req. Analysis

Design

Coding

Testing

Maintenance
V Life Cycle
Model

12/30/2021
V Model
• It is a variant of the Waterfall
 emphasizes verification and
validation
 V&V activities are spread over the
entire life cycle.
• In every phase of development:
 Testing activities are planned in
parallel with development.
Project& Production,
Requirements Operation &
Planning Maintenance

Product System&
Requirements& Acceptance
Specification Testing
Analysis

Architecture Integration&
High Level Testing
Design

Detailed Unit
Design testing

Coding
V Model Steps
• Planning

• Requirements • System and


Specification and acceptance testing
Analysis

• Integration and
• Design
Testing
V Model: Strengths
• Starting from early stages of
software development:

 Emphasize planning for verification


and validation of the software

• Each deliverable is made testable

• Easy to use
V Model Weaknesses
• Does not support overlapping of
phases
• Does not support iterations
• Does not easily handle later changes
in requirements
• Does not support risk analysis
activities
When to use V Model
• Natural choice for systems
requiring high reliability:
 Example: embedded control
applications

• All requirements are known up-


front

• Solution and technology are known


Few More
Basic Concepts
on Testing…
12/30/2021
How Many Latent Errors?
• Several independent studies
[Jones],[schroeder] conclude:
 85% errors get removed at the end
of typical testing process.
 Too bad?
 All practical test techniques are
basically heuristics… they help to
reduce errors… but do not
guarantee complete error removal…
Finding 85% of flaws is pretty good?
• Usually acceptable level of quality:
 Except for critical applications
where life is at stake

“Relax, our
engineers have found
and corrected
85% of the flaws.”
Evolution of Test Automation
1960-1990 1990-2000 2000-

Model-Based
Testing

Scripting

Capture and
Replay

Manual Manual Automated


Test design Test design Test design
and and and
Execution Automated Execution
Execution
57
Abbot/JFCUnit/Marathon…
Testing tools
FIT/Fitnesse (High level)
GUI Perfomance and
Load Testing
JMeter/JUnitPerf
Cactus Business
Logic
HttpUnit/Canoo/Selenium

Junit (Low level)


Web UI

Persistence Junit/SQLUnit/XMLUnit
Layer
58
Ack www.dstb.dk
Fault Model
• Types of faults possible in a
program.

• Some types can be ruled out:

For example, file related-


problems in a program not
using files.
Fault Model of an OO Program
Faults in OO Programs

Structural
Algorithmic
Faults
Faults

Procedural Traceability OO Incorrect Inadequate


Faults Faults Faults Result Performance
Hardware Fault-Model
• Simple:
 Stuck-at 0
 Stuck-at 1
 Open circuit
 Short circuit
• Simple ways to test the presence of
each
• Hardware testing is usually fault-
based testing
Test Cases
• Each test case typically tries to
establish correct working of some
functionality:
 Executes (covers) some program
elements
 For certain restricted types of
faults, fault-based testing can be
used.
Test data versus test cases
• Test data: Inputs used to test
the system

• Test cases: Inputs to test the


system and the predicted outputs
from these inputs
What are Negative Test Cases?
• Ensures that an application can
gracefully handle invalid inputs and
unexpected user inputs.
• Example:
 If a user tries to type a letter in a numeric
field, the correct behavior is to display the
message: “Incorrect data type, please enter a
number…”
• The purpose of negative testing:
 Unexpected inputs are handled
satisfactorily and application does not crash.
Test Cases and Test Suites
• Test a software using a set
of carefully designed test
cases:
The set of all test cases is
called the test suite
Test Cases and Test Suites
• A test case is a triplet [I,S,O]
I is the data to be input to the
system,
S is the state of the system at
which the data will be input,
O is the expected output of the
system.
Test Execution Example: Return Book
• Test case [I,S,O]
1. Set the program in the required state:
Book record created, member record
created, Book issued
2. Give the defined input: Select renew
book option and request renew for a
further 2 wk period.
3. Observe the output and compare to the
expected output.
Sample: Recording of Test Case & Results
Test Case number
Test Case author
Test purpose
Pre-condition:
Test inputs:
Expected outputs (if any):
Post-condition:
Test Execution history:
Test execution date
Test execution person
Test execution result (s) : Pass Fail
If failed : Failure information
: fix status
Test - Human Resources (QA Professional)
• Test Planning: Experienced people
• Test scenario and test case design: Experienced
and test qualified people
• Test execution: semi-experienced to
inexperienced
• Test result analysis: experienced people
• Test tool support: experienced people
• May include external people:
 Users

 Industry experts
Why Design of Test Cases?
• Exhaustive testing of any non-trivial
system is impractical:

 Input data domain is extremely large.

• Design an optimal test suite:

 Of reasonable size, and

 Uncovers as many errors as possible.


Design of Test Cases
• If test cases are selected randomly:
 Many test cases would not contribute to
the significance of the test suite,
 Would only detect errors that are already
detected by other test cases in the suite.

• Therefore, the number of test cases in


a randomly selected test suite:
 Not an indication of effectiveness of
testing.
Design of Test Cases
• Testing a system using a large
number of randomly selected test
cases:
 Does not mean that many errors in
the system will be uncovered.
• Consider following example:
 Find the maximum of two integers x
and y.
Design of Test Cases
• The code has a simple programming
error:

• If (x>y) max = x;
else max = x; // should be max=y;

• Test suite {(x=3,y=2);(x=2,y=3)} can


detect the error,

• A larger test suite {(x=3,y=2);(x=4,y=3);


(x=5,y=1)} does not detect the error.
Design of Test Cases
• Systematic approaches are
required to design an effective
test suite:

Each test case in the suite should


detect different errors.
Sample: Recording Test Case & Test suites
Test Case number
Test Case author
A general description of the test purpose
Pre-condition: “includes test results of other pre-req
modules”
Test inputs
Expected outputs (if any)
Post-condition
Test Case history:
Test execution date
Test execution person
Test execution result (s) : Pass Fail
If failed : Failure information
: fix status
Testing Strategy
• Test Strategy primarily addresses:
 Which types of tests to deploy?

 How much effort on which type of


testing?
• Black-box: Usage–based testing (info on
customers’ actual usage pattern)

• White-box testing can be guided by


black box testing results
Sample 1: Model from “past” data

Percentage Breakdown of Problem Discovery and Fixes

40%
Quiz 4: How would you
use this for planning test
Problems effort?
Detected 25%

15%
10%
10%

Reviews Unit Integration System customer


test test test reported
Sample 2: Model from “past” data

Percentage Breakdown of Problem Discovery and Fixes

Quiz 5: How would you


Problems 50% use this for planning
Detected test effort?
30%

10% 10%

test test test customer


Technique 1 Technique 2 Technique 3 reported
Sample 3: Distribution of Error Prone Areas
customer reported bugs for Release 1

Quiz 6: How would you use


this for planning Release 2 testing?
Problems
Detected

F1 F2 F3 F4 F5 F5
Unit Testing

03/08/10 81
When and Why of Unit Testing?
• Unit testing carried out:

• After coding of a unit is complete


and it compiles successfully.

• Unit testing reduces


debugging effort substantially.
Why unit test?
• Without unit test:
Failure
 Errors become
difficult to track
down.

 Debugging cost
increases
substantially…
Unit Testing
• Each part tested
individually and
independently

• Errors picked up earlier

• Scope is smaller,
easier to locate and
fix errors…
Unit Testing
• Testing of individual methods, modules,
classes, or components in isolation:
 Before they are integrated with other
parts of the software being developed.
• Units testing needs:
 Driver
• Simulates the behavior of a function that calls
and possibly supplies some data to the Driver
function being tested.
Unit
 Stub Stub

• Simulates the behavior of a function that has


not yet been written.
Unit Testing

PROCEDURE
STUB DRIVER
CALL UNDER TEST CALL

Access To Nonlocal Variables


Quiz 7
• Unit testing can be considered as
which one of the following types
of activities?

 Verification

 Validation
Design of Unit Test Cases
• There are essentially three main
approaches to design test cases:

Black-box approach

White-box (or glass-box)


approach

Grey-box approach
Black-Box Testing
• Test cases are designed using only
functional specification of the
software: Input
Software Output

 Without any knowledge of the


internal structure of the software.

• Black-box testing is also known as


functional testing.
Dilbert: Scott Adams
White-box Testing
• To design test cases:
Knowledge of internal
structure of software
necessary.

White-box testing is also


called structural testing.
Black-box Testing

03/08/10 92
Black box testing
• Considers the software as a black box:
Test data derived from the specification
• No knowledge of code necessary

• Also known as:


 Data-driven or
 Input/output driven testing
• The goal is to achieve the thoroughness
of exhaustive input testing:
With much less effort!!!!
Black-Box Testing
• Common approaches to design
black box test cases:
Equivalence class partitioning
Boundary value analysis
Cause-effect (Decision Table)
testing
Combinatorial testing
Equivalence Class
Testing

03/08/10 95
Equivalence Class Partitioning
• The input values to a program:
 Partitioned into equivalence classes.

• Partitioning is done such that:


 Program behaves in similar ways to
every input value belonging to an
equivalence class.
 At the least there should be as many
equivalence classes as scenarios.
Why Define Equivalence Classes?
• Test the code with one
representative value from
each equivalence class:

Premise: Nearly as good as


testing using any other values
from an equivalence class.
Equivalence Class Partitioning
• How do you identify the
equivalence classes?
Identify scenarios
Examine the input data.
•Few guidelines for determining
the equivalence classes can be
given…
Equivalent class partitioning.
• Determine equivalent classes in
outputs:
 Give test cases for each class
• Example: Given three sides,
determine the type of the triangle:
 Isosceles
 Scalene
 Equilateral, etc.
Equivalence Partitioning
• First-level partitioning:
 Valid vs. Invalid test cases

Valid Invalid
Equivalence Partitioning
• Further partition valid and invalid
test cases into equivalence classes
Equivalence Partitioning
• Create a test case for at least one
value from each equivalence class
Equivalence Class Partitioning
• If the input data to the program is
specified by a range of values:
 e.g. numbers between 1 to 5000.

 One valid and two invalid equivalence


classes are defined.
1 5000
Equivalence Class Partitioning
• If input is an enumerated set of
values, e.g. :
 {a,b,c}
• Define:
 One equivalence class for valid input
values.
 Another equivalence class for invalid
input values should be defined.
Example
• A program reads an input value
in the range of 1 and 5000:

Computes the square root of the


input number

SQRT
Example (cont.)

• Three equivalence classes:


 The set of negative integers,
 Set of integers in the range of 1 and
5000,

 Integers larger than 5000.

1 5000
Example (cont.)
• The test suite must include:
Representatives from each of the
three equivalence classes:

A possible test suite can be:


{-5,500,6000}.
1 5000
Equivalence Partitioning: Example 2
 Example: string Fetch(URL)
• Equivalence Definition 1: partition test
cases by URL protocol (“http”, “https”,
“ftp”, “file”, etc.)

• Equivalence Definition 2: partition test


cases by type of file being retrieved
(HTML, GIF, JPEG, Plain Text, etc.)

• Etc.
Equivalence Partitioning: Example 2
Input Valid Equivalence Invalid Equivalence
Classes Classes

A integer N such
that:
-99 <= N <= 99 ? ?
Phone Number
Area code: [11,
999] ? ?
Suffix: Any 6 digits
Equivalence Partitioning: Example 4
Input Valid Equivalence Classes Invalid Equivalence Classes

A integer N such that: [-99, 99] < -99


-99 <= N <= 99 > 99
Malformed numbers
{12-, 1-2-3, …}
Non-numeric strings
{junk, 1E2, $13}
Empty value

Phone Number [11,999][0,9][0,9][0,9][0,9 Invalid format 5555555,


Prefix: [11, 999] ][0,9][0,9] (555)(555)555566, etc.
Suffix: Any 6 digits Area code < 11 or > 999
Area code with non-numeric
characters
Similar for Prefix and
Suffix
Weak Equivalence Class Testing
age

yrs of ed.
Strong Equivalence Class Testing

age

Yrs of ed.
Strong Robust Equivalence Class
Testing
age

yrs of ed.
Quiz 7
• Design Equivalence class test cases:
• A bank pays different rates of interest on
a deposit depending on the deposit period.
 3% for deposit up to 15 days
 4% for deposit over 15days and up to 180
days
 6% for deposit over 180 days upto 1 year
 7% for deposit over 1 year but less than 3
years
 8% for deposit 3 years and above
Quiz 8
• Design Equivalence class test cases:
• For deposits of less than Rs. 1 Lakh, rate of
interest:
 6% for deposit upto 1 year
 7% for deposit over 1 year but less than 3 years
 8% for deposit 3 years and above

• For deposits of more than Rs. 1 Lakh, rate of


interest:
 7% for deposit upto 1 year
 8% for deposit over 1 year but less than 3 years
 9% for deposit 3 years and above
Quiz 9
• Design equivalence class test cases.
 Consider a program that takes 2
strings of maximum length 20 and 5
characters

 Checks if the second is a substring of


the first

 substr(s1,s2);
Boundary Value
Testing

03/08/10 117
Boundary Value Analysis
• Some typical programming errors occur:

 At boundaries of equivalence classes

 Might be purely due to psychological


factors.

• Programmers often fail to see:


 Special processing required at the
boundaries of equivalence classes.
Boundary Value Analysis
• Programmers may improperly
use < instead of <=

• Boundary value analysis:


Select test cases at the
boundaries of different
equivalence classes.
Boundary Value Testing Example
• Process employment applications based
on a person's age.
0-16 Do not hire
16-18 May hire on part time basis
18-65 May hire full time
65-100 Do not hire

• Notice the problem at the boundaries.

 Age "16" is included in two different


equivalence classes (as are 18 and 55).
Boundary Value Testing Example (cont)
• If (applicantAge >= 0 && applicantAge <=16)
hireStatus="NO";

• If (applicantAge >= 16 && applicantAge <=18)


hireStatus="PART";

• If (applicantAge >= 18 && applicantAge <=55)


hireStatus="FULL";

• If (applicantAge >= 55 && applicantAge <=99)


hireStatus="NO";
Boundary Value Testing Example (cont)
• Actually this is what our organization meant:
0–15 Don't hire
16–17 Can hire on a part-time basis only
18–54 Can hire as full-time employees
55–99 Don't hire

• What about ages -3 and 101?

• The requirements do not specify how these


values should be treated.
Boundary Value Testing Example (cont)
• The code that implements the corrected rules is:
If (applicantAge >= 0 && applicantAge <=15)
hireStatus="NO";
If (applicantAge >= 16 && applicantAge <=17)
hireStatus="PART";
If (applicantAge >= 18 && applicantAge <=54)
hireStatus="FULL";
If (applicantAge >= 55 && applicantAge <=99)
hireStatus="NO";
• The interesting values on or near the boundaries in this
example are {-1, 0, 1}, {15, 16, 17}, {17, 18, 19}, {54, 55,
56}, and {98, 99, 100}.
Boundary Value Analysis
• Create test cases to test boundaries
of equivalence classes
Example 1
• For a function that computes
the square root of an integer in
the range of 1 and 5000:
Test cases must include the
values: {0,1,2,4999,5000,5001}.
1 5000
Example 2
• Consider a program that reads the “age” of
employees and computes the average age.
input (ages) → Program → output: average
age
Assume valid age is 1 to 150
• How would you test this?
 How many test cases would you generate?
 What type of test data would you input to test
this program?
Boundaries of the inputs

1 <= age <= 150


1 age 150
The “basic” boundary value testing would include 5
situations:
1. - at minimum boundary
2. - immediately above minimum
3. - between minimum and maximum (nominal)
4. - immediately below maximum
5. - at maximum boundary
Test Cases for this Example
• How many test cases for this example ?
 answer : 5

• Test input values? :


1 at the minimum

2 at one above minimum


45 at middle

149 at one below maximum

150 at maximum
Independent Data
• Suppose there are 2 “distinct” inputs that are
assumed to be independent of each other.
 Input field 1: years of education ( say 1 to 23 )
 Input field 2: age (1 to 150)

• If they are independent of each other, then we


can start with 5 + 5 = 10 sets.
coverage of input data: yrs of ed coverage of input data: age

1. n= 1 ; age = whatever(37) 1. n= 12; age = 1


2. n =2; age = whatever 2. n =12; age = 2
3. n = 12; age = whatever 3. n = 12; age = 37
4. n = 22; age = whatever 4. n = 12; age = 149
5. n = 23; age = whatever 5. n = 12; age = 150
2 – Independent inputs

age

yrs of ed.
- Note that there needs to be only 9 test cases for 2
independent inputs.
- In general, need (4z + 1) test cases for z independent inputs.
Boundary Value Test
Given F(x,y) with constraints a  x  b
c  y  d
Boundary Value analysis focuses on the boundary
of the input space to identify test cases.
Use input variable value at min, just above min, a
nominal value, just above max, and at max.
y
d

x
Single Fault Assumption
• Premise: “Failures rarely occur as the
result of the simultaneous occurrence
of two (or more) faults”

• Under this:

 Hold the values of all but one variable at


their nominal values, and let that one
variable assume its extreme values.
Boundary Value Analysis: Example 1
• Numeric values are often entered as strings :

 Internally converted to numbers [int x = atoi(str);]

• This conversion requires the program to


distinguish between digits and non-digits

• A boundary case to consider: Will the program


accept / and : as digits?

Char / 0 1 2 3 4 5 6 7 8 9 :

ASCII 47 48 49 50 51 52 53 54 55 56 57 58
Robustness testing
• This is just an extension of the Boundary Values
to include:
 Less than minimum
 Greater than maximum

• There are 7 cases or values to worry about for


each independent variable input
• The testing of robustness is really a test of
“error” handling. Levels of
Problem
Severity?
1. Do we anticipate the error situations?
2. Do we issue informative error messages?
3. Do we allow some kind of recovery from the error?
2 – independent inputs for robustness test

Y
- Note that there needs to be only 13 test cases for 2 independent
variables or inputs.
- In general, there will be (6n+ 1) test cases for n independent inputs.
Some Limitations of Boundary Value Testing

• How to handle boolean variables?


 True

 False

(these may be radio buttons)

• What about non-numerical variable


where the values may be text?
Quiz 10: BB Test Design
• Design black box test suite for a
function that solves a quadratic equation
of the form ax2+bx+c=0.

• Equivalence classes
 Invalid Equation
Complex
 Valid Equation: Roots? Coincident
Real
Unique
Decision Table
Testing

03/08/10 138
Combinatorial Testing: Motivation
• The behavior of a program may be affected
by many factors:
 Input parameters,
 Environment configurations, and
 State variables.
• Equivalence partitioning and boundary-value
analysis:
 Identify the possible values of individual
factors.
• In fact, it is impractical to test all possible
combinations of values of all factors.
Decision table-based Testing (DTT)
• Applicable to requirements involving
conditional actions.
• Can be automatically translated into code
Rule1 Rule2 Rule3 Rule4

Conditions = inputs Condition1

Condition2
Yes

Yes
Yes

X
No

No
No

Actions = outputs
Condition3 No Yes No X

Condition4 No Yes No Yes

Action1 Yes Yes No No

Rules =test cases


Action2 No No Yes No

Action3 No No No Yes

• Assume the independence of inputs


• Example
If c1 AND c2 OR c3 then A1
Combinations

• : Rule1 Rule2 Rule3 Rule4

Condition1 Yes Yes No No

Conditi Condition2 Yes X No X


ons
Condition3 No Yes No X

Condition4 No Yes No Yes

Action1 Yes Yes No No

Actions Action2 No No Yes No

Action3 No No No Yes
Sample Decision table
• A decision table consists of a
number of columns (rules) that r1 r2 … rn
comprise all test situations
• Action ai will take place if c1 and C1 0 1 0
c2 are true
c2 - 1 0
• Example: the triangle problem
 C1: a, b,c form a triangle C3 - 1 1
 C2: a=b C4 - 1 0
 C3: a= c
a1 1 0 0
 C4: b= c
 A1: Not a triangle a2 0 1 1
 A2:scalene
a3 0 0 0
 A3: Isosceles
 A4:equilateral
a4 0 1 1
 A5: impossible
a5 0 0
Test cases from Decision Tables
Test Case Expected
ID a b c output

DT1 4 1 2 Not a
Triangle
DT2 2888 2888 2888 Equilateral
DT3 ? | ) Impossible
DT4

DT11
Decision Table for the Triangle
Problem
Conditions
C1: a < b+c? F T T T T T T T T T T
C2: b < a+c? - F T T T T T T T T T
C3: c < a+b? - - F T T T T T T T T
C4: a=b? - - - T T T T F F F F
C5: a=c? - - - T T F F T T F F
C6: b-c? - - - T F T F T F T F
Actions
A1: Not a Triangle X X X
A2: Scalene X
A3: Isosceles X X X
A4: Equilateral X
A5: Impossible X X X 144
Test Cases for the Triangle Problem
Case ID a b c Expected
Output
DT1 4 1 2 Not a
Triangle
DT2 1 4 2 Not a
Triangle
DT3 1 2 4 Not a
Triangle
DT4 5 5 5 Equilateral

DT5 ? ? ? Impossible

DT6 ? ? ? Impossible

DT7 2 2 3 Isosceles

DT8 ? ? ? Impossible

DT9 2 3 2 Isosceles

DT10 3 2 2 Isosceles
145
DT11 3 4 5 Scalene
Decision Table – Example 2
Printer does not print Y Y Y Y N N N N

Conditions A red light is flashing Y Y N N Y Y N N

Printer is unrecognized Y N Y N Y N Y N

Check the power cable X

Check the printer-computer


X X
cable
Actions
Ensure printer software is
X X X X
installed
Check/replace ink X X X X

Check for paper jam X X

Printer Troubleshooting
Quiz 11: Develop BB Test Cases
• Policy for charging customers for
certain in-flight services:

If the flight is more than half-full and


ticket cost is more than Rs. 3000,
free meals are served unless it is a
domestic flight. The meals are
charged on all domestic flights.
Fill all combinations in the table.
POSSIBLE COMBINATIONS

more than
N N N N Y Y Y Y
half-full
CONDITONS

more than
Rs.3000 per N N Y Y N N Y Y
seat

domestic
N Y N Y N Y N Y
flight
ACTIONS
Analyze column by column to determine which
actions are appropriate for each combination
POSSIBLE COMBINATIONS

more than half-


N N N N Y Y Y Y
full
CONDITONS

more than Rs.


N N Y Y N N Y Y
3000 per seat

domestic flight N Y N Y N Y N Y
ACTIONS

serve meals X X X X

free X
Reduce the table by eliminating
redundant columns.
POSSIBLE COMBINATIONS
more than
N N N N Y Y Y Y
half-full
CONDITONS

more than Rs.


N N Y Y N N Y Y
3000 per seat

domestic flight N Y N Y N Y N Y
ACTIONS

serve meals X X X X

free X
Final solution
Combinations

more than half-full N Y Y Y


CONDITONS

more than 3000 per


- N Y Y
seat

domestic flight - - N Y
ACTIONS

serve meals X X X

free X
Assumptions regarding rules
Rules need to be complete:
• That is, every combination of decision
table values including default
combinations are present.

Rules need to be consistent:


• That is, there is no two different
actions for the same combinations of
conditions
Guidelines and Observations
• Decision Table testing is most appropriate for
programs for which:
 There is a lot of decision making
 There are important logical relationships among
input variables
 There are calculations involving subsets of input
variables
 There are cause and effect relationships between
input and output
 There is complex computation logic

• Decision tables do not scale up very well


153
Quiz 12: Design test Cases
• Customers on a e-commerce site get
following discount:
 A member gets 10% discount for
purchases lower than Rs. 2000, else 15%
discount
 Purchase using SBI card fetches 5%
discount
 If the purchase amount after all discounts
exceeds Rs. 2000/- then shipping is free.
Quiz 13: Design Test Cases
• Students in:
 The range [80%, 100%] gpa are
admitted and receive a scholarship.

 The range [70%, 80%) gpa are


admitted but have no scholarship.

 The range [60%, 70%) gpa are


admitted if they have no failures.

 Otherwise they are not admitted


Cause-effect Graphs
• Overview:
Explores combinations of possible inputs
Specific combinations of inputs (causes)
and outputs (effects)
Avoids combinatorial explosion
 Represented as nodes of a cause effect
graph
 The graph also includes constraints and a
number of intermediate nodes linking
causes and effects
Cause-Effect Graph Example
• If depositing less than Rs. 1 Lakh, rate of
interest:
 6% for deposit upto 1 year
 7% for deposit over 1 year but less than 3 yrs
 8% for deposit 3 years and above
• If depositing more than Rs. 1 Lakh, rate of
interest:
 7% for deposit upto 1 year
 8% for deposit over 1 year but less than 3 yrs
 9% for deposit 3 years and above
Cause-Effect Graph Example
Causes Effects
C1: Deposit<1yr e1: Rate 6%

C2: 1yr<Deposit<3yrs e2: Rate 7%

C3: Deposit>3yrs e3: Rate 8%

C4:Deposit <1 Lakh e4: Rate 9%

C5: Deposit >=1Lakh


Cause-Effect Graphing
c4 e10 e1

c5 e2
e20

c1 e30 e3

c2 e40
e4
c3 e50

e60
Develop a Decision Table

C1 C2 C3 C4 C5 e1 e2 e3 e4
1 0 0 1 0 1 0 0 0
1 0 0 0 1 0 1 0 0

0 1 0 1 0 0 1 0 0
0 1 0 0 1 1 0 1 0
• Convert each row to a test case
Capture/Playback Tools
• Automated test tools mimic actions of the tester.

• During testing, the tester uses the keyboard and mouse


to perform some type of test or action.

• Testing tool captures all keystrokes and results:


 Baselined in a test script.

• During test playback, scripts compare latest outputs


with previous baseline.

• Test tools provide for non-intrusive testing:


 interact with the “application-under-test” as if the test tool
was not involved.
QTP: Record
and Playback
• Steps to follow:
• 1 Open Quick Test.

• 2 Open a test:
 To create a new test,
click on New
 To open an existing test,
click on Open

• 3 Click the Record button


If you are recording for
the first time the Record
and Run Settings dialog
box opens.
Playback

Sprint\zXC
abcde
Selenium: History
• Developed in 2004 by Jason Huggins as a JavaScript
library used to automate his manual testing routines
• Selenium Core is born whose functionality underlies the
Selenium RC (Remote Control) and Selenium IDE tools
• The Limitation of having a JavaScript based automation engine
and browser security restricted Selenium to specific
functionality

• Googlebeen a long time user of Selenium, had a developer


named Simon Stewart who developed WebDriver.
• Circumvented Selenium’s JavaScript sandbox to allow it to
communicate with the Browser and Operating System directly

• In 2008, Selenium and WebDriver merged to provide an


excellent test automation framework
Story about Selenium
• Selenium is a chemical element with the atomic number 34, represented
by the chemical symbol Se.
•It is a nonmetal, chemically related to sulfur and tellurium, and rarely
occurs in its elemental state in nature.

Selenium.

•Selenium is used for treating Mercury Poisoning 165


Selenium IDE - UI

Start and Stop


Replay Recording
Toolbar

Selenese
Script
Editor

Accessor
Area

Selenium Log
Recoding a Selenium Test Case
• Open Firefox that has the IDE installed
• Open the base URL of the application to record.
• Keep the application in a common base state.
• Go To Tools  Selenium IDE and the IDE will be
opened
• Now perform the operations on the application as
you are testing the application.
• Once you are done with the recording
 Click on the stop recording button and save the test case
through the file menu.
 By default it will be saved as a selenese script (HTML
167
Cons of Capture/Replay
• High maintenance costs:
 Software change can mean many script
changes
• Fair amount of effort to produce
scripts:
 Similar for each test procedure
 Duplication of effort and high
maintenance costs 168
Duplicated Script

12/30/2021 169
Data-driven Testing
• Test data separated from scripts
 Placed into separate data files

 Control script reads data from data file

• One script implements several tests:


 Reads different data files

 Reduces script maintenance costs

 Faster and easier to automate similar test


procedures 170
Data-driven vs. Keyword Driven

12/30/2021 171
Example Key-word Test

12/30/2021 172
Data-Driven versus Keyword Driven Testing
• These frameworks are similar in that the
data is separated from the test script
• The script is just a "driver" or delivery
mechanism for the data.
• The difference:
 In keyword-driven testing, the navigation data
and test data are contained in the data source

 In data-driven testing, only test data is


contained in the data source.
Advantages of Keyword-Driven Test
automation
• Reduced the cost and time spent maintaining and
updating tests
• The modular structure of keyword-driven testing
means that new tests can easily be created from
pre-existing modules
• The test team is capable of entirely automating
tests, even without programming knowledge
• Can be easily modified to use with different test
tool
• Reusability across different projects
Classic Keyword-Driven Example

Object Action Data

Textfield (username) Enter Text <username>


Combinatorial
Testing

03/08/10 176
Combinatorial Testing

0 = effect off
1 = effect on

210 = 1,024 tests for all combinations

* 10 3 = 1024 * 1000 …. Just too many to test


177
Combinatorial Testing Problem

X1 X2 X3 . . . Xn

System S

•Combinatorial testing problems generally


follow a simple input-process-output model;
•The “state” of the system is not the focus
of combinatorial testing.
178
Combinatorial Testing
• Instead of testing all possible
combinations:
 A subset of combinations is generated.
• Key observation:
 It is often the case that a fault is caused
by interactions among a few factors.
• Combinatorial testing can dramatically
reduce the number of test cases:
 but remains effective in terms of fault
179
detection.
Interaction Testing
Interest Rate | Amount | Months | Down Pmt | Pmt Frequency

All values: every etc. . . .


value of every
parameters
All pairs: every
value of each pair
of parameters

t-way interactions: every


value of every t-way
combination of parameters
How to find all failures?
•Interactions:
•E.g., failure occurs if
pressure < 10 (1-way interaction)
pressure < 10 & volume > 300
(2-way interaction)‫‏‬
• Most complex failure required
4-way interaction
100

90

80

70
% detected

60

50

40

30

20

10

0
1 2 3 4

Interaction
How about other applications?
• Browser

100

90

80

70

60
% detected

50

40

30

20

10

0
1 2 3 4 5 6
Interactions
How about other applications?
• Server

100

90

80

70

60
% detected

50

40

30

20

10

0
1 2 3 4 5 6
Interactions
How about other applications?
• NASA distributed database

100

90

80

70

60
% detected

50

40

30

20

10

0
1 2 3 4 5 6
Interactions
How about other applications?
•TCAS

100

90

80

70

60
% detected

50

40

30

20

10

0
1 2 3 4 5 6
Interactions
When a Tester Works Too Well…

Dilbert: Scott Adams


Pairwise Reductions
Number Number of Number of Size of
of inputs selected combinations pair wise
test data test set
values
7 2 128 8

13 3 1.6 x 106 15

40 3 1.2 x 1019 21

187
Fault-Model
• A t-way interaction fault:
 Triggered by a certain combination of t
input values.

 A simple fault is a 1-way fault

 Pairwise fault is a t-way fault where t = 2.

• In practice, a majority of software


faults consist of simple and pairwise
188
faults.
Single-mode Bugs
• The simplest bugs are single-mode
faults:
 Occur when one option causes a problem
regardless of the other settings

 Example: A printout is always gets


smeared when you choose the duplex option
in the print dialog box

• Regardless of the printer or the other selected


options
Double-mode Faults
• Double-mode faults
 Occurs when two options are
combined
 Example: The printout is smeared
only when duplex is selected and the
printer selected is model 394

190
Multi-mode Faults
• Multi-mode faults

 Occur when three or more settings


produce the bug

 This is the type of problems that make


complete coverage seem necessary
Example of Pairwise Fault
• begin
 int x, y, z;
 input (x, y, z);
 if (x == x1 and y == y2)
• output (f(x, y, z));

 else if (x == x2 and y == y1)


• output (g(x, y));

 Else // Missing (x == x2 and y == y1) f(x, y, z) – g(x, y);


• output (f(x, y, z) + g(x, y))

• end
• Expected: x = x1 and y = y1 => f(x, y, z) – g(x, y);
192
x = x2, y = y2 => f(x, y, z) + g(x, y)
A larger example
• Suppose we have a system with 34 on-off switches:
Example: Android smart phone testing
• Apps should work on all combinations of platform options,
but there are 3 x 3 x 4 x 3 x 5 x 4 x 4 x 5 x 4 = 172,800
configurations

HARDKEYBOARDHIDDEN_NO ORIENTATION_LANDSCAPE
HARDKEYBOARDHIDDEN_UNDEFINED ORIENTATION_PORTRAIT
HARDKEYBOARDHIDDEN_YES ORIENTATION_SQUARE
ORIENTATION_UNDEFINED
KEYBOARDHIDDEN_NO
KEYBOARDHIDDEN_UNDEFINED SCREENLAYOUT_LONG_MASK
KEYBOARDHIDDEN_YES SCREENLAYOUT_LONG_NO
SCREENLAYOUT_LONG_UNDEFINED
KEYBOARD_12KEY SCREENLAYOUT_LONG_YES
KEYBOARD_NOKEYS
KEYBOARD_QWERTY SCREENLAYOUT_SIZE_LARGE
KEYBOARD_UNDEFINED SCREENLAYOUT_SIZE_MASK
SCREENLAYOUT_SIZE_NORMAL
NAVIGATIONHIDDEN_NO SCREENLAYOUT_SIZE_SMALL
NAVIGATIONHIDDEN_UNDEFINED SCREENLAYOUT_SIZE_UNDEFINED
NAVIGATIONHIDDEN_YES
TOUCHSCREEN_FINGER
NAVIGATION_DPAD TOUCHSCREEN_NOTOUCH
NAVIGATION_NONAV TOUCHSCREEN_STYLUS
NAVIGATION_TRACKBALL TOUCHSCREEN_UNDEFINED
NAVIGATION_UNDEFINED
NAVIGATION_WHEEL
Quiz 14
• Design black-box test suite for a
function that accepts two strings of
size upto 10 characters and reports
the number of times the second
string occurs in the first string.
End

03/08/10 196
Cause-Effect Graphing
Example: Control motion module in the automated
train software project
1. List and label all Causes and all effects
Causes Effects
C1: Start e100: Release all Brakes
C2: Idle e200: Engage_Engine
C3: speed = Max_speed e300: Disengage_Engine
C4:Accelerating e400: Apply Ph. 1 Brakes
C5: Speed > Max_speed e500: Release Ph. 1 brakes
C6: Coasting e600: Apply Ph. 2 brakes
C7: Speed <= Min_speed e700: Apply Safety brakes
Software Testing Techniques
Speed > Max_speed /
Apply Ph. 1 brakes
Coasting Decelerating
Speed <= Speed = Max_speed / Stop /
Min_speed/ Disengage_Engine
Engage
Engine
stopping
Accelerating
Speed = Stopping_Speed
Start / Rlease all Braks
Engage Engine

Idle Applying ph II
Cause-Effect Graphing

c1 e10 e100

c2 e200

c3 e20 e300

c4
e40 c5 e30 e400

c7 c6
White-Box Testing

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.

03/08/10 1
What is White-box Testing?

• White-box test cases


designed based on:

Code structure of program.

White-box testing is also called


structural testing.
White-Box Testing Strategies
• Coverage-based:
 Design test cases to cover
certain program elements.

• Fault-based:
 Design test cases to expose
some category of faults
White-Box Testing
• Several white-box testing strategies have
become very popular :
 Statement coverage
 Branch coverage
 Path coverage
 Condition coverage
 MC/DC coverage
 Mutation testing
 Data flow-based testing
Why Both BB and WB Testing?
Black-box White-box
• Impossible to write • Does not address the
a test case for
every possible set of question of whether
inputs and outputs a program matches
• Some code parts the specification
may not be • Does not tell if all of
reachable
the functionality has
• Does not tell if been implemented
extra functionality
has been • Does not uncover any
implemented. missing program logic
Coverage-Based Testing Versus Fault-
Based Testing
• Idea behind coverage-based testing:
 Design test cases so that certain program
elements are executed (or covered).
 Example: statement coverage, path
coverage, etc.
• Idea behind fault-based testing:
 Design test cases that focus on
discovering certain types of faults.
 Example: Mutation testing.
Types of program element Coverage
• Statement: each statement executed
at least once
• Branch: each branch traversed (and
every entry point taken) at least once
• Condition: each condition True at least
once and False at least once
• Multiple Condition: All combination of
Condition coverage achieved
• Path:
• Dependency:
Stronger and Weaker Testing

Coverage

Stronger
Weaker
Complementary Testing

Coverage
Strategy 1
Strategy 2
Stronger, Weaker, and
Complementary Testing

Complementary

Weaker
Statement Coverage
• Statement coverage
strategy:

Design test cases so that


every statement in the
program is executed at least
once.
Statement Coverage
• The principal idea:
Unless a statement is executed,

We have no way of knowing if


an error exists in that
statement.
Statement Coverage Criterion
• However, observing that a
statement behaves properly for
one input value:

 No guarantee that it will behave


correctly for all input values!
Statement Coverage
• Coverage measurement:
# executed statements
# statements

• Rationale: a fault in a statement can


only be revealed by executing the
faulty statement
Example
• int f1(int x, int y){
• 1 while (x != y){
•2 if (x>y) then
•3 x=x-y;
•4 else y=y-x;
•5}
• 6 return x; }
Example
int f1(int x,int y){
1 while (x != y){
2 if (x>y) then
3 x=x-y;
4 else y=y-x;
5 }
6 return x; }
Euclid's GCD Algorithm
• By choosing the test set
{(x=3,y=3),(x=4,y=3), (x=3,y=4)}

All statements are executed at


least once.
Branch Coverage
• Also called decision coverage.
• Test cases are designed such
that:

Each branch condition


•Assumes true as well as false
value.
Example
int f1(int x,int y){
1 while (x != y){
2 if (x>y) then
3 x=x-y;
4 else y=y-x;
5 }
6 return x; }
Example
• Test cases for branch
coverage can be:

• {(x=3,y=3),(x=3,y=2),
(x=4,y=3), (x=3,y=4)}
Branch Testing
• Adequacy criterion: Each branch
(edge in the CFG) must be
executed at least once
• Coverage:
# executed branches
# branches
Quiz 1: Branch and Statement
Coverage: Which is Stronger?

• Branch testing guarantees


statement coverage:

A stronger testing compared


to the statement coverage-
based testing.
Stronger Testing
• Stronger testing:
Superset of weaker testing
A stronger testing covers all the
elements covered by a weaker
testing.
Covers some additional elements
not covered by weaker testing
Coverage Report
Statements vs Branch Testing
• Traversing all edges of a graph causes all
nodes to be visited

 So a test suite that satisfies branch


adequacy criterion also satisfies statement
adequacy criterion for the same program.

• The converse is not true:

 A statement-adequate (or node-adequate)


test suite may not be branch-adequate
(edge-adequate).
All Branches can still miss
conditions
• Sample fault: missing operator (negation)

digit_high == 1 || digit_low == -1

• Branch adequacy criterion can be satisfied


by varying only digit_low

 The faulty sub-expression might not be


tested!

 Even though we test both outcomes of the


branch
Condition Coverage
• Also called multiple condition
(MC) coverage .
• Test case design:
Each component of a composite
conditional expression
•Made to assumes both true and false
values.
Example
• Consider the conditional expression
 ((c1.and.c2).or.c3):

• Each of c1, c2, and c3 are


exercised at least once,
 That is, given true and false values.
Basic condition testing
• Adequacy criterion: each basic
condition must be executed at
least once
• Coverage:
# truth values taken by all basic conditions
2 * # basic conditions
Branch Testing
• To think of it:

Branch testing is the simplest


condition testing strategy:

Compound conditions determining


different branches
•Are given true and false values.
Branch Testing
• Condition testing:
Stronger testing than branch
testing. Multiple Condition

Basic Condition
• Branch testing:
Decision

Stronger than statement


Statement
coverage testing.
Condition Coverage
• Consider a Boolean expression
having n components:
n
 For condition coverage we require 2
test cases.
• Condition coverage-based testing
technique:
 Practical only if n (the number of
component conditions) is small.
Compound conditions: Exponential complexity
(((a || b) && c) || d) && e

Test a b c d e
Case 5
2 =32
(1) T — T — T
(2) F T T — T
(3) T — F T T
(4) F T F T T
(5)
(6)
F
T
F


T
T

T
F
•Short-circuit
(7) F T T — F evaluation often

(8) T F T F
reduces number of test
(9) F T F T F
(10) F F — T F cases to a more
(11) T — F F — manageable number,
(12) F T F F —
(13) F F — F — but not always…
Modified Condition/Decision Coverage (MC/DC)
• Motivation: Effectively test important
combinations of conditions, without
exponential blowup in test suite size
 “Important” combinations means: Each basic
condition shown to independently affect the
outcome of each decision
• Requires:
 For each basic condition C, two test cases
 Values of all evaluated conditions except C are
the same
 Compound condition as a whole evaluates to
true for one and false for the other
Test Coverage Criteria
Condition/Decision Coverage Subsumption hierarchy
 Condition: true, false.
 Decision: true, false. MCC
Multiple Condition coverage (MCC)
 all possible combinations of condition
outcomes in a decision MC/DC
 for a decision with n conditions
2n test cases are required Condition/Decision
Modified Condition/Decision coverage
(MC/DC)
Decision
 Bug-detection effectiveness almost
similar to MCC
Statement
 Linear growth in number of test cases
required.
What is MC/DC?
• MC/DC stands for Modified Condition /
Decision Coverage
• A kind of Predicate Coverage technique
 Condition: Leaf level Boolean expression.
 Decision: Controls the program flow.
• Main idea: Each condition must be
shown to independently affect the
outcome of a decision.
 The outcome of a decision changes as a
result of changing a single condition.
Multiple Condition Coverage
(MCC)
• Every condition in the decision has
taken all possible outcomes at least
once.

If ((a) & (b) | (c)) then…

true false true false true false


MC/DC
Requirement 1:

• Every decision in a program must take T/F


values.

Requirement 2:

• Every condition in a decision must take T/F


values.

Requirement 3:

• Each condition in a decision should independently


affect the decision's outcome.
MC/DC Requirement 1

• The decision takes T/F values.

If (( a ) && (( b ) || ( c ))) then

true false

 As in Branch coverage.
40
MC/DC Requirement 2
• Every condition in the decision has taken
all possible outcomes at least once.

If ( (a) && ( (b) || ( c ) )) then…

true false true false true false

 Aims to cover both outcomes of each


condition.
41
MC/DC Requirement 3
• Every condition in the decision independently
affects the decision’s outcome.

If ( ( a ) && (( b ) || ( c )) ) then…

true false true false

If ( ( a ) && (( b ) || ( c ) )) then…

true true false false

If ( ( a ) && ( ( b ) ||( c ) )) then…

true false true false


 Change the value of each condition individually while
42
keeping all other conditions constant.
MC/DC: Linear complexity
• N+1 test cases for N basic conditions

(((a || b) && c) || d) && e

Test a b c d e outcome
Case
(1) true -- true -- true true
(2) false true true -- true true
(3) true -- false true true true
(6) true -- true -- false false
(11) true -- false false -- false
(13) false false -- false -- false

• Underlined values independently affect the output of the


decision
• Required by the RTCA/DO-178B standard
Creating MC/DC test cases
• Create truth table for conditions.
 Extend the truth table to represent test case pair
that lead to show the independence of each
condition.
Example : If ( A and B ) then . . .
 Show independence of A :
Test A B Output Test Test - Take 1 + 3
Case case case
Number pair pair
for A for B  Show independence of B :
1 T T T 3 2 - Take 1 + 2
2 T F F 1
3 F T F 1 Resulting test cases are
-1+2+3
4 F F F
- ( T, T ) + ( T, F ) + ( F, T )
44
Comments on MC/DC
• MC/DC is
 basic condition coverage (C)
 branch coverage (DC)
 plus one additional condition (M):
every condition must independently affect the
decision’s output
• It is subsumed by compound conditions and
subsumes all other criteria discussed so far
 stronger than statement and branch coverage
• A good balance of thoroughness and test size
and therefore widely used…
More advanced example
If (A and (B or C)) then…

Note: We want to
determine the MINIMAL
set of test cases
Here:
• {2,3,4,6}
•{2,3,4,7}

Non-minimal set is:


•{1,2,3,4,5}
Where does it fit in?
• MC/DC criterion is stronger
than condition/decision
coverage criterion,
 but the number of test cases to
achieve the MC/DC criterions still
linearly in the number of
conditions n in the decisions.
 Much more complete coverage
than condition/decision coverage,
 At the same time it is not terribly
costly in terms of number of test
cases.
Path Coverage
• Design test cases such that:
 All linearly independent paths in
the program are executed at
least once.

• Defined in terms of
 Control flow graph (CFG) of a
program.
Path Coverage-Based Testing
• To understand the path coverage-
based testing:
 We need to learn how to draw control
flow graph of a program.
• A control flow graph (CFG) describes:
 The sequence in which different
instructions of a program get executed.
 The way control flows through the
program.
How to Draw Control Flow Graph?
• Number all statements of a program.
• Numbered statements:
 Represent nodes of control flow graph.
• An edge from one node to another node
exists:
 If execution of the statement
representing the first node can result
in transfer of control to the other
node.
Example
int f1(int x,int y){
1 while (x != y){
2 if (x>y) then
3 x=x-y;
4 else y=y-x;
5 }
6 return x; }
Example Control Flow
Graph
1

3 4
5

6
How to Draw Control flow Graph?
• Every program is composed of:
 Sequence
 Selection
 Iteration
• If we know how to draw CFG
corresponding these basic
statements:
 We can draw CFG for any program.
How to Draw Control flow
Graph?
• Sequence:
1 a=5; 1
2 b=a*b-1;

2
How to Draw Control Flow
Graph?
• Selection:
 1 if(a>b) then 1
2 c=3;
 3 else c=5; 2 3
 4 c=c*c;
4
How to Draw Control Flow
Graph?
• Iteration:
1
 1 while(a>b){
2 b=b*a;
3 b=b-1;} 2
 4 c=b+d;

4
Example Code Fragment
Do
{
if (A) then {...};
else {
if (B) then {
if (C) then {...};
else {…}
}
else if (D) then {...};
else {...};
}
}
While (E);
Example Control Flow Graph

True

True
B

C D
True True

E
True

Source: The Art of Software Testing – Glenford Myers


Path
• A path through a program:
A node and edge sequence
from the starting node to a
terminal node of the control
flow graph.
 There may be several terminal
nodes for program.
Linearly Independent Path
• Any path through the
program that:
Introduces at least one new
edge:
•Not included in any other
independent paths.
Independent path
• It is straight forward:

To identify linearly independent


paths of simple programs.

• For complicated programs:

It is not easy to determine the


number of independent paths.
McCabe's Cyclomatic Metric
• An upper bound:
 For the number of linearly
independent paths of a program

• Provides a practical way of


determining:
 The maximum number of linearly
independent paths in a program.
McCabe's Cyclomatic Metric
• Given a control flow graph G,
cyclomatic complexity V(G):
 V(G)= E-N+2
•N is the number of nodes in G
•E is the number of edges in G
Example Control Flow Graph
1
Cyclomatic
2 complexity =
7-6+2 = 3.
3 4
5

6
Cyclomatic Complexity
• Another way of computing
cyclomatic complexity:
 inspect control flow graph
 determine number of bounded areas
in the graph
• V(G) = Total number of bounded
areas + 1
 Any region enclosed by a nodes and edge
sequence.
Example Control Flow Graph
1

3 4

6
Example
• From a visual examination of
the CFG:
Number of bounded areas is 2.
Cyclomatic complexity = 2+1=3.
Cyclomatic Complexity
• McCabe's metric provides:
• A quantitative measure of testing
difficulty and the ultimate reliability

• Intuitively,
 Number of bounded areas increases
with the number of decision nodes
and loops.
Cyclomatic Complexity
• The first method of computing
V(G) is amenable to automation:
You can write a program which
determines the number of nodes
and edges of a graph

Applies the formula to find V(G).


Cyclomatic Complexity
• The cyclomatic complexity of a
program provides:
A lower bound on the number of
test cases to be designed
To guarantee coverage of all
linearly independent paths.
Cyclomatic Complexity
• A measure of the number of
independent paths in a
program.
• Provides a lower bound:
for the number of test cases
for path coverage.
Cyclomatic Complexity
• Knowing the number of test
cases required:
Does not make it any easier to
derive the test cases,
Only gives an indication of the
minimum number of test cases
required.
Practical Path Testing
• The tester proposes initial set of test
data :
 Using his experience and judgment.
• A dynamic program analyzer used:
 Measures which parts of the program
have been tested
 Result used to determine when to stop
testing.
Derivation of Test Cases
• Draw control flow graph.
• Determine V(G).
• Determine the set of linearly
independent paths.
• Prepare test cases:
 Force execution along each path.
 Not practical for larger programs.
Example
int f1(int x,int y){
1 while (x != y){
2 if (x>y) then
3 x=x-y;
4 else y=y-x;
5 }
6 return x; }
Example Control Flow Diagram
1

3 4
5

6
Derivation of Test Cases
• Number of independent paths: 3
 1,6 test case (x=1, y=1)

 1,2,3,5,1,6 test case(x=1, y=2)

 1,2,4,5,1,6 test case(x=2, y=1)


An Interesting Application of
Cyclomatic Complexity
• Relationship exists between:
McCabe's metric
The number of errors existing
in the code,
The time required to find and
correct the errors.
Cyclomatic Complexity
• Cyclomatic complexity of a
program:
Also indicates the psychological
complexity of a program.
Difficulty level of
understanding the program.
Cyclomatic Complexity
• From maintenance perspective,
 Limit cyclomatic complexity of
modules
• To some reasonable value.
 Good software development
organizations:
• Restrict cyclomatic complexity of
functions to a maximum of ten or so.
White-Box Testing : Summary

statement
weakest coverage

condition branch
coverage (or decision)
coverage

branch and condition


(or condition /decision)
coverage

modified condition / independent path


decision coverage (or basis path)
coverage

multiple- condition
coverage
only if paths across composite
conditions are distinguished

strongest path
coverage
Data Flow-Based Testing
• Selects test paths of a
program:
According to the locations of
•Definitions and uses of
different variables in a
program.
Data Flow-Based Testing
• For a statement numbered S,
 DEF(S) = {X/statement S contains a
definition of X}
 USES(S)= {X/statement S contains a use
of X}
 Example: 1: a=b; DEF(1)={a}, USES(1)={b}.
 Example: 2: a=a+b; DEF(1)={a},
USES(1)={a,b}.
Data Flow-Based Testing
• A variable X is said to be live
at statement S1, if
X is defined at a statement S:
There exists a path from S to
S1 not containing any definition
of X.
DU Chain Example
1 X(){
2 a=5; /* Defines variable a */
3 While(C1) {
4 if (C2)
5 b=a*a; /*Uses variable a */
6 a=a-1; /* Defines variable a */
7 }
8 print(a); } /*Uses variable a */
Definition-use chain (DU
chain)
• [X,S,S1],
 S and S1 are statement numbers,
 X in DEF(S)
 X in USES(S1), and
 the definition of X in the
statement S is live at statement
S1.
Data Flow-Based Testing
• One simple data flow testing
strategy:
 Every DU chain in a program be
covered at least once.
• Data flow testing strategies:
 Useful for selecting test paths of a
program containing nested if and loop
statements.
Data Flow-Based Testing
• 1 X(){
• 2 B1; /* Defines variable a */
• 3 While(C1) {
• 4 if (C2)
•5 if(C4) B4; /*Uses variable a */
•6 else B5;
•7 else if (C3) B2;
•8 else B3; }
• 9 B6 }
Data Flow-Based
Testing
• [a,1,5]: a DU chain.
• Assume:
 DEF(X) = {B1, B2, B3, B4, B5}
 USED(X) = {B2, B3, B4, B5, B6}
 There are 25 DU chains.
• However only 5 paths are needed to
cover these chains.
Summary
• Exhaustive testing of almost
any non-trivial system is
impractical.
we need to design an optimal
test suite that would expose
as many errors as possible.
Summary
• If we select test cases
randomly:
 Many test cases may not add to the
significance of the test suite.
• There are two approaches to
testing:
 black-box testing
 white-box testing.
Summary
• Black box testing is also known as
functional testing.
• Designing black box test cases:
 Requires understanding only SRS
document
 Does not require any knowledge about
design and code.
• Designing white box testing requires
knowledge about design and code.
Summary
• We discussed black-box test
case design strategies:
Equivalence partitioning
Boundary value analysis
• We discussed some important
issues in integration and system
testing.
Test Automation
Software Testing Effort
Utilize Automated Testing Strategies
50% or More of Overall Development and Technology to Improve Productivity
Cost is Typically Spent on Testing and Quality

Spiral / Release 4
Size & Complexity of SW Baseline

Reduction in
Spiral / Release 3 Test Days

Spiral / Release 2
%
Test
Days

%
Spiral / Release 1 Test
Days

%
Test
Day
Size Manual vs.
% Automated
Test
Day
Increased Test
Coverage
Evolution of Testing Techniques
1960- 1990-2000 2000-
1990
Model-Based
Testing

Scripting

Capture and
Replay

Manual Manual Automated


Test design Test design Test design
and and and
Execution Automated Execution
Execution
Test Tool Types Basic Descriptions of Different Types of Test Tools
Test Tools support to create, update, and maintain diverse test
Information information, including test cases, test scripts, test data,
Classification of Software Test Tools
Management test results, and discovered problems.
Test Execution Tools help to set up and run tests, and collect and validate
and Control test results.
Test Tools generate program tests in an automatic way.
Generation
Test Coverage Tools analyze the test coverage during a test process based
Analysis on selected test criteria.
Performance Tools support program performance testing and
Testing performance measurement.
Software Programs are developed to simulate the functions and
Simulators behaviors of external systems, or dependent
subsystems/components for a under test program.
Regression Test tools support the automation performance of
Testing Jerry Gao Ph.D.
regression testing4/2003
and activities, including test recording
and re-playing.
Google search results
Tool Search string Matches

QTP Qtp OR quicktest OR "quick test“ 613


Functional "rational robot" OR "functional 118
Tester tester”
SilkTest silktest OR "silk test” 86
TestComplete testcomplete OR "test complete” 26
TestPartner testpartner OR "test partner“ 19
VSTE VSTE AND test 45
WATIR watir 26
Selenium Selenium 108
Demand per tool
Open Source
Microsoft WATIR Open Source
VSTE 2% Selenium
4% 10%
QTP
Compuware
Functional Tester
TestPartner
HP QTP SilkTest
2%
60% TestComplete
AutomatedQA
TestPartner
TestComplete
2% VSTE
Borland WATIR
IBM
SilkTest Selenium
Functional
8% Tester
12%
Vendor Share
Monkey Testing

• Testing through random inputs:


 The scenario may not be a correct
business case.
 The tester may not be able to
reproduce the failure.
Capture/Playback Tools
• Automated test tools mimic actions of the tester.

• During testing, the tester uses the keyboard and mouse


to perform some type of test or action.

• Testing tool captures all keystrokes and results:


 Baselined in a test script.

• During test playback, scripts compare latest outputs


with previous baseline.

• Test tools provide for non-intrusive testing:


 interact with the “application-under-test” as if the test tool
was not involved.
QTP: Record
and Playback
• Steps to follow:
• 1 Open Quick Test.

• 2 Open a test:
 To create a new test,
click on New
 To open an existing test,
click on Open

• 3 Click the Record button


If you are recording for
the first time the Record
and Run Settings dialog
box opens.
Playback

Sprint\zXC
abcde
Keyword View

1. Actions bring in modularity


2. Actions can be reused.

1. First name is the name of the edit box.


2. Set is the method
Expert View

The Expert View uses VBScript


Selenium: History
• Developed in 2004 by Jason Huggins as a JavaScript
library used to automate his manual testing routines
• Selenium Core is born whose functionality underlies the
Selenium RC (Remote Control) and Selenium IDE tools
• The Limitation of having a JavaScript based automation engine
and browser security restricted Selenium to specific
functionality

• Google been a long time user of Selenium, had a


developer named Simon Stewart who developed
WebDriver.
• Circumvented Selenium’s JavaScript sandbox to allow it to
communicate with the Browser and Operating System directly

• In 2008, Selenium and WebDriver merged to provide an


Story about Selenium
•Selenium is a chemical element with the atomic number 34, represented
by the chemical symbol Se.

•It is a nonmetal, chemically related to sulfur and tellurium, and rarely


occurs in its elemental state in nature.

Selenium.
•Selenium is used for treating Mercury Poisoning 108
Selenium IDE - UI

Start and Stop


Replay Recording
Toolbar

Selenese
Script
Editor

Accessor
Area

Selenium Log
Recoding a Selenium Test Case
• Open Firefox that has the IDE installed
• Open the base URL of the application to
record.
• Keep the application in a common base
state.
• Go To Tools  Selenium IDE and the IDE
will be opened
• Now perform the operations on the
application as you are testing the
Running Your First Selenium Script
• Make sure the application is in the common
base state.

• Click on the run button.

 Here you can also control the speed of


the execution using the
toolbar

• Once the test is run you can view the test


log in the bottom of the IDE window
Testing: A Reflection
• The aim of testing:
Identify all defects in a software
product.
• However, in practice even after
thorough testing:
One cannot guarantee that the
software is error-free.
Testing: A Reflection
• The input data domain of most
software is very large:

It is not practical to test the


software exhaustively with
each input data value.
To Test or Not?
• Testing does expose many
errors:
Provides a practical way of
reducing defects in a system

Increases the users'


confidence in the system.
Linux Capture/Playback Tools
Replay Xcessory http://www.scl.com/products/ics/motif/testing/repla
y/
www.ics.com
QF-Test http://www.qfs.de/en/qftestJUI/index.html

Froglogic http://www.froglogic.com/pg?id=Google&category=squ
ishjava
Redstone Software Eggplant

KD Executor http://www.kdab.net/?page=products&sub=kdexecutor

Jameleon http://sourceforge.net/projects/jameleon/
ShUnit2 for shell scripts testing
GNU Linux Desktop Project http://ldtp.freedesktop.org/wiki/Home

Cantana http://www.ipl.com/pdf/p0003.uk.pdf
crontab Part of Unix
crontab, cruisecontrol,
www.adminschoice.com/docs/crontab.htm
Dogtail http://people.redhat.com/zcerza/dogtail/about.html
http://www.cyberciti.biz/tips/linux-automated-gui-
testing-with-python-based-dogtail-tool.html
White-Box Testing ---
Mutation Testing, Integration and
System Testing,Testing Object-
oriented Programs, Test Automation

1
Mutation Testing
• In this, software is first tested:

– Using an initial test suite designed using


white-box strategies we already discussed.

• After the initial testing is complete,

– Mutation testing is taken up.

• The idea behind mutation testing:

– Make a few arbitrary small changes to a


program at a time. 2
Main Idea

• Insert faults into a program:

–Check whether the test suite


is able to detect these.

–This either validates or


invalidates the test suite.
3
Mutation Testing
• Each time the program is
changed,

–It is called a mutated program

–The change is called a mutant.


4
Mutation Testing
• A mutated program:
–Tested against the full test suite of
the program.

• If there exists at least one test


case in the test suite for which:
–A mutant gives an incorrect result,
–Then the mutant is said to be dead. 5
Mutation Testing
• If a mutant remains alive:
– Even after all test cases have been
exhausted,
– The test suite is enhanced to kill the
mutant.
• The process of generation and killing of
mutants:
– Can be automated by predefining a set of
primitive changes that can be applied to
6
the program.
Mutation Testing
• The primitive changes can be:
–Deleting a statement

–Altering an arithmetic operator,

–Changing the value of a constant,

–Changing a data type, etc.


7
Fault Model
• It is the types of faults possible
in a program.

• Some fault types can be ruled out:

– E.g. concurrency related-problems in


a sequential program

8
Fault Model of an OO Program

OO Faults

Structural
Faults Algorithmic
Faults

Procedural Traceability OO Incorrect Inadequate


Faults Result Performance
Faults Faults

9
Traditional Mutation Operators
• Deletion of a statement
• Boolean:
• Replacement of a statement with another
eg. == and >=, < and <=

• Replacement of boolean expressions with


true or false eg. a || b with true
• Replacement of arithmetic
eg. * and +, / and -
• Replacement of a variable (ensuring same
10
scope/type)
1. Program for triangle
2. Input a
3. Input b
4. Input c
5. If(a<b+c) and (b<a+c) and (c<a+b)
6. Then isatriangle =true
7. Else isatriangle=false
8. Endif
9. If isatriangle
10.Then if(a=b)and(b=c)
11.Output=“equilateral”
12.Else if (a!=b) and (b!=c) and (a!=c)
13.Output=scalene
14.Else output=“isosceles”
15.Endif
16.Endif
17.Else output=not a triangle
18.Endif
19.End triangle 11
Underlying Hypotheses
• Mutation testing is based on the
following two hypotheses:
– The Competent Programmer
Hypothesis

– The Coupling Effect

Both of these were proposed by DeMillo


et al.,1978 12
The Competent Programmer Hypothesis

• Programmers create programs


that are close to being correct:

•Differ from the correct program by


some simple errors.

13
The Coupling Effect

• Complex errors are caused due


to several simple errors.

• It therefore suffices to check


for the presence of the simple
errors
14
The Mutation Process

Program If program is
not error-free,
Create fix it
Mutants Test
Process

Mutation
Mutation Tests
Problem
New Test
with
Mutant Test Tests?
Cases
Mutants
Yes
Mutants that are
Any Live Test
caught by tests are
killed Mutants? No Complete

15
Equivalent Mutants
• There may be surviving mutants that
cannot be killed,
– These are called Equivalent Mutants
• Although syntactically different:
– These mutants are indistinguishable through
testing.
• Therefore have to be checked ‘by hand’
while... while...
... ...
i++ i++
if (i==5) if (i>=5)
break; break; 16
Disadvantages of Mutation Testing

• Computationally very expensive.

• A large number of possible


mutants can be generated.

• Certain types of faults are very


difficult to inject.
17
Quiz 1
• Identify two advantages and two
disadvantages of the mutation test
technique.

18
Quiz 1: Solution
• Identify two advantages and two
disadvantages of the mutation test technique.
• Adv:
– Can be automated
– Helps effectively strengthen black box and coverage-
based test suite

• Disadv:
– Equivalent mutants
– Effective only against minor syntactic bugs
19
Debugging
• Once errors are identified:
– Debug: Identify precise location of errors
– Fix errors
– Regression test

• Each debugging approach has its


advantages and disadvantages:
– Each is useful in appropriate
circumstances. 20
Brute-Force Method
• This is the most common method of
debugging:
–Least efficient method.

–Program is loaded with print statements

–Print the intermediate values

–Hope that some of printed values will


help identify the error. 21
Symbolic Debugger
• More systematic than the Brute force
method:
– Symbolic debuggers get their name for
historical reasons

– Early debuggers supported only


examination of values from a program
dump:
• Tedious to determine which variable a byte
22
sequence corresponds to.
Symbolic Debugger
• Using a symbolic debugger:

–Values of different variables can be


easily checked and modified

–Single stepping to execute one


instruction at a time

–Break points and watch points can be


set to test the values of variables. 23
Backtracking
• This is a fairly common approach.

• Beginning at the statement where


an error symptom has been
observed:
–Source code is traced backwards
until the error is discovered.
24
Example
int main(){
int i,j,s;
i=1;
while(i<=10){
s=s+i;
i++; j=j++;}
printf(“%d”,s);
}
25
Backtracking
• Unfortunately, as the number of
source lines to be traced back
increases,
–The number of potential backward
paths increases
–Becomes unmanageably large for
complex programs. 26
Cause-Elimination Method
• Determine a list of causes:
–which could possibly have contributed
to the error symptom.

–tests are conducted to eliminate each.

• A related technique of identifying


error by examining error symptoms:
–software fault tree analysis. 27
Program Slicing
• This technique is similar to back tracking.

– However, the search space is reduced


by defining slices.

• A slice is defined for a particular variable


at a particular statement:

– Set of source lines preceding this


statement which can influence the value
28
of the variable.
Example
int main(){
int i,s;
i=1; s=1;
while(i<=10){
s=s+i;
i++;}
printf(“%d”,s);
printf(“%d”,i);
} 29
Debugging Guidelines
• Debugging requires a thorough
understanding of program design.
• Debugging may sometimes require
full redesign of the program.
• A common mistake novice
programmers often make:
–Not fixing the error but the error
symptoms.
30
Debugging Guidelines
• Be aware of the possibility:
–An error correction may
introduce new errors.
• After every round of error-
fixing:
–Regression testing must be
carried out. 31
Program Analysis Tools
• An automated (static) tool:
–Takes program source code as input
–Produces reports regarding several
important characteristics of the
program,
–Such as size, complexity, adequacy of
commenting, adherence to
programming standards, etc. 32
Program Analysis Tools
• There are essentially two
categories of program analysis
tools:
–Static analysis tools

–Dynamic analysis tools

33
Static Analysis Tools
• Static analysis tools:

–Assess properties of a
program without executing it.

–Analyze the source code to


certain analytical conclusions.
34
Static Analysis Tools
• Check whether:
– Coding standards been adhered to?
–Commenting is adequate?
• Programming errors such as:
–Uninitialized variables
–Mismatch between actual and formal
parameters.
–Variables declared but never used, etc.
35
Static Analysis Tools
• Can code walk through and
inspection be considered as
static analysis methods?
–The term static program analysis is
generally used for automated
analysis tools.
36
Dynamic Analysis Tools
• Dynamic program analysis tools
require the program to be
executed:
–Its behavior recorded.
–Produce reports such as
adequacy of test cases.
37
System Testing
• Objective:
–Validate a fully developed
software against its
requirements.

38
Integration Testing Approaches
• Develop the integration plan by
examining the structure chart :
–big bang approach
–top-down approach
–bottom-up approach
–mixed approach 39
Example Structured Design

root

Valid-numbers rms
rms
Valid-numbers

Get-good- Compute- Display-solution


data solution

Get- Validate-
data data
40
Big Bang Integration Testing
• Big bang approach is the simplest
integration testing approach:

–All the modules are simply put


together and tested.

–This technique is used only for very


small systems.
41
Big Bang Integration Testing
• Main problems with this approach:
–If an error is found:
• It is very difficult to localize the error
• The error may potentially belong to any
of the modules being integrated.

–Debugging errors found during big


bang integration testing are very
expensive to fix. 42
Bottom-up Integration Testing
• Integrate and test the bottom level
modules first.
• A disadvantage of bottom-up testing:
–When the system is made up of a large
number of small subsystems.
–This extreme case corresponds to the
big bang approach. 43
Top-down Integration Testing
• Top-down integration testing starts with the
main routine:

– and one or two subordinate routines in the


system.

• After the top-level 'skeleton’ has been


tested:

– immediate subordinate modules of the


'skeleton’ are combined with it and tested.
44
Mixed Integration Testing
• Mixed (or sandwiched)
integration testing:

–Uses both top-down and bottom-


up testing approaches.

–Most common approach


45
Integration Testing
• In top-down approach:
–Testing waits till all top-level
modules are coded and unit
tested.

• In bottom-up approach:
–Testing can start only after
bottom level modules are ready. 46
System Testing
• There are three main types
of system testing:

–Alpha Testing

–Beta Testing

–Acceptance Testing 47
Alpha Testing
• System testing carried out
by the test team within the
developing organization.

–Test cases are designed


based on the SRS document
48
Beta Testing

• System testing performed by


a select group of friendly
customers.

49
Acceptance Testing
• System testing performed by
the customer himself:

–To determine whether the


system should be accepted
or rejected.
50
51
Dilbert: Scott Adams
Stress Testing
• Stress testing (also called endurance
testing):
–Impose abnormal input to stress the
capabilities of the software.

–Input data volume, input data rate,


processing time, utilization of
memory, etc. are tested beyond the
designed capacity. 52
53
Dilbert: Scott Adams
54

Dilbert: Scott Adams


Latent Errors: How Many
Errors are Still Remaining?
• Make a few arbitrary changes to
the program:
–Artificial errors are seeded into the
program.

–Check how many of the seeded


errors are detected during testing. 55
Error Seeding
• Let:
–N be the total number of errors in the
system

–n of these errors be found by testing.


–S be the total number of seeded
errors,
–s of the seeded errors be found during
56
testing.
Error Seeding
• n/N = s/S
• N = S n/s
• remaining defects:
N - n = n ((S - s)/ s)

57
Quiz 2
• 100 errors were introduced.
• 90 of these errors were found
during testing
• 50 other errors were also
found.
• Find errors remaining in code. 58
Quiz 2: Solution
• 100 errors were introduced.

• 90 of these errors were found


during testing

• 50 other errors were also found.

• Remaining errors=
50 (100-90)/90 = 6
59
Error Seeding
• The kinds of seeded errors should
match closely with existing errors:
–However, it is difficult to predict the
types of errors that exist.

• Categories of remaining errors:


–Can be estimated by analyzing
historical data from similar projects.
60
Quiz 3
• Before system testing 100 errors were
seeded.

• During system testing 90 of these were


detected.

• 150 other errors were also detected

• How many unknown errors remain


after system testing? 61
What is regression testing?

Regression testing is testing done to


check that a system update does not
cause new errors or re-introduce
errors that have been corrected
earlier.

62
Need for Regression Testing
• Any system during use undergoes
frequent code changes.
– Corrective, Adaptive, and Perfective
changes.
• Regression testing needed after
every change:
– Ensures unchanged features continue
63
to work fine.
Partitions of an Existing Test Suite

To
Obsolete
Tu
Redundant

Tor Tr
Optimized Regression Tests
Regression
Tests

64
Major Regression Testing Tasks
• Test revalidation (RTV):
– Check which tests remain valid
• Test selection (RTS):
– Identify tests that execute modified
portions.
• Test minimization (RTM):
– Remove redundant tests.
• Test prioritization (RTP):
65

– Prioritize tests based on certain criteria.


Software Regression Process:
Step #1: Software Change Analysis
- Understand and analyze various software changes.

Step #2: Software Change Impact Analysis


- Understand and analyze software change impacts

Step #3: Define Regression Test Strategy and Criteria

Step #4: Define, select, and reuse test cases to form a regression
test suite

Step #5: Perform re-testing at the different levels.


- re-testing at the unit level
- re-testing at integration level
- re-testing at the system level

Step #6: Report and analyze regression test results 66


Software Regression Process
Software Change
Analysis

Software Change
Impact Analysis

Define Regression
Testing Strategy

Build Regression
Test Suite

Run Regression
Tests at different levels

Report Retest
Results
67
Automating regression testing

Build results
Test for version x
data

Build tests
for version x

Run tests
for version x Compare Verdict
68
69

Dilbert: Scott Adams


Testing Object-
Oriented Programs

70
Introduction
• More than 50% of development effort is being
spent on testing.

• Quality and effective reuse of software depend


to a large extent:

– on thoroughness of testing.

• It was expected during initial years that OO


would help substantially reduce testing effort:

– But, as we shall find it out today --- it only


complicates testing. 71
Challenges in OO Testing
• What is an appropriate unit for testing?
• Implications of OO features:
– Encapsulation
– Inheritance
– Polymorphism & Dynamic Binding, etc.
• State-based testing
• Test coverage analysis
• Integration strategies 72
What is a Suitable Unit for Testing?
• What is the fundamental unit of testing for
conventional programs?
– A function.
• As far as OO programs are concerned:
– Methods are not the basic unit of testing!
• Weyukar's Anticomposition axiom:
– Any amount of testing of individual
methods can not ensure that a class has
been satisfactorily tested. 73
Suitable Unit for Testing OO Programs

• Class level:

–Testing interactions between


attributes and methods must be
addressed.

–State model of the object must


be considered. 74
Weyukar’s Anticomposition Axiom (IEEE
TSE Dec. 1986)
• Adequate testing of each individual program
components does not necessarily suffice to
adequate test the entire program.

• Consider P and Q as components.


– P has the opportunity to modify the context seen
by Q in a more complex way than could be done by
stubs during testing of components in isolation.

• What is the interpretation for OO programs?


75
Encapsulation
• Encapsulation is not a source of
errors:
– However, an obstacle to testing.
– It prevents accessing attribute
values by a debugger.
• While testing:
– Precise information about current
state is necessary. 76
Solving Encapsulation-Related Problems

Several solutions are possible:


– Built-in or inherited state reporting
methods.
– Low level probes to manually inspect
object attributes.
– Proof-of-correctness technique
(formal). 77
Solving Encapsulation-Related Problems

• Most feasible way:

–State reporting methods.

• Reliable verification of state


reporting methods is a
problem.
78
Inheritance
• Should inherited methods be retested?
– Retesting of inherited methods is the rule,
rather than an exception.
LibraryMember Base Class

Derived
Faculty Students Staff
Classes

UnderGrad PostGrad Research


79
Should Inherited Methods be Retested?
• Retesting required:

– Because a new context of usage occurs


when a subclass is derived.
(Anticomposition axiom)

• Correct behavior at an upper level:

– Does not guarantee correct behavior at a


lower level.
80
Example
Class A{
protected int x=200; // invariant x>100
void m(){ //correctness depends on invariant}
}
Class B extends A{
void m1(){x=1; …} …}
• Execution of m1() causes a bug in m()
• Breaks the invariant, m is incorrect in the
context of B, even though it is correct in A:
81
– Therefore m should be retested in B
Another Example
Class A{
void m() { … m2(); … }
void m2(){…} }
Class B extends A{
void m2(){…} …}
• m2 has been overriden in B, can affect other
methods inherited from A such as m()
– m() would now call B.m2.
– So, we cannot be sure that m is correct
anymore, we need to retest it with B instance.
82
Inheritance --- Overriding

• In case of method overriding:


– Need to retest the classes in the
context of overriding.

– An overridden method must be


retested even when only minor
syntactic changes are made.
83
Which Methods to Test Within A Class?
• New methods:
– Defined in the class under test and not inherited
or overloaded by methods in a superclass:
Complete testing
• Inherited methods:
– Defined in a superclass of the class under test:
Retest only if the methods interacts with new
or redefined method.
• Redefined methods:
– Defined in a superclass of but redefined in the
class under test : complete Retest. 84
Testing Derived Class
• Principle: inherited methods
LibraryMember
should be retested in the show-address() Base Class

context of a subclass
Derived
Faculty Students Staff
Classes

• Example: if we change a
method show-address() UnderGrad PostGrad Research

in a super class, we need to


retest show-address() inside
all subclasses that inherit it 85
Deep Inheritance Hierarchy
• A subclass at the bottom of a deep
hierarchy:
– May have only one or two lines of code.

– But may inherit hundreds of features.

• This situation creates fault hazards:


– Similar to unrestricted access to global
data in procedural programs.

• Inheritance weakens encapsulation. 86


Deep Inheritance Hierarchy cont...
• A deep and wide inheritance hierarchy can
defy comprehension:
– Lead to bugs and reduce testability.
– Incorrect initialization and forgotten
methods can result.
– Class flattening may increase
understandibility.
• Multiple Inheritance:
– Increases number of contexts to test. 87
Abstract and Generic Classes
• Unique to OO programming:
– Provide important support for reuse.
• Must be extended and instantiated to
be tested.
• May never be considered fully tested:
– Since need retesting when new
subclasses are created. 88
Testing an Abstract Class
•Not possible to
directly test it. LibraryMember Abstract Class

•Can only be
Derived
indirectly tested Faculty Students Staff
Classes

through classes
derived from it.
UnderGrad PostGrad Research
•So can never be
considered as fully
89
tested.
Polymorphism
• Each possible binding of a polymorphic
component requires separate testing:

– Often difficult to find all bindings


that may occur.

– Increases the chances of bugs .

– An obstacle to reaching coverage


goals. 90
Polymorphism
cont…

• Polymorphism complicates integration


planning:
– Many server classes may need to be
integrated before a client class can
be tested.

C S1 S3

S2 91
Dynamic Binding
• Dynamic binding implies:

– The code that implements a given


function is unknown until run time.

– Static analysis cannot be used to


identify the precise dependencies in
a program.

• It becomes difficult to identify all


possible bindings and test them. 92
Dynamic Binding: the combinatorial
explosion problem
abstract class Credit {
...
abstract boolean validateCredit( Account a, int amt, CreditCard c);
...
}

EduCredit USAccount VISACard


BizCredit UKAccount AmExpCard
IndividualCredit EUAccount StoreCard
JPAccount
OtherAccount

The combinatorial problem: 3 x 5 x 3 = 45 possible combinations


of dynamic bindings (just for this one method!)
93
How many test cases for pair
wise testing?
m11
m1

m15
m

m51
m5

m55
94
State-Based Testing
• The concept of control flow of a
conventional program :

– Does not map readily to an OO program.

• In a state model:

– We specify how the object's state


would change under certain conditions.
95
State-Based Testing
• Flow of control in OO programs:

– Message passing from one object


to another.

• Causes the receiving object to


perform some operation:

– Can lead to an alteration of its state.


96
State-Based Testing
cont...
• The state model defines the
allowable transitions at each state.
• States can be constructed:
– Using equivalence classes defined
on the instance variables.
• Jacobson's OOSE advocates:
– Design test cases to cover all state
transitions.
97
An Example of A State Chart Diagram

order received
Unprocessed
Order
[reject] checked [accept] checked

Rejected Accepted
Order Order
[some items available]
[some items not processed / deliver
available] processed

[all items
Pending available] Fulfilled
Order newsupply Order

Example: State chart diagram for an order object 98


State-Based Integration Testing
cont...
• Test cases can be derived from the
state machine model of a class:
– Methods result in state transitions.
– Test cases are designed to exercise
each transition at a state.
• However, the transitions are tied to
user-selectable activation sequences:
– Use Cases
99
Difficulty With State Based Integration
Testing
• The locus of state control is distributed
over an entire OO application.
– Cooperative control makes it difficult to
achieve system state and transition
coverage.
• A global state model becomes too complex
for practical systems.
– Rarely constructed by developers.
– A global state model is needed to show100
how classes interact.
Test Coverage
• Test coverage analysis:
– Helps determine the “thoroughness” of
testing achieved.
• Several coverage analysis criteria for
traditional programs have been proposed:
– What is a coverage criterion?
• Tests that are adequate w.r.t a criterion:
– Cover all elements of the domain
determined by that criterion. 101
Test Coverage Criterion cont...

• But, what are the elements that


characterize an object-oriented program?

– Certainly different from procedural


programs.
– For example: Statement coverage is not
appropriate due to inheritance and
polymorphism.

• Appropriate test coverage criteria are


102
needed.
Test Process Strategy
• Object-oriented development tends toward:
– Shorter incremental cycles.
• Development characterized as:
– Design a little,code a little,test a little.
• The distance between OO specification and
implementation, therefore:
– Typically small compared to conventional
systems. 103
Test Process Strategy
cont...
• The gap between white-box/black-box test is
diminished.

– Therefore lower importance of code-based


testing.

– Model-based testing has assumed


importance (also called grey box testing).

• Conventional white-box testing can be used


for testing individual methods. 104
Testers’ Delight!

Dilbert: Scott Adams 105


Integration Testing
• OO does not have a hierarchical control structure:
– So conventional top-down and bottom-up
integration tests have little meaning
• Integration applied three different incremental
strategies:
 Thread-based testing: integrates classes required to
respond to one input or event
 Use-based testing: integrates classes required by one
use case
 Cluster testing: integrates classes
required to demonstrate one
collaboration 106
OO Integration Testing
• Thread-based testing
– Testing all classes required to respond to one
system input or event
• Use-based testing
– Test independent classes first
– Test dependent classes making use of them
next
• Cluster testing
– Groups of collaborating classes are tested for
107
interaction errors
Thread-based Integration Strategies

• A thread consists of:

– All the classes needed to respond to a


single external input.

• Each class is unit tested,

– Then each thread is exercised.

108
A OUTPUT PORT EVENT
Class 3
Class 1 A

meth1 meth2
1

meth1
meth2 meth3
B
B

OUTPUT PORT EVENT

2
Class 2

meth1 meth3
3
MM-Path

Message meth2
109
Use Case-based Integration
• Begin by testing classes that use
services of none (or a few) of other
classes.

• Next, classes that use the first group


of classes are tested.

• Followed by classes that use the


second group, and so on. 110
Which types of Errors Found During
Integration Testing?
• Messaging errors:
– Failure to meet a requirement, i.e., no
method to send or receive a message
– Incompatible method and message in sender
and receiver
– Incorrect event timing between object
actions
– Incorrect instantiation or destruction of
111
objects
Types of Errors Found During
Integration Testing (cont.)
• User interface errors:

– A given sequence of user actions does


not have the expected effect on the
component.

– The timing of events received from


the user results in incorrect
functioning of the component 112
Performance Testing
• Recovery testing:
• how well and quickly does the system recover
from faults
• Security testing:
• verify that protection mechanisms built into the
system will protect from unauthorized access
(hackers, disgruntled employees, fraudsters)
• Stress testing:
• place abnormal load on the system
• Performance testing:
• investigate the run-time performance within 113
the
context of an integrated system
114

Dilbert: Scott Adams


UML Model-Based Testing

115
Testing Based on UML Models
• UML has become the de facto standard for OO
modeling and design:
• Though UML is intended to produce rigorous
models:
– Does incorporate many flexibilities.
– Incomplete, inconsistent, and ambiguous
models often result.
• Never the less:
– UML models are an important source of
116
information for test design.
Use Case Diagram
• Use cases roughly capture
system level requirements.
• A collection of use cases defines:
–Complete functionality of the
system.

117
Use Case Diagram
cont...

• Several general kinds of tests can be


derived from use cases:
1. Tests for basic courses-- “the expected
flow of events” mainline sequence.
2. Tests of other courses-- “all other flows
of events” alternate sequences.
3. Tests of features described in user
documentation traceable to each use case.
118
Use Case Diagram
cont...
• Generic test requirements include:
– At least one test case should
exercise:
• Every Use Case when actor
communicates with Use Case.
• Every extension combination such as
Use Case 1 extends Use Case 2.
• Every uses combination such as Use
119
Case 1 uses Use Case 2.
Class Diagram
• Documents the structure of a system:
– Represents the entities and their inter-
relationships.
• Test cases should exercise:
– Each association.
– Independent creation and destruction of
the container and the components in an
aggregation relation.
– Each inherited method should be 120

retested.
Sequence Diagram
• A sequence diagram documents message
exchanges in time dimension.

• Generic tests include:

– Message coverage: At least one test


case should exercise each message.

– Message path coverage: All end-to-end


paths should be identified and exercised.
121
Difficulties with Sequence Diagrams
• Representing complex control is difficult:
– For example: notation for selection and
iteration is clumsy.
– It becomes difficult to determine
whether all scenarios are covered.
• Dynamic binding and the consequent
superclass/subclass behavior :
– Cannot be represented directly. 122
Activity Diagram
• Activity diagrams are based on:
– Flow charts, state transition diagrams,
flow graphs and Petri nets.
• Can be considered to be an extension of
flow chart:
– Can represent two or more threads of
concurrent execution.
• Supports all features of a basic flow graph:
– Can be used to develop test models for
control flow based techniques. 123
Activity Diagram cont...

• Activity diagram can be used to


construct:
– Decision tables
– Composite control flow graph
representing a collection of sequence
diagrams.
– Control flow graph at method scope:
• This may be useful to analyze path 124

coverage.
Activity Diagram cont...

• Generic test requirements:


– At least one test case should exercise
each different path:
•Action 1 is followed by Action 2
•Synch Point is followed by Action
•Action is started after Signal
•Synch Point is reached after Action 125
Statechart Diagram
• Can be used to represents state-
based behavior of :
– a class, subsystem, or system.

• Statechart model:
– Provides most of the information
necessary for class-level state-based
testing. 126
Component Diagram
• Shows the dependency relationships among:
– Components,
– Physical containment of components,
– Interfaces and calling components.
• The basic testing practice with respect to
component diagrams:
– All call paths should be identified and
exercised. 127
Deployment Diagram
• Represents hardware, software, and network
architecture.
– Useful in integration planning.
• When a component runs on a node,
– Test cases should exercise whether a
component can be loaded and run on each
designated host node.
• When a node communicates with another node,
– Test cases should exercise open, transmit, and
close communication for each remote 128

component.
Test Coverage Criteria Based on UML
Models
• Generalization criterion

• Class attribute criterion

• Condition coverage criterion

• Full predicate coverage criterion

• Each message on link criterion

• All message paths criterion 129


Test Automation

130
Software Testing Effort
Utilize Automated Testing Strategies
50% or More of Overall Development and Technology to Improve Productivity
Cost is Typically Spent on Testing and Quality

Spiral / Release 4
Size & Complexity of SW Baseline

Reduction in
Spiral / Release 3
Test Days

Spiral / Release 2 %
Test
Days
%
Spiral / Release 1 Test
Days
%
Test
Day
%
Test
Size Manual vs.
Automated
Day Increased
131Test
Coverage
Evolution of Testing Techniques
1960- 1990-2000 2000-
1990
Model-Based
Testing

Scripting

Capture and
Replay

Manual Manual Automated


Test Test Test
design and design and design and
Execution Automated Execution 132
Execution
Test Tool Types Basic Descriptions of Different Types of Test Tools
Test Tools support to create, update, and maintain diverse test
Information information, including test cases, test scripts, test data,
Management Classification
test results, andof discovered
Software Test Tools
problems.
Test Execution Tools help to set up and run tests, and collect and validate
and Control test results.
Test Tools generate program tests in an automatic way.
Generation
Test Coverage Tools analyze the test coverage during a test process based
Analysis on selected test criteria.
Performance Tools support program performance testing and
Testing performance measurement.
Software Programs are developed to simulate the functions and
Simulators behaviors of external systems, or dependent
subsystems/components for a under test program.
Regression Test tools support the automation performance of
133
Testing regression testing and activities, including test recording
Jerry Gao Ph.D. 4/2003
and re-playing.
Google search results
Tool Search string Matches

QTP Qtp OR quicktest OR "quick test“ 613


Functional "rational robot" OR "functional 118
Tester tester”
SilkTest silktest OR "silk test” 86
TestComplete testcomplete OR "test complete” 26
TestPartner testpartner OR "test partner“ 19
VSTE VSTE AND test 45
WATIR watir 26
Selenium Selenium 108 134
Demand per tool
Open Source
Microsoft WATIR Open Source
VSTE 2% Selenium
4% 10%
QTP
Compuware
Functional Tester
TestPartner
HP QTP SilkTest
2%
60% TestComplete
AutomatedQA
TestPartner
TestComplete
2% VSTE
Borland WATIR
IBM
SilkTest Selenium
Functional
8% Tester
12% 135
Vendor Share

136
Monkey Testing

• Testing through random inputs:


– The scenario may not be a correct
business case.
– The tester may not be able to
reproduce the failure. 137
Capture/Playback Tools
• Automated test tools mimic actions of the tester.

• During testing, the tester uses the keyboard and mouse to


perform some type of test or action.

• Testing tool captures all keystrokes and results:

– Baselined in a test script.

• During test playback, scripts compare latest outputs with


previous baseline.

• Test tools provide for non-intrusive testing:


– interact with the “application-under-test” as if the test tool
138
was not involved.
QTP: Record and
Playback
• Steps to follow:
• 1 Open Quick Test.

• 2 Open a test:
– To create a new test,
click on New
– To open an existing test,
click on Open

• 3 Click the Record button


If you are recording for the
first time the Record and
Run Settings dialog box
opens. 139
Playback

Sprint\zXC
abcde

140
Keyword View

1. Actions bring in modularity

2. Actions can be reused.

1. First name is the name of the edit box.

2. Set is the method

141
Expert View

The Expert View uses VBScript

142
Selenium: History
• Developed in 2004 by Jason Huggins as a JavaScript
library used to automate his manual testing routines
• Selenium Core is born whose functionality underlies the
Selenium RC (Remote Control) and Selenium IDE tools
• The Limitation of having a JavaScript based automation engine
and browser security restricted Selenium to specific
functionality

• Google been a long time user of Selenium, had a developer


named Simon Stewart who developed WebDriver.
• Circumvented Selenium’s JavaScript sandbox to allow it to
communicate with the Browser and Operating System directly

• In 2008, Selenium and WebDriver merged to provide an


143
excellent test automation framework
Story about Selenium
•Selenium is a chemical element with the atomic number 34, represented
by the chemical symbol Se.

•It is a nonmetal, chemically related to sulfur and tellurium, and rarely


occurs in its elemental state in nature.

Selenium.
•Selenium is used for treating Mercury Poisoning
144
144
Selenium IDE - UI

Start and Stop


Replay
Recording
Toolbar

Selenese
Script
Editor

Accessor
Area

Selenium Log

145
Recoding a Selenium Test Case
• Open Firefox that has the IDE installed
• Open the base URL of the application to record.
• Keep the application in a common base state.
• Go To Tools  Selenium IDE and the IDE will be
opened
• Now perform the operations on the application as you
are testing the application.
• Once you are done with the recording
– Click on the stop recording button and save the test case
through the file menu.
– By default it will be saved as a selenese script (HTML 146
format)
Running Your First Selenium Script
• Make sure the application is in the common
base state.

• Click on the run button.

– Here you can also control the speed of


the execution using the toolbar

• Once the test is run you can view the test


log in the bottom of the IDE window
147
Testing: A Reflection
• The aim of testing:
–Identify all defects in a software
product.
• However, in practice even after
thorough testing:
–One cannot guarantee that the
software is error-free. 148
Testing: A Reflection
• The input data domain of most
software is very large:

–It is not practical to test the


software exhaustively with
each input data value.
149
To Test or Not?
• Testing does expose many
errors:
–Provides a practical way of
reducing defects in a system

–Increases the users'


confidence in the system. 150
Linux Capture/Playback Tools
Replay Xcessory http://www.scl.com/products/ics/motif/testing/replay/
www.ics.com

QF-Test http://www.qfs.de/en/qftestJUI/index.html

Froglogic http://www.froglogic.com/pg?id=Google&category=squis
hjava

Redstone Software Eggplant

KD Executor http://www.kdab.net/?page=products&sub=kdexecutor

Jameleon http://sourceforge.net/projects/jameleon/
ShUnit2 for shell scripts testing
GNU Linux Desktop Project http://ldtp.freedesktop.org/wiki/Home

Cantana http://www.ipl.com/pdf/p0003.uk.pdf
crontab Part of Unix
crontab, cruisecontrol,
www.adminschoice.com/docs/crontab.htm
Dogtail http://people.redhat.com/zcerza/dogtail/about.html
http://www.cyberciti.biz/tips/linux-automated-gui-
testing-with-python-based-dogtail-tool.html 151
Expect http://expect.nist.gov/
Software Quality
Assurance

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.
12/30/2021 1
“It costs a lot to produce a bad product.”
Norman Augustine

2
The Quality Gurus – Edward Deming

•Quality is
“uniformity and
dependability”
•Focus on SPC
and statistical
tools
•“14 Points” for
1900-1993

1986 management

3
The Quality Gurus – Joseph Juran

•Quality is
“fitness for use”
•Pareto Principle
•Cost of Quality
•General
management 1904 - 2008
approach as well
1951 as statistics

4
The Quality Gurus – Phillip Crosby

Quality is free . . .

 “Quality is free. It’s not a gift, but it is free.


What costs money are the unquality things -- all the
actions that involve not doing jobs right the first
time.”

5
Introduction
 How is a quality product
traditionally defined?

 Fitness of purpose:

A quality product does exactly


what the users want it to do.

6
Fitness of Purpose
 What is fitness of purpose for
software products?
 Satisfaction of the requirements specified
in SRS document…

“Quality is conformance to requirements”


-- Philip Crosby, “Quality is Free” 1979

7
Fitness of Purpose
 Basically user’s view…
 A satisfactory definition of quality
for many products:
A car, a table fan, a food mixer,
microwave oven, etc.

 But, not satisfactory for software


products.
 Why? 8
Quality for Software Products
 Consider a software product:
 Functionally correct:
 Performs all functions as specified in
the SRS document.
 But,has an almost unusable user
interface.
 Would you consider it as a quality
product? 9
Quality for Software Products
 Consider another example:
A product which does everything
that users want.
 But
has an incomprehensible and
unmaintainable code.
 Will you call it a quality product?
 Quality needs to described in terms
of a set of quality attributes. 10
Product Quality Attributes
 Attributes of a good software:
 Correctness
 Reliability

 Efficiency:Software should not make wasteful use


of system resources (disk and memory space, CPU
time, etc.) and should satisfy response time
requirements
 Portability
 Usability

 Reusability
 Maintainability 11
Correctness
 When do you call a software
correct?
 Ifthe requirements specified in the SRS
document have correctly been
implemented.

 Failures do not show up during the normal


operation of the software.
12
Portability
 When do you call a software to
be portable?
 If it can be easily made to work
 In different operating systems.
 In different machines,
 With other software, etc.
13
Reusability
 When do you say that software
has good reusability?
 If different parts of the
software can easily be reused to
develop a new software.

14
Usability
 When do you say that a software
has good usability?

 If different categories of users


(i.e. both expert and novice users)
can easily invoke the functions of
the product.
15
Maintainability
 A software product is maintainable:

 If errors can be easily corrected as and


when they show up,

 New functions can be easily added to


the product,

 Functionalities of the product can be


easily modified.
16
Five views of software quality
 Transcendental view:
 Quality is viewed to be something recognized but hard to
define..

 User view:
 Fitness for purpose.

 Manufacturing view:
 Conformance to requirements and “Right the first time” to
avoid costs of rework … theme of ISO 9000, SEI CMM etc

 Product view:
 if a product is manufactured with good internal characteristics
then it will have good external qualities.

 Value-Based view:
 The central view in this case is how much a customer is willing
17
17
to pay for a certain level of quality.
Two Accepted Definition of “Software
Quality”
 IEEE Glossary:
 Degree to which a system, component, or
process meets (1) specified requirements, and
(2) customer or user needs or expectations

 ISO:
 The totality of features and characteristics
of a product or service that bear on its ability
to satisfy specified or implied needs
18
Quality Models

 Boehm’s model Quality Model: A


model with the
 ISO 9126 objective to describe,
assess and/or predict
 Dromey’s Model quality.

19
Boehm’s Quality Model

20
Boehm’s Quality Model (continued)

 Reflects an understanding of quality where


the software:

 does what the user wants it do

 uses computer resources correctly and


efficiently

 is easy for the user to learn and use

 is well-designed, well-coded, and easily tested


and maintained 21
ISO 9126 Quality Model
 A hierarchical model with six
major attributes contributing to
quality:

 Each right-hand characteristic is


related to only to exactly one
left-hand attribute
22
ISO 9126 Quality Model (continued)

23
ISO 9126 Quality Characteristics
Quality Characteristic Definition

Functionality A set of attributes that bear on the existence of a set of functions


that satisfy stated or implied needs

Reliability A set of attributes that bear on the capability of software to maintain


its performance level under stated conditions for a stated period of
time

Usability A set of attributes that bear on the effort needed for use and on the
individual assessment of such use by a stated or implied set of users

Efficiency A set of attributes that bear on the relationship between the software
performance and the amount of resources used under stated conditions

Maintainability A set of attributes that bear on the effort needed to make specified
modifications (which may include corrections, improvements, or
adaptations of software to environmental changes and changes in the
requirements and functional specifications)

Portability A set of attributes that bear on the ability of software to be


transferred from one environment to another (including the
organizational, hardware or software environment) 24
Dromey Quality Model
 Product quality depends on the
tangible properties of components and
component composition:

 Correctness properties

 Internal properties

 Contextual properties

 Descriptive properties 25
Dromey Quality Model Framework
 Linking product properties to quality attributes

26
The current status of software quality
 Microsoft Windows XP End-User License Agreement:
11. LIMITED WARRANTY FOR PRODUCT ACQUIRED IN THE US AND
CANADA.
Microsoft warrants that the Product will perform substantially in
accordance with the accompanying materials for a period of ninety days
from the date of receipt.
(…)
If an implied warranty or condition is created by your state/jurisdiction and
federal or state/provincial law prohibits disclaimer of it, you also have an
implied warranty or condition, BUT ONLY AS TO DEFECTS DISCOVERED
DURING THE PERIOD OF THIS LIMITED WARRANTY (NINETY DAYS).
(…)
Some states/jurisdictions do not allow limitations on how long an implied
warranty or condition lasts, so the above limitation may not apply to you.
(…)
YOUR EXCLUSIVE REMEDY. Microsoft's and its suppliers' entire liability and
your exclusive remedy shall be, at Microsoft's option from time to time
exercised subject to applicable law, (a) return of the price paid (if any) for
the Product, or (b) repair or replacement of the Product, that does not meet
this Limited Warranty and that is returned to Microsoft with a copy of your
receipt.
(..)
This Limited Warranty is void if failure of the Product has resulted from
accident, abuse, misapplication, abnormal use or a virus. 27
Quantitative Targets For Managing US Defense Projects

Item Target Average Realized Level

Fault removal efficiency >95% <70%

Original fault density <4 per function point >7 per function point

Slip or cost overrun 0% >=10%

Total requirements creep <1% per month average >= 50%


(function points or
equivalent)

Total program <3 pages per function >6 pages per function
documentation point point

Staff turnover 1 to 3% per year >5% per year

28
Software Quality Management System

 Also called quality system:


 Principal
methodology used by an
organization to ensure that its
developed software has the
desired quality.

29
Quality Management Activities
 Quality assurance
 set of activities for ensuring quality of the processes by which
software is developed
 Quality planning
 selecting and modifying applicable quality standards and
procedures for a particular project
 Quality control
 series of inspections, reviews, and tests used to ensure
conformance of a work product to its specifications
 ensuring quality standards and procedures are followed by
development team
Note: Quality management should be separated from project
management to ensure independence. 30
Definition
 Q. What is Quality Planning ?

 A. Quality Planning is identifying which


quality standards are relevant to the
project and determining how to satisfy
them .

31
Definition
 Q. What is Quality Assurance

 A. QA is a set of activities for ensuring


quality in the processes by which
software is developed. QA aims to
prevent defects with a focus on the
process used to make the product.

32
Definition
 Q. What is Quality Control

 A. QC is a set of activities for ensuring


quality in products. The activities focus
on identifying defects in the actual
products produced.

33
Software Quality Assurance
 Monitoring processes and products throughout
the software development lifecycle to ensure the
quality of the delivered product(s)
 Monitoring the processes
 Monitor and provide management with objective
feedback regarding process compliance to approved
plans, procedures, standards, and analyses
 Monitoring the products
 Focus on the quality of product within each phase of
the SDLC
 e.g., requirements, test plan, architecture, etc.
 Objective: identify and remove defects throughout
the lifecycle, as early as possible 34
Process Assessment
 Use of standards and process models has a positive
impact on the quality of the software product
 Disciplined, controlled development process

 Examples include:
 ISO 9001
 CMM
 CMU SEI, 5 levels

 SPICE
 A standard for software process assessment
 ISO joint committee, Europe, Australia

 IEEE 1074, IEEE 12207, …


35
Product Assessment
 Reviews, inspections, walkthroughs

 Specialized techniques available:


 How to review/assess requirements,
architecture, detailed designs, code
 …
 Testing
 Simulation
 Protoyping
 Formal verification
36
 Model checking, theorem proving
Formal Technical Reviews
 To uncover errors in function, logic, or
implementation for any representation of the
software
 To verify that software meets its requirements
 To ensure that software representation meets
predefined standards
 To achieve software development in a uniform
manner
 To make projects more manageable
37
What do inspections cover?
 Inspections and walkthroughs:

 Primarily intended to discover defects in


software artifacts.

 This is a static analysis technique of


software testing.

 In addition, inspections address three


major tasks of process management:

 planning, measurement, control. 38


Inspection metrics
 Inspections are used to collect
quantitative quality data at defined points
in the development process.

 This can be used to give feedback to the


developers, feed-forward to future
development, and feed-into future steps
of process.

 Can also provide data on effectiveness of


inspection techniques. 39
What can be inspected?
 Inspections can be held a various
points in development process.
 Fagan recommended carrying out
inspections on:
 Detailed design
 Cleanly compiled code
 Completion of unit test
40
Who is involved?
 At a minimum a formal inspection
includes:
 Designated moderator
 Author of the work
 At least one peer inspector

 Walkthroughs generally do not include


designated moderator and are often led
by the author of the software.
41
Steps of inspection
 Planning
 Overview
 Preparation
 Meeting
 Rework
 Follow-up
42
Planning
 Planning begins when entry criteria for inspection
type is met.
 Moderator is selected – usually a peer or
technical leader
 Selection may be made by developer, but this is
generally not an ideal situation
 Management is encouraged not to look at
individual inspection results
 Moderator verifies that product meets entry
criteria and schedules future steps. 43
Overview
 Presentation to inspectors with any
background information needed to
properly review software product.

 Purpose is educational only

 Data collected is author preparation


time and time spent on presentation.

44
Preparation
 Individual activity
 Author collects all material required
for inspection
 Inspectors study the material and
complete inspection log.
 Defects are noted at this step, but
not collected…
45
Meeting
 Meeting is conducted by moderator
 Agenda includes:
 Introduction
 Establishing readiness
 Examining material and recording defects
 Review defects
 Determine disposition
 Debrief

 Defect data is collected this time 46


Common meeting problems
 Interpersonal tensions are most likely to arise
at this point
 Experienced moderators can detect and defuse
this tension

 The more inspections that occur, the less likely


interpersonal tensions are to interfere

 Effort should be made by all participants to


keep emphasis on producing quality product,
not making fault finding personal…
47
Rework
 Performed by the author in response
to defect disposition determined at
meeting

48
Follow-up
 Moderator verifies that corrections
are made
 Moderator completes inspection
management report and defect
summary report

49
Inspection Roles
 Author – developer of work product
 Moderator – an inspector responsible for
organizing and reporting on inspection
 Reader – an inspector who guides the
examination of the product
 Recorder – an inspector who enters all the
defects found on the defect list
 Inspector – Member of inspection team. Often
chosen to represent specific role- designer,
tester, technical writer, SQA, etc 50
Reviewer Roles
review
leader standards bearer (SQA)

producer

maintenance
oracle

recorder reviewer

user rep

Sometimes invite an expert…


51
The Expert at the Review Meeting…

52
53
Conducting the Review
1. be prepared—evaluate thoroughly before the review

2. review the product, not the producer

3. keep your tone mild, ask questions instead of


making accusations

4. stick to the review agenda


5. raise issues, don't try to resolve them…
6. avoid discussions of style—stick to technical
correctness
7. schedule reviews as project tasks

8. record and report all review results 54


Sticking to Review Agenda…

55
Metrics Collected from Reviews
inspection time per page of documentation
inspection time per KLOC or FP

inspection effort per KLOC or FP

errors uncovered per reviewer hour


errors uncovered per preparation hour
errors uncovered per SE task (e.g., design)

number of minor errors (e.g., typos)


number of major errors (e.g., nonconformance to
req.)
Total number of errors found during preparation
56
Review Guidelines..
 Review the product, not  Limit the number of
producer participants and insist
 Set an agenda and upon advance
maintain it preparation

 Limit the debate  Develop a checklist for


each work product to
 Enunciate problem areas,
be reviewed
not to solve every
problem noted  Training for all
reviewer’s
 Take written notes
 Reviewing earlier
 Allocate resources and
reviews
time schedule for FTR’s
57
16
Inspections and Reviews: What’s
the difference?
 An inspection is a more formal process
compared a walkthrough…
 History of Inspections:
 M.E. Fagan of IBM first defined inspections in
1976.
 E. Yourdon was among the first to publish a book on
inspections in 1978.
 IEEE standard covering inspections first appeared
in 1988.
58
Quality Management System

 A quality system consists of


the following:
 Processes

 Managerial Structure
 Individual Responsibilities.
59
Quality Management System
 Every quality conscious organization has
an independent quality department:
 Performs several quality system activities.
 Needs support of top management.
 Withoutsupport at a high level in a
company:
 Many employees may not take the quality
system seriously.
60
Quality System Activities
 Auditing of projects
 Development of:
 standards, procedures, and guidelines.
 Production of reports for the top
management:
 Summarizing the effectiveness of the
quality system in the organization.
 Review of the quality system itself. 61
62
Quality System
 A good quality system must be well
documented.
 Without a properly documented
quality system,
 Application of quality procedures
become ad hoc,
 Results in large variations in the quality
of the products delivered. 63
Quality System
 An undocumented quality system:
 Sends clear messages to the staff about
the attitude of the organization towards
quality assurance.

 International standards such as ISO


9000 provide:
 Guidance on how to organize a quality
system. 64
Evolution of Quality Systems
 Quality systems have evolved:
 Over the last six decades.
 Prior to World War II:
 Accepted way to produce quality
products:
 Inspect the finished products
 Eliminate defective products. 65
Evolution of Quality Systems
 Since World war II,
 Quality
systems of organizations
have undergone:
 Four stages of evolution.

 Many advances came from


Japanese:
 Helped resurrect Japanese economy.
66
Evolution of Quality Systems

67
Evolution of Quality Systems
 Initial product inspection method:
 Gave way to quality control (QC).

 Quality control:
 Notonly detect the defective
products and eliminate them
 Butalso determine the causes
behind the defects. 68
Quality Control (QC)
 Quality control aims at correcting the
causes of errors:
 Not just rejecting defective products.
 Statistical quality control (SQC):
 Inspection
or testing of all products is
cumbersome and many times not
feasible.
 Quality of the output of the process
is inferred using statistical methods. 69
Scope of Quality Disciplines
Software Quality Engineering

Software Quality Assurance

Software Quality Control

Software Testing

70
71
Quality Control (QC)
 The next breakthrough:
 Development of quality
assurance principles.

72
Quality Assurance
 Basic premise of modern quality
assurance:

 If an organization's processes are


good and are followed rigorously:

 The products are bound to be of


good quality.
73
Quality Assurance
 All modern quality paradigms
include:
 Guidance for recognizing,
defining, analyzing, and
improving the production
process.
74
Total Quality Management (TQM)

 TQM advocates:
 Continuous
process
improvements through
process measurements.

75
76
Business Process Reengineering

 BPR:A term related to TQM.


 Process reengineering goes a
step further than quality
assurance:
 Aimsat continuous process
improvement.
77
Business Process
Reengineering
 TQM focuses on reengineering
of the software process.
 Whereas BPR aims at reengineering
the way business is carried out in any
organization:
 Not just software development.
78
Total Quality Management (TQM)

 TQM goes beyond documenting


processes
 Optimizes them through redesign.

 Over the years the quality paradigm


has shifted:
 Fromproduct assurance to process
assurance. 79
Process Improvement

 Implies introducing process


changes to improve:
 Product quality
 Reduce costs
 Accelerate schedules.

80
Process Attributes
Pr ocess D escription
cha racteristic
U nderstandability To w hat extent is the process explici tl y defined and how easy is it to
understand the process definition?
V isibil ity D o the process activ ities culmi nate in cl ear resul ts so that the progress
of the process is external ly visible?
Supportability To w hat extent can C ASE tools be used to support the process
activ ities?
A cceptability Is t he defined process acceptable to and usable by the engi neers
responsibl e for producing the softw are product?
R eliability Is the process designed i n such a w ay that process errors are av oided or
trapped before they result in product errors?
R obustness C an the process conti nue in spite o f unexpected problems?
M aintainability C an the process ev olv e to reflect changi ng organisati onal requirements
or identifi ed process imp rovements?
R apidity How fast can the process of del iv ering a system from a giv en
specification be comp leted? 81
The Process Improvement Cycle
Measure

Change Analyse

82
Process Improvement Stages
 Process measurement
 Attributes of the process are measured.
 Form a baseline for assessing
improvements.
 Process analysis
 The process is assessed and bottlenecks
and weaknesses are identified.
 Process change
 Changes to the process that have been
identified during the analysis are
83
introduced.
Process and Product Quality
 A good process is usually required to
produce a good product.
 For manufactured goods, process is
the principal quality determinant.
 For design-based activity, other
factors are also involved:
 For example, the capabilities of the
designers. 84
85
ISO 9000
 ISO (international Standards
Organization):
A consortium of 63 countries
established to formulate and foster
standardization.

 ISO published its 9000 series of


standards in 1987.
86
ISO 9000 Philosophy
 Document what you do
 in
conformance with the requirements
of the applicable standard
 Do what you document
 Record what you did
 Prove it
 maintenance of registration requires
audits every three years, with mini-
audits every six months 87
On Being Transferred to the
Quality Department…

88
The ISO 9000 Family
 ISO 9000 is a family of standards for quality
management systems
 Originated in manufacturing, they are now employed
across a wide range of other types of organizations
 Some of the requirements in ISO 9001 (which is one of
the standards in the ISO 9000 family) include
 Documenting all key processes in the business;
 monitoring processes to ensure they are effective;
 keeping adequate records;
 checking output for defects, with appropriate corrective
action where necessary;
 regularly reviewing individual processes and the quality system
89
itself for effectiveness; and
ISO Family of Standards
 ISO 9001:2000 Basis for certification
 ISO 9004:2000 to prepare for national quality award
 ISO 10006 for project management
 ISO 10007 for configuration management
 ISO 10012 for measurement systems
 ISO 10013 for quality documentation
 ISO/TR 10014 managing economics of Quality
 ISO 10015 for training
 ISO/TS 16949 for automotive suppliers
 ISO 19011 for auditing
90
What is ISO 9000 Certification?
 ISO 9000 certification:
 Serves as a reference for
contract between independent
parties.
 The ISO 9000 standard:
 Specifiesguidelines for
maintaining a quality system. 91
What is ISO 9000 Certification?
 ISO 9000 specifies:
 Guidelinesfor repeatable and high
quality product development.
 Also
addresses organizational
aspects
 Responsibilities, reporting, procedures,
processes, and resources for
implementing quality management. 92
ISO 9000
 A set of guidelines for the
production process.
 Notdirectly concerned about
the product it self.
A series of three standards:
 ISO 9001, ISO 9002, and ISO
9003. 93
ISO 9000
 Based on the premise:
 Ifa good production process is
followed:
 Good quality products are bound
to follow.
94
ISO 9001
 Applies to:
 Organizations engaged in design,
development, production, and
servicing of goods.
 Applicable
to most software
development organizations.
95
ISO 9002
 ISO 9002 applies to:
 Organizations who do not design products:
 but are only involved in production.

 Examples of this category of industries:


 Steel or car manufacturing industries
 Buy the product and plant designs from
external sources:
 only manufacture products.
 Not applicable to software development
96
organizations.
ISO 9003

 ISO 9003 applies to:


 Organizations involved only in
installation and testing of
products.

97
ISO 9000 Structure
ISO 9000

ISO 9003
ISO 9002 Quality System Model
ISO 9001 Quality System Model for
Quality System Model for for Quality Assurance
Quality Assurance in in final inspection and
Quality Assurance in design, production, installation, and
development, production, test
servicing
installation and service

ISO 9000-3
Guidelines for the application
of ISO 9001 to the design,
development and maintenance
of software

98
ISO 9000 for Software Industry
 ISO 9000 is a generic standard:
 Applicable to many industries,
 Starting from a steel manufacturing
industry to a service rendering company.

 Many clauses of ISO 9000 documents:


 Use generic terminologies
 Verydifficult to interpret them in the
context of software organizations. 99
Software vs. Other Industries
 Very difficult to interpret many
clauses for software industry:
 Software development is radically
different from development of
other products.

100
Software vs. Other Industries
 Software is intangible:
 Therefore difficult to control.
 It is difficult to control anything that we cannot
see and feel.
 In contrast, in a car manufacturing unit:
 We can see a product being developed through
stages such as fitting engine, fitting doors, etc.
 One can accurately tell about the status of the
product at any time.
 Software project management is an
altogether different ball game… 101
Software vs. Other Industries
 During software development:
 The only raw material consumed is data.
 For any other product development:
 Lot of raw materials consumed
 e.g. Steel industry consumes large volumes of iron
ore, coal, limestone, etc.

 ISO 9000 standards have many clauses


corresponding to raw material control .
 Not relevant to software organizations. 102
Software vs. Other Industries
 Radical differences exist between
software and other product
development:
 Difficultto interpret various
clauses of the original ISO standard
in the context of software industry.

103
ISO 9000 Looks Great on Brochures…

104
ISO 9000 Part-3
 ISO released a separate document
called ISO 9000 part-3 in 1991:
 Tohelp interpret the ISO standard
for software industry.

 At present:
 Official guidance is inadequate.
105
ISO 9001: A Quick History
i. Original Standard in 1987
a) 20 clauses
b) Procedure-based
ii. Revision in 1994
a) A “tweak”
iii. Revision in 2000
a) Major overhaul
b) 8 sections
c) Focus on the Customer
d) Focus on Business Results
iv. Revision in 2008
106
A “tweak”
http://www.iso.org/iso/about.htm
a)
ISO 9000: 2000
 ISO 9001:2000:
 Combines the three standards 9001, 9002, and
9003 into one.
 Design and development procedures are
required:
 Only if a company does in fact engage in the
creation of new products.
 The 2000 version sought to make a radical
change in thinking:
 By actually highlighting the concept of process
107
management.
ISO 9000: 2000
 An important goal is now to improve
effectiveness via process performance
metrics:
 Numericalmeasurement of the
effectiveness of tasks and activities.
 Continualprocess improvement and
tracking customer satisfaction were
made explicit.
108
The 2008 “Tweak”
 ISO 9001:2008 did not introduce additional
requirements
 Nor did it change the intent of the ISO
9001:2000 standard.
 ISO 9001:2008 was developed in order to:
 Introduce clarifications to the existing
requirements of ISO 9001:2000 and
 Introduce changes that are intended to improve
compatibility with ISO 14001:2004, Environmental
109
Management Systems.
Clarification Examples

From To
Regulatory Requirements Statutory and regulatory
requirements
Equipment Devices
Conformity of the product Conformity of the product to
requirements

110
ISO 9000 Process model

111
112
Certification and registration
 Certification is known in some countries as
registration.

 It means that an independent, external body


has audited an organization's management
system and verified that it conforms to the
requirements specified in the standard (ISO
9001 or ISO 14001).

 ISO does not carry out certification and does


not issue or approve certificates.
113
Accreditation
 Accreditation is like certification of the certification
body.
 It means the formal approval by a specialized body - an
accreditation body - that a certification body is
competent to carry out ISO 9001 certification in
specified business sectors.
 Certificates issued by accredited certification bodies -
and known as accredited certificates:
 may be perceived on the market as having increased
credibility.

 ISO does not carry out or approve accreditations.114


Certification not a requirement
 Certification is not a requirement of ISO
9001
 An organization can implement and
benefit from an ISO 9001 system
without having it certified
 The organization can implement them for
the internal benefits without spending
money on a certification program
115
ISO does not certify
 ISO does not carry out ISO 9001
certification
 ISO does not issue certificates
 ISO does not accredit, approve or control
the certification bodies
 ISO develops standards and guides to
encourage good practice in accreditation
and certification
116
ISO Certification Process
Make
commitment

Select Apply for Conduct initial


Registrar registration assessment/doc
review

Conduct full Perform Make


assessment pre/internal improvements/take
assessment audit corrective action

Enter
surveillance
mode 117
Why Get ISO 9000 Certification?
 In Europe (and elsewhere) only buy from
certified companies to ensure safety
 Telecommunications equipment
 Medical devices
 Gas appliances
 Toys
 Construction products
 Required for international competitiveness
 Not to mention all of the other benefits of
trying to improve quality 118
Why Get ISO 9000 Certification?

 Many international software


development contracts insist:
 Development
organization to have
ISO 9000 certification.

119
Why Get ISO 9000 Certification?
 Requires a well-documented software
production process to be in place.
 Contributes to repeatable and higher
quality software.
 Makes development process:
 Focussed, efficient, and cost-effective

120
Why Get ISO 9000 Certification?
 Points out the weakness of an
organizations:
 Recommends remedial action.

 Sets the basic framework:


 Fordevelopment of an optimal
process and TQM.
121
122
How to Get ISO 9000
Certification?
 An organization intending to obtain
ISO 9000 certification:
 Appliesto an ISO 9000 registrar
for registration.

 ISO 9000 registration process


consists of several stages.
123
How to Get ISO 9000
Certification?
 Application stage:
 Appliesto a registrar for
registration.

 Pre-assessment:
 Theregistrar makes a rough
assessment of the organization.
124
How to Get ISO 9000
Certification?
 Document review and adequacy

audit:
 Process
and quality-related
documents.
 The registrar reviews the documents.
 Makes suggestions for improvements.
125
Process Documentation…

126
How to Get ISO 9000
Certification? Compliance Audit

 The registrar checks:


 Whether the suggestions made
by it during review have been
complied.

127
Auditor at work…

128
ISO 9000 Audit….

129
ISO 9000 Audit….

130
How to Get ISO 9000
Certification?
 Registration:

 Theregistrar awards ISO 9000


certificate after successful
completions of all previous phases.

 Continued surveillance:
 Theregistrar continues monitoring
the organization periodically. 131
ISO 9000 Certification
 An ISO certified organization :
 Canuse the certificate for corporate
advertizements.
 Cannot use the certificate to advertize
its products.
 ISO 9000 certifies organization's process
 Not any product of the organization.

 Anorganization using ISO certificate for


product advertizements:
 Risks withdrawal of the certificate. 132
ISO 9001 Requirements
 Management  Control of customer
responsibility supplied product
 Quality system  Product identification
 Contract review and traceability

 Design Control  Process control

 Document and data Inspection


 and testing
control  Control of inspection,

 Purchasing measuring and test


133
equipment 25
ISO 9001 Requirements
 Inspection and test  Control of quality
status records
 Control of non-  Internal quality
confirming product audits
 Corrective and  Training
preventive action  Servicing
 Handling, storage,  Statistical
packaging, techniques
preservation and
delivery 134
26
Summary of ISO 9001
Requirements
 Management responsibility(4.1):

 Management must have an effective


quality policy.
 The responsibility and authority of
all those whose work affects
quality:
 Must be defined and documented. 135
Management Responsibility(4.1)
 Quality system.
 Shouldbe independent of the
development process.
 Can work in an unbiased manner.

 The effectiveness of the quality


system:
 Must be periodically by audited. 136
Quality System (4.2) and Contract Reviews (4.3):
 A quality system must be
maintained and documented.
 Contract reviews (4.3):
 Beforeentering into a contract, an
organization must review the
contract
 Ensure that it is understood,
 Organization has the capability for
carrying out its obligations. 137
Design Control (4.4)
 The design process must be
properly controlled:
 This includes controlling coding
also.
 A good configuration control
system must be in place.
138
Design Control (4.4)
 Design inputs must be verified as
adequate.
 Design must be verified.
 Design output must be of required
quality.
 Design changes must be controlled.
139
140
Document Control (4.5)
 Proper procedures for:
 Document approval, issue and
removal.
 Document changes must be
controlled.
 Use
of some configuration
management tools is necessary. 141
142
Purchasing (4.6)
 Purchased material, including
bought-in software:
 Mustbe checked for
conforming to requirements.

143
Purchaser Supplied Products (4.7)

 Material supplied by a
purchaser:
 For example,
 Client-provided software must
be properly managed and
checked. 144
Product Identification (4.8)

 The product must be


identifiable at all stages of the
process.
 Insoftware development
context this means
configuration management.
145
Process Control (4.9)
 The development must be
properly managed.
 Quality requirements must be
identified in a quality plan.

146
147
Inspection and Testing (4.10)
 In software terms this requires
effective testing i.e.,
 Unittesting, integration testing and
system testing.

 Test records must be maintained.

148
Inspection, Measuring and Test
Equipment(4.11)

 If integration, measuring, and


test equipments are used,
 Must be properly maintained and
calibrated.

149
Control of Nonconforming Product
(4.13)

 In software terms,
 Keepinguntested or faulty
software out of released
product.

150
Corrective Action (4.14)
 This is both about correcting errors
when found:
 Investigating why they occurred
 Improvingthe process to prevent further
occurrences.

 If an error reoccurs despite the


quality system:
 The system needs improvement. 151
Handling (4.15) and Quality
Audits (4.17):
 Handling (4.15) Deals with:
 Storage,
packing, and delivery of the
software product.
 Quality Audits (4.17) :
 Qualitysystem audit must be carried
out to ensure its effectiveness.
152
Training (4.18)
 Training needs must be
identified and met.
 Most items of ISO standard:
 Are largely common sense.

153
The focus is documents…

154
Salient Features of ISO 9001
Requirements:
 All documents concerned with the
development of a software product:
 Shouldbe properly managed,
authorized, and controlled.

 Proper plans should be prepared:


 Progress
against these plans should
be monitored. 155
Salient Features of ISO 9001
Requirements
 Important documents independently
checked and reviewed:
 For effectiveness and correctness.
 The product should be tested :
 Against specification.
 Several organizational aspects:
 e.g., management reporting of the quality
team.
156
157
ISO 9000 and quality management
ISO 9000
quality models

instantiated as

documents
Organization Organiza tion
quality manual quality process

is used to develop instantiated as

Project 1 Project 2 Project 3 Project quality


quality plan quality plan quality plan mana gement

Supports 158
Quality Standards
 Key to effective quality management

 Product standards define the characteristics


exhibited by all components (e.g. programming
style issues)

 Process standards describe how a software


process is to be implemented

 Should encapsulate best practices - this helps


avoid repeating past mistakes
159
Process and Product Standards
Product Standards Process Standards
– Design review form – Design review guidelines
– Document naming – Document submission
standards procedures
– Function prototype – Version release process
format – Project plan approval
– Programming style procedure
standards – Change control process
– Project plan format – Test data recording
– Change request form procedures 160
Shortcomings of ISO 9001
Certification

 ISO 9000 requires a production


process to be adhered to:
 Butdoes not guarantee the process
to be of high quality.
 Doesnot give any guideline for
defining an appropriate process.
161
Shortcomings of ISO
9001 Certification cont…
 ISO 9000 certification process:
 Not fool-proof
 Nointernational accredition agency
exists.
 Likely
variations in the norms of
awarding certificates:
 Among different accredition agencies
162
and among the registrars.
Shortcomings of ISO 9001
Certification (3)
 Organizations qualifying for ISO 9001
certification:
 Tend to downplay domain expertise.
 Tendto believe that since a good
process is in place,
 Any engineer is as effective as any other
engineer in doing any particular activity
relating to software development. 163
Shortcomings of ISO 9001
Certification (4)
 In manufacturing industry:

 Clear
link between process quality and
product quality.
 Once a process is calibrated:
 Can be run again and again producing quality
goods.
 Software development is a creative
process:
 Individualskills and experience is
164
significant.
Shortcomings of ISO 9001
Certification (5)
 Many areas of software development

are very specialized:


 Special
expertize and experience (domain
expertize) required.
 ISO 9001:
 Doesnot automatically lead to continuous
process improvement,
 Does not automatically lead to TQM. 165
Shortcomings of ISO 9001 Certification (6)
 ISO 9001 addresses mostly management
aspects.
 Techniques specific to software
development have been ignored:
 Configuration management
 Reviews
 Release builds
 Problem Notification system
166

 Intranets
SEI CMM

167
SEI Capability Maturity Model (CMM)

 Developed by Software Engineering


Institute (SEI) of the Carnegie Mellon
University, USA:
 To
assist the U.S. Department of
Defense (DoD) in software acquisition.

 The rationale was:


 Includelikely contractor performance as
a factor in contract awards. 168
CMM: A Brief History
 Working with DoD, Carnegie-Mellon University (CMU)
created the Software Engineering Institute
 In September 1987, the SEI released a brief
description of the process maturity framework
 Two methods: software process assessment and software
capability evaluation and a maturity questionnaire were
developed to appraise software process maturity.

 In 1991, SEI released the Capability Maturity Model


for Software version 1.0.
 In 2001, SEI released the Capability Maturity Model –
Integrated (CMMI), superseding the CMM for
169
software.
Software Engineering Institute (SEI)
o Federally Funded Research &
Development Center (FFRDC) at
Carnegie Mellon University

o Mission is to foster
improvement of software
processes

o Developed Capability Maturity


Model and Assessment
Methodology

o Educate “Authorized Lead


Assessors” and organizations

o Many Assessors have been


leading process improvement
efforts since 1989 170
SEI Capability Maturity Model
 Major DoD contractors began CMM-based
process improvement initiatives:
 As they vied for DoD contracts.

 SEI CMM helped organizations:


 Helped Improve quality of software they
developed
 Realized adoption of SEI CMM model had
significant business benefits.

 Other organizations adopted CMM. 171


What is CMM?
 Describes an evolutionary improvement
path for software organizations from an
ad hoc immature process :
 To a mature, disciplined one.

 Provides guidance on how to gain control of


processes for developing and maintaining
software:
 How to evolve toward a culture of software
engineering and management excellence. 172
SW development and football
 What happens when a ball is kicked
off to an unknown team?
 Everyone runs around at random.
 They might do the right thing, or they might not.
 The next time the ball is hit in the same place, they
may do something different.
 What happens when a ball is hit to a professional
team?
 Everyone moves in a coordinated fashion, based on
practicing that play many times.
 Sometimes they fail to make the right play, but they
almost always try to do the right thing. 173
SEI Capability Maturity Model
 In simple words:

 CMM is a model for apprising the


software process maturity of a
contractor into different levels.
 Can be used to predict the most
likely outcome to be expected:
 from the next project that the
organization undertakes. 174
SEI Capability Maturity Model

 Can be used in two ways:


 Capability evaluation
 Softwareprocess
assessment.

175
Capability Evaluation
 Provides a way to assess the
software process capability of
an organization:
 Helps in selecting a contractor

 Indicates the likely contractor


performance.
176
What is a Software Process?

Management

PROCESSES

Staff Technology

SW Process can be defined as a set of activities, methods,


practices and transformations that people use to develop
and maintain software and associated products (e.g.
project plans, design documents, test plans, user manuals
etc.) 177
Software Process Assessment
 Used by an organization to
assess its current process:
 Suggestsways to improve the
process capability.

 Thistype of assessment is for


purely internal use.
178
Process Management Premise
• An undefined
process cannot be
controlled Improve
(or measured)

• An uncontrolled Control
process cannot be Define
improved Measure

• Attempting to Execute
improve an Process
unstable process Adapted from SEI

yields further
instability
179
SEI Capability Maturity Model
 The SEI CMM classifies software
development industries into:
 Five maturity levels.
 Stages are ordered so that
improvements at one stage provide
foundations for the next.
 Based on the pioneering work of Philip
Crosby. 180
SEI Capability Maturity Model
Optimizing (5)

Managed (4)

Defined (3)

Repeatable (2)

Initial (1)

181
Improvement Framework
Productivity and Quality Optimizing - Level 5
Total Organization Involvement Continuous
Improvement
Managed - Level 4
Quantifiable Predictability Quantitative
Understanding
Defined - Level 3
Engineering
Consistency
Process
Focus
Repeatable - Level 2
Management
Disciplined
Process

Initial - Level 1
Chaos
Capability Maturity ModelSM Version 1.1

182
Improvement Framework
Optimizing - Level 5
Defect Prevention
Technology Change Mgmt
Process Change Mgmt.
Productivity
and Managed - Level 4
Quality
Quantitative Process Management
Software Quality Management

Defined - Level 3
Organization Process Focus Organization Process Definition
Training Program Integrated Software Management
Software Product Engineering Intergroup Coordination
Peer Reviews

Repeatable - Level 2
Requirements Management Software Project Planning
Software Project Tracking & Oversight Subcontract Management
Software Quality Assurance Software Configuration

Management
Initial - Level 1
183
184
Level 1: (Initial)
 Organization operates
 Without any formalized process
or project plans

 An organization at this level is


characterized by
 Ad hoc and chaotic activities. 185
Level 1 – Initial
 Team tackles projects in different ways each
time
 Can have strong successes, but may not repeat
 Some time/cost estimates are accurate, many
far off
 Success comes from smart people doing the
right things
 Hard to recover from good people leaving
 Frequent crises and "firefighting.” (Many believe
this is standard for SW development. CMM says
NO.)
 Most SW development organizations are Level1861.
Level 1: (Initial)
 Software development
processes are not defined,
 Differentengineers follow their
own process

 The success of projects depend


on individual efforts and heroics.
187
Level 1: Success depends on heroes
Good performance is possible - but
 Requirements often misunderstood, uncontrolled
 Schedules and budgets frequently missed
 Progress not measured
 Product content not tracked or controlled
 Engineering activities nonstandard, inconsistent
 Teams not coordinated, not trained
 Defects proliferate 188
Level 2: (Repeatable)
 Basic project management practices
 Tracking cost, schedule, and functionality
are followed.
 Size and cost estimation techniques:
 Function point analysis, COCOMO, etc.
used.
 Development process is ad hoc:
 Not formally defined
 Also not documented. 189
Level 2: (Repeatable)
 Process used for different
projects might vary between
projects:
 Earliersuccess on projects with
similar applications can be
repeated.
 Opportunity to repeat process exist
when a company produces a family
190
of products.
CMM Level 2
7 Process Areas
CLARIFY REQUIREMENTS
 Baseline the product requirements
– Requirements Management
(REQM)
DOCUMENT PLANS
 Estimate project parameters, Project Planning (PP)
 Develop plans and processes – Project Monitoring
TRACK PROGRESS and Control (PMC)
 Measure actual progress to enable
– Measurement &
timely corrective action
Analysis (M&A)
 Measure for mgmt. info needs

 Verify adherence of processes


– Process & Product
and products to requirements Quality Assurance (PPQA)

CONTROL PRODUCTS – Configuration


 Identify and control products, Management (CM)
changes, problem reports
– Supplier Agreement
 Select qualified suppliers /
Management (SAM)
191
vendors; manage their activities
Level 3: (Defined)
 All management and
development activities:
 Defined and documented.
 Common organization-wide
understanding of activities, roles,
and responsibilities.
192
193
Level 3: (Defined)
 The process though defined:
 Process
and product qualities are
not measured.

 ISO 9001 aims at achieving


this level.
194
Level 4: (Managed)
 Quantitative quality goals for products
are set.
 Software process and product quality
are measured:
 Themeasured values are used to control
the product quality.
 Resultsof measurement used to evaluate
project performance:
195
 Rather than improve process.
196
Level 4: Managed
• Detailed measures of the software process and
product quality are collected.
• Both the software process and products are
quantitatively understood and controlled.
• Narrowing the variation in process performance to
fall within acceptable quantitative bounds
• When known limits are exceeded, corrective action
can be taken
• Quantifiable and predictable
• predict trends in process and product quality
• Set quantitative quality goals 197
198
Level 5: (Optimizing)
 Statistics collected from process

and product measurements are


analyzed:
 Continuous
process improvement
based on the measurements.
 Known types of defects are prevented
from recurring by tuning the process
 Lessons learned from specific projects
incorporated into the process 199
Level 5: (Optimizing)
 Identify best software engineering
practices and innovations:
 Tools,methods, or process are
identified.
 Transferred throughout the
organization.
 World-wide about 500 organizations
200
have been assessed at this level.
Behaviors at the Five Levels
Maturity Level Process Characteristics Behaviors

Focus on "fire prevention";


Focus is on continuous improvement anticipated and
Optimizing quantitative
desired, and impacts assessed.
improvement

Quantitatively Process is measured Greater sense of teamwork and inter-


Managed and controlled dependencies

Process is characterized Reliance on defined process.


Defined for the organization and People understand, support and
is proactive follow the process.

Process is characterized Over reliance on experience of good


Repatable for projects and is often people – when they go, the process
reactive goes. “Heroics.”

Process is unpredictable, Focus on "fire fighting";


Initial poorly controlled, and effectiveness low – frustration high.
201
reactive
Key Process Areas

 Each level is associated with a


key process area (KPA)
identifies:
 Processareas that an
organization at the previous
level must focus to reach this
level. 202
Level 2 KPAs
 Requirements Management
 Requirements is basis for planning and
managing the software project

 Software project planning:


 Size, cost, schedule.
 Project monitoring

 Configuration management
 Subcontract management
203
CMM Level 2 KPAs
Software
Requirements
Quality
Management Assurance

Software Software
Project Configuration
Planning Management

Software Software
Project Tracking Subcontract
and Oversight Management 204
L2
Level 3 KPAs
 Process definition and
documentation.
 Reviews
 Training program

205
CMM Level 3 KPAs

Organization Organization
Process Process
Focus Definition

Training Inter-group Peer


Program Coordination Reviews

Integrated Software
Software Product
Management Engineering 206
Level 4 KPAs
 Quantitative measurements.

 Quantitative Process
management.
 control process performance quantitatively

 focus on identifying and correcting special


causes of variation with respect to a baseline
process
207
208
Level 5 KPAs
 Defect prevention.
 causal analysis of defects to prevent
recurrence
 Technology change management.
 identify and transfer beneficial new
technologies
 tools
 methods
 processes
 Process change management. 209
Examples of measurements for
size of work products
 Estimated number of requirements
 Actual number of requirements
 Estimated source lines of code (SLOC)
 Actual SLOC
 Estimated number of test cases
 Actual number of test cases
210
Example of measurements of effort
 Estimated man-hours to design/code a

given module
 Actual man-hours expended for
designing/coding the module
 Estimated number of hours to run builds
for a given release
 Actual number of hours spent running
builds for the release 211
Examples of measurements of quality
of the work product

 Number of issues raised at requirements


inspection
 Number of requirements issues open
 Number of requirements issues closed
 Number of issues raised during code
inspection
 Number of defects opened during unit
testing 212
Examples of measurements of quality
of the work product
 Number of defects opened during
system testing
 Number of defects opened during
UAT
 Number of defects still open
 Number of defects closed
 Defect age 213
Examples of measurements of
quality of the work product
 Total number of build failures
 Total number of defects fixed for a
given release
 Total number of defects verified and
accepted
 Total number of defects verified and
rejected 214
CMM Assessment
Projects
Process Fill Out Select Identify
Collect
Data Questionnaire Projects Scope
Documents

Kick-Off
Meeting

Organizational
Review
Documents
Project
Implementation
Project Leaders
Interviews
Middle Managers
Practitioners
SEPG

Findings Findings
Presentation Next Steps

Legend
= Activities completed
prior to on-site visit

215
Typical Assessment
On-site Period
Day 1 Day 2 Day 3 Day 4 Day 5

Project Leader Functional Area Consolidate Present Draft Present Final


Interviews Rep Interviews Data Findings( Pls) Findings

Functional Consolidate Data Follow-on Present Draft Executive Session


Area Rep Interviews (As Findings (FARs)
Interviews required)
Appraisal Wrap-
Rate Organization up
Prepare Draft
Develop Final
Findings
Finding
Next Steps
Presentation

216
Benefits of CMM
• Win more projects due to customers’
trust
• Make large international projects
possible
• Risk mitigation
• Improved project quality
• Make projects success possible when
team members dynamically change. 217
Cons of CMM
High cost: training, writing documents
and synchronizing practice and
documents

% Succeeded
Projects

CMM
1 2 3 4 5 Level

Cost

CMM
1 2 3 4 5 Level 218
Con: Becoming stamp of approval
 Some organizations want CMM only
as a stamp of approval:

 Without a high-level commitment to


process improvement or quality

 Want to find easiest way to get


certified as Level 2 (or 3) without
really changing 219
Con: Not Quality software!
 CMM is, by design, a model for managing
software projects

 They claim most software failures are due to


management problems rather than technical barriers

 But CMM goes too far in this direction

 An organization could write lousy code


(consistently) and be rated highly by CMM

 This is counter-intuitive, since good code is the


goal of software development 220
Con: Not Quality software!
 It is often felt that CMM promotes
bureaucratic attitude, claiming:
 “Anyone can develop good software,
regardless one’s proficiency, experience, and
intellect, by following a cook book process
recipe.”

 CMMI solely concentrates on the process as a


factor in software development, sparing out
people and technology. 221
Comparison Between ISO 9001
and SEI CMM
 ISO 9001 awarded by an
international standards body:

 Canbe quoted in official documents


and communications.

 SEI CMM assessment is purely for


internal or limited use.
222
Comparison Between ISO 9001
and SEI CMM
 SEI CMM was developed specifically
for software industry:
 Addresses many issues specific to
software industry.

 SEI goes beyond quality assurance


 Aims for TQM.
 ISO 9001 corresponds to SEI level 3.
223
Comparison Between ISO 9001
and SEI CMM
 SEI CMM provides a list of key areas:

 Onwhich to focus to take an organization


from one level to the other
 Provides a way for gradual quality
improvements over several stages.
 e.g
trying to implement a defined process
before a repeatable process:
 Counterproductive as managers are
overwhelmed by schedule and budget pressure.
224
ISO and CMM Comparison
ISO CMM
Is a Certification Is an assessment

Used for all industry development Used for software

Yearly re-certification No follow up after reaching level

Outwardly focus Inwardly focus

Third Party Certification Certified by the SEI (Developers of CMM)


225
CMMI

226
So Many Models, So Little Time
• Different structures,
formats, terms, ways
YA- of measuring
Software CMM
EIA 731 maturity
CMM
• Causes confusion,
Systems especially when using
Engr more than one model
CMM
People
CMM • Hard to integrate
IPD Software them in a combined
CMM Acq
CMM improvement program
• Hard to use multiple
FAA Systems
iCMM Security models in supplier
Engr CMM selection 227
CMMI (CMM Integrated)
 CMMI is the successor of the CMM.
 CMM was developed from 1987--1997.
 In 2002, CMMI Version 1.1 was
released.
 Version 1.2 followed in August 2006.
 The goal of CMMI is to integrate many
different models into one framework.
 Itwas created by members of industry,
government and the SEI. 228
Three Flavours of CMMI
 CMMI for Development
 Development and maintenance of products
 Integrates software engineering, systems
engineering, collaborative teams, acquisition from the
supplier’s side
 Not just for software development!
 CMMI for Services
 Organizations that provide services (from taxis to
call centers)
 CMMI for Acquisition
 Acquiring products and services
 Common Process Areas are embedded within all
229
three
The CMMI Solution
A Product Line Approach

SW SE

Industry

IPPD ... SEI


CMMI
Product Suite

Government
Assess

Training CMMI- CMMI- CMMI-


• Team of Teams SW SE SE/SW
• Modeling and
Discipline Experts
CMMI-
SE/SW/
...
• Collaborative IPPD
Process 230
CMMI
 Created Based on the CMM-SW model to assess
the maturity of software development, with
integration into other models.

 Multiple models, based on disciplines addressed


 CMMI - SW: Software Engineering

 CMMI - SE / SW: above plus Systems Engineering

 CMMI - SE / SW / IPPD: above plus Integrated Product


& Process Development

 CMMI - SE / SW / IPPD / SS: above plus Supplier


Sourcing 231
CMMI
 Besides CMMI for Software Engineering.
 There are others such as CMMI for Systems Engineering,
Supplier Sourcing, and Integrated Product and Process
Development
 There are 2 models : Staged and Continuous
 Different levels
 5 levels for Staged
 6 levels for Continuous
 25 major processes grouped into 4 categories:
 Organizational
 Project management
 Engineering
 Support Category
 There are Goals and Practices for Each Process – to be232
satisfied for both models
Why Should I Use the CMMI?
• Structures the effort:
• Where do I start? What is the next activity?

• Helps identify an organization’s


improvement objectives and priorities

• Provides benefit from a larger community’s


experience

• Has an appraisal methodology to diagnose


the state of improvement efforts. 233
CMMI Structure
CMMI is a collection of best practices
 These “best practices” reside in 25 focus areas called “Process
Areas.”

 Each process area has specifically stated goals that have to


be met in order to have “maturity” or “capability” in the
process area.

 Each process area has specific practices, subpractices, typical


work products (outputs), examples, and other informative
material

 Most of the goals are specific to the process area, but there are
some generic or “global” goals that are common to all of the
Process Areas 234
Process Areas by Maturity Level
Maturity Level Process Areas
5 Optimizing Organizational Innovation and Deployment
Causal Analysis and Resolution
4 Quantitatively Managed Organizational Process Performance
Quantitative Project Management
3 Defined Requirements Development Technical Solution
Product Integration Verification
Decision Analysis and Resolution Validation
Organizational Process Focus
Organizational Process Definition +IPPD
Organizational Training
Integrated Project Management +IPPD
Risk Management
2 Managed Requirements Management
Project Planning
Project Monitoring and Control
Supplier Agreement Management
Measurement and Analysis
Process and Product Quality Assurance
Configuration Management 235
1 Initial
4 CMMI Process Areas
 Process Management (5 processes)
 Organizational Process Focus
 Organizational Process Definition
 Organizational Training
 Organizational Process Performance
 Organizational Innovation and Deployment
 Project Management (8 processes)
 Project planning
 Project Monitoring and Control
 Supplier Agreement Management
 Integrated Project Management
 Risk Management
 Integrated Teaming
 Integrated Supplier Management
236
 Quantitative Project Management
4 CMMI Process Areas (cont.)
 Engineering: (6 processes)
 Requirements Management
 Requirements Development
 Technical Solution
 Product Integration
 Verification
 Validation
 Support: (6 processes)
 Configuration Management
 Process and Product Quality Assurance
 Measurement and Analysis
 Organizational Environment for Integration
 Decision Analysis and Resolution 237
 Causal Analysis and Resolution
Staged Model and Maturity Levels (MLs)
ML5:Optimizing
1. Organizational Innovation & Deploy
2. Causal Analysis & Resolution
ML4:Quantitatively
Managed 1. Organizational Process Performance,
2. Quantitative Proj. Mgmt

ML3:Defined
1. Req. Development, 2. Technical solutions, 3. Product
Integration, 4. Verification, 5. Validation, 6.
Organizational Process Focus, 7. Organiz. Process
Definition, 8. Organiz. Training, 9. Integrated Proj.
Mgmt, 10. Risk Mgmt, 11.Integrated Teaming, 12.
Integrated Supplier Mgmt, 13. Decision Analysis and
ML2:Managed Resloution, 14. Organiz. Environment for Integration

1. Requirements Mgmt, 2. Project Planning, 3. Configuration


Mgmt, 4.Supplier Agreement Mgmt, 5. Project Monitoring &
ML1:Initial Cntrl, 6. Measurement & Analysis, 7. Process & Product QA
No Process
238
CMMI Flavours

 2 flavours:
 Continuous

 Staged

239
CMMI: Continuous Representation
 Enables comparisons across and among
organisations on a process area by
process area basis.

 It is a process area which receives a


capability rating.

 An organisation might have a number of


process areas at different levels of
capability
240
CMMI: Staged Versus Continuous
 Flexible versus static order of improvement:
 In continuous, a company may focus on any process it
requires, whereas in Staged, the order in which
processes need to improved is fixed.

 Process areas versus Entire organization:


 In continuous, two companies may be compared for a
specific project whereas for staged the comparison is
for the entire organization.

 Migration:
 Migration from CMM to CMMI is easy for staged
241

model.
What is a SCAMPIsm Appraisal?
 SCAMPIsm – Standard CMMI Appraisal Method
for Process Improvement

 Used for baselining current behaviors to


begin improvement activities or see into
ongoing improvement activities

 To assign a formal rating Uses the CMMI as


reference model.

 SCAMPI goal is to provide an accurate picture


of your organization relative to the reference
242
model.
Maturity Profile – 2010
 The percentage of organizations at each maturity level
based on most recent appraisals of 2753
organizations.

Maturity Profile - CMMI/SCAMPI Results published


March 2010

70.0% 63.0%
60.0%
50.0%
40.0% 25.2%
30.0%
20.0% 1.3% 5.2%
10.0% 0.5%
0.0%
Level 1 Level 2 Level 3 Level 4 Level 5
243
SCAMPI Appraisal
 Minimum team size is four - A Lead Appraiser and
three additional team members.
 At least one team member must be from the appraised
organization.
 All team members must be trained in the official
CMMI and SCAMPI courses
 Conflicts of interest must be avoided
 Exclude process authors and individuals directly impacted by
the outcome of the appraisal
 Team members cannot be managers of any of the
selected projects or groups
 Appraisal sponsors cannot be team members. 244
245
What does the SCAMPI Team do?
 Reviews an organization’s documentation
 Processes, procedures, policies, status
reports, meeting minutes

 Conducts interviews
 To ensure the documentation is actually used

 Maps results to the CMMI


 Practices, Goals, Process Areas

 Assigns ratings 246


What does the Team NOT do?
 Does not go looking for the
documentation
 Easter egg hunts are not allowed!

 Does not judge the “goodness” of


the process
 Does not judge how well you are
doing your job. 247
248
Remarks on Quality Model Usage
 Highly systematic and measured approach to
software development process suits certain
circumstances
 Negotiated or safety-critical software, etc.
 What about small organizations?
 Typically handle applications such as internet, e-
commerce.
 Without an established product range,
 Without revenue base, experience on past projects,
etc.
249
 CMM may be incompatible
Small Organizations
 Small organizations tend to believe:
 We are all competent people hired to
do a job, we can’t afford training.
 We all communicate with one another.
 Osmosis works because we are so close.
 We are all heroes:
 We do what needs to be done.
Therefore rules do not apply to us.
250

Small Organizations
 Often have problems:
 Undocumented requirements
 Inexperienced managers
 Poor Documentation
 Unsystematic Resource allocation
 No Training
 Peer reviews 251
Small Organizations
 A two week CMM-based appraisal
is probably excessive.
 Small organizations need to
operate more efficiently at lower
levels of maturity
 Mustfirst flourish if eventually
they are to mature
252
Personal Software Process (PSP)
 Based on the work of Humphrey.
 PSP is a scaled down version of
industrial software process:
 Suitable for individual use.

 Even CMM assumes that engineers


use effective personal practices.
253
Personal Software Process (PSP)
 A process is the set of steps for doing
a job.
 The quality and productivity of an
engineer
 Largely determined by his process

 PSP framework:
 Helpssoftware engineers to measure
254
and improve the way they work.
Personal Software Process (PSP)
 Helps developing personal skills and
methods.
 Estimating and planning method.
 Shows how to track performance against
plans.
 Provides a defined process;
 Can be fine tuned by individuals.
 Recognizes that a process for individual use is
different from that for a team project. 255
Time Management
 Track the way you spend time:
 Boring activities seem longer than actual.
 Interesting activities seem short.
 Record time for:
 Designing

 Writing code
 Compiling

 Testing 256
Personal Software Process (PSP)

Planning
Design
Code Logs
Compile
Test
Project
Postmortem plan
summary
257
PSP-Planning
 Problem definition
 Estimate max, min, and total LOC
 Determine minutes/LOC
 Calculate max,min, and total
development times
 Enter the plan data in project plan
summary form
 Record the planned time in Log 258
PSP-Design
 Design the program.
 Record the design in specified
format.
 Record the Design time in time
recording log.

259
PSP-Code
 Implement the design.
 Use a standard format for
code text.
 Record the coding time in time
recording log.
260
PSP-Compile
 Compile the program.

 Fix all the defects.

 Record compile time in time


recording log.

261
PSP-Test/Postmortem
 Test:
 Test the program.
 Fix all the defects found.
 Record testing time in time recording
log.
 Postmortem:
 Completeproject plan summary form
with actual time and size data.
 Record postmortem time in time record. 262
Personal Software Process (PSP)

PSP 3  Personal process


evolution

PSP 2  Personal quality management


 Design and code reviews

PSP 1 Personal planning


 Time and schedule

PSP 0  Personal measurement


 Basic size measures
263
Six Sigma
 Six sigma is a quantitative approach to
eliminate defects:
 Applicable
to all types of industry - from
manufacturing, product development, to
service.

 The statistical representation of Six


Sigma quantitatively describes :
 How a process is performing. 264
6  (6 sigma)
 The goal is to ensure that no unacceptable
parts are ever passed on to a customer.
 A defect is anything that does not fall
within the customer’s tolerance limits
 Through continuous process improvement,
 Lower the process variability so low that
the upper and lower specifications are 6
standard deviations above and below the
265
mean
6  (6 sigma)

3 sigma: 3
Probability outside range = (1 – 0.99865) * 2 = 0.0027
Defect rate = 2,699 defects per million opportunities

6
6 sigma:
Probability part outside range = 0.00000000198024
Defect rate = 0.00197 dpm
1.97 defects per BILLION
266
Defect Rates - 1
 3 sigma: 1/.0027 = 1 every 370 parts
 6 sigma: 1/ 0.00000000198024
 = 1 every 504.9 million parts

 If we make a million parts per year, we have:


 3σ: 2,699 defectives
 6σ: 0.0019732 defectives
267
Achieving Six Sigma
 To achieve six sigma:
A process must not produce more than
3.4 defects per million opportunities.
5 Sigma -> 230 defects per million.
4 Sigma -> 6210 defects per million.
 Six sigma methodologies:
 DMAIC (Define, Measure, Analyze,
Improve, Control).
 DMADV: (Define, Measure, Analyze,
268
Design, Verify).
Six Sigma Methodologies
 The methodologies are implemented by
Green belt and Black belt workers:
 Supervised by Master black belt worker.

 Pareto Chart:
 Simple bar chart to represent defect
data
 Used to identify the problems that occurs
with greatest frequency 269
Black Belts
 Green Belts: some 6 sigma training,
take part in teams, small solo work

 Black Belts: Coach or lead 6 sigma


improvement teams

 Master Black Belts: have in-depth


statistical training, serve as Black
Belts for more teams

 Champions: Executives who will back


up the proposals the black belts
270
come up with
271
Current Trends
 Many organizations have already tuned
their process for:
 Budget,

 Schedule, and
 Quality product.
 Competition is challenging them to:
 Reduce time for delivery
 Adopt Six-Sigma methodology 272
Summary
 Evolution of quality system:
 Product inspection
 Quality control
 Quality assurance
 Total quality management (TQM)
 Quality paradigm change:
 From product to process 273
Summary
 ISO 9000:
 Basic premise:
 If a good process is followed
 Good products are bound to follow.

 Providesguidelines for
establishing a quality system.
274
Summary
 ISO 9000:
 Series of three standards
 9001, 9002, and 9003
 9001is applicable to software
industry.
275
Summary
 SEI CMM
 Developed specially for software
industry.
 Classifies
software organizations into
five categories.
 According to the maturity of their
development process.
 CMMI: Integrates existing quality
techniques.
276
277
Defects - 2
 With a 1.5σ shift, defect rates become:
 3σ 66,807 dpm
 6σ 3.4 dpm
 The commonly accepted definition of 6σ quality is
having a defect rate <= 3.4 dpm

3 6
278
Software Reliability

Dr. RAJIB MALL


Professor
Department Of Computer Science &
Engineering
IIT Kharagpur.

12/30/2021 11
Introduction
 Reliability of a software product:
 a concern for most users especially industry
users.
 An important attribute determining the quality
of the product.
 Users not only want highly reliable
products:
 want quantitative estimation of reliability
before making buying decision.
2
Introduction
 Accurate measurement of
software reliability:
a very difficult problem
 Several factors contribute to
making measurement of software
reliability difficult.

3
Major Problems in Reliability
Measurements

 Errors do not cause failures at


the same frequency and severity.
 Measuring latent errors alone not
enough

 The failure rate is observer-


dependent 4
Software Reliability: 2 Alternate
Definitions
 Informally denotes a product’s
trustworthiness or
dependability.
 Probability of the product
working “correctly” over a given
period of time. 5
Software Reliability
 Intuitively:
a software product having a large
number of defects is unreliable.
 It is also clear:
 reliability
of a system improves if
the number of defects is reduced.
6
Difficulties in Software
Reliability Measurement (1)
 No simple relationship between:

 observed system reliability


 andthe number of latent software
defects.

 Removing errors from parts of


software which are rarely used:
 makes little difference to the
7

perceived reliability.
The 90-10 Rule
 Experiments from analysis of behavior
of a large number of programs:
 90% of the total execution time is spent
in executing only 10% of the instructions
in the program.

 The most used 10% instructions:


 called the core of the program.
8
Effect of 90-10 Rule on Software
Reliability

 Least used 90% statements:


 called
non-core are executed only during
10% of the total execution time.

 It may not be very surprising then:


 removing60% defects from least used
parts would lead to only about 3%
improvement to product reliability. 9
Difficulty in Software Reliability
Measurement
 Reliability improvements from
correction of a single error:
 depends on whether the error
belongs to the core or the non-
core part of the program.

10
Difficulty in Software Reliability
Measurement (2)

 The perceived reliability


depends to a large extent upon:

 how the product is used,

 Intechnical terms on its


operation profile.
11
Effect of Operational Profile on
Software Reliability Measurement

 If we select input data:


 only “correctly” implemented
functions are executed,
 none of the errors will be exposed

 perceived reliability of the product


will be high.
12
Effect of Operational Profile on
Software Reliability Measurement

 On the other hand, if we select


the input data:
 suchthat only functions containing
errors are invoked,

 perceived reliability of the system


will be low.
13
Software Reliability
 Different users use a software
product in different ways.
 defects which show up for one user,
 may not show up for another.

 Reliability of a software product:


 clearly observer-dependent

 cannot be determined absolutely. 14


Difficulty in Software Reliability
Measurement (3)

 Software reliability keeps changing


through out the life of the product

 Eachtime an error is detected and


corrected

15
Hardware vs. Software Reliability
 Hardware failures:
 inherently different from software
failures.

 Most hardware failures are due to


component wear and tear:
 some component no longer functions
as specified. 16
Hardware vs. Software Reliability
 A logic gate can be stuck at 1 or 0,
 or a resistor might short circuit.

 To fix hardware faults:


 replace or repair the failed part.

17
Hardware vs. Software
Reliability
 Software faults are latent:
 system will continue to fail:
 unless changes are made to the
software design and code.

18
Hardware vs. Software Reliability
 Because of the difference in
effect of faults:

 Though many metrics are


appropriate for hardware
reliability measurements

 Are not good software reliability


19
metrics
Hardware vs. Software Reliability
 When a hardware is repaired:
 its reliability is maintained

 When software is repaired:


 its
reliability may increase or
decrease.

20
Hardware vs. Software Reliability
 Goal of hardware reliability study:
 stability (i.e. interfailure times
remains constant)

 Goal of software reliability study


 reliability growth (i.e. interfailure
times increases)
21
Hardware Failure Curve

22
Software Failure Curve

23
Reliability Metrics
 Different categories of software
products have different reliability
requirements:
 level of reliability required for a
software product should be
specified in the SRS document.
24
Reliability Metrics
 A good reliability measure
should be observer-
independent,

 sothat different people can


agree on the reliability.
25
Rate of occurrence of failure
(ROCOF)
 ROCOF measures:
 frequency of occurrence failures.
 observethe behavior of a software
product in operation:
 over a specified time interval

 calculate the total number of failures


during the interval.
26
Mean Time To Failure
(MTTF)
 Average time between two
successive failures:
 observed over a large number of
failures.

27
Mean Time To Failure (MTTF)
 MTTF is not as appropriate for
software as for hardware:
 Hardware fails due to a component’s wear
and tear
 thus indicates how frequently the component
fails

 When a software error is detected and


repaired:
 the same error never appears. 28
Mean Time To Failure (MTTF)
 We can record failure data for n
failures:

 let these be t1, t2, …, tn

 calculate (ti+1-ti)

 the average value is MTTF


(ti+1-ti)/(n-1) 29
Mean Time to Repair (MTTR)
 Once failure occurs:

 additional time is lost to fix


faults

 MTTR:

 measures average time it takes to


fix faults. 30
Mean Time Between Failures
(MTBF)
 We can combine MTTF and MTTR:
 to get an availability metric:

 MTBF=MTTF+MTTR

 MTBF of 100 hours would indicae


 Once a failure occurs, the next failure is
expected after 100 hours of clock time
(not running time). 31
Probability of Failure on
Demand (POFOD)
 Unlike other metrics
 This metric does not explicitly involve
time.
 Measures the likelihood of the system
failing:
 when a service request is made.
 POFOD of 0.001 means:
 1 out of 1000 service requests may result in
32
a failure.
Availability
 Measures how likely the system
shall be available for use over a
period of time:
 considersthe number of failures
occurring during a time interval,
 also
takes into account the repair time
(down time) of a system.
33
Availability
 This metric is important for
systems like:
 telecommunication systems,

 operating
systems, etc. which are
supposed to be never down

 where repair and restart time are


significant and loss of service during
that time is important. 34
Reliability metrics
 All reliability metrics we
discussed:
 centeredaround the probability of
system failures:
 take
no account of the consequences
of failures.
 severity of failures may be very
different. 35
Reliability metrics
 Failures which are transient and
whose consequences are not serious:

 of little practical importance in the


use of a software product.

 such failures can at best be minor


irritants.
36
Failure Classes
 More severe types of failures:

 may render the system totally


unusable.

 To accurately estimate reliability


of a software product:

 it is necessary to classify different


types of failures. 37
Failure Classes
 Transient:
 Transient failures occur only for certain
inputs.
 Permanent:
 Permanent failures occur for all input
values.
 Recoverable:
 When recoverable failures occur:
 the system recovers with or without
operator intervention. 38
Failure Classes
 Unrecoverable:
 the system may have to be restarted.
 Cosmetic:
 These failures just cause minor
irritations,
 do not lead to incorrect results.
 An example of a cosmetic failure:
 mouse button has to be clicked twice
instead of once to invoke a GUI function. 39
Reliability Growth Modelling
 A reliability growth model:
a model of how software reliability grows
 as errors are detected and repaired.
 A reliability growth model can be used
to predict:
 when (or if at all) a particular level of
reliability is likely to be attained.
 i.e. how long to test the system? 40
Reliability Growth Modelling
 There are two main types of
uncertainty:
 inmodelling reliability growth which
render any reliability measurement
inaccurate:
 Type 1 uncertainty:
 ourlack of knowledge about how the
system will be used, i.e.
41
 its operational profile
Reliability Growth Modelling
 Type 2 uncertainty:
 reflects
our lack of knowledge about the
effect of fault removal.
 When we fix a fault
 we are not sure if the corrections are
complete and successful and no other faults
are introduced
 Even if the faults are fixed properly
 we do not know how much will be the 42

improvement to interfailure time.


Step Function Model
 The simplest reliability growth
model:
a step function model
 The basic assumption:
 reliability
increases by a constant
amount each time an error is
detected and repaired. 43
Step Function Model

ROCOF

Time

44
Step Function Model
 Assumes:
 all
errors contribute equally to
reliability growth
 highly unrealistic:
 we already know that different errors
contribute differently to reliability
growth. 45
Jelinski and Moranda Model
 Realizes each time an error is
repaired:
 reliability
does not increase by a
constant amount.
 Reliability improvement due to fixing
of an error:
 assumed to be proportional to the
number of errors present in the system
46
at that time.
Jelinski and Moranda Model
 Realistic for many applications,
 still
suffers from several
shortcomings.
 Mostprobable failures (failure
types which occur frequently):
 discovered early during the testing
process.
47
Jelinski and Moranda Model
 Repairing faults discovered early:
 contribute maximum to the reliability
growth.

 Rate of reliability growth should be


large initially:
 slow down later on,
 contrary to assumption of the model
48
Littlewood and Verall’s Model
 Allows for negative reliability growth:

 when software repair introduces further


errors.

 Modelsthe fact that as errors are


repaired:

 average improvement in reliability per


repair decreases. 49
Littlewood and Verall’s Model
 Treats a corrected bug’s contribution to
reliability improvement:
 an independent random variable having
Gamma distribution.

 Removes bugs with large contributions to


reliability:
 earlier than bugs with smaller contribution
 represents diminishing return as test
50
continues.
Reliability growth models
 There are more complex
reliability growth models,
 moreaccurate approximations to
the reliability growth.

 thesemodels are out of scope of


our discussion.
51
Applicability of Reliability Growth
Models

 There is no universally applicable


reliability growth model.

 Reliability growth is not


independent of application.

52
Applicability of Reliability Growth
Models

 Fit observed data to several


growth models.

 Take the one that best fits


the data.

53
Statistical Testing
 A testing process:

 the objective is to determine


reliability rather than discover
errors.

 uses data different from defect


testing.
54
Statistical Testing
 Different users have different
operational profile:
 i.e. they use the system in
different ways

 formally, operational profile:


 probability distribution of input 55
Operational profile: Example
 An expert user might give advanced
commands:
 use
command language interface,
compose commands

 A novice user might issue simple


commands:
 using iconic or menu-based interface.
56
How to define operational profile?
 Divide the input data into a number of
input classes:
 e.g. create, edit, print, file operations,
etc.

 Assign a probability value to each input


class:
a probability for an input value from that
class to be selected. 57
Steps involved in Statistical
testing (Step-I)

 Determine the operational


profile of the software:

 This can be determined by


analyzing the usage pattern.

58
Step 2 in Statistical testing
 Manually select or automatically
generate a set of test data:

 corresponding to the operational


profile.

59
Step 3 in Statistical testing

 Apply test cases to the program:


 record execution time between each
failure

 it
may not be appropriate to use raw
execution time

60
Step 4 in Statistical testing

 After a statistically significant


number of failures have been
observed:
 reliability can be computed.

61
Statistical Testing
 Relies on using large test data
set.
 Assumes that only a small
percentage of test inputs:
 likely to cause system failure.
62
Statistical Testing
 It is straight forward to generate
tests corresponding to the most
common inputs:
 buta statistically significant
percentage of unlikely inputs should
also be included.
 Creating these may be difficult:
 especially if test generators are
63
used.
Advantages of Statistical Testing

 Concentrate on testing parts of


the system most likely to be
used:
 results in a system that the users
find more reliable (than actually
it is!).
64
Advantages of Statistical
Testing
 Reliability predictions based on
test results:
 gives an accurate estimation of
reliability (as perceived by the
average user) compared to other
types of measurements.
65
Disadvantages of Statistical
Testing
 It is not easy to do statistical
testing properly:
 thereis no simple or repeatable
way to accurately define
operational profiles.

 Statistical uncertainty.
66
Summary
 Reliability of a software product:

 essentially denotes its


trustworthiness or dependability.

 probability of the product working


“correctly” over a given period of
time.
67
Summary
 Operational profile of a software

 reflects how it will be used in


practice.

 Consists of specification of:

 classes of inputs

 probability of their occurrence. 68


Summary
 Statistical testing:

 uses large data set selected


based on operational profile.

 Provides more realistic


reliability figures.
69
Emerging Trends in
Software Engineering

Prof. R. Mall
Dept. of CSE, IIT, Kharagpur

1
Introduction
 Technology developments occur too fast:
 To adapt to new environments
 To respond to new challenges

 Few important developments that have


occurred over the last decade or so:
 Desktops have become more powerful and
at the same time more affordable.
 Internet has become widely accepted.
 Mobile computing and cloud computing.
 Outsourcing has become a buzzword… 2
Outsourcing has become prevalent….

3
And technology changes very fast…

4
Background: Basic Software
Engineering Processes

Business Process Change in Business Process

Time Time
required = required = T2
T1
Change in the IT solution
Implementation in IT supporting
the business process

5
Background: Desired Goals
 A. Reduce T1 (and improve quality)‫‏‬
 B. Reduce T2
 A requires:
 Process should efficiently capture
requirements of the business and then
efficiently convert it to code.
 B requires:
 Implementation should be such that
business process changes can be easily
accommodated in the software solution.
6
Challenges Being Faced
 Delivery time requirements are
shortening:
 High business velocity requires this.
 Softwareis becoming a bottleneck in
implementing business process changes.
 Businesses are getting tired of software
cost, late deliveries, poor quality, risk,…
 Hardwareand software cost differentials
are becoming more and more glaring. 7
Challenges Being Faced
cont…
 Software sizes are further
increasing.
 How software is to be effectively
developed in following contexts is
not yet clear:
 Distributed platforms
 Working with Internet
 Distributed development teams 8
Data Interoperability Expands as
Response Time Shrinks

9
9
Noticeable Software Engineering
Technology Trends
 Following software engineering
trends are easily noticeable:
 Client-server
(or Component-
based) development
 Service-Oriented Architecture
(SOA)‫‏‬
 Software as a Service (SaaS) 10
Client-Server Technology
 Both clients and servers are pieces
of software.
 Concept of clients and servers is

nothing new --- existed for ages:


 Clientsare consumers of service.
 Servers are providers of service.
 Why is then such a sudden interest
in client-server software
architecture? 11
Clients
and
Servers

12
Advantages of Client-Server
Compared to Traditional Software
 Flexibility:
 Clients
and servers can be easily
attached and removed.
 Modularity
 Concurrency
Cont…
 Fault-tolerance 13
Advantages of Client-Server Compared to
Traditional Software

 Clients are cheap computers:


 Serversare expensive computers
tucked away in some AC rooms.
 Touse a software you not need not
buy expensive server hardware and
software (application software
provisioning). 14
Client-Server versus Traditional
Software
 The following two factors are possibly the
most relevant:
 Component-based software development:
 To develop a hardware solution an electronic
engineer does not solder transistors and
resistors on a PCB --- uses off-the-shelf ICs.
 Why not do the same for software?
 Current trend of mobile computing:
 Handhelds can only be clients due to low
processing and memory capabilities. 15
Component Architectures
 Two tier architecture: Most obvious

Server 1 Server m

Internet

Client n
Client 1

 But does not work.


16
What are the Problems with the
2-tier Architecture?

 Servers can be bottleneck.


 How to locate servers?
 Client-Server incompatibility:
 Analogy:
House hunting in
Bangalore.
17
Solution: 3-tier
Architecture
Server 1 Server m

Middleware
Internet
Middleware

Client n
Client 1

18
Middleware Standards
 CORBA and COM/DCOM
 CORBA (common object
request broker architecture)‫‏‬
 Being advocated by OMG
 COM/DCOM:
 Being advocated by Microsoft 19
CORBA Architecture
Server 1 Server m
Skeleton DSI Skeleton DSI

ORB
Object Adapter

Stub Stub
Client 1 Client n

20
CORBA Architecture
 Skeleton:
 Marshalls client requests
 The servers register themselves with
the object-adapter.
 The ORB delivers the client request to
the server.
 The Skeleton marshalls the server response.
 DII/DSI for dynamic service
21
invocation.
IDL: Interface Development
Language
 Interfaces between clients and
servers can be specified.
 Similar to C++ or Java:
 But no executable statements.
Interface clock{
set-time(int hh, int mm, int ss);
get-time(int hh, int mm, int ss);
} 22
How to Develop Component-
Based Applications?
 Divide application into
components.
 Determine component interfaces:
 Define using IDL.
 Get available components:
 Build the ones not available
 Integrate components and test 23
CORBA Implementations
 Visigenic
 Iona
 Orbix
 Java IDL
 …
24
COM/DCOM
 COM used when an application runs on a
single machine:
 DCOM for distributed machine.
 Concepts are similar to CORBA:
 Though terminologies are different.
 Proxy on client side.
 More usable than CORBA.
 What is a component in COM/DCOM?
 A .exe or .dll component
25
 Created using VB or VC++
COM/DCOM versus CORBA
 COM/DCOM strong on client side:
 CORBA on server side.
 Java Beans attempt to bridge this gap.
 COM/DCOM more usable:
 Ifyour application is to run only on
Microsoft operating systems, better
use COM/DCOM.
 If
your application needs to run on
heterogeneous platforms, better use
26

CORBA.
Service-Oriented
Architecture (SOA)

27
Motivation
 The ability to program the Web.
 Example:
 Consider an Excel spreadsheet that
summarizes the summary of your company’s
financial picture : stocks, bank accounts,
loans, etc.
 If some of this information is available
through XML Web services, Excel can
update it and present the update information
to the shareholders.
28
Web Service definition
A simple definition:
“A piece of software available over Internet
that can be accessed using standardized
(i.e., XML) messaging system.”

Alternate definition:
“A Web Service is an application component
in the Web that is accessible using open
protocols”.
29
History
 Web services evolved from previous
technologies that served the same
purpose such as DCOM, CORBA and
JAVA RMI.
 Web Services were intended to solve
three main problems:
1. Interoperability
2. Firewall traversal
3. Complexity 30
Interoperability
 Earlier distributed systems suffered
from interoperability issues because
each vendor implemented its own on-
wire format for distributed object
messaging.
 DCOM apps strictly bound to Windows
Operating system.
 RMI apps bound to Java programming
language. 31
SOA: Introduction
 Service-orientation principles:
 Rootsin object and component-
orientation.
 Many claim that service-orientation
will replace object and component-
orientation:
 Othersthink that the three are
complementary paradigms. 32
Firewall traversal
 Collaboration across corporations was an
issue:
 Because distributed systems such as CORBA
and DCOM used non-standard ports.

 Web Services use HTTP as a transport


protocol and most of the firewalls allow
access though port 80 (HTTP):
 leading to easier and dynamic collaboration.
33
34
What is SOA?
 Build applications by composing software
services.
 What are software services?
 Essentially software components.
 Typically implement functionality most humans
would recognize as a service.
 Examples of services:
 Filling out an online application
 Viewing an online bank-statement
 Placing an online booking
35
What is a “Service”?
 A reusable component.
 Changes business data from one
state to another.
 A service is the only way data can
be accessed.
 A service can be described using:
 WSDL. 36 36
Service: More Formally
 A service is a contractually
defined behavior:
 Implementedand provided by a
component for use by an application
developer.

37
Services
 Self contained and reusable units,
 Can be reused to create new business
applications
 Represent a high level business concept
 Can be distributed over a network
 Services can be independently evolved,
moved, scaled even in runtime.
 Contain contract with specification of:
 Purpose, functionality, interfaces, constraints,
38
Why SOA ?
 Systems today are bigger than ever before
 “Complexity increases exponentially with size”
 Systems need to be interconnected
 OO solved the problems of small-medium sized
systems
 CO (Component Orientation) solved problems OO
couldn’t on medium-large systems
 Neither OO nor CO could cope:
 With the problems of very large systems,
 Systems of systems, or integration between
39

3
systems
SOA vs. Component Model
 Several things common between
services and components:
 Multiple-use
 Non-context-specific
 Composable
 Encapsulated --- non-investigable through
its interfaces
 A unit of independent deployment and
versioning
40
 Loose coupling
SOA vs. Component Model
cont…
 Several things different.
 Compared to components:
 SOA's atomic-level objects are often 100
to 1,000 times larger.
 Services may be developed and hosted
separately.
 On the Internet
 Distributed platforms
 Possibly pay per use. 41
SOA vs. Component Model
cont…
 Instead of services embedding calls to
each other in their source code:
 Usedefined protocols which describe
how services can talk to each other.
 This architecture relies on a business
process expert:
 Links
and sequences services to meet a
new business requirement.
42
 The process known as orchestration.
SOA vs. Component Model
cont…

 SOA targets fairly large chunks of


functionality to be strung together to
form new services:
 Built
almost entirely from existing
software services.
 The larger the chunks:
 The fewer the interfacings required;
 Faster development;
 However, very large chunks may not
prove easy to reuse. 43
SOA Basics – What SOA Means
 Architecture composed of services
 SOA raises the level of abstraction
compared to OO and CO:
 Attempts to solve problems more efficiently
 Efficient for:
 large systems
 distributed systems
 systems of systems

 Inefficient for:
 Small – medium sized systems 44

4  Non-distributed systems
SOA Schematic
Service
Service

Service
Internet Service

Service Service
Service
45
SOA Characteristics
 Loosely coupled:
 Minimizes dependencies between services.
 Contractual:
 Adhere to agreement on service
descriptions.
 Autonomous:
 Control
the business logic they
encapsulate.
 Abstract:
 Hidethe business logic from the service
consumers. 46
SOA Characteristics
 Reusable:
 Dividebusiness logic into reusable
services.
 Composable:
 Facilitate assembly of composite services.
 Stateless:
 Minimize retained information specific to
an activity.
 Discoverable:
 Specifiedand registered so that they can
be found and assessed. 47
SOA: Nitty Gritty
 An SOA-based application is a
collection of services:
 Communicate with each other.
 The services are self-contained:
 Donot depend on the context or state of
the other service.
 Each service works:
 Withina distributed-system
architecture. 48
SOA : Nitty Gritty
cont…

 A paradigm for utilizing


distributed capabilities:
 May be under the control of
different ownership domains.
 Provides a uniform means:
 To offer, discover, interact with
and use capabilities to achieve
desired results. 49
SOA: Nitty Gritty
cont…
 SOA would fundamentally change the
way we construct software systems.
 SOA involves statically and dynamically
plugging-in services to build software.
 SOA players:
 BEAAqua logic, Oracle Web services
manager, HP Systinet Registry, MS .Net,
IBM Web Sphere, Iona Artrix, Java
50
composite application suite.
SOA: Nitty Gritty
cont…
 Views software as providing a set of
services:
 Each service composed of smaller services.
 Leverages the Internet and emerging
standardization on it for interoperability
 Hopes that a market place for different
predefined services can emerge:
 Not tied to any specific vendor
 An app can be built using available services:
And building the “missing” ones.
51

Before SOA – After SOA

52
source:IBM
SOA Entities
Service
Consumer

Contract Registry

Service
Provider

53
SOA Implementation
 SOA can be implemented using:

 Web services
 Web services:
 Form the functional building blocks
 Accessible over standard Internet
protocols
 Independentof platforms and
programming languages. 54
Service Orchestration
 Requires metadata to describe:
 Characteristics of the services,
 Data that drives them.
 Protocols:
 Services described by WSDL.
 Communications protocols by SOAP.
 Data and meta data by XML 55
A Few Key SOA Protocols
 UDDI (Universal Description, Discovery, and
Integration:
 Defines the publication and discovery of web service
implementations.
 WSDL (Web Services Description Language):
 XML-based language that defines Web Services.
 SOAP(Service Oriented Architecture Protocol):
 Using it the client) sends a request to a server.
 LDAP (Lightweight Directory Access Protocol):
 Protocol for querying and modifying directory services.
 ETL (Extract, Transform, and Load):
 A process of moving data from a legacy system and
loading it into a SOA application. 56 56
Using Web Services

57
OASIS Symposium 57
2006
Web Service definitions revisited
 A more precise definition:
 an application component that:
 Communicates via open protocols (HTTP,
SMTP, etc.)
 Processes XML messages framed using
SOAP
 Describes its messages using XML Schema
 Provides an endpoint description using
WSDL 58
Web Services Components
 XML – eXtensible Markup Language – A uniform
data representation and exchange mechanism.

 SOAP – Simple Object Access Protocol – A


standard way for communication.

 UDDI – Universal Description, Discovery and


Integration specification – A mechanism to
register and locate WS based application.

 WSDL – Web Services Description Language –


A standard meta language to described the
services offered. 59
Example – A simple Web Service
 A buyer (may be a simple client) is ordering goods from a
seller service.
 The buyer finds the seller service by searching the UDDI
directory.
 The seller service is a Web Service:
 Whose interface is defined using Web Services Description
Language (WSDL).

 The buyer is invokes the order method on the seller


service using Simple Object Access Protocol (SOAP) and
the WSDL definition for the seller service.
 The buyer knows what to expect in the SOAP reply message
because this is defined in the WSDL definition for the seller
60

service.
The Web Service Model
 The Web Services architecture is based
upon the interactions between three roles:
 Service provider
 Service registry
 Service requestor
 The interactions involve the:
 Publish operations
 Find operation
 Bind operations. 61
The Web Service Model (cont)
The Web Services model follows the publish, find, and
bind paradigm.

Web Service
Registry

1. publish 2. find

Web Service 3. bind/invoke


Web Service
Provider Client
62
XML
 XML stands for EXtensible Markup
Language.
 XML is a markup language much like HTML.
 XML was designed to describe data.
 XML tags are not predefined. You must
define your own tags.
 Ideal choice for enabling cross-platform data
communication in Web Services.
63
XML vs HTML

An HTML example:
<html>
<body>
<h2>John Doe</h2>
<p>2 Backroads Lane<br>
New York<br>
045935435<br>
john.doe@gmail.com<br>
</p>
</body>
</html>
64
XML vs HTML
 This will be displayed as:

John Doe

2 Backroads Lane
New York
045935435
John.doe@gmail.com

 HTML specifies how the document is to be displayed,


and not what information is contained in the document.
 Hard for machine to extract the embedded
information. Relatively easy for human. 65
XML vs HTML
 Now look at the following:

<?xml version=1.0?>
<contact>
<name>John Doe</name>
<address>2 Backroads Lane</address>
<country>New York</country>
<phone>045935435</phone>
<email>john.doe@gmail.com</email>
</contact>

 In this case:
 The information contained is being marked, but not for
displaying.
 Readable by both human and machines.
66
UDDI
 UDDI stands for Universal Description,
Discovery and Integration.

 UDDI is a directory for storing


information about web services , like
yellow pages.

 UDDI is a directory of web service


interfaces described by WSDL.

67
Overview of Working

UDDI Registry
WSDL
Document

Registry refers client to WSDL document


WSDL provides data to interact with web service
Client queries registry to locate WSDL
Client accesses servicedocument
Web service returns SOAP-message response
Client sends SOAP-message request

68
Client Web Service Code
Service Architecture Organized by
Layers
Example Layers
Reasons for Layering Presentation
& workflow
1. Flexible composition.
Composed Services
2. Reuse.
3. Separation of Concerns. Basic Services

4. Policies may vary by


Layer Underlying
API

69
Service Types
SOA Management & Security
service mediation, routing, trust
enablement. ESB, Service Registry

Multi channel applications: Mobile,


Smart, Thin, Thick clients, Portals.

Business centric services,


orchestrated workflows.
Intermediate services (gateways,
e
ru e
ur
st vic

facades )
ct
fra er

nt
In S

ie
t Cl Data centric and logic
r
S ma centric consistent services.
Highly reusable, stateless
servers
l
rta

ice te
Po

rv osi
s
Se mp

Foundation
Co

Service Blocks
rv ic
s

Core APIs
ice
Se a s
B

rra
Te re
G dia

a
eo
M

Sh
e
I/CAD

Business
Capabilities
70
ech
I/..

G/T

In
Serv r
i the
SOA Vision
 Have a marketplace for services:
 It will automatically improve quality and
reduce prices.
 To build an application:
 Use off-the-shelf services and possibly
build some.
 Cost of building reduces;
 Also cost of ownership (which is quite
large for regular software) reduces. 71
Great Promise of SOA
 The cost of creating the n-th
application is near-zero:
 All
of the software services
required would already exists.
 Onlyorchestration required to
produce a new application.
72
Why SOA Saves Code
 Provides a standard way of interacting
with software.
 Enables software to become building
blocks for reuse.
 Shifts focus to application assembly
rather than design and coding.
 Creates new applications out of existing
components.
 Integrates with applications in other
enterprises. 73 73
SOA Benefits
SOA allows to align IT with mission of the organization
Better agility, no redundancy, system interactions, and reduces overall costs of system
maintenance

Agility Process Heterogeneity Data Heterogeneity Costs


Focus more on core Allow interoperation Improve semantics of Leverage existing IT
competencies with other systems data exchanged infrastructure
Creates a network of without time during business Reduce costs of
service requesters consuming process execution development of new
(consumers) and customization and Maintain consistency functionalities by
service providers point-to-point of data across acquiring pre-built
(producers) integration different systems components/services
Enable enterprises to Ensure system change Remain platform, Lower maintenance
be more agile and is not a constraint on language, and vendor costs
respond quickly to business or mission independent to
changing requirements change remove IT barriers
Increase business Facilitate integration for using best-of-
flexibility through with multiple solutions breed software
plug-and-play via open IT standards packages
architecture and re-
use of existing
services
74
OASIS Symposium 74
2006
Benefits of SOA
 Better reuse:
 Build new functionality (new execution
semantics) on top of existing Business
Services
 Well defined interfaces :
 Manage changes without affecting the Core
System
 Easier Maintainability:
 Changes/Versions are not all-or-nothing
 Better Flexibility
OASIS Symposium
2006
75 75
Factors Driving Adoption

 Rapid rise of cloud computing


 Cost of buying or developing
software
 Cost and trouble of maintaining
infrastructure
 Maintenance
76
What is Cloud Computing?

77
78
79
80
Commercial Cloud Players

81
82
A Data Center

83
84
Microsoft’s Data Center

85
Cloud Service Models
Software as a Platform as a Infrastructure as
Service (SaaS) Service (PaaS) a Service (IaaS)

SalesForce
CRM
LotusLive

Google
App
Engine

86
Key Technology: Virtualization

App App App

App App App OS OS OS

Operating System Hypervisor

Hardware Hardware

Traditional Stack Virtualized Stack


87
SOA Challenges
 Building services and infrastructure
 Composing services – formal theory and
algebra, languages, semantics
 Testing and verification
 Trust
 Non Functional properties
 Managing changes
 Business level modeling and translation
 Developing the marketplace 88
Software as a
Service (SaaS)

89
Present Challenge
 Owning software is very expensive:
 A Rs. 50 Lakh software running on a Rs. 1 Lakh
computer is common place.
 As with hardware, owning software is the
business tradition:
 Both traditionally viewed as products --- bought
and used.
 However, most of IT budget now goes in
supporting the hardware and software assets.
90
Background
 To have water supply at home:
 Do you install system to pump water from
river directly to your home?
 To get electricity supply:
 Do you install a thermal or hydro electric
generator?
 It would lead to wastage:
 You do not need to have all the water pipes
open all the time.
 Unnecessarily expensive proposition. 91
Background
cont…
 Should you own Rational Suite paying
Rs. 50 Lakhs:
 If you use it only 10 hours every month
 One hour of usage costs Rs. 100/-
 Alsofrees user from maintenance and
data storage costs --- Given that
maintenance is usually a severe
overhead. 92
SaaS
 Also called Application Service
Provider (ASP) model.
 Promotes use of software as a
service rather than a product.
 ASP provides access to and
manages commercially available
application.
93
SaaS cont…

 Lets customers pay for what they


need and when:
 With price reflecting market place
supply and demand.
 SaaS includes:
 Elements of outsourcing and
 Application service provisioning 94
SaaS
 SaaS is a model of software
delivery:
 Software owner takes care of
maintenance, daily technical
operation, and support for the
software.
 Service
provided to the clients on
amount of usage basis. 95
Hidden Cost

96
Company name
SaaS vs. SOA
 SaaS is a software delivery model:
 SOAis a software construction
model.
 SaaS counters the concept of a
user as the owner:
 Owner is a vendor who hosts the
software and charges per usage
units. 97
SaaS versus SOA
 Despite significant differences:
 Espouse closely related architectural models.

 SaaS and SOA complement each other:


 SaaS helps to offer components for SOA to
use.
 SOA helps to help quickly realize SaaS.

 Main enabler of SaaS and SOA:


 Internet and web services technologies. 98
Key Characteristics
 Network-based access and
management of software.‫‏‬
 Enables
customers to access applications
remotely via the Web.
 Application delivery follows a one-to-
many model (single instance, multi-
tenant architecture):
 In
contrast to a traditional one-to-one
99

model.
Business Model
 Shift "ownership" of the software:
 From the customer to a service provider.
 Shift responsibility for hardware and
software management:
 From the customer to the provider
 Reduce the cost of providing software
services:
 Through specialization and economy of
scale.
 Target the "long tail" of small customers
100
Current Business Model

101
Big Deal 2: The Long Tail
Dozens of markets of millions or
$ / Customer millions of markets of dozens?

Large Customers

What if you lower your cost of sale

Typical Customers

New addressable market >> current market


(Currently) “non addressable” Customers

# of Customers
102
SaaS Business Model

103
SaaS Architecture…

Client 1
Application
Meta-Model Instance Client 2
Play/Edit

Player
Client n

Edit
Data Designer

104
Factors Driving Adoption
 Emergence of public clouds
 Rapid deployment
 Less upfront capital investment
 Shifts to service providers :
 continuousoperation, backups, updates
and infrastructure maintenance...
 Reduces investing on an internal IT
team. 105
Factors Driving Adoption
cont…
 Increased availability of the
Internet:
 Improvements in security and
increased broadband availability.
 Painful reminders of lengthy,
unsuccessful deployment cycles:
 Makes buyers investigate simpler,
quicker alternatives. 106
Inhibitors
 Concerns about:
 Data security
 Privacy of critical customer information.
 Huge initial investment costs required
to create infrastructure:
 Restricts new market entrants.
 Constraints on adoption of simplified
efficient solutions. 107
Buyer Benefits
 Low cost infrastructure and usage model
 Rapid deployment
 Simplified configuration & customization:
 In traditional applications important functions
are front-loaded.
 Vendor provides for reserve capacity to
handle usage spikes and outages.
 Access from anywhere - ideal for
distributed workforce
 Upgrades are regular and transparent. 108
Collaboration

109
Buyer Issues
 Integration requirements with
existing applications.
 Security of data.
 Weakened IT management
control.
110
Service Provider Benefits
 Steady recurring revenue.
 Getting customers to buy incremental
functionality later is easier:
 Can start with a simple application
 Leveraging the "long tail”
 You can rope in more smaller customers that
are unreachable at traditional
price/performance ratios.
 Increased revenue leads to greater
investment and higher quality of software. 111
Service Provider Issues
 For existing software houses:
 Organizational implications of moving from a
product-centric to a service-centric delivery
model.
 For start-ups:
 Cash flow develops over time – building a
business is hard.
 For both:
 Strong incentive for adoption required – so
usability is key.
 Reliability of hosted service is critical. 112
Conclusion: Value Comparison

Licensed Software Software-as-a-Service

 High upfront cost +  Lower upfront


annual maintenance subscription costs
costs depending on number
of users per month
 Cost for applications,
maintenance, and  Minimal cost for annual
infrastructure subscription &
application resources.
 Longer time required
to install & configure  Faster implementation
applications & time-to-productivity

 Greater risk  Lower risk 113


Summary
 Some of the basic assumptions of software are
changing
 This is leading to some different paradigms for
software delivery.
 Component-based development:
 Expected to reduce development time, cost and at
the same time improve quality.
 SaaS is changing the way software is delivered.
 SOA conceives a component based assembly
model with independent component vendors.
114

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy