Вы находитесь на странице: 1из 611

Introduction to Software Engineering

Software Engineering Consortium


(SEC)

2004 by SEC

Preface and Introduction (contd)


The objective of this course is to explain the Introduction of
software engineering , and provide an easy and practical
introduction to the important characteristics of software
engineering. After taking this course, students will understand
what is software engineering;
why software engineering is important;
how to develop software and manage a software project by using the
software engineering in detail.

2
2004 by SEC

Preface and Introduction (contd)


This courseware is designed for a semester-long for junior or
senior undergraduate students, and for the industrial parties.
The following professors contribute to the development of
this courseware:
Jonathan Lee, PhD. ( )
Chung-Shyan Liu, PhD. ( )
J.-Y. Kuo, PhD. ( )
Chien-Hung Liu, PhD. ( )

The Minister of Education sponsors this courseware


development.

3
2004 by SEC

Prerequisites

Introduction to Computer Science

Programming Skills

4
2004 by SEC

Contents
Chapter 1. An Overview of Software Engineering
Chapter 2. Software Processes
Chapter 3. Requirements Engineering
Chapter 4. Software Design
Chapter 5. Object-Oriented Software Development
Chapter 6. Software Testing
Chapter 7. Software Project Management and Planning
Chapter 8. Software Quality Assurance
Chapter 9. Software Maintenance
Chapter 10. Formal Methods and Software Engineering
Chapter 11. Advanced Topics in Software Engineering

5
2004 by SEC

References

[Pressman 2004] Roger S. Pressman. Software Engineering: a practitioners


approach, 6th edition. McGRAW-HILL.

[Sommerville 2004] Ian Sommerville. Software Engineering, 7th edition. Addison


Wesley.

[Rumbaugh et al.1991] J. Rumbaugh, M. Blaha, W. Premeerlani, F. Eddy, and W.


Lorensen. Object-Oriented Modeling and Design. PRENTICE HALL, 1991.

[DIL1994] A. Diller. Z: An Introduction to Formal Methods, 2nd Edition. John


Wiley & Sons, 1994

[WOO88] J. Woodcock and M. Loomes. Software Engineering Mathematics:


Formal Methods Demystified. Pitman Publishing. 1988

[WOR92] J.B. Wordsworth. Software Development with Z: A Practical Approach


to Formal Methods in Software Engineering. Addision-Welsey Publishing
Company. 1992

6
2004 by SEC

References (contd)

[Beizer 1990] B. Beizer, Software Testing Techniques, 2nd Edition, Van NostrandReinhold, 1990.

[Boehm 1981] B. Boehm, Software Engineering Economics, Prentice-Hall, 1981.

[Davis 1995] A. Davis, 201 Principles of Software Development, McGraw-Hill,


1995.

[Gao 2003] Jerry Gao, Jacob Tsao, and Ye Wu, Testing and Quality Assurance for
Component-Based Software, Artech House, 2003.

[Kaner 1993] C. Kaner, J. Falk, and H. Q. Nguyen, Testing Computer Software,


2nd Edition, Van Nostrand-Reinhold, 1993.

[Myers 1979] G. Myers, The Art of Software Testing, Wiley, 1979.

7
2004 by SEC

Chapter 1
An Overview of Software Engineering

2004 by SEC

Chapter 1
An Overview of Software Engineering
1.1 Software Crisis
1.2 Software Myths
1.3 Software Engineering Paradigm
1.4 The Evolution of Software Engineering
1.5 Software Engineering in Taiwan

9
2004 by SEC

What is the Problem?

84 % of all software projects do not finish on time and within


budget (Survey conducted by Standish Group)
8000 projects in US in 1995
More than 3o % of all projects were cancelled
189 % over budget

Key issues:
Software firms are always pressured to perform under unrealistic
deadlines.
The clients ask for new features, just before the end of the project, and
unclear requirements.
Software itself is awfully complex.
Uncertainties throughout the development project.

10
2004 by SEC

Real Cases

Bank of America Master Net System


Trust business. 1982.
Spend 18 months in deep research & analysis of the target system.

Original budget: 20 million.

Original Schedule: 9 months, due on 1984/12/31.

Not until March-1987, and spent 60 million.

Lost 600 millions business

Eventually, gave up the software system and 34 billion trust accounts


transferred.

Other cases:
Explosion of Ariane 5 prototype in 1996
Explosion of Boeings Delta III rocket.

11
2004 by SEC

Problems of Software

General issues
HW vs. SW
Productivity: build new programs from scratch
Maintenance: maintain existing programs

Essence vs Accidental (F. Brooks)

12
2004 by SEC

F. Brooks Essence

Essence: the difficulties inherent in the nature of software


Complexity: development process, application domain, internals of the
system (e.g., number of states, size of software, functionality,
structures, and behaviors).
Conformity: software must adapt to interact with people according to
their diverse needs; therefore, software cannot be completely
represented formally.
Changeability: software component is usually the easiest one to
modify; (application changes, software changes).
Invisibility: software structure is hidden, only behavior can be
observed when executing the software.

13
2004 by SEC

F. Brooks Accidents

Accident: difficulties arise in representing, testing the


conceptual constructs (SW) (e.g., software development
process), examples of accidental difficulties:
accidental complexity: abstract program vs concrete machine program;
solved by HLL.
slow turnaround: batch programming vs time-sharing (shortest
response time); solved by time-sharing.
no standard formats: individual programs vs integrated library,
standard formats; solved by unified programming environment.

14
2004 by SEC

Characteristics of Software
Software
logical system element
developed/engineered
Not ware out but deteriorate
- no spare parts
Usually custom-built

Hardware
physical system element
manufactured
ware out
-yes, with spare parts
assembled from existing
component

15
2004 by SEC

Software Myths (contd)

Management Myths
We already have a book thats full of standards and procedures for
building software. Wont that provide my people with everything they
need to know?
My people do have state-of-the-art software development tools; after
all, we buy them the newest computers
If we get behind schedule, we can add more programmers and catch up

16
2004 by SEC

Software Myths (contd)

Customer Myths
A general statement of objectives is sufficient to begin writing
programs we can fill in the details later
Project requirements continually change, but change can be easily
accommodated because software is flexible

17
2004 by SEC

Software Myths (contd)

Practitioners Myths
Once we write the program and get it to work, our job is done
Until I get the program running I really have no way of assessing its
quality
The only deliverable for a successful project is the working program

18
2004 by SEC

What is Software Engineering?

Software Engineering

Real World

Software World

19
2004 by SEC

Software Engineering Paradigm

Software engineering is a discipline that integrates methods,


tools, and procedures for the development of computer
software.
Method: introduce a way to build SW
Tool: automatic, semi-auto support for methods
Procedure: define the sequence in which methods will be
applied, the controls that help ensure quality and coordinate
changes.

20
2004 by SEC

Software Process

Waterfall life cycle

Prototyping

Spiral model

Automatic synthesis model

Object-oriented model

4 GL model

21
2004 by SEC

Traditional Software Engineering


Software Systems

Function
Data Flow
Diagram

Data
Entity-Relation
Diagram

Behavior
State Transition
Diagram

22
2004 by SEC

Object-Oriented Software Engineering


Software Systems

Object
Class
Diagram

Function
Data Flow
Diagram

Behavior
State Chart

23
2004 by SEC

Software Industry

Independent Programming Service

Software Product

Enterprise Solution

Packaged Software for the Mass

Internet Software and Services

24
2004 by SEC

Independent Programming Services


(Era 1)

Feb 1955, Elmer Kubie and John Sheldon founded CUC


the First Software Company that devoted to the construction of
software especially for hardware company.

Promoting Software Industry: two Major Projects,


SABRE, airline reservation system, $30 million.
SAGE, air defense system (1949~1962)
700/1000 programmers in the US. $8 billion.

25
2004 by SEC

Software Product (Era 2)

1964 Martin Goetz developed Flowchart Software -Autoflow for RCA, but rejected.

Sale to the customer of RCA & IBM.

Develop and market software products not specifically designed


for a particular hardware platform.

MARK IV, a pre-runner for the database management system.

IBM unbundled software from hardware.

26
2004 by SEC

Enterprise Solutions (Era 3)

Dietmar Hopp.

IBM Germany

Systems, Applications and Products (SAP) $3.3billion (1997)


Setting up shop in Walldorf, Germany.
Marked by the emergence of enterprise solutions providers.
e.g. Baan 1978. Netherlands. $680 million (1997)
Oracle 1977. U.S.
Larry Ellison.
ERP, $45 billion (1997)

27
2004 by SEC

Packaged Software for the Masses


(Era 4)

Software products for the masses. 1979.


VisiCalc, Spreadsheet program.

August 1981: The deal of the century.


Bill Gates bought the first version of the OS from a small firm called
Seattle Computer Products for $50,000 without telling them it was for
IBM.
The development of the IBM PC, 1981, initiated a 4 th software era.

PC-based mass-market software. Few additional services are


required for installation.

Microsoft reached revenues of $11.6 billion. Packaged Software


Products, $57 billion (1997)

28
2004 by SEC

Internet Software and Services (Era 5)

Internet and value-added services period, 1994. W


with Netscapes browser software for the internet.

29
2004 by SEC

IT Market
Hardware
products

Hardware
Software Products Processing Services
maintenance & Services
and Internet Services

Embedded
Software

Professional
Service

Enterprise
Solution

Software
Products

Packaged
Mass-Market
Software

30
2004 by SEC

Software Products and Services


Professional Software Enterprise
Services
Solutions
Anderson Consulting
IBM
EDS
CSC
Science Applications
Cap Gemini
Hp
DEC
Fujitsu
BSO Origin

Packaged Mars-Market
Software

IBM
Microsoft
Oracle
IBM
Computer Associates Computer Associates
SAP
Adobe
HP
Novell
Fujitsu
Symantec
Hitachi
Intuit
Parametric TechnologyAutodesk
People Soft
Apple
Siemens
The Learning Company

31
2004 by SEC

Exercises

Please find the definition of Software Engineering from the


text books, papers, and Internet as many as possible.

Please survey the software engineering application in


industries of TAIWAN.

32
2004 by SEC

Chapter 2
Software Process Model

2004 by SEC

Chapter 2
Software Process Model
2.1 Introduction to Software Process
2.2 Software Life Cycle
2.2.1 Waterfall Model
2.2.2 Prototyping
2.2.3 Incremental Model
2.2.4 Spiral Model
2.2.5 Fourth-Generation Techniques
2.2.6 Unify Process Model
2.2.7 Automatic Software Synthesis

34
2004 by SEC

Chapter 2
Software Process Model (contd)
2.3 Generic View of Software Engineering
2.4 Comparison of Software Development Processes
2.5 Advanced Topics
2.5.1 CMM/CMMI
2.5.2 Model Driven Development
2.5.3 Extreme Programming
2.5.4 Agile Method

Exercises

35
2004 by SEC

Introduction to Software Process

Requirement acquisition (problem statements)


to describe the problem to be solved and providing a conceptual
overview of the proposed system

Requirement analysis

Requirement specification

System analysis

System design

36
2004 by SEC

Introduction to Software Process (contd)

Detail design

Coding

Testing

Maintenance

37
2004 by SEC

Requirement Analysis

A process of discovering, refinement, modeling and


specification.
Principles: represent information domain of a problem

information flow: data & control changes

information content: composite term.

information structure: organization

Modeling: (graphical & textual description)

modeling methods: SA, OOA, JSD, DSSD, SADT

model component: information, function, behavior

38
2004 by SEC

Requirement Analysis (contd)


Artifact

Requirement specification.
capturing: functionality, behavior, and structure

39
2004 by SEC

Design

The problem is decomposed into modules

The interface between modules must be specified

Define architecture

Artifact: design model


Data design

data abstraction, data structure, data modeling

Procedural design: iteration , conditional, sequence

Architectural design: program structure, software architecture)

40
2004 by SEC

Implementatio
n

Individual module programming


Pseudo-code

The goals
the development of a well-documented
The reliable, easy to read, flexible, correct program

Integration of modules

Artifact: executable program

41
2004 by SEC

Testing

Test the system from requirement engineering to


implementation
Verification and validation

Artifact: testing report

42
2004 by SEC

Maintenance

Maintain the user satisfaction


Repair errors, requirements changed or extended

Changes in both the systems environment and user


requirements are inevitable
Maintenance = Evolution

43
2004 by SEC

Maintenance (contd)

Kinds of maintenance activities


Corrective
Adaptive
Perfective
60-100x

Preventive

1.5-6x
1x
Definition

Development

After release

44

The Impact of Change

2004 by SEC

Software Life Cycle

Waterfall model

Prototyping

Incremental model

Spiral model

Fourth-generation techniques

Unify process model

Automatic software synthesis

45
2004 by SEC

Waterfall Model

Frequently implemented based on a view of the world


interpreted in terms of a functional decomposition.
What does the system do?

Based on functional decomposition.


top-down analysis and design methodology
SA/SD

based on data flows : DFD, DD, structure charts.

easily to map to conventional procedural language

46
2004 by SEC

Waterfall Model (contd)


User Requirements
Analysis

ANALYSIS

WHAT

User Requirements
Specification
Software Requirements
Specification

DESIGN

HOW

System/Board Design
Logical Design
Program/Detailed Design
Physical Design
implementation/Coding
Program Testing : Units

BUILD

Program Testing:
system
Program Use
software Maintenance

47
2004 by SEC

Prototyping Model

Throwaway : implement only aspects poorly understood.

Evolutionary : more likely to implement best understood


benefits :
improve communication
reduce risk
most feasible way to validate specification
for maintenance as well.

48
2004 by SEC

Prototyping Model (contd)

The roles of prototyping


as a means to acquire validate users requirements.
as scaled-down version of the final operational system.
as a means to validate solution specifications.
as a solution specification for design and implementation

49
2004 by SEC

Prototyping Model (contd)

Determine
Requirements
Requirements

Requirements
Adjustments

Construct
Prototype
Prototype
Demonstrate
Prototype

OK

System
Implementation

50
2004 by SEC

Spiral Model

Spiral model
Risk driven
Throwaway prototyping

51
2004 by SEC

Spiral Model (contd)


Determine
objectives,
alternative,
constraints

Cumulative
cost

Progress
through
steps

Risk
analysis

Commitment
partition
Review

Plan next phases

Risk
analysis

Evaluate alternatives
identify, resolve risks
Risk
analysis

Risk
Prototype Operational
analyPrototype Prototype
1
2
3 Prototype
-sis
Simulations, models, benchmarks
Requirements plan
life-cycle plan
Software
Detailed
requirement Software
design
Development Requirement
product
plan
validation
design
Code
Integration
Design validation
Unit
and test plan
and verification
test
Integration
Acceptance and test
Implementest
tation
Develop, verify
next-level product

52

2004 by SEC

Automated Synthesis Model


decision &
rational
formal
development
informal
specification

Specification
Acquisition

high-level
specification
(prototyping)

Specification
Validation

Interactive
Translation

low-level
specification

Automatic
Compilation

source
program

Tuning

Maintenance

53
2004 by SEC

Fourth-generation Techniques
Requirements
gathering
Design
strategy
implementation
using 4GL

Testing

54
2004 by SEC

Object-Oriented Approach

OOA emphasizes on finding and describing the objects - or


concepts - problem domain.

OOD emphasizes on defining logical software object that


will ultimately be implemented in an object-oriented
programming language.

OOP (Programming), implements the designed components


in C++, Java.

55
2004 by SEC

Object-Oriented Approach (contd)

Boat
age

Public class Boat


{
public void sail()
private Date age;
}

OOA

OOD

OOP

Develop model
of requirements

Add detail and


design decisions

Develop code

Users Perspective

Developers Perspective

56
2004 by SEC

Object-Oriented Approach (contd)


Maintenance

Further
Development

Program
Use
System
Testing
Unit
Testing
Coding
Program
Design

bottom-up: develop an
individual class

top-down analysis

System
Design

Software
Requirements
Specification
User
Requirements
Specification
Requirements
Analysis

57
2004 by SEC

Generic View of Software Engineering

Definition: What

Development: How

Maintenance: Change

58
2004 by SEC

Comparing Various Models

Waterfall model problems


traceability/languages in different phases
Process is too linear

requirement acquisition and validation

maintainability : due to the use of functional decomposition


assume fully elaborated documentation at the early stage of the life
cycle.

reusability : top-down design

communication

59
2004 by SEC

Comparing Various Models (contd)


based on functional decomposition

Strongly dependent on detailed functional breakdown

not consider evolutionary changes.

not encourage reusability

Prototyping (partial implementation )


Benefits

improve communication

60
2004 by SEC

Comparing Various Models (contd)


reduce risk
communication between developments
determine a proposed designs unknown properties
address requirement acquisition and validation limitation
provide a basis for assessing the feasibility and
performance of alternative designs
most feasible way to validate specification.
for maintenance as well
Limitation

quick and direct approach without considering issues such as


quality and maintainability.

61
2004 by SEC

Comparing Various Models (contd)


verify correctness
and completeness
of design or
implementation
interconnections
during
architecture and
module design

prototyping
lang.
specification
language
Design
language

supporting containing detail


executable formal
quantifies algorithm
and data
reasoning
structure
low
yes
no
no
priority
must
yes
not
no
necessary
not

no

programming efficient
language

Language

62
2004 by SEC

Comparing Various Models (contd)


E

Functionality

inappropriateness
shortfall
B
lateness

D
C slop : adaptability

original reqt.
t0

waterfall
model

A
t1

longevity
t2

t3

t4

t5

Time

O : (t0) original reqt.


A : ( at t1) an operational product, not satisfying the old to needs
because poor understanding of needs.
A - B : undergo a series of enhancements.
B - D : the cost of enhancements increase, to build a new system.
stop at t4.
* cycle repeat itself

63
2004 by SEC

Throwaway Prototyping and Spiral Model


before understanding
of the user`s need =>
increase in functionality

Functionality

t0

t1

t2

t4

Time

64
2004 by SEC

Evolutionary Prototyping

Functionality

t0

t1

t2

t4

Time

65
2004 by SEC

Automated Software Synthesis

Functionality

t0

t1

t2

t4

t3

Time

66
2004 by SEC

Reusable Software versus Conventional


Reusable Software
approach
conventional
approach
Functionality

user

t0

t1

t2

t4
Time

67
2004 by SEC

Exercise

Do you think complexityand changeis the problems of


software development? Why?

Comparison of different software engineering paradigms :

waterfall, prototyping, spiral, OOLC, 4GL


prototype : both specification and design
program : optimization

68
2004 by SEC

Exercise (contd)

Issues in using different kinds of language in waterfall


model

different phases need different kinds of languages

transformation between languages at different phases.

main features of each language


specification, design, prototype, program
specification : abstract of system functionality
design : abstract of system structure
prototype : both specification and design
program : optimization

69
2004 by SEC

Chapter 3
Requirements Engineering

2004 by SEC

Chapter 3
Requirements Engineering
3.1 Requirements engineering
3.1.1 Software requirements
3.1.2 Characteristics of requirements
3.1.3 Requirements engineering
3.1.4 Requirements elicitation

3.2 Requirements analysis


3.2.1 Software modeling
3.2.2 The analysis process
3.2.3 Entity-Relationship diagram (ERD)
3.2.4 Extended entity-relationship diagram (EERD)
3.2.5 Components of structured analysis

71
2004 by SEC

Chapter 3
Requirements Engineering (contd)
3.3 Object-oriented (OO) software engineering
3.3.1 Steps of analysis: an example using OO approach
3.3.2 Concepts and phenomena
3.3.3 Class and class identification
3.3.4 Pieces of an object model

3.4 Data modeling and OOA


3.4.1 Data modeling and OOA
3.4.2 Software artifacts
3.4.3 Object Orientation
3.4.4 Polymorphism
3.4.5 OMT methodology
3.4.6 Features of object orientation: Blairs version

72
2004 by SEC

3.1 Requirements Engineering

73
2004 by SEC

Software Requirements

Requirement
Functional requirement describes system services or functions
Non-functional requirement is a constraint or a goal on the system or on
the development process

User (Customer) requirement


A statement in natural language plus diagrams of the services the system
provides and its operational constraints

Requirements specification
A structured document for detail description of the system services.
Written as a contract between client and developer

74
2004 by SEC

Characteristics of Requirements

Incomplete Requirements
Most software systems are complex, that developer can never fully
captured during the system development, therefore, requirements are
always incomplete.

Inconsistent Requirement
Different users have different requirements and priorities. There is a
constantly shifting compromise in the requirements.
Prototyping is often required to clarify requirements.

75
2004 by SEC

Requirements Engineering

Requirements elicitation
Determine what the customer requires

Requirements analysis
Understand the relationships among various customer requirements

Requirements negotiation
Shape the relationships among various customer requirements to
achieve a successful result
Research on requirements trade-off analysis (formulating as goals)

Requirements specification
Build a form of requirements

76
2004 by SEC

Requirements Engineering (contd)

Software modeling
Build a representation of requirements that can be assessed for
correctness, completeness and consistency.

Requirements validation
Review the model

Requirements management
Identify, control and track requirements and the changes.

77
2004 by SEC

Requirements Elicitation

Two sources of information for the requirements elicitation


process
User (customer)
Application domain

Asking
Ask users what they expect from the system
Interview, brainstorm and questionnaire

Task analysis
High-level tasks can be decomposed into sub-tasks

Scenario-based analysis
Study instances of tasks
A scenario can be real or artificial

78
2004 by SEC

Requirements Elicitation (contd)

Form analysis
A lot of information about the domain can be found in various forms
(examples in ERD slides)
Forms provide us with information about the data objects of the domain,
their properties, and their interrelations

Natural language description


with background information to be used in conjunction with other
elicitation techniques such as interviews

Derivation from an existing system


Take the peculiar circumstances of the present situation into account
(examples in ERD slides)

Prototyping

79
2004 by SEC

3.2 Requirements Analysis

80
2004 by SEC

Requirement Analysis

Information domain analysis


information flow: data transformation
data content: data dictionary
data modeling

Functional and behavioral representation


function: process transformation
behavior: state transition diagram

Interfaces definition
function/process interface

Problem partition and abstraction


at different levels of abstraction
classification and assembly structure

81
2004 by SEC

Software Modeling

Purpose
focus on those qualities of an entity that are relevant to the solution
of an application problem
abstract away those that are irrelevant

Model: an abstraction for


Understanding before (actually) building
Communication
Visualization
Reducing complexity

Methodology: build (analyze) a model of an application


domain

82
2004 by SEC

Application and Solution Domain

Application Domain (Requirements Analysis)


The environment in which the system is operating

Solution Domain (System Design, Object Design)


The available technologies to build the system

83
2004 by SEC

The Analysis Process


build a
prototype

requirements
the problem elicitation

develop
Specification

Review

create
analysis
models

84
2004 by SEC

Traditional Software Engineering


Software Systems

Function
Data Flow
Diagram

Data
Entity-Relation
Diagram

Behavior
State Transition
Diagram

85
2004 by SEC

From Analysis to Design: A


Traditional Approach
ERD

Database
Tables
Screen
&
Report

DFD

Structured
chart
Structured
English

86
2004 by SEC

Entity-Relationship Diagram

Entity
Primary things an organization collects and records information
about. (noun) (
)

E.g. persons, products, places, etc.

Relationship
Linkage between entities. (verb) (

E.g. Persons perform jobs, Jobs consist-of tasks

Cardinality
Identify how many instances of one entity are related to how many
instances of another entity.

87
2004 by SEC

Entity-Relationship Diagram (contd)


1:1 Persons 1:N Jobs
perform
consist_of

Jobs

Tasks

M:N Persons
serve

Customers

Direction

using an arrow pointing to the object of the action.

Examples

Persons
Perform

Jobs

Serve
Consist-of

Customers
Tasks

88
2004 by SEC

Entity-Relationship Diagram (contd)

Students
Take

Assist
Advice

Courses

Faculty
Teach

Attributes: Properties to describe an entity


key attribute (key, identifier) to characterize the specific entity (to
retrieve a single entity occurrence (instance))

unique: to ensure that no other record has the same identifier.

unchanging: to ensure that it always refers to the same thing.

89
2004 by SEC

Entity-Relationship Diagram (contd)


e.g.

Entity type

Key attribute

Attribute
actual data

Students
Student_id
Entity
occurrence

50416938
71426006

name
Doakes,, Jane
Blough, JO

phone
242-7147
426-4141

Student is an entity about which a university stores info such as the


Student_id, name, and phone.

Compound keys: made up of a number of different subkeys


to produce a unique identifier
e.g. course number + section number + term

The difference between an entity and an attribute is that


attributes are atomic.
i.e. Attributes have no further attributes that describe them. Entities
can be further described by their attributes.

90

2004 by SEC

Advanced Features

Kernel and characteristic entities


Entities can be described by other subsidiary entities in a
hierarchical fashion.

to store related values of one of the attributes of an entity.

Entities
Courses
Sections
Meetings

Keys
Course_id

Attributes
name
credits

Course_id
Section_id

Faculty

Course_id
Section_id
Meeting_id

Meeting_day
Meeting_time
Room

91

2004 by SEC

Advanced Features (contd)


The highest entity type in the hierarchy is called a kernel entity,
which has a unique identity that does not depend on the existence of
any other entity type.
Characteristic entities: to record the repeated characteristics of the
kernel entity.

e.g. Course is a kernel entity, Sections and Meetings are


characteristic entities describing the characteristics of Courses.

The unique identifier for the characteristic entities is a multiple


key.

e.g. Course_id + Section_id are needed to uniquely identify a


section.

92
2004 by SEC

Advanced Features (contd)


Recursive relationships: an entity is related to itself

e.g.

Is_Parent_of
Is_Married_To
Person
Is_Child_of
for retrieving all family relationships

93
2004 by SEC

Advanced Features (contd)


N-ary relationships

e.g.

An example

Faculty

Teach

Occupy

Rooms

Courses

Take

Students

Contain

Sections
Have

Meetings

94
2004 by SEC

Where to look for information?


existing forms

forms organize the data and remind what to collect.

It is common in manual systems to provide large amounts of


redundant data.

e.g. Scholarship Application Form

Student number _____


name ________
Year of program ____
GPA ___
names of Scholarship
applied for
Reference Letters
Requested form:
(names and addresses)

Scholarships
Receive

Apply for

Students
request
Referees

95
2004 by SEC

Existing file structures

Frequently organizations have a collection of application programs


that do not link to each other. They may require complex programs
to transform data used by one application into a form used by
another one.

e.g. existing student record system

Accounts: Account_id, Label


Buildings: Building_id, Name, Address.
Courses: Course_id, Course_Name, Credits.
Course_Program: Course_id, Program_id
Departments: Department_id, Department_Name.
Enrolled: Student_id, Course_id, Section_id, Year, Term, Grade.
Faculty: Faculty_id, Name, Address, Birthday.
Fee_Payments: Student_id, Account_id.
Prerequisites: Course_id, Pre1, Pre2, Pre3.
Programs: Program_id, Program_Name.
Rooms: Building_id, Room_id, Size, Type.
Sections: Course_id, Section_id, Year, Term, Faculty_id (Meeting_id,
Building_id, Room_id, Day, Time) ...
Students: Student_id, Name, Address, Birthday.

96

2004 by SEC

Kernel entities: single keys, such as: Accounts, Buildings,


Courses, Departments, Faculty, Prerequisites, Programs,
and Students

Characteristic entity vs. Relationship (rules)


kernel entity (or characteristic entity)s key + not part of the key
of any entity
=> characteristic entity
multiple keys are combinations of keys for other entities => M:N
relationships
e.g Course_program: course_id, program_id...
Enrolled: students_id, course_id,...
e.g Rooms: building_id <---- from buildings
room_id <--- not identified precisely
characteristic entity

97
2004 by SEC

ERD from Existing Forms and Files


Buildings

Rooms

Meetings

Accounts

Referees

fee-payment
applied-for
Scholarships
Students
receive
Sections

Courses

course-program
Faculty

Departments

Programs

98
2004 by SEC

Testing ERD

No identification key for entity

Two or more entities have the same key

Many relationships to a single entity

Two or more relationships between the same entities

N-ary relationship

An entity has no relationship

99
2004 by SEC

Extended Entity-Relationship Model

To define the logical content of the database

Extension in two dimensions:


to document the attribute of each entity
to document the semantic meaning of the relationships

100
2004 by SEC

Define
Attributes

Attributes: an elementary item of recordable data that cannot


be further subdivided into meaningful data items. (Field or
descriptor)
with two distinguishing features:

atomic fact: an attribute cannot have attributes of its own.

single value: an attribute cannot have more than one value for any
single entity occurrence.

If there is more than one value for the same entity occurrence, a
new characteristic entity must be created to contain the multiple
values.

101
2004 by SEC

Define Attributes (contd)


Primary key: to identify uniquely each occurrence of an entity, with
the following properties:

unique

unchanging

never has a null or missing value

can have more than one attribute to create a unique key.


a single attribute: an atomic key.
multiple attributes: a compound key.

dataless keys are not subject to change in the way that keys
made up of data items often do.

Alternate key: to provide a choice of identifiers.

102
2004 by SEC

Define Attributes (contd)


Foreign key: to create a link with another entity, e.g.
PROGRAM_ID is a foreign key linking STUDENTS to
PROGRAMS.
Null OK: to indicate whether this attribute can ever have a null
value.

if an attribute does not exist for some occurrences of an entity.

if it exists but is not know at the time the entity occurrence is


recorded.

foreign key can have a null value if the relationship that they
map is optional.

Type: types of attributes.


Width: max number of characters or digits.

103
2004 by SEC

Define Attributes (contd)


Example:

Entity STUDENTS
ATTRIBUTE

PRIMARY FOREIGN NULL TYPE WIDTH


KEY
KEY
OK

ID

SURNAME

CHAR

20

FIRSTNAME

CHAR

20

ID

STUDENT_ID

PROGRAM_ID

104
2004 by SEC

Semantics of the Relationships

Relationships
Extension to allow for

optionality: to determine whether the linked entities must


always be linked.

existence dependency: to determine whether the existence of


an entity occurrence depends on the existence of an occurrence
of anther entity.

abstractions: permit the definition of a hierarchy of entities


with rules about how the levels of the hierarchy are related.

105
2004 by SEC

Semantics of the Relationships


(contd)

Optionality:
Mandatory: If the relationship between entities A and B is
mandatory, then each instance of A must correspond to an instance
of B
Optional: If it is optional at the end of A, then some instance of A
can be recorded that has no relationship to any instance of B
e.g.

(OPTIONAL)

(MANDATORY)

STUDENTS

STUDENTS

COURSE

REFEREES

106
2004 by SEC

Semantics of the Relationships


(contd)

Existence Dependency
to describe the relationship between characteristic entities and
kernel entities

Courses
COURSE
Courses
SECTIONS

optionally have
HAVE

must have
HAVE

one or more sections


SECTIONS
one of sections
COURSE

107
2004 by SEC

Semantics of the Relationships


(contd)

Abstractions
the more specific entities inherit the properties of the more abstract
entities

specific entities are collected into subtypes that share common


properties with the more general entity, called a supertype

overlapping subtypes (or aggregation relationship)

IS-PART-OF (

e.g.

optional

ATHLETES

MUSICIANS

STUDENTS

108
2004 by SEC

Semantics of the Relationships


(contd)
Mutually exclusive subtypes (or generalization
relationship)
IS-A (
e.g.

STUDENT

UNDER

GRADUATES

existence dependency

109
2004 by SEC

Semantics of the Relationships


(contd)

Convert M:N Relationships


Problems

Not specific enough for the detailed modeling entities

e.g.

STUDENTS

ENROLL_IN

SECTIONS

does not provide a way of telling which of the many


possible sections a particular student is actually enrolled in.
does not provide a way of telling which of the many actual
students are enrolled in a particular section.

110
2004 by SEC

Semantics of the Relationships


(contd)
Solution

convert M:N relationship into an intersection entity (or


association entity).

an M:N relationship usually represents a transaction that links


the related entities.

can be identified by asking what event or transaction cause the


M:N relationship to occur.

Intersection entity (association entity)

To represent a relationship about which we wish to maintain


some information.

111
2004 by SEC

Semantics of the Relationships (contd)


STUDENTS

ENROLLMENT

SECTIONS

John
Mary
Tania

John ACC-1
John FIN-1
John STA-1
Mary ACC-1
Tania FIN-2

ACC-1
STA-1
FIN-1
FIN-2

STUDENTS

SECTIONS
ENROLLMENT

112
2004 by SEC

EER Model of The Student Subsystem


ENROLLMENTS
EERM

STUDENTS
REGISTRATIONS

association
entities

PROGRAMS
OFFERINGS
COURSES
SECTIONS
FACULTY

characteristi
entities
MEETINGS

113
2004 by SEC

To Sharpen Your EERM Skill


Job_Description

Tasks

Position

Staf

Management

Benefits

Employees

Skills

Stock_Options

Pensions

114
2004 by SEC

To Sharpen Your EERM Skill (contd)

Answer the following questions based on the EERM on the


previous slide:
(1) Does every job description have a related position?
(2) Can a task exist without a related job description?
(3) Can a task be part of more than one job description?
(4) Can a skill exist without a related task?
(5) Can an employee be both staff and management at the same time?

115
2004 by SEC

To Sharpen Your EERM Skill (contd)


(6) How many staff can a manager supervise?
(7) Which employees get both a pension and stock options?
(8) Can a manager get both pensions and stock options?
(9) Do all managers get both pensions and stock options?
(10) Does every recorded position gave an employee in it?

116
2004 by SEC

To Sharpen Your EERM Skill (contd)

Draw EERM based on the statements below:


(1) A country has a capital city.
(2) A dining philosopher is using a fork.
(3) A file is an ordinary file or a directory file.
(4) Files contain records.
(5) A polygon is composed of an ordered set of points.
(6) A drawing object is text, a geometrical object, or a group.

117
2004 by SEC

To Sharpen Your EERM Skill (contd)


(7) A person uses a computer language on a project.
(8) Modems and keyboards are input/output devises.
(9) Object classes may have several attributes.
(10) A person plays for a team in a certain year.
(11) A route connects two cities.
(12) A student takes a course from a professor.

118
2004 by SEC

To Sharpen Your EERM Skill (contd)

Apply ERD and EERM to model the text description below.


(a) A person has a name, address, and social security number. A person
may charge time to projects and earn a salary. A company has a name,
address, phone number, and primary product. A company hires and
fires persons. Person and Company have a many-to-many relationship.

119
2004 by SEC

To Sharpen Your EERM Skill (contd)


(b) There are two types of persons: workers and managers. Each
worker works on many projects; each manager is responsible for many
projects. A project is staffed by many workers and exactly one
manager. Each project has a name, budget, and internal priority for
securing resources.

120
2004 by SEC

To Sharpen Your EERM Skill (contd)


(c) A company is composed of multiple departments; each department
within a company is uniquely identified by its name. A department
usually, but not always, has a manager. Most managers manage a
department; a few managers are not assigned to any department. Each
department manufactures many products; while each product is made
by exactly one department. A product has a name, cost, and weight.

121
2004 by SEC

Components of Structured Analysis


data &
process
modeling)
DFD

SA

CFD
control

process
PSPEC
processing narrative
external entity
PDL
data item
E-R diagram(data
data store
Data Dictionary (content)
quasicontinuous data flow
control process
control item
control store
multiple instances of the same process
control item
(CSPEC bar) a reference to CSPEC
122
CSPEC
STD
2004 by SEC
PAT

Structured Analysis:
Modeling Technique

model: describe information(data & control), flow, content.

control-oriented applications

data-intensive applications

deficiency

123
2004 by SEC

Basic Notation

DFD:

: process (transformer of information) (I: data/control?)


(O:data/control?)

: external entity (procedure/consumer of information)

: data item

: data store (repository of data observed by processes)


** Control flow is not explicit.
** The truth is that control is excluded in DFD intentionally.

124
2004 by SEC

Basic Notation (contd)

DFD can be used to represent a system at any level of abstraction.


(refine)
level 0: context model (a single bubble)
information flow continuity: I/O to each refinement must remain the same.
(balancing)

No explicit indication of the sequence of processing is supplied by


the DFD.
Explicit procedural representation delayed until design.

125
2004 by SEC

Basic Notation (contd)

Content of data (implied by the arrow or described by the store)


a collection of items: using data dictionary. (DD) (only content)
a need to represent the relationship between complex collections of data. (ER diagram for data modeling)

126
2004 by SEC

Basic Notation (contd)

processing narrative: describe (usually natural language) a process


bubble.
To specify the processing details in the bubble.

inputs to the bubble

algorithm applied to the input

Output

Restrictions & limitations imposed on the process.

Performance characteristics related to the process.

Design constraints

127
2004 by SEC

Extensions

Data-intensive application:
Data modeling to describe the relationship between complex
collections of data. (E-R diagram)

Control-oriented application:
To describe/represent control flow and control processing as well as
data flow and processing.

128
2004 by SEC

Extensions (contd)
(1)Ward & Mellor extensions: extend SA notation.

: quasicontinuous data flow (I:control /


O:control)

: control process

: control item

: control store

: process (multiple instances of the


same process)

129
2004 by SEC

Extensions (contd)
(2)Hatley and Pirbhai Extensions: extend on representation of the control-oriented
aspects. (control/event)
Notation:

: control flow (separate control flow diagram CFD from DFD)


: reference to a control specification (CSPEC)

a window into an executive (CSPEC) that controls the processes in


DFD based on the event that is passed through the window.

CSPEC: (Control Specification)


- How the software behaves when a control signal is sensed.
- Which processes are invoked as a consequence of the occurrence of
the control/event.

PSPEC: (Process Specification)


- To describe the inner workings of a process representation.

130
2004 by SEC

Extensions (contd)

Relation between data and control models

Data input

Process
model
DFDs
PSPECs

Process
activators

Control
model
CFDs

Control
output

CSPEC
s

Data output

data conditions:
occurs when data
input a
process results in a
control ** data conditions:
above pressure
output

** refer to CSPEC:
Control invoke reduce tank
pressure

input

131

2004 by SEC

Extensions (contd)

CSPEC: if a data conditions occur which refers to a


CSPEC bar, we must check CSPEC to determine what
happens when this event occurs.
Process activation table (PAT): To indicate which processes are
activated by a given event that flows through the vertical bar.
State transition diagram (STD): To indicate how the system moves
from state to state (behavior model)

state, any observable mode of behavior

events, cause the system to change state

132
2004 by SEC

Data Dictionary

precise, rigorous definitions of all data elements pertinent to


the system.

usually contain the following information:


Name, Alias, Where used/How used, Content description,
supplementary information.

Content description notation

recorded automatically from


the flow models

=
/ + / [ | ] / { }n / ( )
and selection repetition option comments

composed of

133
2004 by SEC

Fundamental Issue
data

data

control

Conventional
I: data/control
O: data/control
in DFD

control

Ward-Mellor
I/O data & control
I/O control in DFD

Hatley-Pirbhai
I/O data in DFD
I/O control in DFD

134
2004 by SEC

SA and its Extension

Summary:
(1)Conventional:

process
Ward-Mellor:

control data item

control
process

process
data item
Hatley-Pirbhai:

process
CSPEC bar

135

2004 by SEC

SA and its Extension (contd)


(2)Modeling:

(1) information (control & data)


flow and content

--- DFD / CFD

(2) functionality
(3) behavior

--- data & process (DFD)


--- CSPEC (STD)

136
2004 by SEC

Balancing EERD against DFD

Every data store on the DFD must correspond to an entity


type, or a relationship, or a combination of an entity type and
relationship.
If there is a store on the DFD that does not appear on the EERD,
something is wrong; and if there is an entity or relationship on the
ERD that does not appear on the DFD, something is wrong.

137
2004 by SEC

The Analysis Process


build a
prototype

requirements
the problem elicitation

develop
Specification

Review

create
analysis
models

138
2004 by SEC

3.3 Object-oriented (OO) Software


Engineering

139
2004 by SEC

Object-Oriented Software Engineering


Software Systems

Object
Class
Diagram

Function
Data Flow
Diagram

Behavior
State Chart

140
2004 by SEC

Steps of Analysis: An Example


Using OO Approach

Define use cases

Extract candidate classes

Establish basic class relationships

Define a class hierarchy

Identify attributes for each class

Specify methods that service the attributes

Indicate how classes/objects are related

Build a behavioral model

141
2004 by SEC

Application and Solution Domain

Application Domain

Solution Domain

Application Domain Model

System Model

TrafficControl
Aircraft

UML Package

TrafficController

FlightPlan

Airport

SummaryDisplay

MapDisplay

FlightPlanDatabase
TrafficControl

142
2004 by SEC

Concepts and Phenomena

Phenomenon (object): An object instance in the world of a


domain,
E.g. My black watch

Concept (object class): Describes the properties of phenomena


that are common,
E.g. Black watches

A concept is a 3-tuple:
Its Name distinguishes it from other concepts.
Its Purpose are the properties that determine if a phenomenon is a member
of a concept.
Its Members are the phenomena which are part of the concept.

143
2004 by SEC

Concepts and Phenomena (contd)


Name

Clock

Purpose

Members

A device that
measures time.

Modeling: Development of abstractions to answer specific


questions about a set of phenomena while ignoring irrelevant
details.

144
2004 by SEC

Class

Class:
An abstraction in the context
encapsulates both state (variables) and behavior (methods)
Can be defined in terms of other classes using inheritance

Criteria of selecting classes


Retained information
Needed services
Multiple attributes
Common attributes
Essential requirements

145
2004 by SEC

Class Identification

Identify the boundaries of the system


What object is inside, what object is outside?

Identify the important entities in the system


Learn about problem domain: Observe your client
Take the flow of events and find participating objects in use cases
(Scenarios and use cases)
Apply design patterns
Nouns are good candidates for classes

146
2004 by SEC

Mapping Parts of Speech to


Object Model Components
Part of speech

Example

Proper noun

Model
component
object

Improper noun

class

Toy, doll

Doing verb

method

Buy, recommend

being verb

inheritance

is-a (kind-of)

having verb

aggregation

has an

modal verb

constraint

must be

adjective

attribute

3 years old

transitive verb

method

enter

intransitive verb

method (event)

depends
on

Jim Smith

147
2004 by SEC

Pieces of an Object Model

Classes

Associations (Relations)
Part of- Hierarchy (Aggregation)
Kind of-Hierarchy (Generalization)

Attributes
Application specific
Attributes in one subsystem can be classes in another subsystem, turning
attributes to classes

Service
Domain Methods: Dynamic model, Functional model
Operation: A function or transformation applied to objects in a class. All objects
in a class share the same operations (Analysis Phase)
Signature: Number & types of arguments, type of result value. All methods of a
class have the same signature (Object Design Phase)
Method: Implementation of an operation for a class (Implementation Phase),
Polymorphic operation: The same operation applies to many different classes.

148
2004 by SEC

Object Types

Entity Objects: represent the persistent information (Application


domain objects, Business objects)

Boundary Objects: represent the interaction between the user and the
system

Control Objects: represent the control tasks performed by the system

<<entity>>
Year
<<entity>>
Month

<<control>>

ChangeDateControl

<<boundary>>
ButtonBoundary
<<boundary>>

LCDDisplayBoundary

<<entity>>
Day

149
2004 by SEC

Model Behavior

Indicate different states of the system

Specify events that cause the system to change state

150
2004 by SEC

Modeling Example: A Banking


System
Foo
Balance
CustomerId
Deposit()
Withdraw()
GetBalance()

Class Identification: Name of Class, Attributes and Methods

151
2004 by SEC

Naming

Account
Dada

Foo

Balance

Balance

Balance

CustomerId

CustomerId

CustomerId

Deposit()
Withdraw()
GetBalance()

Deposit()
Withdraw()
GetBalance()

Deposit()
Withdraw()
GetBalance()

152
2004 by SEC

Finding New Objects


Bank
Name

Account
Balance
AccountId

Customer
Name
CustomerId

Deposit()
Withdraw()
GetBalance()

IterateonNames,AttributesandMethods

153
2004 by SEC

Finding New Objects


Account
Bank
Name

Balance
AccountId
Deposit()
Withdraw()
GetBalance()

*
Has

Customer
Name
CustomerId

Iterate on Names, Attributes and Methods


Find Associations between Objects
Label the associations
Determine the multiplicity of the associations

154
2004 by SEC

Categorize
Bank

Name

Account
Balance
AccountId
Deposit()
Withdraw()
GetBalance()

*
Has

Customer
Name
CustomerId

Mortgage
Account

Checking
Account

Saving
Account

Withdraw()

Withdraw()

Withdraw()

Dont put too many classes into the same package: 7+-2 (or even 5+-2)

155
2004 by SEC

The Analysis Process


build a
prototype

requirements
the problem elicitation

develop
Specification

Review

create
analysis
models

156
2004 by SEC

3.4 Data Modeling and OOA

157
2004 by SEC

Data Modeling

data-intensive applications

attributes
relationship
aggregation

E-R Diagram

Semantic Data
Modeling
OOA

OOPL

Service
Message between objects
classification & inheritance

158
2004 by SEC

OOA & Data Modeling

Similarity describe relationships between objects

Differences
data modeling does not concern how these relationships are
achieved
without concern for the processing that must be applied to
transform the data

in general, no concept of methods is considered

Data objects can be defined in terms of a set of attributes


encapsulates data only, that is , no reference within a data object to
operations that act on the data

159
2004 by SEC

OOA & Data Modeling (contd)

Data object attributes


data object tables : normalization result in minimum redundancy,
that is , the amount of information that we need to maintain to
satisfy a particular problem is minimized.

Normalization rules
(1) only one value for each attribute
(2) attributes should contain no internal structure

160
2004 by SEC

Software Artifacts

Problem statements:
to describe the problem to be solved and providing a conceptual overview of
the proposed system

Analysis:
to understand and model the application and the domain (usually called a
modeling activity)
the output is a model capturing: functionality, behavior, and structure

Design:
Data Design:data abstraction;data structure;data modeling
Procedural Design: iteration , conditional, sequence
Architectural Design: program structure ( control hierarchy ); system
organization ( software architecture )

Implementation:
Executable code

161
2004 by SEC

Why Objects?

Real-world objects v.s. software objects


communications

Problem
domain
Object necessary
for describing a
solution - problem
space

Solution
domain
Object required
for implementation
a solution - solution
space

software realization
of the real-world
problem

162
2004 by SEC

Object Orientation

Identity:
each object is a discrete and distinguishable entity.
each real-world object is unique due to its existence.
each object has its own inherent identity, therefore, two objects are
distinct even if all their attribute values are identical.

Classification:
objects with the same attributes and operations are grouped into a
class
Attributes:
each object is said to be an instance of its
frame size
class
wheel size
Operations:
e.g. Bicycle object -------> Bicycle class
shift
move
1993 - 2003, Jonathan Lee, All Right Reserved.

163

2004 by SEC

Object Orientation (contd)

Polymorphism:
the same operation may behave differently on different classes
an operation is an action or transformation that an object performs or is
subject to
method: a specific implementation of an operation

a polymorphic operation is an operation that has more than one


method implementing it.

Inheritance:
the sharing of attributes and operations among classes based on a
hierarchical relationship
each subclass inherits all of the properties of its superclass and adds its
own unique properties (called extension)
reusability
164

1993 - 2003, Jonathan Lee, All Right Reserved.

2004 by SEC

Polymorphism (having many forms)

Static polymorphism
Overloading: an invocation can be operated on arguments
of more than one type.
Class TimeOfDay {
public void setTime(char[8] time) {};
public void setTme(int h, int m, int s) {};
}
TimeOfDay aClock= new TimeOfDay( );
aClock.setTime(17,1,0);
aClock.setTime(11:55:00);

165
2004 by SEC

Polymorphism

Dynamic polymorphism: an object has more than one type


object reference can refer to an instance of any of descendants of its class
an instance of the class created, and is also an instance of each that classs
ancestors
the same operation may behave differently on different classes

method: a specific implementation of an operation

a polymorphic operation is an operation that have more than one


method implementing it.

166
2004 by SEC

Polymorphism: Example
class Student extends Person {
void getName() { System.out.println(Student); }
class Employee extends Person {
void getName() { System.out.println(Employee); }
}
public static void main(String [ ] args) {
Person p;
BufferedReader in=new BufferedReader(
new InputStreamReader(System.in));
int num=Integer.parseInt(in.readLine());
if (num= =1) p = new Employee( );
else p = new Student( );
p.getName( );
}

167
2004 by SEC

Object-Oriented Development

Life-cycle
development:analysis,design,and implementation
testing:
maintenance:

modeling vs. implementation


OOP: back-end implementation issues.

restrict design choices.

OOA/D: front-end conceptual issues

reduce cost.

168
2004 by SEC

OMT Methodology

Stages:

problem
statements

Analysis:

Problem statement. (usually incomplete, incorrect)

Analysis
-abstraction

Analysis
model

of what the
desired system must do.
-application-domain concepts System Design
NOT implementation concepts
-organize the target system into
Design:
subsystems
System design
-decide performance characteri

Decision making
stage

object design

object design

depends on
the
-data structural & algorithm
performanc
169
to implement each class.
measure
2004 by SEC

OMT Methodology (contd)

Three models:
object model: the static structures of objects &
their relationships

object diagrams: object classes (node), relationships


(arc).

dynamic model: interactions(control) among objects

change over
time

state diagrams: states(node), transitions(arc) by events

functional model: data transformation of objects

data flow diagrams: processes(node), dataflows(arc).

170
2004 by SEC

Basic Concepts

Abstraction: focus on the essential, inherent aspects of entity


and ignoring its accidental properties.
e.g. Use of abstraction during analysis: deciding only with
application-domain concepts, not making design and implementation
decisions.

Encapsulation: (OO) separate the external aspects of an


object, which are accessible to their objects, from the internal
implementation details of the object, which are hidden from
other objects.

Sharing through inheritance (Reuse)


data structures and behaviors(design)
code

171
2004 by SEC

Features of Object Orientation:


Blairs Version

Identify
The unique identification of every object is through the use of an
object identifier.

Encapsulation
The selection of properties to be encapsulated.

attributes, operations, representations, algorithms...

The determination of visibility of these properties. (I.e. a welldefined interface)

Classification: group associated objects according to


common properties
The Intent of a classification is the description of that classification
characteristics, therefore, the intent specifies a predicate.

172
2004 by SEC

Features of Object Orientation:


Blairs Version (contd)
The extend of a classification is the set of objects in the current environment
which features such behavior, that is, a population selected by applying a
predicate.

Flexible sharing: The ability for an object to belong to more than


one classification. and will require a flexible form of behavior
sharing.
are based on the encapsulated properties, the considered classification
scheme, the relationship between classifications.

Interpretation: The resolution of the precise semantics of the


shared item of behavior.
two steps involved in the resolution: type checking and binding.

typing checking: determination of whether operations are supported by


a particular object

binding: locate the correct implementation of the operation .

173
2004 by SEC

Exercises

Both SA and OOA offer the mechanism for the partition. Do


they support the interactions between the different levels?

Compare the similarity and differences between the data


modeling and object-oriented modeling.

174
2004 by SEC

Chapter 4
Software Design

2004 by SEC

Chapter 4
Software Design
4.1 Design Fundamentals
4.2 Design Method
4.3 Architecture Design
4.3.1 Architecture Patterns
4.4 Data Design
4.5 Interface Design
4.6 Procedural Design

176
2004 by SEC

Design Fundamentals

Design Step Procedures

functional
requirement

{
{

nonfunctional
requirement

informal model
functional model
behavioral model
design constrain
performance
cost

data design
architecture
design
procedure
design

data structure
relationship between structure
depict structure component
ie. a procedural description
of software

Software Design vs Requirement Analysis


Software design: requirement a representation of software
requirement analysis: create a model to represent to represent the
requirements

177
2004 by SEC

Design Fundamentals (contd)

Common Characteristics
A mechanism for the translation of information domain representation
into design representation
A notation for representing functional components and their interfaces
Heuristics for refinement and partitioning

178
2004 by SEC

Design Fundamentals (contd)

Fundamental Concepts
Abstraction

Level of abstraction
Highest level
.
Low level
.
Lowest level

Language used
Program-oriented terminology
.
Procedural-oriented terminology
.
Implementation-oriented terminology

procedural abstraction
a named sequence of instruction that has a specific function

data abstraction
a named collection of data
that describes a data object
can refer all the data by stating the name of the data abstraction
original abstraction data type is used as a template or generic
data structure from which the data structure can be instructed.

179

2004 by SEC

Fundamental Concepts
Refinement

Top-down design strategy

A hierarchy is developed by decomposing a statement of function ( a


procedural abstraction) in a stepwise fashion until programming statements
are reached
Every refinement step implies some design decisions

A process elaboration
Statement of function (description of information) without the internal
working of the function (internal structure of the information)
Providing more and more details as each successible refinement occurs

180
2004 by SEC

Fundamental Concepts (contd)


Modularity

Modules: software is divided into separately named and addressable


components

Modules vs. interfaces between modules


Avoid overmodularity & undermodularity; notice that the
relationship between modules (that is, the number of interfaces
increase expontentially with the number of modules)

Software architecture

Hierarchy structure of procedural components

Structure of data

It relates elements of a software solution to parts of a real-world


problem

181
2004 by SEC

Fundamental Concepts (contd)


Control hierarchy (program structure)

The organization of program components & implies a hierarchy of


control
Does not represent procedural aspects of software (iteration,
condition, sequence)

Depth / width / fan-in / fan-out / superordinate / subordinate

Two characteristic of software architecture


Visibility: program components may be invoked or used as data
by given component (indirectly) (e.g. M4 is visible to M1)
Connectivity: program components are directly invoked or used
as data by given component (e.g. M2 is connected to M1)

A module that directly causes another module to begin


execution is connected to it

M1

M2

M3

M4

182
2004 by SEC

Fundamental Concepts (contd)


Software procedure focuses on the processing details of each module
individually (sequence, iteration, condition)

a procedural representation of software is layered

Information hiding

modules should be specified and designed so that information


(procedure & data) contained within a module are inaccessible to
other modules that have no need for such information.

abstraction defines the procedural entities

hiding defines access constraints to both procedural detail within a


module and local data structure used by the modules

183
2004 by SEC

Effective Modular Design

Effective modular design


A modular design reduces complexity, facilitates changes, results in an
easier implementation.

monolithic
program

module
program

object-oriented
program

code-and-fix
Classification (based on temporal aspect)

sequential

/ incremental

/ parallel

subroutines

/ coroutines

/ conroutines

Without apparent / Can be


/ execute
interruption
interrupted before simultaneously with
completion
another module

184
2004 by SEC

Effective Modular Design (contd)


A typical control hierarchy may not be encountered when coroutines or
conroutines are used
Functional independence (independent effective modules)

Effective modularity: function compartmentalized and interfaces


simplified

Cohesion: relative functional strength of a module


low

high

coincidental : tasks relate to each other loosely

logical : performing tasks related logically ( all output )

temporal : all tasks executed with the same span of time

procedural : must be executed in a specific order

communicational : concentrate on one area of a data structure

sequential

functional

185
2004 by SEC

Effective Modular Design (contd)


Coupling: interconnection among modules

low

depends on the interface complexity between modules, entity point


or reference to a module, what data passes across the interface

No direct coupling : module subordinate to different modules


Data coupling : data passed via argument list
Stamp coupling : data structure passed via argument list
control coupling : passes control data
external coupling : modules are tied to an external environment
common coupling : refer to a global data area
content coupling :
one module makes use of data or control information
maintained within the boundary of another module .
branches are made into the middle of a module

middle

high

186
2004 by SEC

Data Design
Define data abstractions

data abstraction

Select an appropriate data structure to implement the abstraction


data structure

Using entity-relationship modeling depict relationship between


objects

data modeling

187
2004 by SEC

Architectural Design

Program architecture, domain specific software


architecture

(1) program
structure

Develop a modular program structure


Represent the control relationship between modules

Control hierarchy connecting modules

Define interface that enable data to flow throughout the program


System organization
DSSA

(2) domain-specific
Software
architecture

Pipes & filters


I: a stream of inputs
O: a stream of outputs

188
2004 by SEC

Architectural Design (contd)

Layered systems:
System organized hierarchically with each layer providing
service to the layer about it

System
Basic
Core

Knowledge Base

Rule-based system

Input

Output

Working
Memory

Rule
interpreter

RB

Fact

selected Rule & data


rules/data element

Blackboard systems: a central data structure represents the current


state of the computation, a collection of knowledge sources.
Blackboard

189
2004 by SEC

Procedural Design

Structure programming
logical constructs: sequence, conditional, iteration
to limit the procedural design to a small number of predictable
operations
reduce program complexity
lead to more readable, testable code

Flow charts
Graphical representation for procedural design
Limitation

Introduce inefficiency when an escape from a set of nested loops


or nested conditions is required

Additional complications of logical tests

190
2004 by SEC

Procedural Design (contd)

Program design language (PDL)


Structured English (pseudocode)

Uses the vocabulary of English

Overall syntax of a structure programming language

Difference between PDL and programming language

The use of narrative text embedded directly within PDL statements

PDL cannot be compiled but can be translated into a graphical


structure

Why design language

can be embedded with source code


can be a derivative of the high order language .eg. Ada PDL
easy to review
can be represented in great detail

191
2004 by SEC

PDL

Data structure
TYPE <var-name> IS

<q-1> <q-2>

eg. TYPE table IS INSTANCE OF symboltable

Abstract data type: data abstraction


Generic data structure (template) from which other data structures can
be instantiated
e.g. TYPE table IS INSTANCE OF symboltable
Block structure
BEGIN
< ..... >
END

192
2004 by SEC

PDL (contd)
Conditional
-IF <

-CASE OF <
>
WHEN <
> SELECT <
.
.
DEFAULT: <
>
ENDCASE

>

THEN <

>

ELSE <

>

ENDIF

Iteration
-REPEAT UNTIL <
<

>

>

>

ENDREP
-DO WHILE <
<

>

>

ENDDO
-DO FOR <
<

>
>

ENDFOR

193
2004 by SEC

Chapter 5
Object-Oriented Software
Development

2004 by SEC

Chapter 5
Object-Oriented Software Development
5.1 Object Orientation
5.1.1 Object and Class
5.1.2 Encapsulation and information hiding
5.1.3 Inheritance
5.1.4 Polymorphism

5.2 Object-oriented analysis


5.2.1 Object modeling
5.2.2 Dynamic modeling
5.2.3 Functional modeling

5.3 Object-oriented design


5.4. Design patterns

195
2004 by SEC

Chapter 6
Software Testing

2004 by SEC

Chapter 6
Software Testing
6.1 Software Testing Fundamentals
6.1.1 What is Software Testing
6.1.2 Verification and Validation
6.1.3 The V Model

6.2 Testing Principles


6.3 Testing Techniques
6.3.1 White-Box Testing Techniques
6.3.2 Black-Box Testing Techniques

197
2004 by SEC

Chapter 6
Software Testing (contd)
6.4 Software Testing Strategies
6.4.1 Unit Testing
6.4.2 Integration Testing
6.4.3 System Testing

6.5 Object-Oriented Testing


Exercise

198
2004 by SEC

Software Testing Fundamentals

What is software testing?


Myers: The process of executing a program with the intent of finding
errors.
Beizer: The act of designing and executing tests.
Whittaker: The process of executing a software system to determine
whether it matches its specification and executes in its intended
environment
IEEE: The process of operating a system or component under specified
conditions, observing or recording the results, and making an evaluation
of some aspect of system or component.

199
2004 by SEC

Software Testing Fundamentals (contd)

Why do we test?

To check if there are any errors in a part or a product.


To gain the confidence in the correctness of the product.
To ensure the quality and satisfaction of the product

Testing vs. debugging


Testing is to show that a program has bugs
Debugging is to locate and correct the error or misconception that
cause the program failures

200
2004 by SEC

Software Testing Fundamentals (contd)

Who Tests the Software?


Development engineers

Understand the system, but test gently

Driven by delivery

Only perform unit tests and integration tests

Test engineers

Need to learn the system, but attempt to break it

Driven by quality

Define test cases, write test specifications, run tests, analyze results

Customers

Driven by requirements

Determine if the system satisfies the acceptance criteria

201
2004 by SEC

How to do Software Testing?

Software testing can be approached in the following phases


Modeling the softwares environment
Selecting test scenario
Running and evaluating test scenario
Measuring testing progress

202
2004 by SEC

Verification and Validation

Software testing is one element of a broader topic:


verification and validation (V&V)
Verification are we building the product correctly?*
The set of activities to ensure that software correctly implements
specific functions

Validation are we building the correct product?*


The set of activities to ensure that the developed software is traceable
to customer requirements

203

Note: [Boehm 1981]

2004 by SEC

Verification and Validation (contd)

The definition of V&V encompasses many activities that is referred to


as software quality assurance (SQA) including

Formal technical review


Quality and configuration audits
Performance monitoring
Simulation
Feasibility study
Documentation review
Database review
Algorithm analysis
Development testing
Qualification testing
Installation testing

204
2004 by SEC

The V model

The V model
Emerged in reaction to some waterfall models that showed testing as a
single phase following the traditional development phases of
requirements analysis, high-level design, detailed design and coding.
The V model portrays several distinct testing levels and illustrates how
each level addresses a different stage of the software lifecycle.
The V shows the typical sequence of development activities on the lefthand (downhill) side and the corresponding sequence of test execution
activities on the right-hand (uphill) side.

205
2004 by SEC

The V model (contd)


Requirements
Analysis

Acceptance
Testing

Architecture
Design

System
Testing

Detailed
Design
Code

Integration
Testing
Unit Testing

206
2004 by SEC

The V model (contd)

The V model is valuable because it highlights the existence of


several levels of testing and delineates how each relates to a
different development phase:
Unit testing: concentrates on each unit (i.e., component) of the
software (white box)
Integration testing: focuses on design and the construction of the
software architecture (black box, limited amount of white box)

207
2004 by SEC

The V model (contd)


System testing: verifies that all elements mesh properly and that overall
system function/performance is achieved.
Acceptance testing: are ordinarily performed by the business/users to
confirm that the product meets the business requirements.

208
2004 by SEC

Testing Principles

Davis in his book, 201 Principles of Software Development,


suggests a set of testing principles:
All tests should be traceable to customer requirements.
Tests should be planned long before testing begins.
The Pareto principle applies to software testing.

80% of all errors uncovered during testing will likely be traceable to


20% of all program modules.

Testing should begin in the small and progress toward testing in the
large.

209
2004 by SEC

Testing Principles (contd)


Exhaustive testing is not possible.
To be most effective, testing should be conducted by an independent
third party.

Glen Myers suggests a number of testing principles:


Testing is a process of executing a program with the intent of finding
errors.
A good test case is one that has high probability of detecting an as-yet
undiscovered error
A successful test case is one that detects an as-yet undiscovered error

210
2004 by SEC

Attributes of A Good Test

Kaner, Falk, and Nguyen in their book, Testing Computer


Software, suggest the following attributes of a good test
A good test has a high probability of finding an error
A good test is not redundant
A good test should be best of breed
A good test should be neither too simple nor too complex

211
2004 by SEC

Exhaustive Testing

Is it possible to develop test cases to exercise all logical paths


of a program?
Even small programs, the number of possible logical paths can be very
large
Example: Consider a program contains 2 nested loops that each executes
1 to 20 times depending on the input data. The interior loop has 4 if-thenelse constructs

There are 1014 possible paths! If we exercise one test per


millisecond, it would take 3170 years to complete test

Exhaustive testing is impractical for large software system


Selective testing is required

212
2004 by SEC

When Testing Can Stop?

Team consensus

When test adequate criteria are met


Coverage
Error discovery rate

Testing is never done, the burden simply shifts from you to


the customer

When the product has been irrevocably retired

213
2004 by SEC

Testing Methods

Two general software testing methods:


White-box testing: (logic-driven)

Design tests to exercise internal structures of the software to make


sure they operates according to specifications and designs

Black-box testing: (data-driven or input/output-driven)

Design tests to exercise each function of the software and check its
errors.

White-box and black-box testing approaches can uncover different class


of errors and are complement each other

214
2004 by SEC

White-Box Testing

White-box testing
Also known as glass-box testing or structural testing
Has the knowledge of the programs structures
A test case design method that uses the control structure of the
procedural design to derive test cases
Focus on the control structures, logical paths, logical conditions, data
flows, internal data structures, and loops.
W. Hetzel describes white-box testing as testing in the small

215
2004 by SEC

White-Box Testing (contd)

Using white-box testing methods, we can derive test cases


that
Guarantee that all independent paths within a module have been
exercised at least once.
Exercise all logical decisions on their true and false sides.
Execute all loops at their boundaries and within their operational
bounds.
Exercise internal data structures to assure their validity.

216
2004 by SEC

Basis Path Testing

Basic path testing (a white-box testing technique):


First proposed by Tom McCabe.
Can be used to derive a logical complexity measure for a procedure
design.
Used as a guide for defining a basis set of execution path.
Guarantee to execute every statement in the program at least one time.

217
2004 by SEC

Basis Path Testing (contd)

The basic structured-constructs in a flow graph :

Sequence
While

If Else
..
.
Until

Case

218
2004 by SEC

Basis Path Testing (contd)

Flow graph notation (control flow graph)


Node represents one or more procedural statements.

A sequence of process boxes and a decision diamond can map into a


single node

A predicate node is a node with two or more edges emanating from it

Edge (or link) represents flow of control


Region: areas bounded by edges and nodes

When counting regions, include the area outside the graph as a


region

219
2004 by SEC

Basis Path Testing (contd)


Compound condition

Occurs when one or more Boolean operators (OR, AND, NAND,


NOR) is present in a conditional statement

A separate node is created for each of the conditions C1 and C2 in


the statement IF C1 AND C2

if (c1 AND c2) then


print T;
else
F
print F;
end if;

predicate nodes

c1
c2
F

220
2004 by SEC

binarySearch() Example

public int binarySearch(int sortedArray[ ], int searchValue)


{
int bottom = 0;
int top = sortedArray.length - 1;
2
int middle, locationOfsearchValue;
boolean found = flase;
locationOfsearchValue = -1;
/* the location of searchValue in the sortedArray */
/* location = -1 means that searchValue is not found */
while ( bottom <= top && !found)
{
3
middle = (top + bottom)/2;
4
if (searchValue == sortedArray[ middle ])
{
found = true;
5
locationOfsearchValue = middle;
}
6 else if (searchValue < sortedArray[ middle ])
top = middle - 1;
else
7
8
bottom = middle + 1;
} // end while

10
}

return locationOfsearchValue;

221
2004 by SEC

The Control Flow Graph (CFG) of


Function binarySearch()
1
2
3
4
5

6
8

7
9
10

222
2004 by SEC

Cyclomatic Complexity

Cyclomatic complexity is a software metric


provides a quantitative measure of the global complexity of a program.
When this metric is used in the context of the basis path testing

the value of cyclomatic complexity defines the number of


independent paths in the basis set of a program

the value of cyclomatic complexity defines an upper bound of


number of tests (i.e., paths) that must be designed and exercised to
guarantee coverage of all program statements

223
2004 by SEC

Cyclomatic Complexity (contd)

Independent path
An independent path is any path of the program that introduce at least
one new set of procedural statements or a new condition
In a flow graph, an independent path must move along at least one edge
that has not been traversed before the path is defined

Examples: consider the CFG of binarySearch()


Path 1: 1-2-10
Path 2: 1-2-3-4-6-8-9-2-10
Path 3: 1-2-3-4-6-8-9-2-3-10
Path 4: 1-2-3-4-6-8-9-2-3-4-6-8-9-2-10 (not an independent path)
independent paths

224
2004 by SEC

Cyclomatic Complexity (contd)

Three ways to compute cyclomatic complexity:


The number of regions of the flow graph correspond to the cyclomatic
complexity.
Cyclomatic complexity, V(G), for a flow graph G is defined as V(G) = E
-N+2
where E is the number of flow graph edges and N is the number of flow
graph nodes.
Cyclomatic complexity, V(G) = P + 1
where P is the number of predicate nodes contained in the flow graph G.

225
2004 by SEC

Cyclomatic Complexity of Function


binarySearch()
1

predicate nodes

2
3
4

R3

R2

R4 7

R1

regions

R5

9
10

226
2004 by SEC

Deriving Basis Test Cases

The following steps can be applied to derive the basis set:


1.

Using the design or code as a foundation, draw the corresponding


flow graph.

2.

Determine the cyclomatic complexity of the flow graph.

V(G) = 5 regions

V(G) = 13 edges 10 nodes + 2 = 5

V(G) = 4 predicate nodes + 1 = 5

227
2004 by SEC

Deriving Basis Test Cases (contd)


3.

4.

Determine a basis set of linearly independent paths.

Path 1: 1-2-10

Path 2: 1-2-3-10

Path 3: 1-2-3-4-5-9-2-

Path 4: 1-2-3-4-6-7-9-2-

Path 5: 1-2-3-4-6-8-9-2-

Prepare test cases that force the execution of each path in the basis set

Path 1 test case:


Inputs: sortedArray = { }, searchValue = 2
Expected results: locationOfSearchValue = -1

228
2004 by SEC

Deriving Basis Test Cases (contd)

Path 2 test case: cannot be tested stand-alone!


Inputs: sortedArray = {2, 4, 6}, searchValue = 8
Expected results: locationOfSearchValue = -1

Path 3 test case:


Inputs: sortedArray = {2, 4, 6, 8, 10}, searchValue = 6
Expected results: locationOfSearchValue = 2

Path 4 test case:


Inputs: sortedArray = {2, 4, 6, 8, 10}, searchValue = 4
Expected results: locationOfSearchValue = 1

Path 5 test case:


Inputs: sortedArray = {2, 4, 6, 8, 10}, searchValue = 10
Expected results: locationOfSearchValue = 4

229
2004 by SEC

Deriving Basis Test Cases (contd)

Each test cases is executed and compared to its expected


results.

Once all test cases have been exercised, we can be sure that all
statements are executed at least once

Note: some independent paths cannot be tested stand-alone


because the input data required to traverse the paths cannot be
achieved
In binarySearch(), the initial value of variable found is FALSE, hence
path 2 can only be tested as part of path 3, 4, and 5 tests

230
2004 by SEC

Graph Matrices

A graph matrix
A tabular representation of a flow graph
A square matrix with a size equal to the number of nodes on the flow
graph
Matrix entries correspond to the edges between nodes
Adding link weight to each edge to represent

The connection between nodes

The probability of the edge to be executed

The resource (e.g., processing time or memory) required for


traversing the edge

231
2004 by SEC

Graph Matrices (contd)

A connection matrix
A graph matrix with the link weight is 1 (representing a connection
exists) or 0 (representing a connection does not exist)
Each row of the matrix with two or more entries represents a predicate
node
Provide another method for computing the cyclomatic complexity of a
flow graph

232
2004 by SEC

Graph Matrices (contd)


Node

Connected to node
1
1

3
c

2
b

f
e
g

1
1

4
5

Flow Graph

Graph Matrix

Connection Matrix

Connections
1-1=0
2-1=1

2-1=1

Cyclomatic
complexity

2-1=1
----------3+1=4

233
2004 by SEC

Condition Testing

Condition Testing
Test case design method that exercise the logical conditions in a
program module

Logical conditions
Simple condition:

(a rel-op b) where rel-op={<, , =, , , >} (may be negated with


NOT)

Example: a b; NOT(a b)

234
2004 by SEC

Condition Testing (contd)


Compound condition:

Two or more simple conditions connected with AND, OR

Example: (a > b) AND (c < d)

Relational expression:

(E1 rel-op E2) where E1 and E2 are arithmetic expressions

Example: ((a*b+c)>(a+b+c))

Boolean expression

A condition without relational expressions

If a condition is incorrect, then at least one component of the


condition is incorrect

235
2004 by SEC

Condition Testing (contd)

The type of errors in a condition include :


Boolean operator (incorrect/missing/extra Boolean operators)
Boolean variable error
Boolean parenthesis error
Relational operator error
Arithmetic expression error

The purpose of condition testing is to detect not only errors in


the conditions of a program but also other errors in the
program.
Detect faults in the condition, statements executed before the condition,
and the statements executed after the condition

236
2004 by SEC

Condition Testing (contd)

Branch testing
The simplest condition testing strategy
For a compound condition C, test (1) true and false branches of C and
(2) every simple condition of C at least once
Example: for C = (a>b) AND (c<d) we test for

TRUE and FALSE

a>b

TRUE and FALSE

c<d

TRUE and FALSE

237
2004 by SEC

Condition Testing (contd)

Domain testing
For a relational expression, require 3 or 4 tests to be derived
For an expression E1 rel-op E2, test for E1 greater than, equal to, or less
than E2
Guarantees detection of rel-op error if E1 and E2 are correct
To detect errors in E1 and E2, the difference between E1 and E2 for the
tests E1 greater or less than E2 should be as small as possible
For an expression with n variables, 2n tests are required

238
2004 by SEC

BRO Testing

K.C. Tai suggests a condition testing strategy called branch


and relational operator (BRO) testing.
Can detect branch and relational operator errors in a condition
provided that all Boolean variables and relational operators in the
condition occur only once and have no common variable
Uses condition constraint for a condition C which is defined as (D 1, D2,
, Dn) where Di specifies the constraint on the outcome of i-th
condition of C

239
2004 by SEC

BRO Testing (contd)


Boolean variables have constraint on the outcome that must be either
True (t) or False (f)
For relational expression symbols <, >, = are used to specify the
constraints on the outcome of the expression
A condition constraint D for condition C is said to be covered by an
execution of C if, during the execution of C, the outcome of each
simple condition in C satisfies the corresponding constraint in D.

240
2004 by SEC

BRO Testing (contd)

Example C1: B1 & B2


Constraint set = (D1, D2) = {(t,t), (t,f), (f,t)}
If C1 is incorrect due to one or more Boolean operator errors, at least
one of the constraint set will force C1 to fail

Example C2: B1 & (E3=E4)


Constraint set = (D1, D2) = {(t,=), (t,>), (t,<), (f,=)}
Coverage of the preceding constraint set will detect the Boolean and
relational operator errors in C2

Example C3: (E1 > E2) & (E3=E4)


Constraint set = {(>,=), (<,=), (>,>), (>,<), (=,=)}
Coverage of the preceding constraint set will detect the relational
operator errors in C3

241
2004 by SEC

Data Flow Testing

Data flow testing


A testing technique that selects test paths of a program according to the
locations of definitions and uses of variables in the program.
DEF(S) = {X| statement S contains a definition of X}
USE(S) = {X| statement S contains a use of X}

C-use (computation use)


Use in a computation or output statement; associated with each
node

P-use (predicate use)


Use in a predicate; associated with each edge

242
2004 by SEC

Data Flow Testing (contd)


The definition of variable X at statement S is said to be live at
statement S if there exists a path from statement S to statement S that
contains no other definition of X
A definition-use (DU) chain of variable X is of the form [X, S, S],
where S and S are statement numbers, X is DEF(S) and USE(S), and
the definition of X in statement S is live at statement S.

243
2004 by SEC

Data Flow Testing Example

p-use(counter, (5,11))
c-use (largest, 11)

11

exit

public void Largest() {


entry
1
int counter, number, largest;
2
printf("Enter the first number: ");
3
scanf("%d", &largest);
1
4
counter = 2;
5
while( counter <= 10)
{
2
6
printf("Enter next number: ");
7
scanf("%d", &number);
8
if (number > largest)
3
def(largest, 3)
9
largest = number;
10
counter++;
4
def(counter, 4)
}
11
printf ("Largest is %d\n", largest);
p-use(counter, (5,6))
5
}
6
def(number, 7)
7
p-use(number, (8,9))
p-use(largest, (8,9))
8
c-use(number,9)
9
def(largest, 9)
p-use(number, (8,10))
c-use (counter, 10)
10
p-use(largest, (8,10))
def(counter, 10)
244

2004 by SEC

Data Flow Testing Example (contd)

DU testing strategy
A strategy for selecting the derived DU chains as test cases

All use coverage: every DU chain to be covered at least once

DU Chains of the Largest() Example


(3, 11, largest), (3, (8,9), largest), (3, (8,10), largest),
(4, 10, counter), (4, (5,6), counter), (4, (5,11), counter), (10, 10,
counter),
(7, 9, number), (7, (8,9), number), (7, (8,10), number)

245
2004 by SEC

Data Flow Testing Example (contd)

Test paths selected according to all use coverage:


path1 1-2-3-4-5-11 cover (3, 11, largest), (4, (5,11), counter)
path2 1-2-3-4-5-6-7-8-10-5-11 cover (3, (8,10), largest), (4,
(5,6), counter),
path3 1-2-3-4-5-6-7-8-9-10-5-11 cover (3, (8,9), largest), (4, 10,
counter),
path4 1-2-3-4-5-6-7-8-10-5-6-7-8-10-5-11 cover (10, 10,
counter),
path5 1-2-3-4-5-6-7-8-9-10-11-5-6-7-8-10-11 cover (9, (8,9),
largest)
path6 1-2-3-4-5-6-7-8-9-10-5-6-7-8-9-10-5-11 cover (9, (8,10),
largest)

246
2004 by SEC

Loop Testing

Simple Loops (n iterations)

skip the loop entirely


only one pass through the loop
two passes through the loop
m passes through the loop where m < n
n-1, n, n+1 passes through the loop

247
2004 by SEC

Loop Testing (contd)

Nested Loops
conduct simple loop tests for the innermost
loop while holding the outer loops at their
minimum iteration
work outward, conducting tests for the next
innermost loop
continue until all the loops have been tested
tests grow geometrically as the level of nesting
increases

248
2004 by SEC

Loop Testing (contd)

Concatenated Loops
independent loops using simple loop
testing
dependent loops using nested loop testing

249
2004 by SEC

Loop Testing (contd)

Unstructured Loops
Whenever possible, redesign the code to
reflect the use of structured programming
constructs.
Then apply the appropriate loop testing
strategy.

250
2004 by SEC

Test Adequacy Criteria

Test adequacy criteria


Stopping rule determinates whether sufficient testing has been done

How do you know when you have tested enough?

How do you pick test cases?

Control flow coverage criteria


Statement coverage
Edge coverage
Condition coverage
Path coverage

251
2004 by SEC

Black-Box Testing

Black-box testing
Also known as functional testing, behavioral testing, or specificationbased testing
Does not have the knowledge of the programs structures
Discover program errors based on program requirements and product
specifications
Derive sets of inputs to fully exercise all functional requirements for a
program
Complementary to white-box testing

252
2004 by SEC

Black-Box Testing (contd)


Focuses on the functional requirements of the software including
functions, operations, external interfaces, external data and information
Attempts to find errors in the following:

Incorrect of missing functions

Interface errors

Errors in data structures or external database access

Performance errors

Initialization and termination errors

253
2004 by SEC

Random Testing

Random testing is a method that select test cases randomly


from the entire input domain of the program.
The input values of each test case are randomly generated
The overall distribution of the test cases need to conform to the
distribution of input domain or operational profile.

Example: for an ATM system that 80% transactions are withdrawal


transactions and 20% transactions are transfer transactions

80% test cases will be generated randomly to test withdrawal


transaction and 20% test cases will be generated randomly to test
transfer transaction

Random testing is considered to be efficient since test cases can be


generated automatically
However, to obtain a precise operational profile is very difficult

254
2004 by SEC

Partition Testing

Partition testing
The input domain of the program is partitioned into different disjointed
subdomains
Ideally, the partition divides the domain into subdomains with property
that within each subdomain, either the program produces the correct
answer or the program produce an incorrect answer for every element
Only an element randomly selected from each subdomain is needed for
testing the program in order to determine program faults

255
2004 by SEC

Equivalence Partitioning

Equivalence partitioning
The input domain of a program is partitioned into a finite number of
equivalence classes from which test cases are derived
An equivalence class consists of a set of data that is treated the same
by the program or that should generate the same result
Test case design is based on an evaluation of equivalence classes for an
input condition
Can reduce the total number of test cases to be developed

256
2004 by SEC

Equivalence Partitioning (contd)

The equivalence classes are identified based on the set of


valid or invalid states for each input condition

An input condition can be


A specific numeric value
A range of values
A set of related values
A Boolean condition

257
2004 by SEC

Equivalence Partitioning (contd)

The following guidelines can help to define the equivalence


classes [Pressman 2004]:
If an input condition specifies a range, one valid and two invalid
equivalence class are defined.
If an input condition requires a specific value, one valid and two invalid
equivalence classes are defined.
If an input condition specifies a member of a set, one valid and one
invalid equivalence classes are defined.
If an input condition is Boolean, one valid and one invalid classes are
defined.

258
2004 by SEC

Equivalence Partitioning Example

Consider we are writing a program for computing letter


grades based on the numerical scores of students, where
the input variable is Score. The rule of computing the
grade is as follows:
Score

Grade

90~100

80~89

70~79

60~69

0~59

259
2004 by SEC

Equivalence Partitioning Example (contd)

The input domain of Score can be partitioned into 5 valid equivalence


classes and 2 invalid equivalence classes
Valid classes: 0~59, 60~69, 70~79, 80~89, 90~100
Invalid classes: smaller than 0 and greater than 100

Any data value within a class is considered equivalence in terms of testing

Using the equivalence partitioning testing, we can reduce the test cases
from 100 (assume 0 <= score <= 100) to 7

260
2004 by SEC

Boundary Value Testing

Based on programming experience, more errors are found at the


boundaries of an input/output domain than in the center.

In addition to select test data inside an equivalence class, data at the


edges of the equivalence class also need to be examined

user
mouse output promptsFK
queries picks formats
input

input domain
Note: Redraw from [Pressman 2004]

data

output domain

261
2004 by SEC

Boundary Value Testing (contd)

Boundary value analysis (BVA)


A test case design technique complements to equivalence partition
Rather selecting any element from an equivalence class, BVA leads to
the selection of test cases that exercise bounding values (edge of the
class)
Unlike equivalence partition that derives test cases only from input
conditions, BVA derives test cases from both input conditions and
output domain

262
2004 by SEC

Boundary Value Testing (contd)

Guidelines [Pressman 2004]:


1.

If an input condition specifies a range [a, b], test cases should be


designed with value a and b, just above and below a and b

2.

Example: Integer D with input condition [-3, 5], BVA test values
are -3, -2, 5, 6, 0

If an input condition specifies a number values, test cases should be


developed to exercise the minimum, number, maximum number, and
values just above and below minimum and maximum

Example: Enumerate data E with input condition: {3, 5, 100, 102},


BVA test values are 3, 102, 2, 4, 101, 103

263
2004 by SEC

Boundary Value Testing (contd)


3.

Guidelines 1 and 2 are applied to output condition

4.

If internal program data structures have prescribed boundaries, be


certain to design a test case to exercise the data structure at its
boundary

Array input condition:


Empty, single element, full element, out-of-boundary

Search output condition:


Element is inside array or the element is not inside array

264
2004 by SEC

Decision Table-Based Testing

Partition testing and boundary value testing assume that the


input variables of program are independent
In reality, variables can depend on each other

Decision table is a way to describe how different combinations


of inputs may produce outputs

A decision table includes two parts:


All possible input conditions and the different combinations
All possible actions and corresponding responses to different input
conditions

The two parts together specify under what condition will an


action be performed

265
2004 by SEC

Decision Table-Based Testing (contd)

Consider an ATM system for providing withdrawal transaction


service. The relevant conditions and actions of the system are:
C1: The ATM card is valid
C2: The password matches
C3: There is enough money in the ATM machine
A1: Dispense money
A2: Prompt to indicate not enough money
A3: Prompt to indicate invalid ATM card or password

266
2004 by SEC

Decision Table-Based Testing (contd)

The decision table is


1

C3

A1

C1
C2

A2
A3

X
X

C: denotes a condition
A: denotes an action
T: denotes true
F: denotes false
X: denotes action to be taken.

267
2004 by SEC

Decision Table-Based Testing (contd)

Action A1 is performed when conditions C1, C2, and C3 are true

Action A2 is performed when conditions C1 and C2 are true and C3 is


false

Action A3 is performed when condition C1 is false or C2 is false

268
2004 by SEC

Error Guessing

Identify potential errors and design test cases based on intuition


and experiences
Test cases can be derived by making a list of possible errors or
error-prone situations

Empty or null lists


Zero instances or occurrences
Blanks or null strings
Negative numbers
Maintain a history of defect

269
2004 by SEC

A Strategic Approach to Software


Testing

Testing begins at the module level and works outward toward


the integration of the entire computer-based system.

Different testing techniques are appropriate at different points


in time.

Testing is conducted by the developer of the software and (for


large projects) an independent test group.

Testing and debugging are different activities, but debugging


must be accommodated in any testing strategy

270
2004 by SEC

Unit Testing

Unit testing
Is normally considered as an adjunct to the coding step
Focuses verification effort on the smallest unit of software design the
software component or module
Using the component-level design description as a guide
Provide a release criterion for a programming task
Encourage early defect discovery
Discourage big-bang integration with its late defect discovery
Find "side effect" defects, especially in highly coupling designs.
Is white-box oriented and the step can be conducted in parallel for
multiple components

271
2004 by SEC

Unit Testing (contd)

Module

interface
local data structures
boundary conditions
independent paths
error-handling paths

Test
Cases
272

Note: Redraw from [Pressman 2004]

2004 by SEC

Considerations of Unit Test

Interface
Ensures that information properly flows in and out of the component

Local data structures


Ensures that data stored temporarily maintains its integrity during
execution

Boundary conditions
Ensures that the component operates properly at boundaries established
to limit or restrict processing

Independent paths (basis paths)


Ensures that all paths in a component have been executed at least once

Error-handling paths
Ensures that errors are correctly handled

273
2004 by SEC

Unit Test Cases

Unit test cases should be designed to uncover errors due to


erroneous computation, incorrect comparisons, or improper
control flow

Common errors in computation


Misunderstood or incorrect arithmetic precedence
Mixed mode operations
Incorrect initialization
Precision inaccuracy
Incorrect symbolic representation of an expression

274
2004 by SEC

Unit Test Cases (contd)

Common errors in comparison and control flow


Comparison of different data types
Incorrect logical operators or precedence
Expectation of equality when precision error makes equality unlikely
Incorrect comparison of variables
Improper or nonexistent loop termination
Failure to exit when divergent iteration is encountered
Improperly modified loop variables

275
2004 by SEC

Unit Test Cases (contd)

What should be tested when error handling is evaluated?


Error description is unintelligible
Error noted does not correspond to error encountered
Error condition causes system intervention prior to error handling
Exception-condition processing is incorrect
Error description does not provide enough information to assist in the
location of the cause of the error

Boundary testing
An important task of the unit test step
Test cases that exercise data structure, control flow, and data values just
below, at, and just above maxima and minima are vary likely to uncover
errors

276

2004 by SEC

Unit Test Procedure

Review of design information (provided as guidance) to


establish test cases that are likely to uncover errors previous
noted

Each test case should be couple with a set of expected results

Develop driver and/or stub software for each unit test


Driver: nothing more than a main program that accept test case data,
passes such data to the component to be tested, and prints relevant
results
Stub: serves to replace modules that are subordinate called by the
component to be tested.
Drivers and stubs represent overhead

Execute and evaluate the unit test

277
2004 by SEC

Unit Test Environment

Driver

Module
to be
tested
Stub

interface
local data structures
boundary conditions
independent paths
error-handling paths

Stub

results

Test
Cases
278

Note: Redraw from [Pressman 2004]

2004 by SEC

JUnit

JUnit
An Open source Unit Test Framework for Java (http://www.junit.org)

Provides the test drivers for unit testing

Provides automatic test runs

Provides automatic result checks

The Steps of using JUnit

Write a test case

Run the test

Verify the result

279
2004 by SEC

JUnit (contd)

Write a test case


Create your own test case as a subclass of JUnit TestCase.
Override the setUp() method to initialize object(s) under test
Override the tearDown() method to release object(s) under test

Run the test


Define a public test???() method for exercising the object(s) under test

Verify the result


Assert expected result of the test case using assertEquals()

Error vs. Failures


Error: unanticipated problem like an
ArrayIndexOutOfBoundsException
Failure: is anticipated and can be checked with assertions

280
2004 by SEC

JUnit Example for binarySearch


import junit.framework.TestCase;
public class TestBinarySearch extends TestCase {
BinarySearch search;
int sortedArray[];
int sortedArray2[]={2,4,6};
int sortedArray3[]={2,4,6,8,10};

public void test_case1() {


assertEquals(search.binarySearch(sortedArray,2),-1);
}
public void test_case2() {
assertEquals(search.binarySearch(sortedArray2,8),-1);
}
public void test_case3() {
assertEquals(search.binarySearch(sortedArray3,6),2);
}
public void test_case4() {
assertEquals(search.binarySearch(sortedArray3,4),1);
}
public void test_case5() {
assertEquals(search.binarySearch(sortedArray3,10),4);
}
// test case for showing the JUnit failure
public void test_case6() {
assertEquals(search.binarySearch(sortedArray3,7),4);
}

public TestBinarySearch(String name) {


super(name);
}
public static void main(String[] args) {
junit.swingui.TestRunner.run(TestBinarySearch.cl
ass);
}
void setUp() throws Exception {
super.setUp();
search=new BinarySearch();
sortedArray=new int[0];
}
protected void tearDown() throws Exception {
super.tearDown();
}

281
2004 by SEC

JUnit Example for binarySearch (contd)

282
2004 by SEC

Integration Testing

Big bang (non-incremental integration)


All components are combined in advance. The entire program is tested
as a whole
When a set of errors is encountered, correction is difficult because
isolation of causes is complicated by the vast expanse of entire
program
Once these errors are corrected, new ones appear and the process
continues in a seemingly endless loop

283
2004 by SEC

Integration Testing (contd)

Incremental integration
The program is constructed and tested in small increments, where
errors are easier to isolate and correct
Interfaces are more likely to be tested completely
A systematic test approach may be applied

Top-down integration

Bottom-up integration

Sandwich testing (combination of above two approaches)

284
2004 by SEC

Top Down Integration

Modules are integrated by moving download through the


control hierarchy
Beginning with the main control module (main program)
Modules subordinate (and ultimately subordinate) to main control
module are incorporated into the structure in either a depth-first or
breadth-first manner

285
2004 by SEC

Top Down Integration (contd)

The integration process:


The main control module is used as a test driver and stubs are substituted
for all components directly subordinate to the main control module
Depending the depth-first or breadth-first, subordinate stubs are replaced
one at a time with actual components
Test are conducted as each component is integrated
On completion of each set of tests, another stub is replaced with the real
component
Regression testing may be conducted to ensure that new errors have not
been introduced
Repeat from step 2 until the entire program structure is built

286
2004 by SEC

Top Down Integration (contd)


M1
M1

M2
M2

M5
M5

M3
M3

M6
M6

M8
M8

M7
M7

top module is
tested with stubs
M4
M4
stubs are replaced
one at a time

as new modules are integrated,


some subset of tests is re-run
287

Note: Redraw from [Pressman 2004]

2004 by SEC

Top Down Integration (contd)

Advantages
Is better at discovering errors in the system architecture (verifies major
control or decision points early)
Can demonstrate a complete function of the system early (if depth-first
integration is selected)
Disadvantages
Logistical problems can raise
Need to write and test stubs (costly)

To solve the logistical problem:


Delay many tests until stubs are replaced with actual modules
Develop stubs that perform limited functions that simulate the actual
module (requires significant overhead)
Integrate the software from the bottom of the hierarchy upward

288
2004 by SEC

Bottom Up Integration

Begins construction and testing with atomic modules (i.e.,


components at the lowest levels in the program structure).

The integration process:


Low-level components are combined into clusters (sometimes called
builds) that perform a specific software subfunction
A test driver is written to coordinate test case input and output
The cluster is tested
The test drivers are removed and clusters are combined moving upward
in the program structure.

As the integration moves upward, the need for separate test


drivers lessens.

289
2004 by SEC

Bottom Up Integration (contd)


M
Mc c
M
Ma a
D1
D1

M
Mb b
D2
D2

D3
D3

Cluster 3
Cluster 1

Cluster 2
290

Note: Redraw from [Pressman 2004]

2004 by SEC

Bottom Up Integration (contd)

Advantages
Easier test case design and no need for stubs
Can starts at an early stage in the development process (not require to
wait until the architectural design of the system to be completed)
Potentially reusable modules are adequately tested

Disadvantages
User interface components are tested last
The program as an entity does not exist until the last module is added
Major design faults show up late

291
2004 by SEC

Sandwich Integration Testing

The advantages of one integration strategy tend to result in


disadvantages for the other strategy.

In practice, most integration involves a combination of both


the top-down and bottom-up integration strategies, i.e.,
sandwich integration and testing

The sandwich integration and testing


The decision modules (logic modules) are integrated and tested topdown so that major design faults can be revealed early
The worker modules (operational modules) are integrated and tested
bottom-up so that the potentially reusable modules are adequately tested
while reducing the constructions of test stubs
The sandwich integration and testing has the strengths of both top-down
and bottom-up integration strategies while avoiding their weaknesses

292

2004 by SEC

Regression Testing

Each time a new module is added as part of integration


testing, or a bug is fixed (as the results of uncovering errors
through testing) in the software, the software changes.

These changes may cause problems with functions that


previously worked.

Regression testing is the re-execution of some subset of tests


that have already been conducted to ensure that changes have
not generated unintended side effects.

293
2004 by SEC

Regression Testing (contd)

Regression testing may be conducted


Manually by re-executing a subset of all test cases
Using automated capture/playback tools enable software engineer to
capture test cases and results for subsequent playback and comparison.

The regression test suite contains three different classes of test


cases:
A representative sample of tests that will exercise all software functions
Additional tests that focus on software functions that are likely to be
affected by the change
Tests that focus on the software components that have been changed

294
2004 by SEC

Regression Testing (contd)

As integration testing proceeds, the number of regression tests


can grown quite large
The regression test suite should be designed to include only those tests
that address one or more classes of errors in each of the major program
functions.
It is impractical and inefficient to re-execute every test for every
program function once a change has occurred

295
2004 by SEC

System Testing

System testing
The system software is tested as a whole. It verifies all elements mesh
properly to make sure that all system functions and performance are
achieved in the target environment.

The focus areas are

System functions and performance


System reliability and recoverability (recovery test)
System installation (installation test)
System behavior in the special conditions (stress and load test)
System user operations (acceptance test/alpha test)
Hardware and software integration and collaboration
Integration of external software and the system

System testers: test engineers in ITG or SQA people.

296
2004 by SEC

System Testing (contd)

Recovery tests
Verify that the system can recover when forced to fail in various ways
database recovery is particularly important
Example: measure time to recover (MTTR)

Stress tests
Verify that the system can continue functioning when confronted with
many simultaneous requests (abnormal situations)
Execute the system by demanding resource in abnormal quantity,
frequency, or volume (subject to extreme data & event traffic )
Excessive interrupt, high input data rate, maximum memory,
How high can we go? Do we fail-soft or collapse?
Sensitivity testing (a variation of stress testing)
Attempts to uncover data combinations within valid input classes that
may cause instability or improper processing (performance
degradation)

297
2004 by SEC

System Testing (contd)

Security tests
Verify that access protection mechanisms work make penetration cost
more than value of entry
Subject to compromise attempts
E.G., Measure average time to break in

Performance
Is designed to test the run-time performance of software (real-time and
embedded systems) within the context of an integrated system
Measure speed, resource utilization under various circumstances.
Is often coupled with stress testing and usually requires both hardware
and software instrumentation
Occurs throughout all steps in the testing process

298
2004 by SEC

Alpha and Beta Testing

Alpha and beta testing


When software is developed as a product to be used by many customers, a
process called alpha and beta testing is used to uncover errors that only
end-user seems able to find.

Alpha Tests

Conducted at developers site


Conducted by customer
Developer looks over the shoulder
Developer records the errors and problems
Conducted in a controlled environment

299
2004 by SEC

Alpha and Beta Testing (contd)

Beta Tests

Conducted at one or more customer sites


Conducted by end-user
Developer is not present
Uncontrolled environment
Errors may be real or imagined
Customer reports the errors
Accordingly modifications are made
Final product is released

For commercial products - testing is done

300
2004 by SEC

Acceptance Testing

Acceptance tests are performed after system testing if the


software is being developed for a specific client

Acceptance tests are usually carried out by the clients or end


users

Acceptance test cases are based on requirements


User manual can be an additional source for test cases
System test cases can be reused

301
2004 by SEC

Acceptance Testing (contd)

The software must run under real-world conditions on


operational hardware/software

The clients determine if the software meet their requirements

302
2004 by SEC

Object-Oriented Testing

Although there are similarities between testing conventional systems and


Object-Oriented systems, Object-Oriented testing has significant
differences

The characteristics of Object-Oriented systems influence both testing


strategy and testing methods.
The class become the natural unit for test case design
Implications of Object-Oriented concepts such as inheritance, encapsulation, and
polymorphism pose testing challenges
Testing the state-dependent behavior of Object-Oriented systems become important
since no clear control flow in Object-Oriented programs
Integration strategies change significantly since no obvious top module to the
system for top-down integration

303
2004 by SEC

Unit Testing in the OO Context

Smallest testable unit is the encapsulated class


A single operation needs to be tested as part of a class hierarchy
because its context of use may differ subtly
Inheritance allows an operation exists in many different classes where the
operation is applied within the context of different attributes and is used
in various subtle ways

Class testing is the equivalent of unit testing in conventional


software
Approach:
Methods within the class are tested
The state behavior of the class is examined

Unlike conventional unit testing which focuses on the inputprocess-output view of software, algorithm detail of a module,
and the data that flow across the module interface, class testing
focuses on designing sequences of methods to exercise the states
of a class
But white-box methods can still be applied

304

2004 by SEC

Integration Testing in OO Context

The OO integration strategy changes dramatically


OO does not have a hierarchical control structure so conventional topdown and bottom-up integration tests have little meaning.
Integrating operations one at a time into a class is often impossible
because the direct and indirect interactions of the components that
make up the class

OO integration applied three different incremental strategies


Thread-based testing: integrates classes required to respond to
one input or event.
each thread is integrated and tested individually.

305
2004 by SEC

Integration Testing in OO Context (contd)

Use-based testing: integrates the set of classes required to


respond to use dependency
independent classes: use very few (if any) of server classes
dependent classes: the classes use independent classes
testing the independent classes first and then dependent classes

Cluster testing: integrates classes required to demonstrate one


collaboration
A cluster of collaborating classes is tested to uncover the collaborating
errors

306
2004 by SEC

Validation Testing in an OO Context

At the validation or system level, the details of class connections


disappear
Like conventional validation, the OO validation focuses on uservisible actions and user-recognizable outputs
Approach:
Use-case scenarios from the analysis model has a high likelihood to
uncover errors of user interaction requirements
Conventional black-box testing methods can be used to create a deficiency
list
Test cases may be driven from the object-behavior model and from event
flow diagram created as part of OOA
Acceptance tests through alpha (at developers site) and beta (at customers
site) testing with actual customers

307
2004 by SEC

OOTTest Case Design

Berard in his book, Essays on Object-Oriented Software


Engineering, proposes the following approach for OO test
case design:
Each test case should be uniquely identified and should be explicitly
associated with the class to be tested
The purpose of the test should be stated
A list of testing steps should be developed for each test and should
contain:
A list of specified states for the object that is to be tested
A list of messages and operations that will be exercised as a
consequence of the test
A list of exceptions that may occur as the object is tested
A list of external conditions (i.e., changes in the environment
external to the software that must exist in order to properly
conduct the test)
Supplementary information that will aid in understanding or
implementing the test

308

2004 by SEC

OOTTest Case Design (contd)

Fault-based testing
The tester looks for plausible faults (i.e., aspects of the implementation
of the system that may result in defects). To determine whether these
faults exist, test cases are designed to exercise the design or code.

Class Testing and the Class Hierarchy


Inheritance does not obviate the need for thorough testing of all
derived classes. In fact, it can actually complicate the testing process.

Scenario-Based Test Design


Scenario-based testing concentrates on what the user does, not what
the product does. This means capturing the tasks (via use-cases) that
the user has to perform, then applying them and their variants as tests.

309
2004 by SEC

OOT Methods: Random Testing

Random testing
Identify operations applicable to a class
Define constraints on their use
Identify a minimum test sequence

An operation sequence that defines the minimum life history of the


class (object)

Generate a variety of random (but valid) test sequences

Exercise other (more complex) class instance life histories

310
2004 by SEC

OOT Methods: Partition Testing

Partition testing
Reduces the number of test cases required to test a class in much the same
way as equivalence partitioning for conventional software
State-based partitioning
Categorize and test operations based on their ability to change the
state of a class
Attribute-based partitioning
Categorize and test operations based on the attributes that they use
Category-based partitioning
Categorize and test operations based on the generic function each
performs

311
2004 by SEC

OOT Methods: Inter-Class Testing

Inter-class testing
For each client class, use the list of class operators to generate a series
of random test sequences. The operators will send messages to other
server classes.
For each message that is generated, determine the collaborator class
and the corresponding operator in the server object.
For each operator in the server object (that has been invoked by
messages sent from the client object), determine the messages that it
transmits.
For each of the messages, determine the next level of operators that are
invoked and incorporate these into the test sequence

312
2004 by SEC

OOT Methods: State-Based Testing

State-based testing
Basic idea is to derive tests from the object-behavioral analysis model
to check the state behaviors of a system.
A state machine (state transition diagram or statechart) is used to define
test cases and test criteria to uncover the incorrect state behavior of a
program.

Coverage criteria:
State node coverage
Transition path coverage

Applications:
Very useful to check protocol-based program communications.
Good to check problems in state-driven or event-driven application
programs.
Can be used at both specification and code levels

313
2004 by SEC

OOT Strategy

Class testing is the equivalent of unit testing


Operations within the class are tested
The state behavior of the class is examined

Integration applied three different strategies


Thread-based testingintegrates the set of classes required to respond to
one input or event
Use-based testingintegrates the set of classes required to respond to
one use case
Cluster testingintegrates the set of classes required to demonstrate one
collaboration

314
2004 by SEC

Exercises

315
2004 by SEC

Reference

[Beizer 1990] B. Beizer, Software Testing Techniques, 2nd Edition, Van Nostrand-Reinhold,
1990.
[Boehm 1981] B. Boehm, Software Engineering Economics, Prentice-Hall, 1981.
[Davis 1995] A. Davis, 201 Principles of Software Development, McGraw-Hill, 1995.
[Gao 2003] Jerry Gao, Jacob Tsao, and Ye Wu, Testing and Quality Assurance for
Component-Based Software, Artech House, 2003.
[Kaner 1993] C. Kaner, J. Falk, and H. Q. Nguyen, Testing Computer Software, 2nd Edition,
Van Nostrand-Reinhold, 1993.
[Myers 1979] G. Myers, The Art of Software Testing, Wiley, 1979.
[Pressman 2004] Roger S. Pressman, Software Engineering A practitioners Approach, 6th
Edition, McGraw Hill, 2004.
[Sommerville 2004] Ian Sommerville, Software Engineering, 7th Edition, Addison Wesley,
2004.

316
2004 by SEC

Reference (contd)

[Hetzel 1984] W. Hetzel, The Complete Guide to Software Testing, QED Information
Sciences, 1984.

[Tai 1989] K. C. Tai, What to Do Beyond Branch Testing, ACM Software Engineering
Notes, vol. 14, no. 2, April 1989, pp. 58-61.

[Whittaker 2000] James A. Whittaker, What Is Software Testing? And Why Is It So Hard,
IEEE Software, 2000.

[Weyuker 1991] E. Weyuker and B. Jeng, Analyzing Partition Testing Strategies, IEEE
Transaction on Software Engineering, Vol. 17, No. 7, 1991, pp. 703-711.

317
2004 by SEC

Chapter 7
Software Project Management and
Planning

2004 by SEC

Chapter 7
Software Project Management and
Planning
7.1 Project Management Concepts
7.2 People Management
7.2.1 Team Building
7.2.2 Other Team types
7.2.3 Team Management
7.3 Process Management
7.3.1 Process Attributes
7.3.2 Process Modeling and Analysis
7.3.3 Process Measurement

319
2004 by SEC

Chapter 7
Software Project Management and
Planning (contd)
7.4 Product Management
7.4.1 Project Planning
7.4.2 Work Breakdown Structure
7.4.3 Software Cost Estimation
7.5 Risk Analysis and Management
7.5.1 Risk Management Concepts
7.5.2 Risk Identification
7.5.3 Risk Analysis
7.5.4 Risk Planning
7.5.5 Risk Monitoring

320
2004 by SEC

Chapter 7
Software Project Management and
Planning (contd)
7.6 Software Configuration Management
7.6.1 Configuration Management Concepts
7.6.2 Software Configuration
7.6.3 Change Control
7.6.4 Version Control
Exercise

321
2004 by SEC

7.1 Project Management Concepts

2004 by SEC

Goals

To ensure that software is developed according to its


requirements

To ensure that software and other artifacts are delivered on


time and within budget

323
2004 by SEC

Activities

Project planning

Project scheduling

Project costing

Team building, personnel selection and evaluation

Project monitoring

Post project review

Proposal writing, report writing, and presentation

324
2004 by SEC

Software Characteristics and Project


Management

The basic management activities for most engineering are


very much the same
Most concepts and techniques in engineering project management are
applicable to software project management

Software characteristics
The product is intangible and only visible late in project
The product is flexible and prone to changes
The development process is not standardized

325
2004 by SEC

7.2 People management


7.2.1 Team Building
7.2.2 Other Team Types
7.2.3 Team Management

2004 by SEC

7.2.1 Team building

Staffing

Selecting people

Working environment

327
2004 by SEC

Staffing

Conventional Team Organization


Project manager
System analyst
System architect
Programmers
Testers
Secretary and logistic support

328
2004 by SEC

Staffing (contd)

Consideration for selecting people


In most project, there is less workload at initial and final stages
Needs to average out the workload by proper staffing
Resource allocation

Development center
A pool of programmer and testers are available to all projects in the
organization
Programmers can be assigned to different project on demand basis
Can be outsourced

329
2004 by SEC

Selection of People

Criterion
Domain knowledge and experiences
Education background
Personality, attitude, and willingness to work in a team
Enrichment and diversity of the team

Appointment decision
Information provided by the candidate (e.g., CV)
Information gathered at interview
Recommendation from other people

330
2004 by SEC

Working Environment

Physical workspace is an important factor on productivity and


satisfaction

Health and safety consideration


Lighting, air conditioning and heating, furniture

Privacy and personalization


A personal space can provide engineers an area of uninterrupted work
and increased productivity

Team space is needed for meeting and informal gathering

331
2004 by SEC

7.2.2 Other Team Types

Chief programming team

Pair programming

332
2004 by SEC

Chief Programming Team

Proposed by IBM and used in New York Times project in early


70s

Consists of
Chief programmer: responsible for design, programming, testing and
installation
Back-up programmer: supports the chief programmer and does software
validation
Librarian: maintains the project production library and documentation
Programmer (usually less than 5): coding

333
2004 by SEC

Problems in Chief Programmer Team

Difficult to find chief programmer


Must be both a highly talented programmer and a successful manager

Almost impossible to find back-up programmer


Should be as competent as chief programmer but has to take the back
seat

Organisational structures and grades may be unable to


accommodate this type of group

334
2004 by SEC

Pair programming

From extreme programming

Two people are assigned to the same task


Work and sit together
Share only one set of computer equipment
When one works, the other is supposed to observe and review the
peers work

335
2004 by SEC

7.2.3 Team Management

Team cohesiveness and team communication

Retaining and motivating people

336
2004 by SEC

Team Cohesiveness

Advantages of a cohesive team


Team quality can be developed
Team members work closely together an learn from each other
Team members know each others work and continuity can be
maintained if a member leaves
Egoless programming can be practiced as programs are regarded as
team property

How to build a cohesive team


Emphasis on performance
Leadership to share information to encourage trust and responsibility

337
2004 by SEC

Team Communication

Good communication are necessary for team working and


strengthening the team cohesiveness

Factors
Team size
Organizational structure: are members need to communicate through
mediators or the management?
Team composition
Physical working environment and working space layout

338
2004 by SEC

Retention of People

Turn over rate for IT professionals is about 20%

Factors
Organizational commitment: an individuals identification with the
organization
Organizational citizenship behaviors: employees willingness to do
more work then assigned
Human resource management practices: empowering, perceived
justice, training, work family conflict resolution, information sharing
Compensation: salary, bonus, and other benefits

Not really important

Demographic diversity: age, organizational tenure, education

339
2004 by SEC

Motivating People

People are motivated by satisfying their needs

Human needs hierarchy


Physiological needs
Safety needs
Social needs
Esteem needs

To satisfy social needs


Time and space for people to meet co-workers
Informal and easy to access communication channels

E-mail, caf, social clubs

340
2004 by SEC

Motivating People (contd)

To satisfy esteem needs


To show people that they are valued

Public recognition, pay raise

Training and more responsibility


Emphasis on performance

341
2004 by SEC

7.3 Process Management


7.3.1 Process Attributes
7.3.2 Process Modeling and Analysis
7.3.4 Process Measurement

2004 by SEC

Process Management

Goal
To improve product quality by improving process

To reduce defects in product

Process/product relationship is not obvious in intangible product (e.g.,


software)

Factors on product quality


Process quality: more important for larger project
People quality: most important factor
Development technology: more important for smaller project
Cost, time, schedule: practically the dominating factor for most
organization

343
2004 by SEC

Process Attributes

Understandability
Is it easy to understand the defined process

Visibility
Are the activities, their progress and results visible by external
observers

Supportability
Can the process activities be supported by automated tools

Acceptability
Are the process activities acceptable to engineers

344
2004 by SEC

Process Attributes (contd)

Reliability
Can the defined process avoid product error

Robustness
Can the process tolerate exceptional conditions

Maintainability
Can the process evolve as organization and environment change

Rapidity
How fast the process can deliver a system

345
2004 by SEC

7.3.2 Process Modeling and Analysis

Process modeling elements

Process modeling and analysis techniques

346
2004 by SEC

Process Analysis and Modeling

Modeling elements

Process modeling techniques

Process analysis technique

347
2004 by SEC

Modeling Elements

Activity
An activity is an action that has a clearly defined goal, an entry
condition and an exit condition

Process
A set of activities that must be done as a whole

Deliverable
A tangible output

Condition
Either a pre-condition or a post-condition

348
2004 by SEC

Modeling Elements (contd)

Role
A person with responsibilities for accomplishing some activities

Exception
Some unexpected events

Communications
Interchange of information between roles, activities, and processed

349
2004 by SEC

Process Modeling Techniques

State machines

Petri net

350
2004 by SEC

Process Analysis Techniques

Published standard or process models


CMMI, ISO 9000

Questionaire and interview

Ethnographic analysis
By observation of people in working

351
2004 by SEC

7.3.4 Process Measurement

To collect data for possible improvement

Data collected
Time: calendar time or efforts
Resources: human resources or other physical resources
Events: number of defects discovered

Goal-question-metric paradigms
Goal: what needed to be achieved
Question: specific areas related to goals
Metric: measurement

352
2004 by SEC

7.4 Software Project Planning and


Scheduling
7.4.1 Project Planning
7.4.2 Work Breakdown Structure
7.4.3 Software Cost Estimation
7.4.4 Project Scheduling

2004 by SEC

7.4.1 Project Planning

Planning and scheduling

Project planning steps

354
2004 by SEC

Software Project Planning and


Scheduling

Project planning: to provide a framework for managers to


monitor and control a software project

Project scheduling: to estimate what will be done by when


and by whom

355
2004 by SEC

Project Planning Steps

Work breakdown and effort estimation of each task

Risk analysis and risk management

Project scheduling

Control and monitoring plan

356
2004 by SEC

7.4.2 Work Breakdown Structure

357
2004 by SEC

Work Breakdown Structure

To decompose the work of a project into a number of smaller


task

For software project, start with the development process


phases
Continue decompose the tasks until each task can be

Estimated

Assigned to an individual or a team

358
2004 by SEC

Work Breakdown Structure (contd)

359
2004 by SEC

7.4.3 Software Cost Estimation

Software project estimation

Function point analysis and object point

COCOMO-81 and COCOMO-2

360
2004 by SEC

Software Project Estimation

Estimation objectives
Budget and pricing for a software project
Project scheduling and monitoring
Cost database

Estimation accuracy
Planning phase: 50% ~ 100%
Requirement and definition phase: 25% ~ 50%
Design phase: 10% ~ 25%

361
2004 by SEC

Software Cost Components

Machine and tool costs

Training and travel

Efforts
Engineer salaries, benefits, and overhead

Insurances

Office, phone and networking, shared facilities and supporting

About 1M NT/per year in Taiwan

362
2004 by SEC

Estimation Techniques

Professional or expert judgment


By experts with experiences in developing software in the application
domain

Past project experiences


Comparing to similar project in cost datsbase

Algorithmic cost modeling


Function point analysis and object point
COCOMO and COCOMO 2

363
2004 by SEC

Function Point Analysis (FPA)

Aims to provide a standardized methodology for measuring


various functions of a software system
From users point of view: based on user requests and reception of
returns

Function point measurement


Unadjusted function points: functional size measurement, by
assignment weights to each function
Value adjustment factor: take environmental and processing
complexity into consideration

364
2004 by SEC

FPA Measurement Process

Analyze the project documentation to obtain a list of logical


files

Identify the boundary between the application and its external


environment, and classify logical files into
Internal logical files
External interface files

Count number of data element types, record element types,


and file types

Compute the function points of all logical files and add them
to produce unadjusted function points

365
2004 by SEC

Function Point Calculation

Based on a combination of program size and technical


complexity
Internal logical files
external interface files
External inputs
External outputs
External inquiries

A weight is associated with each characteristics


Low (e.g., 7)
Average (e.g., 10)
High (e.g., 15)

366
2004 by SEC

Function Point Calculation (contd)

The unadjusted function point (UFP) is computed by


multiplying each raw count with the weight and summing all
values

The UFP is multiplied by a complexity adjustment factor


The adjustment factor is between 0.65 and 1.35
Computed from general system characteristics (GSC) to assess the
environment and processing complexity

367
2004 by SEC

Function Point Calculation (contd)


Functional type

Count

Scale

Weight

Sum

Internal logical files

Average

10

30

External interface files

Average

External inputs

Average

External output

Average

10

External inquiries

Average

20

Count total

68

Complexity

0.77

Functional point

52

368
2004 by SEC

Usage of Function Point

FPs can be used to estimate LOC (Lines of Code) or efforts


(in man-month)
Language dependent: different languages have different LOC or manmonth per FP
LOC = AVC * number of function points
AVC is a language-dependent factor varying from 200-300 for
assemble language to 2-40 for a 4GL

FPs are very subjective and dependent on the estimator


Difficult to have automatic function-point counting

369
2004 by SEC

Usage of Function Point (contd)

Work-effort = 0.2 * TDET + 2.71 * TGRE + 79


Work-effort: person-days
TDET: number of data elements

Unique user identifiable field on an internal logical file or external


interface file (e.g., var or field in structure)

TGRE: number of data element groups

Unique user identifiable subgroup of data elements within an


internal logical file or external interface file (e.g., structure, union,
or other record type)

370
2004 by SEC

Object Point

Object points are an alternative to function point when 4GLs


or object-oriented languages are used for development

Object points are not number of object classes

The number of object points in a program is a weighted


estimate of
The number of separate screens that are displayed
The number of reports that are produced by the system
The number of code modules that must be developed

371
2004 by SEC

Object Point (contd)

Object points are easier to estimate from a specification than


function points as they are simply concerned with screens,
reports and code modules

They can be estimated at an early point in the development


process.

Can be used for web-based development

372
2004 by SEC

COCOMO/COCOMO 2
Constructive Cost Model

An empirical model based on database of different projects

History
COCOMO 81 (original COCOMO model)

Classify project into three classes

Basic, intermediate and advanced stages

Estimate project efforts, duration and staff from lines of code

COCOMO 2

Three levels: different development stage

Takes into account on development approaches, component reuse,


etc

More complicated

373
2004 by SEC

Project Classes in COCOMO 81

Organic mode:
Small teams, in familiar environment, well-understood applications, no
difficult non-functional requirements
Examples: most simple data processing

Semi-detached mode
Project team may have experience mixture, system may have more
significant non-functional constraints, organization may have less
familiarity with application
Examples: transaction processing, distributed data collection and
monitoring

374
2004 by SEC

Project Classes in COCOMO 81


(contd)

Embedded
Hardware/software systems, tight constraints, highly distributed and
networking requirements
Examples: real-time systems, embedded software

375
2004 by SEC

COCOMO 81 Stages

Basic
Gives a 'ball-park' estimate based on product
attributes

Intermediate
Modifies basic estimate using project and process attributes

Advanced
Estimates project phases and parts separately

376
2004 by SEC

COCOMO 81 Estimates

Primary parameter
Lines of code
KDSI (thousands of delivered source instructions)

Estimates
Project efforts: in terms of man-month
Project duration
Staffing requirements

377
2004 by SEC

Basic COCOMO 81 Formula

Organic mode
Man-month (PM) = 2.4 (KDSI) 1.05

Semi-detached mode
Man-month (PM) = 3 (KDSI) 1.12

Embedded mode
Man-month (PM) = 3.6 (KDSI) 1.2

378
2004 by SEC

Project Duration and Staffing

Organic
Calendar time (TDEV) = 2.5 (PM) 0.38

Semi-detached
Calendar time (TDEV) = 2.5 (PM) 0.35

Embedded mode
Calendar time (TDEV) = 2.5 (PM) 0.32

Personnel requirement: N = PM/TDEV

379
2004 by SEC

Examples

Organic mode project, 44 KLOC


PM = 2.4 (44) 1.05 = 128 person months
TDEV = 2.5 (128) 0.38 = 16 months
N = 128/16 = 8 people

Embedded mode project, 44 KLOC


PM = 3.6 (44)1.2 = 338 person-months
TDEV = 2.5 (338)0.32 = 16 months
N = 338/16 = 21 people

380
2004 by SEC

Examples

Organic mode project, 128 KLOC


PM = 2.4 (128) 1.05 = 392 person months
TDEV = 2.5 (392) 0.38 = 24 months
N = 392/24 =16 people

Embedded mode project, 128 KLOC


PM = 3.6 (128)1.2 = 1216 person-months
TDEV = 2.5 (1216)0.32 = 24 months
N = 1216/24 = 51 people

381
2004 by SEC

COCOMO 2

COCOMO 2 consists of three models that allow increasingly


detailed estimates to be made as development progresses
Application composition (or early prototyping) model

Used during the early stages of a project

Estimates based on object points and a simple formula is used for


effort estimation

Early design model

Used when requirements are stabilized

Estimates based on function points that are translated to LOC

Post-architecture model

Used during development stages

Estimates based on lines of source code

382
2004 by SEC

Early Prototyping Model

Used during the early stages of a project

To estimate the efforts for prototyping or for projects that is


composed of components

Based on weighted object points

Formula
PM = ( NOP (1 - % of reuse/100 ) ) / PROD

PM is the effort in person-months

NOP is the number of object points

PROD is the productivity

383
2004 by SEC

Early Design Model

Estimates is made after the requirements have been stabilized

Based on standard algorithmic models


PM = A SizeB M + PMm

M = PERS RCPX RUSE PDIF PREX FCIL SCED


PMm = (ASLOC (AT/100)) / ATPROD

A = 2.5 in initial calibration

Size in KLOC

B ranges from 1.1 to 1.24 depending on novelty of the project,


development flexibility, risk management approaches and the
process maturity

384
2004 by SEC

Multipliers

M represents the capability of the developers, the non-functional


requirements, the familiarity with the development platform, etc.
RCPX - product reliability and complexity
RUSE required reusability
PDIF - platform difficulty
PREX - personnel experience
PERS - personnel capability
SCED required development schedule
FCIL - the team support facilities

385
2004 by SEC

Multipliers (contd)

PMm reflects the amount of automatically generated code


ASLOC: number of automatically generated lines of source code
ASPROD: productivity level for this type of code production
AT: percentage of total system code that is automatically generated

386
2004 by SEC

Post Architecture Model

Used during development stages and uses same formula as


early design level

Estimate of total lines of code is adjusted for


Requirements volatility

Rework required to support change

Extent of possible reuse

Reuse is non-linear and has associated costs so this is not a simple


reduction in LOC

387
2004 by SEC

Estimation of Equivalent Lines of Code

ESLOC = ASLOC (AA + SU +0.4DM + 0.3CM


+0.3IM)/100
ASLOC is the number of lines of reusable code which must be
modified
DM is the percentage of design modified
CM is the percentage of the code that is modified
IM is the percentage of the original integration effort required to
integrate the reused software
SU is a factor based on the cost of software understanding
AA is a factor which reflects the initial assessment costs of deciding if
software may be reused

388
2004 by SEC

The Exponent Term in Early Design


and Post Architecture Models

PM = A SizeB M + PMm

The factors on computing B


Precedentedness: previous experiences
Development flexibility: development process flexibility
Architecture and risk resolution: the extent that risk analysis is
performed
Team cohesion: how well the team work together
Process maturity of the organization

Each factor is valued between 0 and 5

B = (sum of factor values / 100) + 1.01

389
2004 by SEC

7.4.4 Project Scheduling

Project scheduling concepts

Activity network and critical path analysis

Gantt chart

390
2004 by SEC

Project Scheduling Concepts

Work breakdown structure

Cost and effort estimation of each task

Precedence relationships between tasks


Represented in a network notation
Activity network
PERT and critical path analysis

Gantt chart and progress monitoring

391
2004 by SEC

Task Duration and Precedence


Task

Duration

Precedence

T1: Prototyping planning

T2: Requirement A

15

T1

T3: Requirement B

10

T1

T4: Requirement C

10

T1

T5: Requirement
verification

T2, T3, T4

T6: Prototype A imple

25

T5

T7: Prototype B imple

15

T5

T8: Prototype C imple

20

T5

392
2004 by SEC

Task Duration and Precedence (contd)


T9: Integration

15

T6, T7, T8

T10: Customer validation

T9

393
2004 by SEC

Activity Network

394
2004 by SEC

Critical Path Analysis

395
2004 by SEC

Gantt Chart
4/7

11/7

18/7

25/7

1/8

8/8

15/8

22/8

29/8

5/9

12/9

19/9

Start
T4
T1
T2
M1
T7
T3
M5
T8
M3
M2
T6
T5
M4
T9
M7
T10
M6
T11

M8

T12
Finish

396
2004 by SEC

Staff/Resource Allocation
4/7
Fred

11/7

18/7

25/

1/8

8/8

15/8 22/8

29/8

5/9

12/9

19/9

T4
T8

T11
T12

Jane

T1
T3
T9

Anne T2
T6
Jim
Mary

T10

T7
T5

397
2004 by SEC

7.5 Risk Management


7.5.1 Risk Management Concepts
7.5.2 Risk Identification
7.5.3 Risk Analysis
7.5.4 Risk Planning
7.5.5 Risk Monitoring

2004 by SEC

7.5.1 Risk Management Concepts

Risk management process

399
2004 by SEC

Risk Management

Risk management types


Reactive: react to risks when they occur

Crisis management: reduce the risk impact when they occur

Plan or additional resources needed in anticipation of risks

Proactive: correct the root causes of risks

Formal risk analysis is performed

400
2004 by SEC

Risk Management Process

Risk identification
Identify project, product, and business risks
Risk item checklist

Risk analysis
Assess the likelihood and impacts of risks
Risk table

Risk, probability, impact, action, cost

Risk planning
How to avoid risks or reduce the impacts of risks

Risk monitoring

401
2004 by SEC

7.5.2 Risk Identification

Risk categories

Risk factors and risk database

402
2004 by SEC

Risk Identification

Risk categories
Product size
Business risk
Customer characteristics
Process definition
Physical development environment
Technologies and tools used
Staff size and experiences

403
2004 by SEC

Business Risk

Market risk and sales risk


To develop a product that no one wants
To develop a product that no one knows how to sell

Strategic risk
To develop a product that does not fit in organizational overall business
strategy

Management risk
Lack support from top management

Budget risk
Losing budget commitment or out run budget allocated

404
2004 by SEC

Risk Factors and Risk Database


(Example)

Lack of top management commitment

Failure to gain user commitment

Misunderstanding of requirements

Lack of adequate user involvement

Failure to manage user expectation

Changing scope and objectives

Lack of required knowledge in the project staff

Lack of frozen requirements

Introduction of new technology

Inappropriate staffing

Conflict between user department

405
2004 by SEC

7.5.3 Risk Analysis

Assess probability and impact of each risk


Probability scale

Very high, high, medium, low, very low

Percentage from past experiences

Impact

Catastrophic, serious, tolerable, negligible

Results: risk table

406
2004 by SEC

Risk Table
Risk

Probability

Impact

Users not
communicating

high

serious

Staff turn over,


programmers leave

very high

serious

Customer
organization
restructured

very low

catastrophic

407
2004 by SEC

How the Probability and Impact


Derived

From past experiences

Risk database

408
2004 by SEC

7.5.4 Risk Planning

For each risk, develop a plan to manage the risk


Proactive: try to eliminate the cause of a risk or to reduce the
probability of its occurrence
Impact reduction: contingency plan

Risk
Users not
communicating
Programmers leave

Strategy
1.

More meetings with users

2.

Prototyping

Backup programmers

409
2004 by SEC

Risk Plan
Risk
Users not
communicating

Action
1.

2.

Programmers
leave

Weekly
meeting with
users
Prototyping

Backup
programmer

Who
1.

2.

System
analyst
Project
team

Cost
1.
2.

50000
250000, 3
month

Junior prog

410
2004 by SEC

7.5.5 Risk Monitoring

Monitoring the identified risks regularly to determine if some


risks become less or more likely

Indicators or conditions
Risk
Users not
communicating
Programmers leave

Indicators
1.

Users not knowing computers

1.

Outside job market

2.

3.

Unwillingness to help other


team members
Frequent on leaves

411
2004 by SEC

7.6 Configuration Management


7.6.1 Configuration Management Concepts
7.6.2 Software Configuration
7.6.3 Change Control
7.6.4 Version Control

2004 by SEC

7.6.1 Configuration Management


Concepts

Change control
There is always changes during the software development cycle
Software systems may be evolving

Version control
Software systems are developed for different platforms and different
OS
May become more important for component-based software
development

413
2004 by SEC

Configuration Management Planning

Software configuration item identification

Configuration management database and configuration item


tree

Change control process

414
2004 by SEC

7.6.2 Software Configuration

What is software configuration

Baseline

Configuration management database

Software configuration item tree

415
2004 by SEC

What is Software Configuration

Design object (DO)


A piece of software or document that is being designed or modeled by
the developers

Software configuration item (SCI)


Reshaping, forming or grouping of some design objects or other SCIs
Used by configuration management

Software configuration: relative arrangement of software parts


A collection of SCIs that are related to one another in a clearly defined
manner

416
2004 by SEC

Baseline

A reference point in the development of a system

Types of baselines
Functional baseline: requirement document, project planning document
Allocated baseline: SW/HW decomposition
Design baseline: S/W design

417
2004 by SEC

SCI Identification

Identify all available documents and code

Decide which documents and code to be managed


Name the documents and code so that related documents have related
names
Hierarchical naming scheme should be used

418
2004 by SEC

CM Database

Maintains all configuration management items

Change control
What parts will be affected by a change to component X (ripple effect)

Version control
Who owns a particular system version?
What platform is required for a particular version

419
2004 by SEC

SCI Tree

420
2004 by SEC

7.6.3 Change Control

Change control process

421
2004 by SEC

Change Control Process

Identify the part to change and decide whether to change

Perform change

Test and release the change and update configuration


management database

422
2004 by SEC

Change Identification

423
2004 by SEC

Perform Change

424
2004 by SEC

Test and Release Change

425
2004 by SEC

7.6.4 Version Control

Versions and releases

Version control tools

Concurrent Versions System (CVS)

Source Code Control System (SCCS)

Revision Control System (RCS)

426
2004 by SEC

Version Control

Record changes made to codes or documents


Changes made
Rationale or why the change made
Who made the change
When the change was made

Included as comments to code

427
2004 by SEC

Versions and Releases

Version
An instance of a system which is functionally distinct in some way
from other system instances

Release
An instance of a system which is distributed to users outside of the
development team

428
2004 by SEC

Version identification

Version numbering
Derivation structure, such as V1, V1.1, V1.2, V2.1, V2.2

Attribute-based identification
Attributes associated with a version to identify that
version
Date, Creator, Programming Language, Customer, Status

Change-oriented identification
Integrates versions and the changes made to create these versions

429
2004 by SEC

Version Tree

430
2004 by SEC

Version Control Tools

The version control program owns all source files or


documents
Check-out a file: when a change is needed
Check-in the file: when a change is completed and verified

Version control tools


Concurrent Versions System (CVS)
Source Code Control System (SCCS): Unix, SunOS
Revision Control System (RCS): Unix, open source
Source safe: Windows

431
2004 by SEC

CVS

Setting cvs root


setenv CVSROOT /usr/local/cvsroot

Starting a project
cvs import proj_dir yoyo start

Install files in current directory into $CVSROOT/proj_dir

yoyo: vendor tag

start: release tag

Add files into repository


cvs add prog.c
cvs commit prog.c

432
2004 by SEC

CVS

Checkout files into a local directory


cvs checkout tc

Check in a file
cvs commit prog.c

Create a branch
cvs tag b branch_name (e.g., rel-1-1-patches)

Check out a branch


cvs checkout r branch_name local_dir

433
2004 by SEC

SCCS

Starting a project
Make an sccs sub-directory under project directory
%W: filename + version number
%G: date checked-in

Add files to sccs


sccs enter prog.c

Check out a file for reading only


sccs get prog.c, sccs get r1.3 prog.c

Check out for editing


sccs get prog.c, sccs get r1.3 prog.c

434
2004 by SEC

SCCS (contd)

Check in a file
sccs delta prog.c

Create a new branch


Allow to create a branch on prog.c

sccs admin fb prog.c

sccs edit r1.3 b prog.c

Report differences between different versions


sccs diff prog.c

435
2004 by SEC

RCS

Starting a project
Create an rcs sub-directory to hold project files
/* $Id$ */

Add files in the project to RCS


ci prog.c,

Check out a file


For reading: co prog.c, co r1.3
For locking (editing): co l prog.c
An earlier version: cp r2.1 prog.c

436
2004 by SEC

RCS (contd)

Check in a file
ci prog.c

Create a new branch


Check out an earlier version
Check in the version with new version number

co r1.3 prog.c

ci r1.3.1 prog.c

437
2004 by SEC

Exercises
1)

2)

Take a nontrivial program that you have written before, such as a term
project in another class, then compute the function point of your program
and estimate the effort of your program. Compare the estimated work
effort and your actual effort and try to discuss the discrepancy.
Using COCOMO-81 to estimate the efforts and duration of your
program in previous exercise, and compare it with the estimate of
function point.

438
2004 by SEC

Chapter 8
Software Quality Assurance

2004 by SEC

Chapter 8
Software Quality Assurance
8.1 Quality Concepts
8.2 Software Reviews
8.3 Formal Technical Reviews
8.4 Software Measurement and Quality Metrics
8.5 SQA Plan
8.6 Software Quality Standards
Exercise

440
2004 by SEC

Chapter 9
Software Maintenance

2004 by SEC

Chapter 9
Software Maintenance
9.1 Software Evolution
9.2 Types of Software Maintenance
9.3 Maintenance Techniques
9.4 The Management of Maintenance
9.5 Qualities in Maintenance
9.6 Reengineering, Reverse Engineering and Forward
Engineering
Exercise

442
2004 by SEC

9.1 Software Evolution

443
2004 by SEC

Software Evolution

It is impossible to produce system of any size which do not


need to be changed. Once software is put into use, new
requirements emerge and existing requirements changes as the
business running that software changes.

Parts of the software may have to be modified to correct errors


that are found in operation, improve its performance or other
non-functional characteristics.

All of this means that, after delivery, software systems always


evolve in response to demand for change.

444
2004 by SEC

Program Evolution Dynamic

Program evolution dynamic is the study of system change.


The majority of work in this area has been carried out by
Lehman and Belady. From these studies , they proposed a sets
of laws concerning system change.

Law

Description

Continuing change

A program that is used in real-world environment


necessarily must change or become progressively
less useful in that environment.

Increasing complexity

As an evolving program changes, its structure


tends to become more complex. Extra resources
must be devoted to preserving and simplify the
structure.

445
2004 by SEC

Program Evolution Dynamic (contd)


Law

Description

Large program evolution

Program evolution is self-regulation process.


System attributes such as size, time between
release and the number of report errors are
approximately invariant for each system
release

Organizational stability

Over a programs lifetime, its rate of


development is approximately constant and
independent of the resources devoted to the
system development

Conservation of familiarity

Over the lifetime of system, the incremental


change in each release is approximately
constant.

446
2004 by SEC

Software Evolution Approaches

There are a number of different strategies for software change


.[SOM2004]
Software maintenance
Architectural transformation
Software re-engineering.

Software maintenance
Changes to the software are made in response to changed requirements
but the fundamental structure of the software remains stable. This is
most common approach used to system change.

447
2004 by SEC

Software Evolution Approaches (contd)

Architectural transformation
This is a more radical approach to software change then maintenance
as it involves making significant change to the architecture of the
system.

Software re-engineering
This is different from other strategies in that no new functionality is
added to the system.
System re-engineering may involve some structural modifications but
dose not usually involves major architectural change.

448
2004 by SEC

9.2 Types of Software Maintenance

449
2004 by SEC

Software Maintenance

Software maintenance is the general process of changing a


system after it has been diverted.

The change may be simple changes to correct coding errors,


more extensive changes to correct design errors or significant
enhancement to correct specification error or accommodate
new requirements.

450
2004 by SEC

Maintenance Characteristics

We need to look at maintenance from three different


viewpoints: [PRE2004]
the activities required to accomplish the maintenance phase and the
impact of a software engineering approach (or lack thereof) on the
usefulness of such activities
the costs associated with the maintenance phase
the problems that are frequently encountered when software
maintenance is undertaken

451
2004 by SEC

Types of Maintenance

Maintenance to repair software faults

Maintenance to adapt software to a different operating


environment

Changing a system to correct deficiencies in the way meets


its requirements

Changing a system so that it operates in a different environment


(computer, OS, etc.) from its initial implementation

Maintenance to add to or modify the systems functionality

Modifying the system to satisfy new requirements

452
2004 by SEC

Maintenance effort distribution .[SOM2004]

453
2004 by SEC

Development vs. Maintenance


not directly linked to the
real world

directly driven by the real


world

freedom

constrained by existing
system

defects have no
immediate effect

defects disrupt production

methods available

system not using current


methods

standards may be
enforced

shifting standards, if any

454
2004 by SEC

Maintenance Examples

Y2K
many, many systems had to be updated
language analyzers (find where changes need to be made)

Anti-Virus Software
don't usually have to update software, but must send virus definitions

455
2004 by SEC

Maintenance Examples (contd)

Operating System Patching


Microsoft, Apple, Linux/Unix
OS is core to use of computer, so it must be constantly maintained

Commercial Software in General


customers need to be informed of updates
updates have to be easily available - web is good tool

456
2004 by SEC

The Maintenance Process

Maintenance process vary considerably depending on the


types of software being maintained, the development
processes used in an organization and people involved in the
process.

Change
requests

Impact
analysis

Release
planning

Fault
repair

Flat form
adaptation

Change
implementation

System
release

System
enhancement

Overview of the Maintenance Process .[SOM2004]

457
2004 by SEC

Change Requests

Change requests are requests for system changes from users,


customers or management

In principle, all change requests should be carefully analysed


as part of the maintenance process and then implemented

In practice, some change requests must be implemented


urgently

Fault repair

Changes to the systems environment

Urgently required business changes

458
2004 by SEC

Change Implementation

Proposed
changes

Requirements
analysis

Requirements
updating

Software
development

Change implementation. [SOM2004]

459
2004 by SEC

Emergency Repair

Change
requests

Analyze
sourcecode

Modify
sourcecode

Delivermodified
system

Emergency repair [SOM2004]

460
2004 by SEC

Why is Maintenance Inefficient?

Factors adversely effect maintenance


Lack of models or ignorance of available models (73%)
Lack of documentation (67.6%)
Lack of time to update existing documentation (54.1%)

Other factors (1994 study)


Quality of original application
Documentation quality
Rotation of maintenance people

461
2004 by SEC

Why is Maintenance Inefficient?


(contd)

More factors (Yip 95 study)


Lack of human resources
Different programming styles conflict
Lack of documentation and tools
Bad maintenance management
Documentation policy
Turnover

462
2004 by SEC

9.3 Maintenance Techniques

463
2004 by SEC

Architectural Evolution

There is a need to convert many legacy systems from a


centralised architecture to a client-server architecture

Change drivers

Hardware costs. Servers are cheaper than mainframes

User interface expectations. Users expect graphical user interfaces

Distributed access to systems. Users wish to access the system


from different, geographically separated, computers

464
2004 by SEC

Distribution Factors [SOM2004]


Factor
Business
importance

Systemage
Systemstructure

Hardware
procurement
policies

Description
Returnsontheinvestmentofdistributingalegacysystem
dependonitsimportancetothebusinessandhowlongit
willremainimportant.Ifdistributionprovidesmoreefficient
supportforstablebusinessprocessesthenitismorelikelyto
beacosteffectiveevolutionstrategy.
Theolderthesystemthemoredifficultitwillbetomodify
itsarchitecturebecausepreviouschangeswillhavedegraded
thestructureofthesystem.
Themoremodularthesystem,theeasieritwillbetochange
thearchitecture.Iftheapplicationlogic,thedata
managementandtheuserinterfaceofthesystemareclosely
intertwined,itwillbedifficulttoseparatefunctionsfor
migration.
Applicationdistributionmaybenecessaryifthereis
companypolicytoreplaceexpensivemainframecomputers
withcheaperservers..

465
2004 by SEC

Legacy System Structure

Ideally, for distribution, there should be a clear separation


between the user interface, the system services and the
system data management

In practice, these are usually intermingled in older legacy


systems

466
2004 by SEC

Legacy System Structures [SOM2004]


Userinterface

Services

Database

Idealmodelfordistribution

Userinterface

Services

Database
Reallegacysystems

467
2004 by SEC

Layered Distribution Model [SOM2004]


Presentation
Datavalidation
Interactioncontrol
Applicationservices
Database

468
2004 by SEC

Legacy System Distribution [SOM2004]


DesktopPCclientsrunningapplication
Legacysystem
Application
services
Database

Middlewarelayer(wrapper)

Userinterface
Legacysystem
Characterterminals

469
2004 by SEC

Distribution Options

The more that is distributed from the server to the client, the
higher the costs of architectural evolution

The simplest distribution model is UI distribution where


only the user interface is implemented on the server

The most complex option is where the server simply


provides data management and application services are
implemented on the client

470
2004 by SEC

Distribution Option Spectrum


[SOM2004]
Server: Interactioncontrol
Datavalidation
Services
Database

Server: Services
Database

Server:Database

Client:Presentation

Client:Presentation
Interactioncontrol
Datavalidation

Client:Presentation
Interactioncontrol
Datavalidation
Services
Increasingcost
andeffort

471
2004 by SEC

User Interface Distribution

UI distribution takes advantage of the local processing


power on PCs to implement a graphical user interface

Where there is a clear separation between the UI and the


application then the legacy system can be modified to
distribute the UI

Otherwise, screen management middleware can translate


text interfaces to graphical interfaces

472
2004 by SEC

User Interface Distribution [SOM2004]


Screendescriptions

DesktopPCclientswith
GUIinterface

Legacysystem
Application
services
Database

Screenmanagement
middleware

Userinterface

473
2004 by SEC

UI Migration Strategies [SOM2004]

474
2004 by SEC

9.4 The Management of Maintenance

475
2004 by SEC

Model of Maintenance Effort


Model of maintenance effort M = p + K^(c-d) [PRE2004]

M = total maintenance effort over entire lifecycle

p = productive efforts: analysis, design, code, test

c = complexity due to lack of structured design and documentation

d = degree of familiarization with the system

K = empirically determined constant

476
2004 by SEC

Model of Maintenance Effort (contd)


Model of maintenance effort M = p + K^(c-d)

Cost of maintenance increases exponentially.

Costs are reduced by structured development

Costs are reduced by giving the maintenance team time to become


thoroughly familiar with the system

477
2004 by SEC

What Affects the Maintainability of an


Application?

Application age
(software rust?) older programs were probably worse written and have
probably been patched more

Size
measured in KLOC, number of input/output files

Programming language
4gls are supposed to produce more maintainable code than 3gls

478
2004 by SEC

What Affects the Maintainability of an


Application? (contd)

Processing environment
files harder to maintain than databases, real-time harder than batch

Analysis and design methodologies


well designed software is supposed to be much easier to maintain

Structured programming
there is conflicting evidence whether this really helps

479
2004 by SEC

What Affects the Maintainability of an


Application? (contd)

Modularization
(central thesis of all the oo techniques) small reasonably self contained
pieces of code should be easier to maintain

Documentation generation
maintenance of documentation is as expensive as maintenance of code

End-user involvement
some researchers believe when end users are more involved
maintenance decreases

480
2004 by SEC

What Affects the Maintainability of an


Application? (contd)

Maintenance management
scheduling and the attitudes of management to affects productivity

481
2004 by SEC

Problems in Managing Maintenance

Changing priorities
chaotic nature of maintenance requests, the length of maintenance
tasks causing new requests to come along before an ongoing task is
done.

Inadequate testing methods


lack of time set aside for testing, of comprehensive test data, of
rigorous testing requirements as a standard for signing off.

Performance measurement difficulties


how do you measure individual or group performance?

System documentation incomplete or non-existent


training takes a long time for learning an application so programmers
get stuck on one piece of software.

Adapting to the rapidly changing business environment


hardware and software also become obsolete.

482
2004 by SEC

Problems in Managing Maintenance


(contd)

From survey of 60 US & Canadian companies in Software


Maintenance News 1992
These are the consequence of the lack of mature tools and techniques
for software maintenance and its management.
We need predictive models of maintenance to estimate how much
effort needs to go into it.
By and large maintainers work in isolation and are not closely
managed. Each one has to learn from personal experience good
methods of working.

483
2004 by SEC

Maintenance Prediction

Maintenance prediction is concerned with assessing which


parts of the system may cause problems and have high
maintenance costs

Change acceptance depends on the maintainability of the


components affected by the change

Implementing changes degrades the system and reduces its


maintainability

Maintenance costs depend on the number of changes and costs of


change depend on maintainability

484
2004 by SEC

Maintenance Prediction (contd)

Predicting the number of changes requires and


understanding of the relationships between a system and its
environment

Tightly coupled systems require changes whenever the


environment is changed

Factors influencing this relationship are

Number and complexity of system interfaces

Number of inherently volatile system requirements

The business processes where the system is used

485
2004 by SEC

Maintenance Prediction (contd)

Predictions of maintainability can be made by assessing the


complexity of system components

Studies have shown that most maintenance effort is spent on


a relatively small number of system components

Complexity depends on

Complexity of control structures

Complexity of data structures

Procedure and module size

486
2004 by SEC

Maintenance Prediction (contd)

Process measurements may be used to assess maintainability

Number of requests for corrective maintenance

Average time required for impact analysis

Average time taken to implement a change request

Number of outstanding change requests

If any or all of these is increasing, this may indicate a


decline in maintainability

487
2004 by SEC

Maintenance Costs

Usually greater than development costs (2* to


100* depending on the application)

Affected by both technical and non-technical


factors

Increases as software is maintained.


Maintenance corrupts the software structure so
makes further maintenance more difficult.

Ageing software can have high support costs


(e.g. old languages, compilers etc.)

488
2004 by SEC

Maintenance Costs (contd)

Time and money (software that costs 10 a line to develop costs 400 a
line to maintain)

Organizations become maintenance bound and cannot produce new


software

Customer dissatisfaction when seemingly legitimate requests for repair or


modification cannot be addressed in a timely manner

Reduction in overall software quality as changes introduce latent errors in


the maintained software

Upheaval caused during development efforts when staff must be pulled


to work on a maintenance task

489
2004 by SEC

Development/Maintenance Costs [SOM2004]

System1
System2
0

50

100 150

Developmentcosts

200 250

300

350 400 450

500

Maintenancecosts

490
2004 by SEC

Maintenance Cost Factors

Team stability

Contractual responsibility

The developers of a system may have no contractual responsibility for


maintenance so there is no incentive to design for future change

Staff skills

Maintenance costs are reduced if the same staff are involved with them for
some time

Maintenance staff are often inexperienced and have limited domain


knowledge

Program age and structure

As programs age, their structure is degraded and they become harder to


understand and change

491
2004 by SEC

Change Management

Change is a fact of life for large software. A defined change


management process and associated CASE tools ensure that
these changes are recorded and applied to the system in a
cost-effective way.

The change management process should come into effect


when the software associated document is put under the
control of the configuration management team.

Change management procedures should be designed to ensure


that the costs and benefits of change are properly analyzed
and changes to a system are made in a controlled way.

492
2004 by SEC

Change Management Process


Request change by completing a change request form
Analyze change request
If change is valid then {
Assess how change might be implemented
Assess change cost
Record change request in database
Submit request to change control board

493
2004 by SEC

Change Management Process (contd)


If change is accepted then{
Repeat{
make changes to software
record changes and link to associated change request
submit changed software for quality approval}
Until{
software quality is adequate
create new system version}}
else
{reject change request}}

494
2004 by SEC

Change Request Form


[SOM2004]
Project: Proteus/PCL-Tools
Number: 23/94
Change requester: I.Sommerville

Date: 1/9/98

Requested change: when a component is selected from the structure, display the name of the file
where it is stored.
Change analyzer: G.Dean

analysis Date:10/9/98

Components affected: Display-icon.Select, Display-icon.Display


Associated component: File Table
Change assessment: Relatively simple to implement as a file name table is available. Requires
the design and implementation of a display field. No changes to associated components are
required.
Change priority: Low
Change implementation:
Estimated effort: 0.5 days
Date to CCB: 15/9/98

CCB decision date: 1/11/98

Change implementor:

Date of change:

Date submitted to QA:

QA decision:

Date submitted to CM:


comments

CCB- change control board

495
2004 by SEC

9.5 Qualities in Maintenance

496
2004 by SEC

Maintenance Side Effects

In this context a side effect implies an error or undesirable


behavior that occurs as the result of a modification.

the three major areas are[PRE2004]


code
data structures
documentation

497
2004 by SEC

Documentation Side Effects

These consist of the failure to update documentation so that it


no longer matches the code.

If the user doesnt know about changes frustration is


inevitable.

The entire documentation should be reviewed before rerelease

498
2004 by SEC

Coding Side Effects

Any change can cause side-effects but these tend to be more


error prone a subprogram is deleted or changed

A statement label is deleted or modified

An identifier is deleted or modified

Changes are made to improve execution performance

499
2004 by SEC

Coding Side Effects (contd)

Logical operators are modified

Files are opened or closed

Design changes which translate into major code changes

Changes are made to logical tests of boundary conditions

These may be caught in testing or cause software failure


during operation.

500
2004 by SEC

Data Side Effects

Data side effects occur as the result of modifications made to


a data structure. The most error-prone are:
redefinition of local and global constants
redefinition of record or file formats
Incr. or decr. in size of array or other data structure
modification of global data
re initialization of control flags and pointers
rearrangements of parameters (especially in I/O)

501
2004 by SEC

9.6 Re-engineering, Reverse


Engineering and Forward Engineering,

502
2004 by SEC

Software Rejuvenation

Re-documentation
Creation or revision of alternative representations of software

at the same level of abstraction

Generates:

data interface tables, call graphs, component/variable cross


references etc.

Restructuring
transformation of the systems code without changing its behavior

503
2004 by SEC

Software Rejuvenation (contd)

Reverse Engineering
Analyzing a system to extract information about the behavior and/or
structure
also Design Recovery - recreation of design abstractions from
code, documentation, and domain knowledge
Generates:
structure charts, entity relationship diagrams, DFDs, requirements
models

Re-engineering
Examination and alteration of a system to reconstitute it in another
form
Also known as renovation, reclamation

504
2004 by SEC

System Re-engineering

Re-structuring or re-writing part or all of a


legacy system without changing its
functionality

Applicable where some but not all sub-systems


of a larger system require frequent
maintenance

Re-engineering involves adding effort to make


them easier to maintain. The system may be re-structured
and re-documented

505
2004 by SEC

When to Re-engineer

When system changes are mostly confined to


part of the system then re-engineer that part

When hardware or software support becomes


obsolete

When tools to support re-structuring are


available

506
2004 by SEC

Re-engineering Advantages

Reduced risk

There is a high risk in new software development. There may be


development problems, staffing problems and specification
problems

Reduced cost

The cost of re-engineering is often significantly less than the costs


of developing new software

507
2004 by SEC

Forward Engineering and Reengineering [SOM2004]

System
specification

Designand
implementation

Ne w
system

Understandingand
transformation

Reengineered
system

Forwardengineering
Existing
softwaresystem
Softwarereengineering

508
2004 by SEC

The Re-engineering Process [SOM2004]


Program
documentation

Original
program

Modularised
program

Originaldata

Reverse
engineering
Program
modularisation

Sourcecode
translation

Data
reengineering

Program
structure
improvement
Structured
program

Reengineered
data

509
2004 by SEC

Re-Engineering Cost Factors

The quality of the software to be re-engineered

The tool support available for re-engineering

The extent of the data conversion which is required

The availability of expert staff for re-engineering

510
2004 by SEC

Re-Engineering Approaches [SOM2004]

Automatedprogr am
restructuring

Automatedsource
codeconversion

Programanddata
restructuring

Automatedr estructuring
withmanualchanges

Restructuringplus
architecturalchanges
Increasedcost

511
2004 by SEC

Source Code Translation

Involves converting the code from one language (or


language version) to another e.g. FORTRAN to C

May be necessary because of:

Hardware platform update

Staff skill shortages

Organisational policy changes

Only realistic if an automatic translator is available

512
2004 by SEC

The Program Translation Process


[SOM2004]

Systemtobe
reengineered

Identifysource
codedifferences

Designtranslator
instructions

Systemtobe
reengineered

Reengineered
system

Automatically
transla tecode

Manually
transla tecode

513
2004 by SEC

Program Structure Improvement

Maintenance tends to corrupt the structure of a program. It


becomes harder and harder to understand

The program may be automatically restructured to remove


unconditional branches

Conditions may be simplified to make them more readable

514
2004 by SEC

Spaghetti Logic [SOM2004]

515
2004 by SEC

Structured Control Logic [SOM2004]

516
2004 by SEC

Condition Simplification
Complexcondition
ifnot(A>Band(C<Dornot(E>F)))...
Simplifiedcondition
if(A<=Band(C>=DorE>F)...

517
2004 by SEC

Automatic Program Restructuring


[SOM2004]

Programtobe
restructured

Restructur ed
program
Analyserand
graphbuilder

Program
generator
Graph
repr esentation

518
2004 by SEC

Restructuring Problems

Problems with re-structuring are:

Loss of comments

Loss of documentation

Heavy computational demands

Restructuring doesnt help with poor modularisation where


related components are dispersed throughout the code

The understandability of data-driven programs may not be


improved by re-structuring

519
2004 by SEC

Module types

Data abstractions

Hardware modules

All functions required to interface with a hardware unit

Functional modules

Abstract data types where data structures and associated operations


are grouped

Modules containing functions that carry out closely related tasks

Process support modules

Modules where the functions support a business process or process


fragment

520
2004 by SEC

Recovering Data Abstractions

Many legacy systems use shared tables and global data to


save memory space

Causes problems because changes have a wide impact in the


system

Shared global data may be converted to objects or ADTs

Analyse common data areas to identify logical abstractions

Create an ADT or object for these abstractions

Use a browser to find all data references and replace with reference
to the data abstraction

521
2004 by SEC

Data Abstraction Recovery

Analyse common data areas to identify logical abstractions

Create an abstract data type or object class for each of these


abstractions

Provide functions to access and update each field of the data


abstraction

Use a program browser to find calls to these data


abstractions and replace these with the new defined
functions

522
2004 by SEC

Data Re-engineering

Involves analysing and reorganising the data structures (and


sometimes the data values) in a program

May be part of the process of migrating from a file-based


system to a DBMS-based system or changing from one
DBMS to another

Objective is to create a managed data environment

523
2004 by SEC

Approaches to Data Re-engineering


[SOM2004]

524
2004 by SEC

Data Problems

End-users want data on their desktop machines rather than in


a file system. They need to be able to download this data
from a DBMS

Systems may have to process much more data than was


originally intended by their designers

Redundant data may be stored in different formats in


different places in the system

525
2004 by SEC

Data Problems (contd)

Data naming problems

Field length problems

Names may be hard to understand. The same data may have


different names in different programs

The same item may be assigned different lengths in different


programs

Record organisation problems

Records representing the same entity may be organised differently


in different programs

Hard-coded literals

No data dictionary

526
2004 by SEC

Data Conversion

Data re-engineering may involve changing the data structure


organisation without changing the data values

Data value conversion is very expensive. Special-purpose


programs have to be written to carry out the conversion

527
2004 by SEC

The Data Re-engineering Process


[SOM2004]
Data
analysis

Programtobereengineered

Data
analysis

Entityname
modification
Literal
replacement
Datadefinition
reordering
Stage1

Data
reformatting
Defaultvalue
conversion
Validationrule
modification
Stage2

Changesummarytables

Data
conversion

Stage3
Modified
data

528
2004 by SEC

Reverse Engineering

Analysing software with a view to understanding its design


and specification

May be part of a re-engineering process but may also be


used to re-specify a system for re-implementation

Builds a program data base and generates information from


this

Program understanding tools (browsers, cross-reference


generators, etc.) may be used in this process

529
2004 by SEC

The Reverse Engineering Process


[SOM2004]

Programstucture
diagrams

Automated
analysis
Systemtobe
reengineered
Manual
annotation

System
information
store

Document
generation

Datastucture
diagrams
Traceability
matrices

530
2004 by SEC

References

[PRE2004] Roger S. Pressman. Software Engineering: a practitioners


approach, 6th edition. McGRAW-HILL, 2004.

[SOM2004] Ian Sommerville. Software Engineering, 7th edition. Addison


Wesley, 2004

531
2004 by SEC

Chapter 10
Formal Methods and Software
Engineering

2004 by SEC

Chapter 10
Formal Methods and Software
Engineering
10.1 Formal Method Concepts
10.2 Software Engineering Mathematics
10.3 Algebra-Based Specification
10.4 Model-Based Specification
10.5 A Formal Specification in Z
Exercise

533
2004 by SEC

10.1 Formal Method Concepts

2004 by SEC

Formal Method

Using a formal syntax and semantics and often mathematical


in form (rigorous, mathematical notation).

To check consistency, completeness and correctness of a


system.

Use formal method during


development: help eliminate ambiguity, incompleteness, and
inconsistency.
design: program verification

535
2004 by SEC

Formal Method (contd)

Formal methods include

Formal specification

Specification analysis and proof

Transformational development

Program verification

These are all based on mathematical representation and


analysis of software

536
2004 by SEC

Acceptance of Formal Methods

Formal methods have not become mainstream software


development techniques as was once predicted

Successful software engineering

Other software engineering techniques have been successful at


increasing system quality. Hence the need for formal methods
has been reduced

Market changes

Market changes have made time-to-market rather than software


with a low error count the key factor. Formal methods do not
reduce time to market

537
2004 by SEC

Acceptance of Formal Methods (contd)


Limited scope of formal methods

They are not well-suited to specifying and analysing user


interfaces and user interaction

Limited scalability of formal methods

Formal methods are hard to scale up to large systems

538
2004 by SEC

Use of Formal Methods

Formal specification involves investing more effort in the


early phases of software development

This reduces requirements errors as it forces a detailed


analysis of the requirements

Incompleteness and inconsistencies can be discovered and


resolved

Hence, savings as made as the amount of rework due to


requirements problems is reduced

539
2004 by SEC

Formal Specification in the Software


Process

There are three levels of software specification which may


be developed

User requirements

System requirements

Software design specification

Formal specifications are expressed in a


mathematical notation with precisely defined
vocabulary, syntax and semantics.

540
2004 by SEC

Formal Specification in the Software


Process (contd)
Increasing contractor involvement
Decreasing client involvement
User
User
requirements
requirements
definition
definition

System
System
requirements
requirements
definition
definition

Architectural
Architectural
design
design

Formal
Formal
specification
specification

High-level
High-level
design
design

Specification
Design
Specification and design [SOM2004]

541
2004 by SEC

Formal Specification in the Software


Process (contd)
System
System
requirements
requirements
definition
definition

Formal
Formal
specification
specification

User
User
requirements
requirements
definition
definition

High-level
High-level
design
design

System
System
modeling
modeling

Architectural
Architectural
design
design

Formal specification in the software process [SOM2004]

542
2004 by SEC

Cost Profile

The use of formal specification means that the cost profile


of a project changes

There are greater up front costs as more time and effort are spent
developing the specification;

However, implementation and validation costs should be reduced


as the specification process reduces errors and ambiguities in the
requirements.

543
2004 by SEC

Validation

cost

Design and
implementation

Validation
Design and
implementation
Specification

Specification

Without formal specification

With formal specification

Software development costs with formal specification [


SOM2004]

544
2004 by SEC

Specification Techniques

Algebraic approach

The system is specified in terms of its operations and their


relationships

Model-based approach

The system is specified in terms of a state model that is constructed


using mathematical constructs such as sets and sequences.
Operations are defined by modifications to the systems state

545
2004 by SEC

Specification Techniques (contd)


Sequential
Algebraic

Larch (Guttag et.al., 1985, 1993)


OBJ (Futatsugi et. al., 1985)

Model-based

Concurrent
Lotos (Bolognesi and
Brinksma, 1987)

Z (Spivey, 1992)

CSP (Hoare, 1985)

VDM (Jones, 1980)

Petri Nets (Peterson,


1981)

B (Wordsworth, 1996)

Formal specification languages [SOM2004]

546
2004 by SEC

10.2 Software Engineering Mathematics

547
2004 by SEC

Formal Language

A formal language comprises two parts


Its alphabet which specifies what symbols are to be found in the
language

By writing down the symbols in curly brackets: {}, sparated


by commas

Its syntax which specifies how these symbols may be put together

An acceptable string of symbols in a language is called a well


formed formula (wff) of that language

Exactly what constitutes a wff is defined by the grammar rules

A metalanguage for expressing grammar rules


Could be a natural language or another formal language

548
2004 by SEC

Semantics

To give the formal language semantics


By specifying the meaning of each wff admitted by the grammar

549
2004 by SEC

Formal System

A formal system consists


A formal language
A deductive apparatus

A deductive apparatus has two components


Axioms

wffs which can be written down without reference to any other


wffs in the language

Inference rules

Rules which allow us to produce wffs in the language as


immediate consequences of other wffs

550
2004 by SEC

Formal System (contd)

A proof (F) in a formal system is a finite sequence of wffs in


the associated formal language, each of which is either an
axiom of F or an immediate consequence of one or more
preceding wffs (as determined by the inference rules of the
system)

A wff which can be proved within the formal system F is


called a theorem of F

All axioms of proof are also theorems of F

551
2004 by SEC

Formal System Examples


Propositional Calculus

Propositional calculus is a formal system for discussing the


truth or falsity of a particular kind of statement called a
proposition
For examples

Some birds can fly .(true)

Five is bigger than four ..(false)

Formal language: proposition logic

Deductive apparatus: natural deduction system


As there are many choices of language suitable for representing
propositions, so too there are many choices of deductive apparatus for
a propositional calculus

552
2004 by SEC

Formal System Examples (contd)


Predicate Calculus

Predicate calculus is another formal system allows us to


reason about statements which are rather more complex than
propositions
A predicate expresses a property or relation of objects
For examples

duck(x) means the x is a duck

father_of(x, y) captures the idea that x is the father of y

It is built upon propositional calculus by adding more


expressive power to the language and additional rules to the
deductive apparatus

553
2004 by SEC

Formal System Examples (contd)


Predicate Calculus

Predicate calculus
Formal language: predicate logic

Including predicates and propositions

A predicate itself is not truth valued, it expresses a property or


relation using variables

Free variables in a predicate can be bound by the quantification


symbol ( and ), and then forms the predicate as a proposition
x P(x)

Deductive apparatus: extending the natural deduction system by adding


new rules for the two quantifiers.

554
2004 by SEC

Set Theory

A set is any well-defined collection of object. The objects in a


set are called the elements of members of the set
Well-defined means that given a value, it is possible to decide
whether it is a member of the set
In a set, there is no concept of order and of repetition of elements

555
2004 by SEC

Set Theory (contd)

Set membership: for any x is an element of singleton set


containing it
x x { x }

Empty set: there is no object x in the empty set


xx{}

Equality between sets: two sets S and T are equal if they both
have the same members
( S = T ) ( x x S x T )

556
2004 by SEC

Set Theory (contd)

Set Comprehension: the set of all x in S that satisfy predicate P(x)


{x:S|P(x)}
e.g.:

prime number {x : N | y ( y N y x ) ( y 1 y x )}

Power set: the set of all subsets of a set S


e.g: P {a, b, c} ={ {},{a},{b},{c},{a,b},{a,c},{b,c},{a,b,c} }

Cartesian products: the set of all ordered pairs (x, y), where
xS yT is called the cartesian product of sets S and T

557
2004 by SEC

Relation

A set of ordered pairs is called a relation


S

Relation

x
Binary relation: R: S T

E.g.: wrote: Author Title


or represented as wrote: P (Author Title)

maplet: represents one particular pair

E.g.: x y R

558
2004 by SEC

Relation (contd)

The domain of a relation is the set of first members of the pairs


in the relation
E.g. suppose R: S T then dom R is the set
{ x: S | (y: T x y R)}

The range of a relation is the set of second members of the pairs


in the relation
E.g. suppose R: S T then ran R is the set
{ y: T | (x: S x y R)}

559
2004 by SEC

Relation (contd)

Composition of relations:
If R and Q are two relations declared as follows:
R: X Y and Q: YZ
then their composition is

R ; Q {x : X ; z : Z | (y : Y ( x R y y Q x )) x z}

560
2004 by SEC

Title

Author
wrote

Author

Publisher
issued_by

Publisher
wrote ; issued_by

Composition of relations [WOR92]

561
2004 by SEC

Relation (contd)

Domain restriction
For drawing attention to those pairs in a relation whose first members
are members of some other set of interest
E.g.

Female wrote

Domain subtraction
For drawing attention to those pairs in a relation whose first members
are NOT members of some other set of interest
E.g.

Female wrote

562
2004 by SEC

Relation (contd)

Range restriction
For drawing attention to those pairs in a relation whose second members
are members of some other set of interest
E.g.

wrote novel

Domain subtraction
For drawing attention to those pairs in a relation whose second members
are NOT members of some other set of interest
E.g.

wrote novel

563
2004 by SEC

Author

title

female

Domain restriction and domain subtraction [WOR92]


Author

title

novel

Range restriction and range subtraction [WOR92]

564
2004 by SEC

Functions

A function between two sets S and T is a relation between


those sets that has a special property, namely that each
member of the from-set is related to at most one member of
the to-set

Injection
A function in which the second members of the pairs are unique is
called injection
Injections are functions whose inverses are also functions
one-to-one

565
2004 by SEC

Functions (contd)

Surjection
A surjection function from S to T is one where the range is the whole
of T
onto

Total and partial


Total function: every element of S, exact one element of T (dom f = S)
Partial function: at most one element of T

566
2004 by SEC

Functions (contd)
Function

Injection
f:S

f:ST
total

1
2
3
4

a
b

partial

1
2
3
4

a
b

1
2
3
4

f:S
a
b
c
d
e

1
2
3
4

f:S

f:ST

Surjection

1
2
3
4

T
a

f:S

a
b
c

1
2
3
4

T
a
b
c

567
2004 by SEC

Functions (contd)

Bijection
The set of all partial bijections from S to T to be those partial functions
that are both injections and surjections
The set of all total bijections fro S to T to be those partial bijections
that are total

Functional overriding
f g = (dom g f ) g
f g : a function identical to f except on the
domain of g it agrees with g

568
2004 by SEC

10.3 Algebra-Based Specification

569
2004 by SEC

Interface Specification

Large systems are decomposed into subsystems with welldefined interfaces between these subsystems

Specification of subsystem interfaces allows independent


development of the different subsystems

Interfaces may be defined as abstract data types or object


classes

The algebraic approach to formal specification is


particularly well-suited to interface specification

570
2004 by SEC

Sub-System Interfaces [SOM2004]


Interface objects

Sub-system
A

Sub-system
B

571
2004 by SEC

Specification Components

Introduction

Description

Informally describes the operations on the type

Signature

Defines the sort (the type name) and declares other specifications
that are used

Defines the syntax of the operations in the interface and their


parameters

Axioms

Defines the operation semantics by defining axioms which


characterise behaviour

572
2004 by SEC

The Structure of an Algebraic


Specification [SOM2004]
<SPECIFICATION_NAME> (Generic Parameter)

sort <name>
imports <LIST OFSPECIFICATION NAMES>
Informal description of the sort and its operations
Operation signatures setting out the names and the types
of the parameters of the operations defined over the sort
Axioms defining the operations over the sort

573
2004 by SEC

Systematic Algebraic Specification

Algebraic specifications of a system may be developed in a


systematic way

Specification structuring.

Specification naming.

Operation selection.

Informal operation specification

Syntax definition

Axiom definition

574
2004 by SEC

Specification Operations

Constructor operations

Inspection operations

Operations which create entities of the type being specified

Operations which evaluate entities of the type being specified

To specify behaviour, define the inspector operations for


each constructor operation

575
2004 by SEC

Example:
Interface Specification in Critical
Systems [SOM2004]

Consider an air traffic control system where aircraft fly


through managed sectors of airspace

Each sector may include a number of aircraft but, for safety


reasons, these must be separated

In this example, a simple vertical separation of 300m is


proposed

The system should warn the controller if aircraft are


instructed to move so that the separation rule is breached

576
2004 by SEC

A Sector Object

Critical operations on an object representing a controlled


sector are

Enter. Add an aircraft to the controlled airspace

Leave. Remove an aircraft from the controlled airspace

Move. Move an aircraft from one height to another

Lookup. Given an aircraft identifier, return its current height

577
2004 by SEC

Primitive Operations

It is sometimes necessary to introduce additional operations to simplify the specification


The other operations can then be defined using these more primitive operations
Primitive operations

Create. Bring an instance of a sector into existence


Put. Add an aircraft without safety checks
In-space. Determine if a given aircraft is in the sector
Occupied. Given a height, determine if there is an aircraft within 300m of that height

578
2004 by SEC

Sector
specification
[SOM2004]

SECTOR
sort Sector
imports INTEGER, BOOLEAN
Enter - adds an aircraft to the sector if safety conditions are satisfed
Leave - removes an aircraft from the sector
Mo ve - moves an aircraft from one height to another if safe to do so
Lookup - Finds the height of an aircraft in the sector
Cre ate - creates an empty sector
Put - adds an aircraft to a sector with no constraint checks
In-space - checks if an aircraft is already in a sector
Occupied - checks if a specified height is available
Enter (Sector, Call-sign, Height) Sector
Leave (Sector, Call-sign) Sector
Mo ve (Sector, Call-sign, Height) Sector
Lookup (Sector, Call-sign) Height
Cre ate Sector
Put (Sector, Call-sign, Height) Sector
In-space (Sector, Call-sign) Boolean
Occupied (Sector, Height) Boolean
Enter (S, CS, H) =
if
In-space (S, CS ) the n S exception (A ircraft already in sector)
elsif Occupied (S, H) the n S exception (Height conflict)
else Put (S, CS, H)
Leave (Create, CS) = Create exception (A ircraft not in sector)
Leave (Put (S, CS1, H1), CS) =
if CS = CS1 the n S else Put (Leave (S, CS), CS1, H1)
Mo ve (S, CS, H) =
if
S = Create the n Create exception (No aircraft in sector)
elsif not In-space (S, CS) the n S exception (A ircraft not in sector)
elsif Occupied (S, H) the n S exception (Height conflict)
else Put (Leave (S, CS), CS, H)
-- NO-HEIGHT is a co nstant indicating that a valid height cannot be returned
Lookup (Create, CS) = NO-HEIGHT exception (A ircraft not in sector)
Lookup (Put (S, CS1, H1), CS) =
if CS = CS1 the n H1 else Lookup (S, CS)
Occupied (Create, H) = false
Occupied (Put (S, CS1, H1), H) =
if
(H1 > H and H1 - H 300) or (H > H1 and H - H1 300) the n true
else Occupied (S, H)
In-space (Create, CS) = false
In-space (Put (S, CS1, H1), CS ) =
if CS = CS1 the n true else In-space (S, CS)

579
2004 by SEC

Specification Commentary

Use the basic constructors Create and Put to specify other


operations

Define Occupied and In-space using Create and Put and use
them to make checks in other operation definitions

All operations that result in changes to the sector must check


that the safety criterion holds

580
2004 by SEC

10.4 Model-Based Specification

581
2004 by SEC

Model-Based Specification

Defines a model of a system using well-understood


mathematical entities such as sets and functions

The state of the system is not hidden (unlike algebraic


specification)

State changes are straightforward to define

VDM and Z are the most widely used


model-based specification languages

582
2004 by SEC

Behavioural Specification

Algebraic specification can be cumbersome when the object


operations are not independent of the object state

Model-based specification exposes the system state and


defines the operations in terms of changes to that state

The Z notation is a mature technique for model-based


specification. It combines formal and informal description
and uses graphical highlighting when presenting
specifications

583
2004 by SEC

10.5 A Formal Specification in Z

584
2004 by SEC

Z as a Specification Language

Based on typed set theory

Probably now the most widely-used


specification language

Includes schemas, an effective low-level


structuring facility

Schemas are specification building blocks

Graphical presentation of schemas make Z


specifications easier to understand

585
2004 by SEC

The Z Specification Process [SOM2004]

Definegiven
setsandtypes

Writeinformal
specification

Decompose
system

Specifysystem
components

Compose
component
specifications

Definestate
variables

Defineinitial
state

Define
correct
operations

Define
exceptional
operations

Combine
operation
schemas

586
2004 by SEC

Schemas

Z schemas

For grouping together all the relevant information that belongs to a


state description

Introduce specification entities and defines invariant predicates


over these entities

A schema includes

A name identifying the schema

A signature (or declaration) part

introducing entities (variables) and their types

A predicate part

defining invariants over these entities

587
2004 by SEC

Schemas (contd)

e.g. [DIL94]
Schema name

PhoneDB
members: P Person
telephones: Person phone

Declaration part

dom telephones members

Predicate part

588
2004 by SEC

Schemas (contd)

Schemas are used for several different purposes


Type definition: for defining a basic type
State schema: for describing the abstract state of an abstract data type
(state space) of a given specification
Operation schema: for describing the specification of an abstract
operation

A schema may be written in a vertical or a horizontal format


The former is preferred if there are more than a very few declarations
and predicates

589
2004 by SEC

Example:
Internal Telephone Directory

Requirements[DIL94]
A university wants to computerize its internal telephone directory. The
database must keep a record of all the people who are currently
members of the university (as only they can have telephone
extensions). The database must cope with the possibility that one
person may be reached at several extensions and also with the
possibility that several people might have to share an extension.

590
2004 by SEC

Example:
Internal Telephone Directory (contd)
Six operations are to be provided, namely

That of adding an entry to the database, where an entry is an


association between a person and a telephone extension

That of interrogating the database by person

That of interrogating the database by extension number

That of removing an entry from the database

That of adding a person to the databases record of who is currently


a member of the university and

That of removing a person from the database along with all those
entries in which he or she figures

591
2004 by SEC

Type Definition

Type definition

There are a number of built-in types (such as INTEGER) in Z

Other types may be defined by enumeration

Week = { Sun, Mon, Tue, Wed, Thu, Fri, Sat }

Z Schemas may also be used for type definition. The predicates


serve as constraints on the type

592
2004 by SEC

Type Definition (contd)

Given sets or basic types


Z does not require everything to be defined at specification time
Some entities may be given and defined later
The first stage in the specification process is to introduce these given
sets
e.g. [Person, Phone, Report]

593
2004 by SEC

State Space

Relation

telephones: Person Phone

State schema for the telephone database

PhoneDB
members: P Person
telephones: Person Phone
dom telephones members

594
2004 by SEC

State Space (contd)

In order to specify a state transformation we need to represent


the before and after states
The after state is represented by decorating all the variables with a
prime
i.e. the after state of PhoneDB is declared as PhoneDB, that means

PhoneDB
members: P Person
telephones: Person phone
dom telephones members

595
2004 by SEC

State Space (contd)

A variable name decorated with a quote mark (N) represents


the value of the state variable N after an operation

Note that the definition of PhoneDB just given is not a legal


Z definition of a schema, because every defined schema name
must be an undecorated identifier. It is only included here to
show what PhoneDB looks like when written out in full

596
2004 by SEC

Defining the Initial State

InitPhoneDB
PhoneDB
members =
telephones =

597
2004 by SEC

Schema Operations

Linking schemas with propositional connectives


e.g. Let the Alpha and Beta be the following schemas

Beta

Alpha
x: Z
U, V: P Z

x, y: Z
U: P Z

xV
U V

xy
x+yU

Gamma
Gamma

Alpha Beta

x, y: Z
U, V: P Z
(x V U V ) (x y x + y U)

598
2004 by SEC

Schema Operations (contd)

Schema inclusion

Alpha
x, y: Z
U: P Z
x<y

Beta
Alpha
V: P Z
xU

Beta
Expanding Beta as:

x, y: Z
U, V: P Z
x<y
xU

599
2004 by SEC

Schema Operations (contd)

The and conventions


A schema name prefixed by the Greek letter Delta () means that the
operation changes some or all of the state variables introduced in that
schema

PhoneDB
PhoneDB
PhoneDB

600
2004 by SEC

Schema Operations (contd)


A schema name prefixed by the Greek letter Xi () means that the
defined operation does not change the values of state variables

PhoneDB
PhoneDB
members = members
telephones = telephones

601
2004 by SEC

Operation Specification

Operations may be specified incrementally as separate schema then the


schema combined to produce the complete specification

Define the normal operation as a schema

Define schemas for exceptional situations

Combine all schemas using the disjunction (or) operator

A variable name decorated with a ! represents an output

A variable name decorated with a ? represents an input

602
2004 by SEC

Operation: Add an Entry to the


Database
AddEntry
PhoneDB
name?: Person
newnumber?: Phone
name? members
name? newnumber? telephones
telephones = telephones {name? newnumber?}
members = members

603
2004 by SEC

Operation: Add an Entry to the


Database (contd)

Deal with the Success or Errors


Success
rep!: Report
rep! = Okay

NotMember
PhoneDB
name?: Person
rep!: Report
name? members
rep! = Not a member

604
2004 by SEC

Operation: Add an Entry to the


Database (contd)

Total specification of the operation of adding an entry to the


database
DoAddEntry AddEntry Success

NotMember

EntryAlreadyExists

605
2004 by SEC

Operation: Interrogating the Database


by Person
FindPhones
PhoneDB
name?: Person
numbers!: P Phone
name? dom telephones
numbers! = telephones ( {name?} )

UnknownName
PhoneDB
name?: Person
rep!: Report
name? dom telephones
rep! = Unknown name

606
2004 by SEC

Operation: Interrogating the Database


by Person (contd)

Relational image
y F ( U ) ( x: X xU x y F )

Total specification of the operation of interrogating the


database by person is given as:

DoFindphone Findphones Success

UnknownName

607
2004 by SEC

The Format of a Sequential System

Basic types

Global constants

User-defined sets

The state space

The and schemas

The initial state

The operations

The user-interface

The exceptional operations

Combine the operation

608
2004 by SEC

References

[DIL1994] A. Diller. Z: An Introduction to Formal Methods, 2nd Edition. John


Wiley & Sons, 1994

[PRE2004] R.S. Pressman. Software Engineering: a practitioners approach, 6th


edition. McGRAW-HILL, 2004.

[SOM2004] I. Sommerville. Software Engineering, 7th edition. Addison Wesley,


2004

[WOO88] J. Woodcock and M. Loomes. Software Engineering Mathematics:


Formal Methods Demystified. Pitman Publishing. 1988

[WOR92] J.B. Wordsworth. Software Development with Z: A Practical Approach


to Formal Methods in Software Engineering. Addision-Welsey Publishing
Company. 1992

609
2004 by SEC

Chapter 11
Advanced Topics in Software
Engineering

2004 by SEC

Chapter 11
Advanced Topics in Software
Engineering
11.1 Rapid Software Development
11.2 Component-Based Software Engineering
11.3 Web Engineering
11.4 Agent-Based Software Engineering
11.5 Software Engineering with Computational Intelligence
11.5.1 Knowledge-Based Software Engineering
11.5.2 Trade-off Analysis
11.5.3 Fuzzy Object Oriented Modeling
11.5.4 Goal-Driven Software Engineering
11.6 Real Time Software Design
Exercise

611
2004 by SEC

Вам также может понравиться