0% found this document useful (0 votes)
11 views500 pages

SWE Full Notes

The document discusses software processes and models, highlighting key activities such as specification, design, implementation, validation, and evolution. It contrasts plan-driven and agile processes, detailing models like the waterfall model and incremental development, along with their benefits and drawbacks. Additionally, it introduces agile software development principles and techniques, emphasizing rapid delivery and customer involvement in the development process.

Uploaded by

microwave python
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views500 pages

SWE Full Notes

The document discusses software processes and models, highlighting key activities such as specification, design, implementation, validation, and evolution. It contrasts plan-driven and agile processes, detailing models like the waterfall model and incremental development, along with their benefits and drawbacks. Additionally, it introduces agile software development principles and techniques, emphasizing rapid delivery and customer involvement in the development process.

Uploaded by

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

Software Engineering

CE2006/CZ2006

Software Processes

Software Processes (adapted from:


1
Software Engineering by Ian Sommerville)
Topics covered

 Software process models


 Process activities

Software Processes (adapted from:


2
Software Engineering by Ian Sommerville)
The software process

 A structured set of activities required to develop a


software system.
 Many different software processes but all involve:
 Specification – defining what the system should do;
 Design and implementation – defining the organization of the
system and implementing the system;
 Validation – checking that it does what the customer wants;
 Evolution – changing the system in response to changing
customer needs.
 A software process model is an abstract representation
of a process. It presents a description of a process from
some particular perspective.
Software Processes (adapted from:
3
Software Engineering by Ian Sommerville)
Software process descriptions

 When we describe and discuss processes, we usually


talk about the activities in these processes such as
specifying a data model, designing a user interface, etc.
and the ordering of these activities.
 Process descriptions may also include:
 Products, which are the outcomes of a process activity;
 Roles, which reflect the responsibilities of the people involved in
the process;
 Pre- and post-conditions, which are statements that are true
before and after a process activity has been enacted or a
product produced.

Software Processes (adapted from:


4
Software Engineering by Ian Sommerville)
Plan-driven and agile processes

 Plan-driven processes are processes where all of the


process activities are planned in advance and progress
is measured against this plan.
 In agile processes, planning is incremental and it is
easier to change the process to reflect changing
customer requirements.
 In practice, most practical processes include elements of
both plan-driven and agile approaches.
 There are no right or wrong software processes.

Software Processes (adapted from:


5
Software Engineering by Ian Sommerville)
Software process models

Software Processes (adapted from:


6
Software Engineering by Ian Sommerville)
Software process models

 The waterfall model


 Plan-driven model. Separate and distinct phases of specification
and development.
 Incremental development
 Specification, development and validation are interleaved. May
be plan-driven or agile.
 Integration and configuration
 The system is assembled from existing configurable
components. May be plan-driven or agile.
 In practice, most large systems are developed using a
process that incorporates elements from all of these
models.
Software Processes (adapted from:
7
Software Engineering by Ian Sommerville)
The waterfall model

Software Processes (adapted from:


8
Software Engineering by Ian Sommerville)
Waterfall model phases

 There are separate identified phases in the waterfall


model:
 Requirements analysis and definition
 System and software design
 Implementation and unit testing
 Integration and system testing
 Operation and maintenance
 The main drawback of the waterfall model is the difficulty
of accommodating change after the process is
underway. In principle, a phase has to be complete
before moving onto the next phase.

Software Processes (adapted from:


9
Software Engineering by Ian Sommerville)
Waterfall model problems

 Inflexible partitioning of the project into distinct stages


makes it difficult to respond to changing customer
requirements.
 Therefore, this model is only appropriate when the requirements
are well-understood and changes will be fairly limited during the
design process.
 Few business systems have stable requirements.
 The waterfall model is mostly used for large systems
engineering projects where a system is developed at
several sites.
 In those circumstances, the plan-driven nature of the waterfall
model helps coordinate the work.

Software Processes (adapted from:


10
Software Engineering by Ian Sommerville)
Incremental development

Software Processes (adapted from:


11
Software Engineering by Ian Sommerville)
Incremental development benefits

 The cost of accommodating changing customer


requirements is reduced.
 The amount of analysis and documentation that has to be
redone is much less than is required with the waterfall model.
 It is easier to get customer feedback on the development
work that has been done.
 Customers can comment on demonstrations of the software and
see how much has been implemented.
 More rapid delivery and deployment of useful software to
the customer is possible.
 Customers are able to use and gain value from the software
earlier than is possible with a waterfall process.

Software Processes (adapted from:


12
Software Engineering by Ian Sommerville)
Incremental development problems

 The process is not visible.


 Managers need regular deliverables to measure progress. If
systems are developed quickly, it is not cost-effective to produce
documents that reflect every version of the system.
 System structure tends to degrade as new increments
are added.
 Unless time and money is spent on refactoring to improve the
software, regular change tends to corrupt its structure.
Incorporating further software changes becomes increasingly
difficult and costly.

Software Processes (adapted from:


13
Software Engineering by Ian Sommerville)
Integration and configuration

 Based on software reuse where systems are integrated


from existing components or application systems
(sometimes called COTS -Commercial-off-the-shelf)
systems).
 Reused elements may be configured to adapt their
behaviour and functionality to a user’s requirements
 Reuse is now the standard approach for building many
types of business system

Software Processes (adapted from:


14
Software Engineering by Ian Sommerville)
Types of reusable software

 Stand-alone application systems (sometimes called


COTS) that are configured for use in a particular
environment.
 Collections of objects that are developed as a package
to be integrated with a component framework such as
.NET or J2EE.
 Web services that are developed according to service
standards and which are available for remote invocation.

Software Processes (adapted from:


15
Software Engineering by Ian Sommerville)
Reuse-oriented software engineering

 Requirements specification
 Software discovery and evaluation
 Requirements refinement
 Application system configuration
 Component adaptation and integration

Software Processes (adapted from:


16
Software Engineering by Ian Sommerville)
Advantages and disadvantages

 Reduced costs and risks as less software is developed


from scratch
 Faster delivery and deployment of system
 But requirements compromises are inevitable so system
may not meet real needs of users
 Loss of control over evolution of reused system elements

Software Processes (adapted from:


17
Software Engineering by Ian Sommerville)
Process activities

 Real software processes are inter-leaved sequences of


technical, collaborative and managerial activities with the
overall goal of specifying, designing, implementing and
testing a software system.
 The four basic process activities of specification,
development, validation and evolution are organized
differently in different development processes.
 For example, in the waterfall model, they are organized
in sequence, whereas in incremental development they
are interleaved.

Software Processes (adapted from:


18
Software Engineering by Ian Sommerville)
Key points

 Software processes are the activities involved in


producing a software system. Software process models
are abstract representations of these processes.
 General process models describe the organization of
software processes.
 Examples of these general models include the ‘waterfall’ model,
incremental development, and reuse-oriented development.
 Requirements engineering is the process of developing a
software specification.

Software Processes (adapted from:


19
Software Engineering by Ian Sommerville)
Key points

 Design and implementation processes are concerned


with transforming a requirements specification into an
executable software system.
 Software validation is the process of checking that the
system conforms to its specification and that it meets the
real needs of the users of the system.
 Software evolution takes place when you change
existing software systems to meet new requirements.
The software must evolve to remain useful.

Software Processes (adapted from:


20
Software Engineering by Ian Sommerville)
Software Engineering
CE2006/CZ2006

Agile Software Development

Agile Software Development (Adapted


from: Software Engineering by Ian 1
Sommerville)
Topics covered

 Agile methods
 Agile development techniques
 Agile project management

Agile Software Development (Adapted


from: Software Engineering by Ian 2
Sommerville)
Rapid software development

 Rapid development and delivery is now often the most


important requirement for software systems
 Businesses operate in a fast –changing requirement and it is
practically impossible to produce a set of stable software
requirements
 Software has to evolve quickly to reflect changing business needs.
 Plan-driven development is essential for some types of
system but does not meet these business needs.
 Agile development methods emerged in the late 1990s
whose aim was to radically reduce the delivery time for
working software systems
Agile Software Development (Adapted
from: Software Engineering by Ian 3
Sommerville)
Agile development

 Program specification, design and implementation are


inter-leaved
 The system is developed as a series of versions or
increments with stakeholders involved in version
specification and evaluation
 Frequent delivery of new versions for evaluation
 Extensive tool support (e.g. automated testing tools)
used to support development.
 Minimal documentation – focus on working code

Agile Software Development (Adapted


from: Software Engineering by Ian 4
Sommerville)
Plan-driven and agile development

 Plan-driven development
 A plan-driven approach to software engineering is based around
separate development stages with the outputs to be produced at
each of these stages planned in advance.
 Not necessarily waterfall model – plan-driven, incremental
development is possible
 Iteration occurs within activities.
Agile Software Development (Adapted
from: Software Engineering by Ian 5
Sommerville)
Plan-driven and agile development

 Agile development
 Specification, design, implementation and testing are inter-
leaved and the outputs from the development process are
decided through a process of negotiation during the software
development process.

Agile Software Development (Adapted


from: Software Engineering by Ian 6
Sommerville)
Agile methods

Agile Software Development (Adapted


from: Software Engineering by Ian 7
Sommerville)
Agile manifesto
 The aim of agile methods is to reduce overheads in the
software process (e.g. by limiting documentation) and to
be able to respond quickly to changing requirements
without excessive rework.
 We are uncovering better ways of developing software
by doing it and helping others do it. Through this work
we have come to value:
 Individuals and interactions over processes and tools
Working software over comprehensive documentation
Customer collaboration over contract negotiation
Responding to change over following a plan
 That is, while there is value in the items on the right,
we value the items on the left more.
Agile Software Development (Adapted
from: Software Engineering by Ian 8
Sommerville)
The principles of agile methods

Principle Description
Customer involvement Customers should be closely involved throughout the
development process. Their role is provide and prioritize new
system requirements and to evaluate the iterations of the
system.
Incremental delivery The software is developed in increments with the customer
specifying the requirements to be included in each increment.

People not process The skills of the development team should be recognized and
exploited. Team members should be left to develop their own
ways of working without prescriptive processes.
Embrace change Expect the system requirements to change and so design the
system to accommodate these changes.

Maintain simplicity Focus on simplicity in both the software being developed and
in the development process. Wherever possible, actively work
to eliminate complexity from the system.

Agile Software Development (Adapted


from: Software Engineering by Ian 9
Sommerville)
Agile method applicability

 Product development where a software company is


developing a small or medium-sized product for sale.
 Custom system development within an organization,
where there is a clear commitment from the customer to
become involved in the development process and where
there are few external rules and regulations that affect
the software.

Agile Software Development (Adapted


from: Software Engineering by Ian 10
Sommerville)
Agile methods across organizations

 Project managers who do not have experience of agile


methods may be reluctant to accept the risk of a new approach.
 Large organizations often have quality procedures and
standards that all projects are expected to follow and, because
of their bureaucratic nature, these are likely to be incompatible
with agile methods.
 Agile methods seem to work best when team members have a
relatively high skill level. However, within large organizations,
there are likely to be a wide range of skills and abilities.
 There may be cultural resistance to agile methods, especially in
those organizations that have a long history of using
conventional systems engineering processes.
Agile Software Development (Adapted
from: Software Engineering by Ian 11
Sommerville)
Agile development techniques

Agile Software Development (Adapted


from: Software Engineering by Ian 12
Sommerville)
Extreme programming

 A very influential agile method, developed in the late


1990s, that introduced a range of agile development
techniques.
 Extreme Programming (XP) takes an ‘extreme’ approach
to iterative development.
 New versions may be built several times per day;
 Increments are delivered to customers every 2 weeks;
 All tests must be run for every build and the build is only
accepted if tests run successfully.

Agile Software Development (Adapted


from: Software Engineering by Ian 13
Sommerville)
The extreme programming release cycle

Agile Software Development (Adapted


from: Software Engineering by Ian 14
Sommerville)
Extreme programming practices (a)
Principle or practice Description
Incremental planning Requirements are recorded on story cards and the stories to be
included in a release are determined by the time available and
their relative priority. The developers break these stories into
development ‘Tasks’. See Figures 3.5 and 3.6.

Small releases The minimal useful set of functionality that provides business
value is developed first. Releases of the system are frequent
and incrementally add functionality to the first release.

Simple design Enough design is carried out to meet the current requirements
and no more.
Test-first development An automated unit test framework is used to write tests for a
new piece of functionality before that functionality itself is
implemented.
Refactoring All developers are expected to refactor the code continuously as
soon as possible code improvements are found. This keeps the
code simple and maintainable.

Agile Software Development (Adapted


from: Software Engineering by Ian 15
Sommerville)
Extreme programming practices (b)

Pair programming Developers work in pairs, checking each other’s work and
providing the support to always do a good job.
Collective ownership The pairs of developers work on all areas of the system, so that
no islands of expertise develop and all the developers take
responsibility for all of the code. Anyone can change anything.
Continuous integration As soon as the work on a task is complete, it is integrated into
the whole system. After any such integration, all the unit tests in
the system must pass.
Sustainable pace Large amounts of overtime are not considered acceptable as
the net effect is often to reduce code quality and medium term
productivity
On-site customer A representative of the end-user of the system (the customer)
should be available full time for the use of the XP team. In an
extreme programming process, the customer is a member of
the development team and is responsible for bringing system
requirements to the team for implementation.

Agile Software Development (Adapted


from: Software Engineering by Ian 16
Sommerville)
Influential XP practices

 Extreme programming has a technical focus and is not


easy to integrate with management practice in most
organizations.
 Consequently, while agile development uses practices
from XP, the method as originally defined is not widely
used.
 Key practices
 User stories for specification
 Refactoring
 Test-first development
 Pair programming
Agile Software Development (Adapted
from: Software Engineering by Ian 17
Sommerville)
User stories for requirements

 In XP, a customer or user is part of the XP team and is


responsible for making decisions on requirements.
 User requirements are expressed as user stories or
scenarios.
 These are written on cards and the development team
break them down into implementation tasks. These tasks
are the basis of schedule and cost estimates.
 The customer chooses the stories for inclusion in the
next release based on their priorities and the schedule
estimates.

Agile Software Development (Adapted


from: Software Engineering by Ian 18
Sommerville)
A ‘prescribing medication’ story

Agile Software Development (Adapted


from: Software Engineering by Ian 19
Sommerville)
Examples of task cards for prescribing medication

Agile Software Development (Adapted


from: Software Engineering by Ian 20
Sommerville)
Refactoring

 Conventional wisdom in software engineering is to


design for change. It is worth spending time and effort
anticipating changes as this reduces costs later in the life
cycle.
 XP, however, maintains that this is not worthwhile as
changes cannot be reliably anticipated.
 Rather, it proposes constant code improvement
(refactoring) to make changes easier when they have to
be implemented.

Agile Software Development (Adapted


from: Software Engineering by Ian 21
Sommerville)
Refactoring

 Programming team look for possible software


improvements and make these improvements even
where there is no immediate need for them.
 This improves the understandability of the software and
so reduces the need for documentation.
 Changes are easier to make because the code is well-
structured and clear.
 However, some changes requires architecture
refactoring and this is much more expensive.

Agile Software Development (Adapted


from: Software Engineering by Ian 22
Sommerville)
Examples of refactoring

 Re-organization of a class hierarchy to remove duplicate


code.
 Tidying up and renaming attributes and methods to make
them easier to understand.
 The replacement of inline code with calls to methods that
have been included in a program library.

Agile Software Development (Adapted


from: Software Engineering by Ian 23
Sommerville)
Test-first development

 Testing is central to XP and XP has developed an


approach where the program is tested after every
change has been made.
 XP testing features:
 Test-first development.
 Incremental test development from scenarios.
 User involvement in test development and validation.
 Automated test harnesses are used to run all component tests
each time that a new release is built.

Agile Software Development (Adapted


from: Software Engineering by Ian 24
Sommerville)
Test-driven development

 Writing tests before code clarifies the requirements to be


implemented.
 Tests are written as programs rather than data so that
they can be executed automatically. The test includes a
check that it has executed correctly.
 Usually relies on a testing framework such as Junit.
 All previous and new tests are run automatically when
new functionality is added, thus checking that the new
functionality has not introduced errors.

Agile Software Development (Adapted


from: Software Engineering by Ian 25
Sommerville)
Test automation

 Test automation means that tests are written as


executable components before the task is implemented
 These testing components should be stand-alone, should
simulate the submission of input to be tested and should check
that the result meets the output specification. An automated test
framework (e.g. Junit) is a system that makes it easy to write
executable tests and submit a set of tests for execution.
 As testing is automated, there is always a set of tests
that can be quickly and easily executed
 Whenever any functionality is added to the system, the tests can
be run and problems that the new code has introduced can be
caught immediately.

Agile Software Development (Adapted


from: Software Engineering by Ian 26
Sommerville)
Pair programming

 In pair programming, programmers sit together at the


same computer to develop the software.
 Pairs are created dynamically so that all team members
work with each other during the development process.
 The sharing of knowledge that happens during pair
programming is very important as it reduces the overall
risks to a project when team members leave.
 Pair programming is not necessarily inefficient and there
is some evidence that suggests that a pair working
together is more efficient than 2 programmers working
separately.

Agile Software Development (Adapted


from: Software Engineering by Ian 27
Sommerville)
Pair programming

 Pair programming involves programmers working in


pairs, developing code together.
 This helps develop common ownership of code and
spreads knowledge across the team.
 It serves as an informal review process as each line of
code is looked at by more than 1 person.
 It encourages refactoring as the whole team can benefit
from improving the system code.

Agile Software Development (Adapted


from: Software Engineering by Ian 28
Sommerville)
Agile project management

Agile Software Development (Adapted


from: Software Engineering by Ian 29
Sommerville)
Agile project management

 The principal responsibility of software project managers


is to manage the project so that the software is delivered
on time and within the planned budget for the project.
 The standard approach to project management is plan-
driven. Managers draw up a plan for the project showing
what should be delivered, when it should be delivered
and who will work on the development of the project
deliverables.
 Agile project management requires a different approach,
which is adapted to incremental development and the
practices used in agile methods.
Agile Software Development (Adapted
from: Software Engineering by Ian 30
Sommerville)
Scrum

 Scrum is an agile method that focuses on managing


iterative development rather than specific agile practices.
 There are three phases in Scrum.
 The initial phase is an outline planning phase where you
establish the general objectives for the project and design the
software architecture.
 This is followed by a series of sprint cycles, where each cycle
develops an increment of the system.
 The project closure phase wraps up the project, completes
required documentation such as system help frames and user
manuals and assesses the lessons learned from the project.

Agile Software Development (Adapted
from: Software Engineering by Ian 31
Sommerville)
Scrum terminology (a)

Scrum term Definition

Development team A self-organizing group of software developers, which should be no more than
7 people. They are responsible for developing the software and other
essential project documents.
Potentially shippable The software increment that is delivered from a sprint. The idea is that this
product increment should be ‘potentially shippable’ which means that it is in a finished state and
no further work, such as testing, is needed to incorporate it into the final
product. In practice, this is not always achievable.

Product backlog This is a list of ‘to do’ items which the Scrum team must tackle. They may be
feature definitions for the software, software requirements, user stories or
descriptions of supplementary tasks that are needed, such as architecture
definition or user documentation.

Product owner An individual (or possibly a small group) whose job is to identify product
features or requirements, prioritize these for development and continuously
review the product backlog to ensure that the project continues to meet critical
business needs. The Product Owner can be a customer but might also be a
product manager in a software company or other stakeholder representative.

Agile Software Development (Adapted


from: Software Engineering by Ian 32
Sommerville)
Scrum terminology (b)

Scrum term Definition


Scrum A daily meeting of the Scrum team that reviews progress and prioritizes
work to be done that day. Ideally, this should be a short face-to-face
meeting that includes the whole team.

ScrumMaster The ScrumMaster is responsible for ensuring that the Scrum process is
followed and guides the team in the effective use of Scrum. He or she is
responsible for interfacing with the rest of the company and for ensuring
that the Scrum team is not diverted by outside interference. The Scrum
developers are adamant that the ScrumMaster should not be thought of
as a project manager. Others, however, may not always find it easy to
see the difference.

Sprint A development iteration. Sprints are usually 2-4 weeks long.

Velocity An estimate of how much product backlog effort that a team can cover in
a single sprint. Understanding a team’s velocity helps them estimate
what can be covered in a sprint and provides a basis for measuring
improving performance.

Agile Software Development (Adapted


from: Software Engineering by Ian 33
Sommerville)
Scrum sprint cycle

Agile Software Development (Adapted


from: Software Engineering by Ian 34
Sommerville)
The Scrum sprint cycle

 Sprints are fixed length, normally 2–4 weeks.


 The starting point for planning is the product backlog,
which is the list of work to be done on the project.
 The selection phase involves all of the project team who
work with the customer to select the features and
functionality from the product backlog to be developed
during the sprint.

Agile Software Development (Adapted


from: Software Engineering by Ian 35
Sommerville)
The Sprint cycle

 Once these are agreed, the team organize themselves to


develop the software.
 During this stage the team is isolated from the customer
and the organization, with all communications
channelled through the so-called ‘Scrum master’.
 The role of the Scrum master is to protect the
development team from external distractions.
 At the end of the sprint, the work done is reviewed and
presented to stakeholders. The next sprint cycle then
begins.

Agile Software Development (Adapted


from: Software Engineering by Ian 36
Sommerville)
Practical Aspects of Scrum

Agile Software Development (Adapted


from: Software Engineering by Ian 37
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 38
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 39
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 40
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 41
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 42
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 43
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 44
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 45
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 46
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 47
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 48
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 49
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 50
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 51
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 52
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 53
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 54
Sommerville)
 Estimated
Each PBI has a size estimate corresponding to the
effort required to develop the item. PO uses these
estimates as one of several inputs to help determine
a PBI’s priority (and therefore position) in the PB.

 Prioritized
 Useful to
prioritize the
near-term
items that
are destined
for the next
few Sprints

Agile Software Development (Adapted


from: Software Engineering by Ian 55
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 56
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 57
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 58
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 59
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 60
Sommerville)
Agile Software Development (Adapted
from: Software Engineering by Ian 61
Sommerville)
Teamwork in Scrum

 The ‘Scrum master’ is a facilitator who arranges daily


meetings, tracks the backlog of work to be done, records
decisions, measures progress against the backlog and
communicates with customers and management outside
of the team.
 The whole team attends short daily meetings (Scrums)
where all team members share information, describe
their progress since the last meeting, problems that have
arisen and what is planned for the following day.
 This means that everyone on the team knows what is going on
and, if problems arise, can re-plan short-term work to cope with
them.

Agile Software Development (Adapted


from: Software Engineering by Ian 62
Sommerville)
Scrum benefits

 The product is broken down into a set of manageable


and understandable chunks.
 Unstable requirements do not hold up progress.
 The whole team have visibility of everything and
consequently team communication is improved.
 Customers see on-time delivery of increments and gain
feedback on how the product works.
 Trust between customers and developers is established
and a positive culture is created in which everyone
expects the project to succeed.
Agile Software Development (Adapted
from: Software Engineering by Ian 63
Sommerville)
Key points

 Agile methods are incremental development methods that focus on


rapid software development, frequent releases of the software,
reducing process overheads by minimizing documentation and
producing high-quality code.
 Agile development practices include
 User stories for system specification
 Frequent releases of the software,
 Continuous software improvement
 Test-first development
 Customer participation in the development team.

Agile Software Development (Adapted


from: Software Engineering by Ian 64
Sommerville)
Key points

 Scrum is an agile method that provides a project


management framework.
 It is centred round a set of sprints, which are fixed time periods
when a system increment is developed.
 Many practical development methods are a mixture of
plan-based and agile development.
 Scaling agile methods for large systems is difficult.
 Large systems need up-front design and some documentation
and organizational practice may conflict with the informality of
agile approaches.

Agile Software Development (Adapted


from: Software Engineering by Ian 65
Sommerville)
Software Engineering
CE2006/CZ2006

Requirements Elicitation 1 of 3
Discussion Topics
• Requirements Elicitation
• Functional & Non-Functional
Requirements
• Data Dictionary
• Requirements Validation
• Prototype

Reading
– Bruegge Chapter 4 sections 4.1-4.3
2
Correct Requirements Elicitation and
Specification are Necessary for a Successful Project

3
Requirements Specification Activities
Requirements Specification SDLC
PMS: Document Requirements
SRS: Document Specification
Project
Elicit
Mission Design
Requirements
Statement

Implementation
Review
Requirements
Testing

Software
Validate Requirement Maintenance
Requirements Specification

4
Project Mission Statement
A simple short statement of what you intend to accomplish in
your project.

Companies and organisations have mission statements:

Google - to organize the world’s information and make it universally


accessible and useful.

BMW - the BMW Group is the world’s leading provider of premium


products and premium services for individual mobility.

Apple – Apple designs Macs, the best personal computers in the world,
along with OS X, iLife, iWork and professional software. Apple leads the
digital music revolution with its iPods and iTunes online store. Apple has
reinvented the mobile phone with its revolutionary iPhone and App
store, and is defining the future of mobile media and computing devices
with iPad.
5
Project Mission Statement
A project should have a project mission statement that describes the
project in two or three sentences.

Typically these sentences define

1. The problem: what will be done (scope and limits)


2. The stakeholders, developers and users
3. The outcomes and benefits of the project

Example:

The GoFast team will develop a website that enables airline travellers to
rate their travel experiences. This project will be considered complete when
the website has been tested and approved for release by the FactFinding
Organisation. This project supports the International Travel Watchdogs
objective to ensure air passengers can openly compare airlines.
6
Requirements Elicitation
Eliciting stakeholder needs and desires through:

• Interview
• Observation Learn problem
• Workshop domain
• Legacy Product Study Study user
• Competitive Product Study tasks
• Prototype

7
Types of Requirements
• Functional requirements describe interactions
between the system and the environment, to map
program inputs to program outputs. Basically the
things that the system must do.

• Non-Functional requirements describe the


properties the system must have, that is not
directly related to the functional behaviour of the
system.

8
Examples of Functional Requirements
System functionality to be performed
e.g., The library member must be able to search the library catalog.
e.g., The bank customer must be able to withdraw cash from the ATM.

Information to be processed
e.g. The system must display the current time in 24 hour format.
e.g. The system must display the temperature in degrees centrigrade in
the range -10C to +130C to one decimal place of accuracy.

Interface with other systems


e.g. The system must be able to use wifi to communicate all
transactions with a clients secure database.
e,g. The system must be able to control up to six robot arms
simultaneously.
9
Examples of
Non-Functional Requirements
Usability Help messages must be displayed in the
local language according to the user’s
locale.
Reliability After a system reboot, the full system
functionality must be restored within 5
minutes.
Performance When a book is placed in the checkout
pad, the system must detect it within 2
seconds.
Supportability The database must be replaceable with
any commercial product supporting
standard SQL queries. 10
Documenting the Requirements
•Use good technical writing style
• Write complete, simple, precise, unambiguous sentences using
active voice
• Define terms clearly and use them consistently
• Use clear layout and formatting (e.g., organizing the
requirements in a hierarchy)

• State requirements in an atomic manner, such


that the specification is verifiable and traceable
and unambiguous.

11
Atomic Requirements
When a computer is added, the tracking system requires the user
to specify its type and allow the user to provide a description.
Both these fields must be text of length >0 and <512 characters.

1.1 When a computer is added to the tracking system, the


user must enter the computer type.
1.1.1 The computer type data must be text of at least one
character and less than 512 characters.
1.2 When a computer is added to the tracking system, the
user must enter a description of the computer.
1.2.1 The description of the computer must be text of at
least one character and less than 512 characters.
12
Requirements Verifiability
Verifiable - sufficiently specific to be testable

The user interface must be user-friendly.


80% of first-time users must be able to enter a
simple search query within 2 minutes of
starting to use the system.

The system must control more than one drill press.

The system must control up to seven drill presses


concurrently.
13
Requirements Traceability

• The ability to track requirements from their


expression in an SRS (software requirements
specification) to their realization in design,
documentation, source code and their
verification in reviews and tests

• The ability to track dependencies among


requirements, system functions and system
components
14
Requirements Validation

Stakeholders – the system specified meets their needs


and desires (i.e. correct) and requirements are
prioritized
Development Team – requirements (and underlying
assumptions) are properly understood
• Review
• Walkthrough, inspection, critical review
• Checklist for completeness, consistency, unambiguity,
correctness
• Prototype
15
User Interface Prototype
A picture is worth a thousand words.
Sketches or a model of what a system will look like brings the
requirements to life for all stakeholders.

Can be implemented using

• Story Boarding – sequence of graphics


showing different views of the interface in a
specific interaction.

• Still images created on a computer.

• Interactive prototype that illustrates some simulated


dialogue
16
The Data Dictionary
The problem domain glossary
• Ensures consistent unambiguous terminology that all
stakeholders can agree on

E.g. within a university/college define the terms

• Programme of Study
• Course
• Degree Programme

• Ensures specialised terms are defined E.g.


• Lecture
• Tutorial
• Class
• Laboratory
• Seminar
17
Example of Data Dictionary
Term Definition
Program of Study A university program that a student enrolls into. There are three levels
of programs: undergraduate, master, and PhD.
Semester There are four semesters in an academic year. Semester 1 and Semester
4 have 13 teaching weeks. Semester 2 and Semester 3 have 5 teaching
weeks.,
Course A course is a basic unit of teaching. A course must be either
compulsory or elective. A course must include lectures and tutorials .
Some courses may have labs.
Lecture The traditional form of class that are delivered in lecture theaters. Each
lecture will be video recorded and published in the learning
management system
Tutorial The interactive, small-size classes that are conducted in technology-
enhanced tutorial rooms. Tutorials will not be video recorded.
….

Focus on problem domain terms,


not implementation terms.
18
Software Engineering
CE2006/CZ2006

Requirements Elicitation 2 of 3
Discussion Topics

• Use Case modeling


• Use Case diagram
• How to develop Use Cases from functional
requirements

• Reading
– Bruegge Chap 4.4
– Fowler Chap 9
UML: Unified Modeling Language
• Created by Booch, Jacobson & Rumbaugh in 1996

• Version 1.1 was adopted by the Object Management Group (OMG) in 1997. The latest
version is 2.5 (August 2015).

• What is it?
It is a graphical notation with textual annotation for specifying,
documenting and communicating various aspects of the
structure, functionality and dynamic behaviour of complex
software systems.

It is NOT a programming language (although its supporters


are working towards that goal).
It is NOT the answer to all your modelling and design
problems.

UML is an Industry Standard tool and therefore


Provides Standardization!
In the laboratory you can use Visual Paradigm to draw
UML diagrams for your project work.
UML Diagram Types
Diagram

Structure Behavior
Diagram Diagram

Class Component Object Activity Use Case State


Diagram Diagram Diagram Diagram Diagram Machine
Diagram
Composite Deployment Package Interaction
Structure Diagram Diagram Diagram
Diagram

Sequence Interaction
Not all diagrams are needed to specify a Diagram Overview Diagram
System. Only use the diagrams that are useful
and necessary to define the system. Communication Timing 4
Diagram Diagram
We will only cover these diagrams in this course
(Others will be covered in CZ3003)
Software Development Lifecycle Activities

Requirements System Detailed Implemen-


Analysis Testing
Elicitation Design Design tation

Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By

class...
class...
class... ?
class.... ?
Use Case Application Solution
Domain Subsystems Source Test
Model Domain
Objects Code Cases
Objects
Use Cases
• A use case is a software and system
engineering term that describes how a
user uses a system to accomplish a
particular goal. – Google

• A use case is a list of actions or event


steps typically defining the interactions
between a role (known as an actor) and
a system to achieve a goal. – Wikipedia
Functional Requirements
versus Use Cases
• Both are about system functionalities
– Functional requirements: what (user,
external system, functionality, and
information)
– Use cases: how (actors interact with
system functionality)

Functional requirements are the staring points


for use case modeling.
Use Case Model

Use Case Diagram (static)


+
Use Case Description (dynamic)

• Provides coherent visual and textual description of


system functionalities
• In use-case-driven iterative development, prioritise use
cases for implementation
Use Case Diagram Elements
Name Notation Description
Actor An external entity that
interacts with system

Use Case Unit of functionality


Activity performed by system,
which yields result /
value for Actor
Association Connects Actor to Use
Cases(s) in which they
participate
Example of Use Case Diagram
ATM Machine

Withdraw
money

Verify
Customer Customer Bank

Check
Balance
Use Case Associations

• Dependencies between use cases are represented by


use case associations
• Associations are used to reduce complexity
• Two types of use case associations
– Includes
– Extends
<<include>>:Functional Decomposition
• Problem: A function in the original problem statement is too complex
• Solution: Describe the function as the aggregation of a set of simpler
functions. The associated use case is decomposed into shorter use
cases

Manage Incident

<<include>> <<include>>
<<include>>
Create Handle Close
Incident Incident Incident
<<include>>: Reuse Existing Functionality
• Problem: There are overlaps among use cases.

• Solution: The include association from use case A to use case B


indicates that an instance of use case A performs all the behaviour
described in use case B (“A delegates to B”)

• Example: Use case “View Map” describes behaviour that can be used
by use cases “Open Incident” and “Allocate Resources”

Open <<include>>
Incident

View Map

Allocate
<<include>>
Resources
<<extend>>: Adding Optional Functionality
• Problem: The functionality in the original problem statement needs
to be extended.

• Solution: An extend association from use case A to use case B

• Example: “ReportEmergency” is complete by itself, but can be


extended by use case “Help” for a scenario in which the user
requires help

Help

<<extend>>
Report
Emergency
Include, extend associations

• Include = reuse of functionality


– denotes a dependency on another use case. Included
Use Cases are always used in a parent Use Case.

• Extends = adding (optional) functionality. Extends are


only used in the parent Use Case in exceptional or
unusual circumstances.

.
Example Functional Requirements
of a Library Management System
1. The library member must be able to search the system for
library materials
2. The library member must be able to loan library materials
3. The library management system must verify the library
membership with the University Account System before the
library member can loan library materials
4. The library member must return library materials via library
dropoff kiosk
5. The library management system must send overdue notice
using the CITS Email Sever to the library member
6. When there are network issues to connect to CITS Email
Server, the library management system must log the event
Identify Potential Actors

1. The library member must be able to search the system for


library materials
2. The library member must be able to loan library materials
3. The library management system must verify the library
membership with the University Account System before the
library member can loan library materials
4. The library member must return library materials via library
dropoff kiosk
5. The library management system must send overdue notice
using the CITS Email Sever to the library member
6. When there are network issues to connect to CITS Email
Server, the library management system must log the event
Identify Potential Use Cases

1. The library member must be able to search the system for


library materials
2. The library member must be able to loan library materials
3. The library management system must verify the library
membership with the University Account System before the
library member can loan library materials
4. The library member must return library materials via library
dropoff kiosk
5. The library management system must send overdue notice
using the CITS Email Sever to the library member
6. When there are network issues to connect to CITS Email
Server, the library management system must log the event
Identify Potential Associations
Between Use Cases
1. The library member must be able to search the system for
library materials
2. The library member must be able to loan library materials
3. The library management system must verify the library
membership with the University Account System before the
library member can loan library materials
4. The library member must return library materials via library
dropoff kiosk
5. The library management system must send overdue notice
using the CITS Email Sever to the library member
6. When there are network issues to connect to CITS Email
Server, the library management system must log the event
Use Case Diagram 1

Loan
Material Verify University
Member AccountSystem

Return
Material
Member

Search
Material
Send
CITS
Log Overdue
EmailSystem
Network Notice
Issues
Use Case Diagram 2

Loan
Material
Member
Login

University
Search AccountSystem
Material
Member
Return
Material
Send CITS
Log Overdue EmailSystem
Network Notice
Issues
Use Case Diagram 3

Loan
Material Verify University
Member AccountSystem
Member
Search
Material

Return
Material
Send
Library Overdue
Dropoff Log CITS
Network Notice
Kiosk EmailSystem
Issues
Software Engineering
CE2006/CZ2006

Requirements Elicitation 3 of 3
Discussion Topics

• Use Case description


• Review of requirement elicitation process
• Software Requirements Specification (SRS)

• Reading
– Bruegge Chap 4.4
– Fowler Chap 9
Use Case Model

Use Case Diagram (static)


+
Use Case Description (dynamic)

• Provides coherent visual and textual description of


system functionalities
• In use-case-driven iterative development, prioritise use
cases for implementation
Each Use Case Must have a Use Case
Description that contains
• Participating Actors (Initiating Actor)
– A use case can have more than one participating actors
– Initiating actor triggers the use case
– If the use case is triggered by a system event or another use case, the
initiating actor is NULL

• Entry conditions (Pre-condition)


– The system state must be satisfied to execute a use case
• Exit Conditions (Post-condition)
– The system state must be reached after executing a use case
Each Use Case Must have a Use Case
Description that contains
• Flow of Events (a.k.a Normal or Main Successful Flow)
– Step #1 – How Actor triggers the use case
– Step #2 – How System responds
– Step #3 – …

• Alternative Flows
– Variations or errors in the interaction (e.g., wrong username/password)
– Return back to the normal flow of events

• Exceptions
– Exceptional situations that cause the failure of the use case (e.g.,
network not available)
Example of Use Case Diagram
ATM Machine

Withdraw
money

Verify
Customer Customer Bank

Check
Balance
Example #1 Actor, Entry/Exist Conditions
The Bank Customer Withdraw Money Using ATM
Participating actor:
Bank Customer (Initiating Actor), Bank

Entry Conditions:
1. Bank Customer has a Bank Account with the Bank
and
2. Bank Customer has an ATM Card and PIN
Exit Conditions:
1. Bank Customer receives the requested cash
or
2. Bank Customer receives an explanation from the
ATM why the cash could not be dispensed
Example #1 Flow of Events (Normal Flows)
Actor steps System steps

1.The Bank Customer inputs the


card into the ATM 2.The ATM requests the input of
a six-digit PIN.
3. The Bank Customer enters a PIN
4. The ATM verifies the card and PIN
with the account information in the
Bank
5.If the card and PIN is verified the
ATM requests the amount to withdraw
6. The Bank Customer enters an
amount 7. The ATM verifies the amount is
available in the customer account
8. If the customer account has
sufficient funds, the ATM outputs
the money and card and a receipt
9. The Bank Customer removes
card, receipt and money
Example #1 Flow of Events (Normal Flows)
1.The Bank Customer inputs the
card into the ATM
2.The ATM requests the input of
a six-digit PIN.
3. The Bank Customer enters a PIN
4. The ATM verifies the card and PIN
with the account information in the
Bank
5.If the card and PIN is verified the
ATM requests the amount to withdraw
6. The Bank Customer enters an
amount
7. The ATM verifies the amount is
available in the customer account
8. If the customer account has
sufficient funds, the ATM outputs
the money and card and a receipt
9. The Bank Customer removes
card, receipt and money
Example #1 Alternative Flows

AF-S5: If the card and PIN are invalid


1. The ATM displays the message “Invalid card and
PIN. Please try again!” for 2 seconds
2. The ATM returns to the step 2

AF-S8: If the customer account has insufficient funds


1. The ATM displays the message “Insufficient funds
in your account! Please enter a smaller amount!” for 2
seconds
2. The ATM returns to the step 6
Example #1 Exceptions

EX1: If the Bank Customer enters invalid PIN for three


times
1. The ATM displays the message “Card is
suspended! Please call the customer service (1633) to
reactive the card” for 2 seconds
2. The ATM outputs the card

EX2: If the ATM has insufficient funds


1. The ATM displays the message “This ATM is off-
service due to insufficient funds!” at the start screen
2. The ATM does not accept the card
Example #2 Course Registration System
• Registrar manages the course curriculum for a semester

• Students select 4 primary courses and 2 alternate courses


• Students use the system to add and drop courses till the end of the
second week of the semester
• Once a Student registers courses for a semester, the registration
system notifies the Billing System so the student may be billed for
the semester

• Professors use the system to find their course schedule

• All users of the registration system must login the course


registration system with the assigned password before performing
the tasks
Example #2 Course Registration System
• Registrar manages the course curriculum for a semester

• Students select 4 primary courses and 2 alternate courses


• Students use the system to add and drop courses till the end of the
second week of the semester
• Once a Student registers courses for a semester, the registration
system notifies the Billing System so the student may be billed for
the semester

• Professors use the system to find their course schedule

• All users of the registration system must login the course


registration system with the assigned password before performing
the tasks
Example#2 Use Case Diagram
• Actors are identified and Use Case diagram are
created to visualize the relationships between
actors and Use Cases

Select Find
Courses Course
<<include>> Schedule
Student Professor
Login <<include>>

<<include>>
Manage Manage
Billing of Students Curriculum

Billing System Registrar


Example#2 Use Case Diagram
• More use cases

Select Find
Courses Course
Schedule
Add Professor
Courses <<include>>

Manage
Drop <<include>>
Curriculum
Student Courses
Login<<include>>
Registrar
<<include>>
Send
Notice AddCourse DeleteCourse ReviewCourses

Billing System
Example#2 Use Case Description:
Manage Curriculum - Flow of Events
1. The system uses the included use case Login to verify the Registrar.
2. On successful login, the system prompts the Registrar to select the
current semester or a future semester.
3. The Registrar selects the desired semester.
4. The system prompts the Registrar to select the desired activity: ADD,
DELETE, REVIEW, or QUIT.
5. If the Registrar selects the activity ADD, then he uses the included
use case AddCourse to add a course.
6. If the Registrar selects the activity DELETE, then he uses the
included use case DeleteCourse to delete a course.
7. If the Registrar selects the activity REVIEW, then he uses the
included use case ReviewCourses to review existing courses.
8. If the Registrar selects the activity QUIT, the system returns to the
semester selection screen.
A Use Case Template should be
used to describe each Use Case
See the Use Case Description Template available on NTULearn course website.

Use Case ID:


Use Case Name:
Created By: Last Updated By:
Date Created: Date Last Updated:

Actor:
Description:
Preconditions:
Postconditions:
Priority:
Frequency of Use:
Flow of Events:
Alternative Flows:
Exceptions:
Includes:
Special Requirements:
Assumptions:
Notes and Issues:
Review of Requirement
Elicitation Process
Key Concepts and Deliverables

• Functional requirements
• Use case model
– Use case diagram
– Use case description
• Non-functional requirements
• Data dictionary (problem domain
glossary)
• UI prototype
Steps 1. Project Team
Review clients specification and review any legacy
or competitive products (if available) to:
1. Atomise requirements.
2. Identify Actors
3. Identify main Use Cases (Functional
Requirements)
4. Identify Non-Functional requirements
5. Initiate generation of Data Dictionary
6. Identify uncertainties to clarify with client (TBD
– To Be Determined). Do not guess the user
requirements.
Step 2. Project Team meet Client
(Choose appropriate meeting - Interview, Observation,
Workshop ……..)

The agenda and necessary outcomes of the meeting must


be set and agreed before the meeting.
Do not waste the Project Teams or Clients time in
unstructured unproductive meetings.

Typical Agenda
1. Present and walk through the initial requirements and
Data Dictionary. Get agreement.
2. Clarify uncertainties (the TBD issues).
3. Discuss any new requirements the client identifies.
Repeat Steps 1 & 2.
Project Team and Client
The refining process continues iteratively until all
uncertainties and ambiguities of the functional and non-
functional requirements and the definition of terms in the
data dictionary are agreed with the clients.

A prototype demonstrating the appearance or user


interface and dialogues of the functionality may be
produced to show the intended functionality.

Try to minimize number of meetings by making meetings


productive.
Software Engineering
CE2006/CZ2006

Requirements Analysis: Conceptual Models

Shen Zhiqi
Email: [email protected]
Office: N4-02b-43
Discussion Topics
 Analysis Modeling
 Class Diagram

 Reading
 Bruegge Chap 2.3 Modelling Concepts
 Chap 2.4.2 Class Diagrams
 Fowler Chap 3 Class Diagrams
Chap 6 Object Diagrams
Software Development Lifecycle Activities

Requirements Requirement System Detailed Implemen-


Testing
Elicitation Analysis Design Design tation

Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By

class...
class...
class... ?
class.... ?
Use Case Problem Solution
Domain Subsystems Source Test
Model Domain
Objects Code Cases
Objects
Requirements Elicitation versus
Requirements Analysis
• Requirements Elicitation:
– Purpose: finding out what customers want
– Output: a description of the system in terms
of actors and use cases
• Requirements Analysis:
– Purpose: produce a system model that is
correct, complete, consistent, unambiguous
based on use cases
– Output: conceptual model (system structure)
+ dynamic model (system behavior)
Formalizing Requirements with
Analysis Models
• Clarifies structural and dynamic aspects of
system to be build
• Validates requirements
• Underpins solution modelling
Requirement Analysis Goals

• Conceptual model (structural aspect)


– Analyze use cases to identify the objects
and roles of objects involved in the system
• Dynamic model (dynamic aspect)
– Determine how to fulfill the processes
defined in the use cases and which objects
do these processes
Conceptual Model
• Objects: Anything that has a state and exhibits
behavior
– e.g., Bus, Dog, Company
– e.g., LoginForm, UserVerifier, UserList
• Operations: Procedures through which objects
communicate amongst themselves
– e.g: Bus: Stop, Start. Dog: Bark, Growl. Company: Sell,
Quote.
– e.g., LoginForm: submit. UserVerifier: autheticate. UserList:
SearchUser
• Attributes: Variables that hold state information
– e.g. Bus: Seats, Colour. Dog: Name, Breed. Company:
Name, Employees
Conceptual Model in Class Diagram

• Document and visualize conceptual


model in class diagram
– Object Class
– Roles (Attributes and operations) of
object Attributes and methods of
class
Classes Name (The class name is
the only mandatory
information)
Type
TarifSchedule
Table zone2price Attributes
Enumeration getZones()
Price getPrice(Zone) Operations
Methods
Signature

• A class represents a concept


• A class encapsulates states (attributes) and behaviour (operations)
Each attribute has a type
Each operation has a signature
Associations

TarifSchedule
TripLeg
Price
Enumeration getZones()
Price getPrice(Zone)
* * Zone

Many-to-Many Associations

Associations denote relationships between classes


The multiplicity of an association end denotes how many
objects the instance of a class can legitimately reference.

Multiplicity is a number (e.g. 3), a range of numbers (1..6) or


a large unspecified number (many) (*)
1-to-1 and 1-to-many Associations

Person 1 1 Head

name:String size : Double


1-to-1 association

Point
Polygon 1
* x: Integer
1-to-many association
y: Integer
draw()
Class Relationships

• generalization: an inheritance relationship


– inheritance between classes
– interface implementation

• association: a usage relationship


– dependency
– aggregation
– composition
Class Relationships
 generalization (inheritance) relationships
 hierarchies drawn top-down with arrows pointing
upward to parent
 line/arrow styles differ, based on whether parent
is a(n):
 class:

solid line, black arrow


 abstract class:

solid line, white arrow


 interface:

dashed line, white arrow

 we often don't draw trivial / obvious


generalization relationships, such as drawing the
Object class as a parent
Class Relationships Car

1
 aggregation: "is part of" aggregation
1
 symbolized by a clear white diamond
Engine

 composition: "is entirely made of" Book


 stronger version of aggregation composition
 the parts live and die with the whole
1
 symbolized by a black diamond
*
Page
 dependency: "uses temporarily"
 symbolized by dotted line
dependency
 often is an implementation
detail, not an intrinsic part of
that object's state Lottery Random
Ticket
Requirement Analysis and Conceptual
Modeling Activities
1. Identify the Classes Use case model → Class diagram
2. Find the attributes for each Class
3. Find the methods/operations for each Class
4. Find the associations between Classes

Class name BankCustomer


Associations with
AccountName Other Classes
Class attributes CreditLimit
AccountNumber

UpdateAccount()
Class methods WithdrawCash()
Identification of Initial Objects or Classes

Look for
1. Recurring nouns / concepts in the use cases
2. Real-world entities the system must track
3. Application (problem) domain terms in data
dictionary

Review definitions and attributes with stakeholders


Stereotypes of Classes

Boundary Class <<boundary>>


– interaction between Actor & System

Control Class <<control>>


– logic to realize use case

Entity Class <<entity>>


–information tracked by System
Example:
EnterSecureFacility Use Case Description
Identify recurring nouns, real-world entities,
domain terms – these may be Classes
Flow of Events:
1. User presses finger on FingerprintReader.
2. FingerprintReader scans fingerprint and sends image to
the FacilityAccessSystem.
3. The FacilityAccessSystem validates fingerprint and
unlocks EntryGate.
4. EntryGate sends a signal to the FacilityAccessSystem that
it has opened.
5. The FacilityAccessSystem locks EntryGate, logs entry
event and increments occupant count.
Example:
EnterSecureFacility Use Case Description
Identify recurring nouns, real-world entities,
domain terms – these may be Classes
Flow of Events:
1. User presses finger on FingerprintReader.
2. FingerprintReader scans fingerprint and sends image to
the FacilityAccessSystem.
3. The FacilityAccessSystem validates fingerprint and
unlocks EntryGate.
4. EntryGate sends a signal to the FacilityAccessSystem that
it has opened.
5. The FacilityAccessSystem locks EntryGate, logs entry
event and increments occupant count.
Example:
EnterSecureFacility - Possible Classes

FingerprintReader EntryGate

FacilityAccessSystem Employee
(Fingerprint?)
Stereotyping to Indicate
Class Responsibilities
<<read>>
Employee

FingerPrint <<call>> FacilityAccess


Reader System

client supplier <<singal>>

Usage dependency

EntryGate
Summary

• Analysis Modelling
• Class Diagram
Software Engineering
CE2006/CZ2006

Requirements Analysis: Dynamic Models 1


Discussion Topics

• Interaction Diagrams
– Sequence Diagram
– Communication Diagram

• Reading
– Bruegge chap. 2.4.3, 5.4.4
– Fowler chap.4 and chap. 12 Bruegge
chap.2.4.4, 5.4.9
– Fowler chap.10
Requirement Analysis Goals

• Conceptual model (structural aspect)


– Analyze use cases to identify the objects
and roles of objects involved in the system

• Dynamic model (dynamic aspect)


– Determine how to fulfill the processes
defined in the use cases and which objects
do these processes
Document and Visualize Dynamic
Model
• Using the following types of diagrams
– Sequence diagram
– Communication diagram
– State machine
– Activity diagram
Sequence Diagram and
Communication Diagram
Captures how a group of objects (in a Class Diagram)
interact or collaborate to achieve an activity as described in
a Use Case.

Usually captures the dynamics of a single scenario and the


sequence of messages that are passed between the objects
and the sequence of events that happen during the
scenario.

Both diagrams essentially show the same information –


 Sequence diagrams emphasise the sequence and
timing of calls and messages between the objects
 Communication diagrams emphasise the
communication links between the objects
Example: EnterSecureFacility Use Case Description

Flow of Events:
1. User presses on FingerprintReader.
2. FingerprintReader scans fingerprint and validates image with the
FacilityAccessValidator.
3. The FacilityAccessValidator finds fingerprint in the EmployeeList.
4. The FacilityAccessValidator validates fingerprint and unlocks EntryGate.
5. ...

Too much text!


Class Diagram

Time ordering info is lost!


<<read>>
Employee

FingerPrint <<call>> FacilityAccess


Reader System

<<singal>>
Boundary Object
How to visualize the
Controller Object workflow
EntryGate
Entity Object
Sequence Diagram: Definitions

1 • Used during requirement analysis


– To refine use case descriptions
– Find additional/missing objects
1. Objects are represented by
2 rectangles
2. Messages are represented by
3
arrows
4 3. Activations are represented by
narrow bars
4. Lifelines are represented by
dashed lines
Example: EnterSecureFacility Use Case Description
Drawing sequence diagram:
Flow of Events: Identify important verbs
1. User presses on FingerprintReader.
2. FingerprintReader scans fingerprint and validates image with the
FacilityAccessValidator.
3. The FacilityAccessValidator finds fingerprint in the EmployeeList.
4. The FacilityAccessValidator validates fingerprint and unlocks EntryGate.
5. ...
Example: EnterSecureFacility Sequence Diagram
sd EnterSecureFacility

1
Objects :EmployeeList
:FingerprintReader :FacilityAccess
:User Validator
press Async
scan
Sync
3 Action or message validate(image)
find(image)
Active found
4 Period of
object

Return
2 Lifeline of Object
Refine EnterSecureFacility Use Case Description

Flow of Events:
1. User presses on FingerprintReader.
2. FingerprintReader scans fingerprint and sends the image to
FacilityAccessValidator.
3. The FacilityAccessValidator validates fingerprint with the scanned
fingerprint image.
4. If the fingerprint image is found in the employee list, the
FacilityAccessValidator unlocks EntryGate.
5. …

Alternative Flows:

AF-4. If the fingerprint image is not found in the employee list


1. FingerprintReader displays a “Please try again” message
2. Go back to Step 1
Example: EnterSecureFacility Sequence Diagram
sd EnterSecureFacility
Partial diagram for slide clarity

:FingerprintReader :FacilityAccess :EmployeeList :Gate


:User Unlocker
press Validator

scan Interaction
frame
validate(image)
find(image)

Frame found
label
alt [found==true]
unlock(image)

invaliduser [else]
Types of Interaction Frames
sd sequence diagram

ref reference another sequence diagram

loop the actions loop until guard condition is false


(as in while, for)

opt/alt optional/alternative flow


(as in if-then, if-then-else, switch-case)

par each action is run in parallel

See UML cheetsheet for examples!


Refine EnterSecureFacility Sequence Diagram
sd EnterSecureFacility Partial diagram for slide clarity

:FingerprintReader :FacilityAccess :EmployeeList :Gate


:User Unlocker
press Validator

scan

validate(image)
find(image)
found

alt [found==true]
unlock(image)
invaliduser
[else]

opt [invaliduser==true]
displayRetryMsg
Refine Class Diagram Employee

fpimage
isYou(image)
Partial diagram for slide clarity

<<call>>
Employee
List
FingerPrint
<<call>> FacilityAccessValid find(image)
Reader
ator
Unlocker
press()
validate(image)
scan() : image
<<call>> Gate
beep()
Unlocker
displayRetryMsg() <<singal>>
unlock()
EntryGate
Class Diagram

Time ordering info is lost!


<<read>>
Employee

FingerPrint <<call>> FacilityAccess


Reader Validator Gate
<<call>>
Unlocker

<<singal>>
Boundary Object
How to visualize the
Controller Object workflow
EntryGate
Entity Object
Communication diagram

• Models the interaction between objects or parts in


terms of sequenced messages.
• Represents a combination of information taken
from Class, Sequence, and Use-Case Diagrams
describing both the static structure and dynamic
behavior of a system.
• Messages are labeled with a chronological number.
• Compare with sequence diagram:
• Communication diagrams show which elements
each one interacts with better
• Sequence diagrams show the order in which
the interactions take place more clearly.
Example: EnterSecureFacility Communication Diagram

Partial diagram for slide clarity


2: scan

3: validate(image) : validuser
Finger Facility
1: press print Access
Reader Validator

5: unlock()
4: find(image) : found

Gate Employee
Unlocker List
Communication diagram (example)
Communication diagram (example)
Communication diagram (example)
Communication diagram (example)
Communication diagram (example)
Summary
Sequence Diagrams are useful for:
Refining the Use Cases
• Identifying missing steps and flows Visual Paradigm
can automatically
• Identifying unnecessary steps and flows
switch between the
Refining the Class Diagrams (objects) two if you create
• Identifying missing classes the Sequence
• Identifying unnecessary classes Diagram first.
• Identifying class operations
• Identify class attributes
Identifying all relationships between classes

Communication Diagrams serve a similar purpose by


visualizing the sequence of messages differently.

In general, you need a sequence or communication


diagram for each use case.
Summary
• Why sequence diagram?
– Use cases are too wordy and also hard to read
– Class diagram loses information on time ordering
– Sequence diagram is more detailed than use case, not
for non-technical communication in general.
• When to use sequence diagram?
– Good at capturing interactions between objects
• Use sequence diagram to look at the behaviour of several
objects within a single use case.
– Not so good at precise definition of behaviours
• State diagrams (single object in many use cases).
• Activity diagram (many use cases and many threads).
• We will look at them later in the course.
Software Engineering
CE2006/CZ2006

Requirements Analysis: Dynamic Models 2


Discussion Topics

• Interaction Diagrams
– State Machine Diagrams
– Activity Diagrams
• Software Requirement Specifications

• Reading
– Bruegge chap. 2.4.3, 2.4.4, 2.4.5
– Fowler chaps. 4, 10 and 12
State Machine Diagram
Also known as Statecharts, Finite State Automata.

Models a system or an object based on the “States” it can be in.

A “State” is a stable condition of a system, that can exist for a


period of time, or for all time, until some ACTION drives the
system into another stable state.

Most systems will have a finite number of states in which it can


be depending on the previous state and actions which move it to
another state.
• e.g. a 2-bit binary counter has 4 states and moves from one
state to the next when a clock signal drives it to the next state.

-> 00 -> 01 -> 10 -> 11 –


State Machine Diagram
In UML, a State is represented as a rectangle with rounded
corners with a name at the top and optionally a description
of the state and/or actions and activities performed while in
that state.

State name
State name
In this state the system is ….
Entry / action
Exit / action
Do / activity

State name
State Machine Diagram
A state machine diagram begins with a start node followed by a series
of states connected by transitions and finally an end node (unless the
system is in an infinite loop and there is no end node).

A transition from one state to the next is assumed to be instantaneous in


response to an event. A transition can have optionally:
• event: event triggers the transition
• guard: the condition which must be true to take the transition
• action: action to do during the transition

State name 1 event(arguments)[guard]/action


Entry / action
Exit / action
Do / activity State name 2
Entry / action
Exit / action
Do / activity
Dialog Map: State Machine Diagrams in
Prototyping
Prototyping is a technique to reduce the risk of building the wrong
product, or of building the right product badly.

Using a State Machine Diagram and a prototype users can experiment


with the navigation options and preview the functionality available
at each screen to assess the look and feel of the system.

Many user interfaces can be thought of as finite state machines,


with only one display screen or window active at a time (a state), and
defined conditions for moving from one state to another (a transition).

Such diagrams are sometimes called dialog maps.


• The dialog map helps us find missing or incorrect navigation
pathways early, when they are cheap to fix.
• We can also spot opportunities for reuse and redundancies in the user
interface, without worrying about the details of screen design
prematurely.
Example: Dialog Map of Vending Machine
Power On / Reset Power Off
Idle
entry / amount := 0
do / display(greeting)

insert(c:Coin)

Accumulate insert(c:Coin)
entry / amount := amount+c.amount
do / display(amount)

[amount=0] select(i:item)[amount is enough for i]

Vend
entry / amount := amount-i.cost
do / dispense(i); display(vending)
[amount > 0 ]
ReturnChange
do / return(amount)
Example: Dialog Map of Student
Management System

Students List

add new cancel save

Student Details

next next
Personal Info Academic Info Activity Info
Form back Form back Form
Practice: Stopwatch Functionality

Click Close
Ready Window
Click Reset entry / Reset
time
Click Start

Continuous Update
Click Close
do / Display time Window
elapsed

Click Stop Click Start

Time Paused
Click Close
Window
UML Activity Diagram
• Activities are the execution of one or more basic
operations. Represented by a rounded rectangle.

• Control flow between activities represented by arrows.

• Forks are when control flow has one input and two or more
outputs (go to concurrent activities).

• Joins are when two or more control flows come together


into a single control flow.

• Decision boxes (branches) are when control flow can go in


one of several directions depending on a condition.

• Merge several branches into one branch


Example:
Activity Diagram of Do Laundry
Do Laundry
Sort Clothes in Whites
and Darks

Wash Whites Wash Darks

Dry Clothes
Example:
Activity Diagram of Dry Clothes
Dry
Clothes

Run Dryer

[still wet]

[else]

Fold Clothes
More Examples
More Examples
Example of Activity Diagram
Difference between State Machine
Diagram and Activity Diagram
Activity diagrams are used as a flow chart of activities performed by the
system. They describe the workflow behavior of a system in terms of
activities.

State machine diagram models a system or an object based on the


“States” it can be in.

We have already used


Activity Diagrams
Review of Requirement
Elicitation and Analysis Process
Activity Diagram of Requirement
Elicitation and Analysis
5. Identify Classes 6. Add associations, multiplicities
Add Sequence Diagrams,
1. Study clients and draw initial
State Diagrams,
initial specification Class Diagrams Activity Diagrams, and
other diagrams
List any new uncertainties
2. Generate initial
Use Case Diagram
and Descriptions, 9. Refine Class 7. Review requirements
Data Dictionary and Diagrams and other with client
list of uncertainties / affected diagrams
ambiguities /
functional / non-
functional [Initial
Requirements
requirements. elicitation 8. Update
Agreed]
Use Cases [Use
Case
affected] [Requirement
3. Review requirements s Agreed]
with client. (Interview,
Observation, 10. Agree and Sign-
Workshop, Legacy Off on Software
4. Refine Use Case Diagram and
Product Study, Requirements
Descriptions and Data Dictionary and list
Competitive Product Specification
of uncertainties / ambiguities /
Study, Prototype)
Functional / non-functional requirements.
Software Requirement Specification
(SRS)
Contents of the SRS
1. Each organisation will have its own template for an SRS.

2. There are key content that must be addressed in an SRS

3. There is an IEEE standard


830-1998 - IEEE Recommended Practice for Software
Requirements Specifications.

This is a document that you can download from


IEEEXplore.
How and Who should write the SRS?
1. It should be written in natural language, in an unambiguous
manner that may also include diagrams as necessary.

2. At the same time the detailed functional and non-functional


requirements need to be defined and understood by the
development team.

3. Development team members (programmers and managers) are


seldom the best writers of formal documents. However, they
often have to write it!

4. It is good practice to involve a technical writer with the


development team in the drafting of the SRS because they are
usually better at assessing and planning documentation projects
and better meet customer document needs.
Contents of the SRS
1) Product Description
a) Purpose of the System (mission statement)
b) Scope of the System
c) Users and Stakeholders
d) Assumptions and Constraints
2) Functional Requirements
3) Non-Functional Requirements
4) Interface Requirements
a) User
b) Hardware
c) Software
5) Data Dictionary
See detailed SRS description and SRS template on NTULearn course website.
Summary

• Interaction Diagrams
– State Machine Diagrams
– Activity Diagrams

• Software Requirement Specifications


Software Engineering
CE2006/CZ2006

UML Review 1
Lesson Objectives
Review UML with an example

At the end of the lesson, you should be able to:


• Describe UML diagrams learned so far
• Explain the purposes of different kinds of UML diagrams
• Use different diagrams at different steps in software
requirement elicitation and analysis process
UML diagrams learned

Activity diagram: Flow from one activity to another describing the operation of a system.
Use Case diagram: describes the functionality provided by a system in terms of actors, their goals
represented as use cases, and any dependencies among those use case descriptions.
Class diagram (Static structure diagram): describes the structure of a system by showing the system's
classes, their attributes, and the relationships among the classes.
Sequence diagram and Communication diagram: shows how objects communicate with each other in
terms of a sequence of messages.
State machine diagram: describes the states and state transitions of the system.
Requirement Elicitation and Analysis Process
5. Identify Classes 6. Add associations, multiplicities
1. Study clients initial and draw initial Class Add Sequence Diagrams,
specification Diagrams State Diagrams,
Activity Diagrams, and
other diagrams
List any new uncertainties
2. Generate initial Use
Case Diagram and
Descriptions, Data 7. Review requirements
9. Refine Class
Dictionary and list of with client
Diagrams and other
uncertainties /
affected diagrams
ambiguities / functional
/ non- functional
requirements.
[Initial Requirements
elicitation
Agreed] 8. Update
Use Cases [Use Case
affected]
[Requirements
3. Review requirements Agreed]
with client. (Interview,
Observation, Workshop, Legacy
Product Study, Competitive 10. Agree and Sign-
Product Study, Prototype)
4. Refine Use Case Diagram and Off on Software
Descriptions and Data Dictionary and list of Requirements
uncertainties / ambiguities / Specification
Functional / non-functional requirements.
Example: A security door access system
1. A door access system is needed to allow employees to enter a secure area using their
fingerprint.
2. When an employee needs to open the door he/she must place their index finger on a
fingerprint reader located beside the door.
3. The scanned fingerprint is compared and validated against a company database of
employee fingerprints.
4. If a fingerprint match is found the message “Please enter” is displayed and the door is
opened to allow the employee to enter.
5. If the fingerprint match fails the message “Access Denied” is displayed and the access
system reverts to waiting for a new fingerprint to scan.
6. Every time a door access is attempted a record log is maintained. The information
recorded for a successful access is the Time of Access and the name of employee allowed
access. The information recorded for a failed access is the Time of Unsuccessful
Attempted Access.
7. The company’s Human Resources department maintains a database of employee
fingerprints. These are collected once during the new employee enrolment process and are
removed when an employee leaves the company.
8. The Human Resources department can view the record log of accesses and attempted
accesses and update the employees fingerprint data if necessary.
First Step – Generate Use Case Diagram

1. Study clients initial Identify the Actors


specification

Identify the main Use Cases


2. Generate initial Use
Case Diagram and
Descriptions, Data
Dictionary and list of
uncertainties /
ambiguities / functional
/ non- functional
requirements.
[Initial Requirements
elicitation
Agreed]

3. Review requirements
with client. (Interview,
Observation, Workshop, Legacy
Product Study, Competitive
Product Study, Prototype)
4. Refine Use Case Diagram and
Descriptions and Data Dictionary and list of
uncertainties / ambiguities /
functional/ non-functional requirements.
1. Study clients initial specification
IDENTIFY THE ACTORS
1. A door access system is needed to allow employees to enter a secure area using their
fingerprint.
2. When an employee needs to open the door he/she must place their index finger on a
fingerprint reader located beside the door.
3. The scanned fingerprint is compared and validated against a company database of
employee fingerprints.
4. If a fingerprint match is found the message “Please enter” is displayed and the door is
opened to allow the employee to enter.
5. If the fingerprint match fails the message “Access Denied” is displayed and the access
system reverts to waiting for a new fingerprint to scan.
6. Every time a door access is attempted a record log is maintained. The information
recorded for a successful access is the Time of Access and the name of employee allowed
access. The information recorded for a failed access is the Time of Unsuccessful
Attempted Access.
7. The company’s Human Resources department maintains a database of employee
fingerprints. These are collected once during the new employee enrolment process and
are removed when an employee leaves the company.
8. The Human Resources department can view the record log of accesses and attempted
accesses and update the employees fingerprint data if necessary. 7
2. Generate initial Use Case diagram
IDENTIFY THE ACTORS

Door

Human
Resources

Employee Fingerprint
Reader
1. Study clients initial specification
IDENTIFY THE MAIN USE CASES (action verb)
1. A door access system is needed to allow employees to enter a secure area using their
fingerprint.
2. When an employee needs to open the door he/she must place their index finger on a
fingerprint reader located beside the door. Validate
3. The scanned fingerprint is compared and validated against a company database of
employee fingerprints. Scan fingerprint
4. If a fingerprint match is found the message “Please enter” is displayed and the door is
opened to allow the employee to enter.
5. If the fingerprint match fails the message “Access Denied” is displayed and the access
system reverts to waiting for a new fingerprint to scan.
6. Every time a door access is attempted a record log is maintained. The information
recorded for a successful access is the Time of Access and the name of employee allowed
access. The information recorded for a failed access is the Time of Unsuccessful
Attempted Access.
7. The company’s Human Resources department maintains a database of employee
fingerprints. These are collected once during the new employee enrolment process and
are removed when an employee leaves the company. Add employee
8. The Human Resources department can view the record log of accesses and attempted
accesses and update the employees fingerprint data if necessary. 9
2. Generate initial Use Case diagram
IDENTIFY THE MAIN USE CASES

Door

Validate door
entry
Manage door
database
Human
Resources

Employee Fingerprint
Reader
2. Generate initial Use Case descriptions
See the Use Case Description Template available on NTULearn course website.
Use Case ID:

Use Case Name:

Created By: Last Updated By:

Date Created: Date Last Updated:

Actor:
Description:
Preconditions:
Postconditions:
Priority:
Frequency of Use:
Flow of Events:
Alternative Flows:
Exceptions:
Includes:
Special Requirements:
Assumptions:
Notes and Issues:
3 & 4. Refine Use Case diagram
REFINE THE MAIN USE CASES
1. A door access system is needed to allow employees to enter a secure area using their
fingerprint.
2. When an employee needs to open the door he/she must place their index finger on a
fingerprint reader located beside the door.
3. The scanned fingerprint is compared and validated against a company database of
employee fingerprints.
4. If a fingerprint match is found the message “Please enter” is displayed and the door is
opened to allow the employee to enter.
5. If the fingerprint match fails the message “Access Denied” is displayed and the access
system reverts to waiting for a new fingerprint to scan.
6. Every time a door access is attempted a record log is maintained. The information
recorded for a successful access is the Time of Access and the name of employee allowed
access. The information recorded for a failed access is the Time of Unsuccessful
Attempted Access.
7. The company’s Human Resources department maintains a database of employee
fingerprints. These are collected once during the new employee enrolment process and
are removed when an employee leaves the company.
8. The Human Resources department can view the record log of accesses and attempted
accesses and update the employees fingerprint data if necessary. 12
3 & 4. Refine Use Case diagram
REFINING THE MAIN USE CASES

Remove a View the


person Entry log
Door
<<include>> <<include>>

Validate door
entry
Manage door
database
Human
Resources
<<include>>
Add a
person
Employee Fingerprint
Reader
3 & 4. Refine Use Case diagram
REFINING THE MAIN USE CASES

Scan
fingerprint

Remove a View the


<<include>> person Entry log
Door
<<include>>
<<include>>
<<include>>

Validate door
entry
Manage door
database
Human
Resources
<<include>>
Add a
person
Employee Fingerprint
Reader
3 & 4. Refine Use Case descriptions
See the Use Case Description Template available on NTULearn course website.
Use Case ID:

Use Case Name:

Created By: Last Updated By:

Date Created: Date Last Updated:

Actor:
Description:
Preconditions:
Postconditions:
Priority:
Frequency of Use:
Flow of Events:
Alternative Flows:
Exceptions:
Includes:
Special Requirements:
Assumptions:
Notes and Issues:
EXAMPLE USE CASE DESCRIPION Scan
fingerprint

ValidateDoorEntry
Entry Gate <<include>>

Use Case Description Validate


DoorEntry

Flow of Events:
1. Employee presses finger on FingerprintReader. User

2. FingerprintReader scans fingerprint (using use case Scan


fingerprint) and sends image to the FacilityAccessManager.
3. The FacilityAccessManager validates the fingerprint
4. If fingerprint is valid display the message “Please enter” and unlock the
EntryGate.
4.1 The EntryGate sends a signal to the FacilityAccessManager
that it has opened and closed.
4.2 The FacilityAccessManager locks the EntryGate, and logs the
entry time and name of the employee who entered in the entry
log.

Alternative Flow:
AF-S4. If fingerprint is not valid display the message “Access denied” and
log the attempted entry time in the entry log.
Example: A security door access system
QUESTIONS THAT ARISE AND NEEDCLARIFICATION WITH
THE CLIENT
1.What is the detailed process when a fingerprint is validated?
What if the gate is opened and no one enters?
What if the gate is opened and does not close?
Is there a timeout?
What if more than one person enters?

2.Is there a particular format the Employee data is to be recorded


in the log?
Does it need to be exported to another system or printed?

Other questions will arise as detailed Use Cases are written.


These need to be clarified with the customer reflected in
changes in the Use Case diagrams and descriptions
Summary:
Requirement Elicitation and Analysis Process
5. Identify Classes 6. Add associations, multiplicities
Add Sequence Diagrams,
1. Study clients initial and draw initial Class
State Diagrams,
specification Diagrams Activity Diagrams, and
other diagrams
List any new uncertainties
2. Generate initial Use
Case Diagram and
Descriptions, Data 9. Refine Class 7. Review requirements
Dictionary and list of Diagrams and other with client
uncertainties / affected diagrams
ambiguities /
functional / non-
functional [Initial
requirements. Requirements
elicitation 8. Update
Agreed]
Use Cases [Use Case
affected]
[Requirement
3. Review requirements s Agreed]
with client. (Interview,
Observation,
Workshop, Legacy 10. Agree and Sign-
Product Study, 4. Refine Use Case Diagram and Off on Software
Competitive Product Descriptions and Data Dictionary and list of Requirements
Study, Prototype) uncertainties / ambiguities / Specification
Functional / non-functional requirements.
Software Engineering
CE2006/CZ2006

UML Review 2
Lesson Objectives
Review UML with an example

At the end of the lesson, you should be able to:


• Describe UML diagrams learned so far
• Explain the purposes of different kinds of UML diagrams
• Use different diagrams at different steps in software
requirement elicitation and analysis process
Second Step – Generate Class Diagram
5. Identify Classes 6. Add associations, multiplicities
Add Sequence Diagrams,
and draw initial Class State Diagrams,
Diagram Activity Diagrams, and
other diagrams
List any new uncertainties

Read the Use Case description


and identify the recurring nouns –
these may be Classes

[Initial Requirements
elicitation Agreed]
5. Identify Classes <<include>>
Scan
fingerprint
Entry Gate

Validate
ValidateDoorEntry Use Case Description DoorEntry

User

1. Employee presses finger on FingerprintReader.


2. FingerprintReader scans fingerprint (using use case Scan fingerprint)
and sends image to the FacilityAccessManager.
3. The FacilityAccessManager validates the fingerprint.
4. If fingerprint is valid display the message “Please enter” and unlock
the EntryGate.
4.1 The EntryGate sends a signal to the FacilityAccessManager
that it has opened and closed.
4.2 The FacilityAccessManager locks the EntryGate, and logs the
entry time and name of the employee who entered in the entry log.
AF-S4:
If fingerprint is not valid display the message “Access denied” and
log the attempted entry time in the entry log.
5. Draw initial Class Diagram
INITIAL CLASSES AND TYPES

Fingerprint EntryGate
Reader

FAMgr

Fingerprint Entry Log


6. Add properties and operations
ADDINIG INITIAL OPERATIONS TO CLASSES

Fingerprint EntryGate Interface


Reader Interface
Unlock()
Lock()

FASMgr
Validate(Img)
GateOpened()

Fingerprint Entry Log


FindMatch(Img) RecordEntry(time: Date)
6. Add Sequence Diagrams

Entry Log
:FingerprintReader :Fingerprint :EntryGate
:User Interface Interface
:FASMgr
Press
Validate(img)

[not last record and not found]


loop
FindMatch(img)

opt [img matched]


Unlock()
GateOpened()

Lock()

RecordEntry()
Example: FingerprintReader Functionality

Ready
entry / initialize scanner

press

[invaliduser= Scan Warn


false] do / scan fingerprint entry / beep
do / display retry msg

/send image

WaitConfirmation [invaliduser=tr
ue]
Example: Validate Door Entry System
Third Step – Refine Class (& Use Case) Diagrams

Iteratively refine the Class


9. Refine Class
Diagram and Sequence Diagram.
Diagrams and other 7. Review requirements
affected diagrams with client
This may involve some
refinement of the Use Cases.

Repeat until the Functional


Requirements of the System are
fully specified. 8. Update
Use Cases [Use Case
affected]
[Requirements
Agreed]

10. Agree and Sign-


Off on Software
Requirements
Specification
Summary
UML Review with an Example

First Half of the Course


Introduction to Software Engineering
Requirement Elicitation
Use Case Diagram
Requirement Analysis
Class Diagram
Sequence/Communication Diagram
State Machine Diagram
Activity Diagram

Second Half of the course


Software Design
Software Testing
Liu Yang
1
SDLC Activities
Problem Solution

Requirements Requirements System Object


Impls Testing
Elicitation Analysis Design Design

Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By

class...
class...
class... ?

Requirement Analysis SW Design Source Test


Specification Model Architecture Model Code Case
s
2
Components of Requirements
Engineering

3
Understand What Customers Want
 From project Informal
Requirements
mission statement Vague
Elicitation Incomplete

 To Requirement
specification (SRS)
 Func & non-func
requirements Formal
 Data dictionary Technical
Requirement Consistent
Specification  Use case model
(SRS)
4
Bridge Customer Perspective to Software
Engineer Perspective
 From Requirement More
Requirements Specification (SRS) about
Analysis Customer
 Func & non-func
requirements
Expressed in
Terms Of  Data dictionary
 Use case model

 To analysis model More


 Class diagram (boundary, about
Analysis control, entity) Software
Model  Sequence diagram Engineer
 State machine
5
6
 Larger
 Source size, Binary size
 Number of users, user input
 Number of developers
 Life of the project (decades...)
 Number of changes, versions

 Complexity is increasing
 Environment
 Technologies
 Hardware
 …

7
 Cost is critical (limited budget/resource)
 Schedule constraints (tight schedule)
 Maintenance

8
 Non-functional Requirements
 Performance
 Availability
 Security
 Scalability
 Extensibility

9
10
Software architecture is considered as a description
of the high level structure of a software system in
terms of architectural elements and the interactions
between them.

‘Abstractly, software architecture involves the


description of elements from which systems are built,
interactions among those elements, patterns that guide
their composition, and constraints on these patterns.’
(Shaw and Garlan, 1996)
11
Software Architecture = {Components, Connectors}
 Components
 A component is a unit of software that performs some function at run-time.
 Examples: programs, objects, processes, clients, servers, databases

 Connectors
 Interactions among components:
 communication, coordination, or cooperation among components.

 Examples: shared variable access, procedure calls, remote procedure calls,


communication protocols, data streams, transaction streams.

 Implementations of connectors are usually distributed over many system components;


often do not correspond to discrete elements of the running systems.
12
External Viewer View Control File System

WWW Client
CGI
Presentation UI WWW Server
Manager Manager
Path
Resolver
Access
Manager
Cache HTTP Access
Manager Protocol Server List
Manager

Stream HTTP Stream


Manager protocol Manager

13
14
 Architecture is abstract
 The details of the components and connectors are hidden

 Architecture is about structure and interactions


 Focus on the topology
 Components
 Data and control communication

 Architecture is purposeful
 demonstrate or analyse the properties of interest
 design documentation, as transferable knowledge about
software design, evaluation, and so on
15
Functional Non-functional Design Design Constraints
Requirement Requirement Principles Patterns • Languages
• Dynamic Models • Efficiency • Modularity • Layered • Libraries
• Analysis Object • Reliability • Abstraction Architecture • Communications
Models • Robustness • Open-Closed • Client and Server
• Security • Reusability • Data Centered
• Maintainability

16
Don’t repeat yourself Modularity

Open Close Principle

Principle of Least Knowledge Single Responsibility


Principle
 One of the hallmarks of software architectural
design is the use of idiomatic patterns of system
organization.
 An architectural style defines a family of systems
in terms of a pattern of structural organization.
 A vocabulary of component and connector types
 A set of constraints on how they can be combined
 One or more semantic models that specify how to
determine a system's overall properties from the
properties of its parts

18
 A set of component types
 Filters in pipe-and-filter styles
 MVC

 A set of connectors
 subroutine calls, remote procedure calls, data streams, and
sockets

 A topological structure
 A set of semantic constraints
 Filters in a pipe-and-filter architecture do not share states
with each other
 One layer can only call the service provided by the lower
layer in a layered system
19
 The number of components involved
 a pipe-and-filter architecture
▪ 2 filters connected by 1 pipe or
▪ 20 filters connected by 19 pipes

 The mechanism of interaction


 In a layered system, the call to the lower layer can be
▪ local procedure calls, or remote procedure calls, or other process
communication mechanisms.

 The function of the system and components
 one of the components in an architectural style may be a
database, but the kind of data may vary. 20
Independent Communicating processes – client & server
components Event systems Implicit invocation
Explicit invocation
Batch sequential
Data flow
Pipe-and-filter
Repository
Architectural Data-centered
styles Blackboard
Interpreter
Virtual machine
Rule-based system
Main program and subroutine
Call and return Object-oriented
Layered system
21
22
23
Advantages Disadvantages
 Modifiability by  Components are
decoupling the independent
computation  Message received?
 Concurrent execution  Solution: complicated
 Scalability
protocols
 Easy integration
 Correctness is hard to
achieve

24
Descriptive modes:
External Identify Describe what designers do in
Requirements
requirements nature of design.
specification
requirements
Analyze &
Specification/ build model
comparison of problem
Specification
criteria Specification
New
Designer’s Constraints
models Postulate Seek new Mismatches
design solution between model and
solution(s) requirements
Compare Validate Revise
solutions Seek new each design
Designer’s
solutions model solution solution
Selected design Validated Designer’s
solution model model
Elaborate
solution
‘Blueprint’ 25
New Features

Maintainability Extensibility

Performance
New Features Scalability

26
27
Why What

How

Non-
Functional Design Design
functional Constraints
Requirement Principles Patterns
Requirement

28
Liu Yang
1
Why What

How

Non-
Functional Design Design
functional Constraints
Requirement Principles Patterns
Requirement

2
SDLC Activities
Problem Solution

Requirements Requirements System Object


Impls Testing
Elicitation Analysis Design Design

Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By

class...
class...
class... ?

Requirement Analysis SW Design Source Test


Specification Model Architecture Model Code Case
s
3
WWW Client-Server Architecture
External Viewer View Control File System

WWW Client
CGI
Presentation UI WWW Server
Manager Manager
Path
Resolver
Access
Manager
Cache HTTP Access
Manager Protocol Server List
Manager

Stream HTTP Stream


Manager protocol Manager

4
Interface specification:
Reuse: Existing libraries and
operations, arguments, type
Design Patterns
signatures, and exceptions

Object Design

Restructuring: to meet the


Optimization: speed or
design goal maintainability,
memory
flexibility…

5
6
Good Design
Maintainability

The
Extensibility
Scalability

ro a
Testability

d to
Reusablilty

goo
Design Patterns

dd
Singleton

esi
Abstract Factory

gn
DAO
Strategy
Decorator

Design Principles
Program to an interface, not an implementation
High cohesion
Low coupling
Open-Closed
Separation of concerns

University of Kansas 7
 A design pattern
 a proven solution to a problem in a context.
 abstracts a recurring design structure
 A template with class and/or object
▪ dependencies,
▪ structures,
▪ interactions, or
▪ conventions

“Gang of Four” (GoF) Book, 1996


 Name
 Describes the pattern
 Adds to common terminology for facilitating communication (i.e. not just
sentence enhancers)

 Problem
 Describes when to apply the pattern
 Answers - What is the pattern trying to solve?

 Solution
 Describes elements, relationships, responsibilities, and collaborations
which make up the design

 Consequences
 Results of applying the pattern
 Benefits and Costs
 Subjective depending on concrete scenarios
University of Kansas 9
 Creational Patterns  Behavioral Patterns
▪ Abstract Factory ▪ Chain of Responsibility
▪ Builder ▪ Command
▪ Factory Method ▪ Interpreter
▪ Prototype ▪ Iterator
▪ Singleton ▪ Mediator
 Structural Patterns ▪ Memento
▪ Adapter ▪ Observer
▪ Bridge ▪ State
▪ Composite ▪ Strategy
▪ Decorator ▪ Template Method
▪ Façade ▪ Visitor
▪ Flyweight
▪ Proxy
 Design problem: A set of algorithms or objects
should be interchangeable.
 Solution: Strategy Pattern

uses Strategy
Context
doSomething()

implements or realizes implements or realizes

ConcreteStrategyA ConcreteStrategyB

11
 Pros
 Provides encapsulation
 Hides implementation
 Allows behavior change at runtime

 Cons
 Results in complex, hard to understand code if overused

3/15/2018 University of Kansas 12


When to Use the Observer Pattern
 When you need
many objects (called
observers) to receive
an update when
another object
(called subject)
changes

a.k.a. Subscriber – Publisher Pattern


Consumer – Producer Pattern
13
Why to use the Observer Pattern?
Subject
• I do not know (or care) who are looking after
me and how many are looking after me
• I want to let whoever are looking after me
know when I cry
• It is up to caregivers to decide what to do with
me crying

Observer
• Sometimes I want to look after the baby,
sometimes I do not
• I want to know the incident once the baby cries,
but I do not know when he will cry
• I cannot constantly check the baby’s status
because I have to do something else important

4
Why to use the Observer Pattern?
Subject
• I do not know (or care) who are looking after
me and how many are looking after me
• I want to let whoever are looking after me
know when I cry
• It is up to caregivers to decide what to do with
me crying

What kind of coupling (tight or loose) is preferred? Why?


Observer
• Sometimes I want to look after the baby,
sometimes I do not
• I want to know the incident once the baby cries,
but I do not know when he will cry
• I cannot constantly check the baby’s status
because I have to do something else important

5
Why to use the Observer Pattern?
Subject
• I do not know (or care) who are looking after
me and how many are looking after me
• I want to let whoever are looking after me
know when I cry
• It is up to caregivers to decide what to do with
me crying

Loose coupling is a benefit for both sides!


Observer
• Sometimes I want to look after the baby,
sometimes I do not
• I want to know the incident once the baby cries,
but I do not know when he will cry
• I cannot constantly check the baby’s status
because I have to do something else important

6
When to Use the Observer Pattern
 When you need
many objects
(called observers)
to receive an
update when SE2006NTU
another object E-learning
video released
(called subject) Examinable

changes

 Who’s the Subject?


 Who’s the Observer?
17
Why to use the Observer Pattern?
Subject
• It does not matter who register the
course and how many register the course
• I want to let whoever register the course
know the latest announcement
• It is up to course takers to decide what to
do with the change

Observer
• I want to be able to register/dropoff the course
• I want to know the latest announcement once it
occurs, but I do not know when it will occur
• I cannot constantly check the announcement
because I have to do something else
important
8
Why to use the Observer Pattern?
Subject
• It does not matter who register the
course and how many register the course
• I want to let whoever register the course
know the latest announcement
• It is up to course takers to decide what to
do with the change

What kind of coupling (tight or loose) is preferred?


Observer
• I want to be able to register/dropoff the course
• I want to know the latest announcement once it
occurs, but I do not know when it will occur
• I cannot constantly check the announcement
because I have to do something else
important
9
Why to use the Observer Pattern?
Subject
• It does not matter who register the
course and how many register the course
• I want to let whoever register the course
know the latest announcement
• It is up to course takers to decide what to
do with the change

Loose coupling is a benefit for both sides!


Observer
• I want to be able to register/dropoff the course
• I want to know the latest announcement once it
occurs, but I do not know when it will occur
• I cannot constantly check the announcement
because I have to do something else
important
10
When to Use the Observer Pattern
 When you need
many objects
(called observers)
to receive an
update when
another object
(called subject)
changes

 Who’s the Subject?


 Who’s the Observer?
21
Why to use the Observer Pattern?
Subject
• I do not care who invest in the market and how
many invest in the market
• I want to let whoever invest in the market
know the latest stock change
• It is up to investors to decide what to do with the
change

Observer
• I want to be able to invest in or withdraw from
the market freely
• I want to know the latest stock change once it
occurs, but I do not know when it will occur
• I cannot constantly check the change because I
have to do something else important

12
Why to use the Observer Pattern?
Subject
• I do not care who invest in the market and how
many invest in the market
• I want to let whoever invest in the market
know the latest stock change
• It is up to investors to decide what to do with the
change
Loose coupling is a benefit for both sides!
Observer
• I want to be able to invest in or withdraw from
the market freely
• I want to know the latest stock change once it
occurs, but I do not know when it will occur
• I cannot constantly check the change because I
have to do something else important

13
Observer Pattern – Design Problems
 Defines a one-to-many dependency
between objects so that when one object
changes state, all of its dependents are
notified and updated automatically.

Easy Subscription and Automatic


Notification

24
How to Resolve these Problems?
 Subscription mechanism
 Observers freely register/unregister their
interests in Subject

 Notification mechanism
 Subject propagates the change to Observer
when the change occurs

25
Understand How it Works: NTULearn
Case Study
 In NTULearn system
 Subject: SE2006NTU
 Observers: Course takers (your NTU account)

SE2006NTU YourAccount

26
Subscription Mechanism
 Add to course
(i.e., register) SE2006NTU
register(YourAccount)
 Remove from course unregister(YourAccount)
(i.e., unregister)

Your SE2006 Your SE2006


Account NTU Account NTU

register(YourAcct) unregister(YourAcct)

addtoList( rmfromList(
YourAcct) YourAcct)

27
Notification Mechanism – Pull Update
 SE2006NTU sends simple
notification (e.g., new SE2006NTU YourAccount

announcement)
loop [for each account]
 YourAccount calls back for newanncment()
getAnncment()
details
anncment
subject
SE2006NTU 1
notify()
getAnncment() : Anncment * observers

YourAccount
for each account in observers newanncment()
account.newanncment();
subject.getAnncment();
yourProcess(anncment);
28
Pull it Together in a Class Diagram
subject observers
SE2006NTU 1 *
YourAccount
register(YourAccount) newanncment()
unregister(YourAccount)
notify()
getAnncment() : Anncment subject.getAnncment();
for each account in observers yourProcess(anncment);
account.newanncment();

subject observers
SE3003NTU 1 HisAccount
*
register(YourAccount) newanncment()
unregister(YourAccount)
notify()
subject.getAnncmemnt();
getAnncment() : Anncment
hisProcess(anncment);

for each account in observers


account.newanncment(); 29
Abstract Commonalities into Superclasses –
CourseTaker – Course Design
subject observers
Course 1 *
CourseTaker
register(YourAccount) newanncment()
subject.
unregister(YourAccount) getAnncment();
notify()
getAnncment() : Anncment
YourAccount HisAccount
SE2006NTU SE3003NTU newanncment() newanncment()
- data:SE2006NTUData - data:SE3003NTUData

getAnncment() :Anncment getAnncment() :Anncment super.newanncment();


yourProcess(anncment);

for each account in observers


account.newanncment(); 30
Caregiver – Baby Design
subject observers
Baby 1 *
Caregiver
lookafter(Caregiver) babycry()
donotLookafter(Caregiver)
notify() subject.getBabyStatus();
getBabyStatus() :Status

Daddy
Infant babycry()

- data: BabyData
super.babycry();
getDabyStatus() :Status stopPlaygame();
handle(status);
for each caregiver in observers
caregiver.babycry();

31
Investor – StockMarket Design
subject observers
StockMarket 1 *
Investor
invest(Investor) marketchange()
stopInvest(Investor)
notify() subject.getStockDetails();
getStockDetails() :Details

VeteranInvestor
SGX marketchange()
- data: SGXData
super.marketchange();
getStockDetails() :Details sell(details);

for each investor in observers


investor.marketchange();

32
Observer Pattern Template
subject observers
Subject 1 *
Observer
register(Observer) update()
unregister(Observer)
notify() subject.getData();
getData() :Details
ConcreteObserver
ConcreteSubject update()
- data
getData() : Details super.update();
observerSpecificUpdate();

for each o in observers


o.update();
33
Notification Mechanism – Push Update
 SE2006NTU sends details SE2006NTU YourAccount
about the announcement
 YourAccount does not need loop [for each account]
update(anncment)
to call back
subject
SE2006NTU 1
notify()
getAnncment() :Anncment * observers
YourAccount
anncment = getAnncment();
for each account in observers update(Anncment)
account.update(anncment);
yourProcess(anncment);
34
Observer Pattern Template
Subject subject observers Observer
1 *
register(Observer) update(Anncment)
unregister(Observer)
notify()
getAnncment() :Anncment
ConcreteObserver
ConcreteSubject update(Anncment)

- data
observer-specific actions
getAnncment() :Anncment

anncment = getAnncment();
for each o in observers
o.update(anncment);
35
Update Protocol: Pull or Push?
Which one is better?
 Pull update
 Subject sends simple notification (via
Observer.update()).
 The Observer calls back (via Subject.getData())
for details explicitly (if Observer is interested) –
two way communication.

 Push update
 Subject sends detailed information about the
change (or update), whether Observer wants it
(interested) or not – Observer does not need to
call back – one way communication.
36
Observer Pattern – Push + Pull Update
Subject subject observers Observer
1 *
register(Observer) update(SomeDetail)
unregister(Observer)
notify()
getSomeData() : SomeDetail
getMoreData() : MoreDetail
ConcreteObserver
update(SomeDetail)
ConcreteSubject
- data
if(interested in somedetails) {
getSomeData() :SomeDetail
subject.getMoreData();
getMoreData() :MoreDetail
observerSpecificProcess();
}
somedetails = getSomeData();
for each o in observers How to apply this design to
o.update(somedetails);
course announcement, e.g.
37 NTULearn?
Notification Mechanism –
Selective Notification
SE2006NTU YourAccount
 SE2006NTU notifies those
who register a particular loop [for each account of a tutorial]
update(tutorial)
tutorial (i.e. interests)
getData(tutorial)
details
subject
SE2006NTU 1
notify(Tutorial) * observers
getData(Tutorial) :Details
YourAccount
update(Tutorial)
for each account in observers
of a particular tutorial
subject.getData(tutorial);
account.update(tutorial);
yourProcess(details);
38
Subscription Mechanism –
Interests Subscription
 Add to course
(i.e., register) SE2006NTU Interests

 Remove from course register(YourAccount,tutorial)


unregister(YourAccount,tutorial)
(i.e., unregister)
Your SE2006 Your SE2006
Account NTU Account NTU

register( unregister(
YrAcct,tutorial) YrAcct,tutorial)
addtoList( rmfromList(
YrAcct,tutorial) YrAcct,tutorial)

Indicate your tutorial session when registering the course


39
Observer Pattern – Interest
Subscription + Selective Notification
Subject subject observers Observer
1 *
register(Observer, Interest) Interest update(Interest)
unregister(Observer, Interest) subscription
notify(Interest)
getData(Interest) Selective
notification ConcreteObserver
ConcreteSubject update(Interest)

- data
getData(Interest)
subject.getData(interest)

for each o in observers of
the given interest
o.update(interest); 40
Event Handling – Design Problems
 Loose coupling between an event source
(subject) and its dependent event handlers
(observers)
 Event source wants to notify event handlers the
event once it occurs, but even handlers can
change their interests in event source freely

 Event handlers want to know the evet once it


occurs, but they do not know when the event will
occur in event source

41
Event Handling & Observer Pattern –
Design Problems
 Loose coupling between an event source (subject)
and its dependent event handlers (observers)
Event Handling

 Event source wants to notify event handlers the event once


it occurs, but even handlers can change their interests in
event source freely
 Event handlers want to know the evet once it occurs, but
they do not know when the event will occur in event source

 Loose coupling between an object (subject) and its


Observer Pattern

dependent objects (observers)


 Subject wants to notify observers the change once it occurs,
but observers can change their interests freely and constantly
 Observers wants to know the change once it occurs, but they
do not know when the change
42 will occur
Java Swing Event Handling
actionListeners
AbstractButton * *
ActionListener
addActionListener(ActionListener) actionPerformed(ActionEvent)
removeActionListener(ActionListener)
addItemListener(ItemListener) Due to space, only
removeItemListener(ItemListener)
ActionListener
fireActionPerformed(ActionEvent) observer is shown ActionEvent
fireItemStateChanged(ItemEvent) getSource()
getActionCommand()
getHideActionText() getModifiers()
getText() getWhen()
paramString()

MyActionListener
JButton JMenuItem

What are the event sources?


What are the43event handlers?
Java Swing Event Handling
Subject Observer
actionListeners
AbstractButton * *
ActionListener
addActionListener(ActionListener) actionPerformed(ActionEvent)
removeActionListener(ActionListener)
addItemListener(ItemListener)
removeItemListener(ItemListener)

fireActionPerformed(ActionEvent)
ActionEvent
fireItemStateChanged(ItemEvent) getSource()
Some
Details getActionCommand()
getHideActionText() getModifiers()
getText() getWhen()
paramString()

MyActionListener
JButton JMenuItem
Concrete
Concrete subjects 44 observer
Java Swing Event Handling
actionListeners update
AbstractButton * *
ActionListener (push)
addActionListener(ActionListener) actionPerformed(ActionEvent)
register/ removeActionListener(ActionListener) Interest
unregister addItemListener(ItemListener) subscription
removeItemListener(ItemListener)

fireActionPerformed(ActionEvent) selective
ActionEvent
notify fireItemStateChanged(ItemEvent) notification getSource()
some getActionCommand()
get more getHideActionText() details getModifiers()
data getText() getWhen()
paramString()
To get the event source, listener can call
ActionEvent.getSource()
Jbutton JMenuItem MyActionListener
To get more information, listener can pull more
• Register different interests information, e.g. ActionEvent.getSource().getText()
• Selective notification
• Push + Pull update 45
 Pros
 Abstracts coupling between Subject and Observer
 Supports broadcast communication
 Enables reusability of subjects and observers independently of each
other
Loose coupling is a benefit for both sides!
 Cons
 Slower performance
 If not used carefully the observer pattern can add unecessary
complexity

3/15/2018 University of Kansas 46


Interface specification:
operations, arguments, Reuse: Existing libraries
type signatures, and and Design Patterns Good Design
exceptions Maintainability

The
Extensibility
Scalability

ro a
Testability

d to
Reusablilty

goo
Design Patterns
Object

dd
Singleton

esig
Abstract Factory

Design DAO

n
Strategy
Decorator

Design Principles
Program to an interface, not an implementation

Restructuring: to meet High cohesion


Low coupling
Open-Closed
the design goal Optimization: speed or Separation of concerns

maintainability, memory
flexibility…

University of Kansas 47
Liu Yang
1
Interface specification:
operations, arguments, Reuse: Existing libraries
type signatures, and and Design Patterns
exceptions

Object Design

Restructuring: to meet
the design goal Optimization: speed or
maintainability, memory
flexibility…

University of Kansas 2
GoF Patterns (23)
– Creational Patterns – Behavioral Patterns
• Abstract Factory • Chain of Responsibility
• Builder • Command
• Factory Method • Interpreter
• Prototype • Iterator
• Singleton • Mediator
– Structural Patterns • Memento
• Adapter • Observer
• Bridge • State
• Composite • Strategy
• Decorator • Template Method
• Façade • Visitor
• Flyweight
• Proxy
What To Do When System Starts Up
 Create objects, and associate them up
according to the class diagram

See EMSNoFactory.zip for implementation!


4
When To Use Factory Pattern?
 When you’ve a set of classes but don’t know exactly which
one you’ll need to instantiate until runtime.
 When you need to create one of
of several classes that implement
a common superclass without
exposing the creation logic
to the client.
 When you want to localize the logic to instantiate objects.
Solution: Factory Pattern
 Defines an interface for creating different objects, without
knowing beforehand what sort of objects it needs to create
or how the object is created – lets subclasses decide
which class to instantiate. 5
What Are The Design Problems?
 Decouple class selection and object creation
(abstract instantiation process) from the client
where the object is used allowing greater
flexibility in object creation
 Existing subclasses can be replaced, or new
subclasses can be added
 Process of selecting subclass to use and creating
object can be complex
 Client does not know ahead of time which class will
be used, and the class can be chosen at runtime
6
Factory Pattern (a.k.a. Static Factory Pattern)
– “Standard” Version (Template)

 Context uses StaticFactory to obtain an object


that implements AbstractProduct interface.
7
Data Access: Strategy Design + Factory Design

DataStoreFactory
Resource + getDatastore() : DataStoreInterface
Manager
<<create>>
datastore
DataStoreInterface
retrieveMap()
createIncident()
dispatchResource()

FlatFileImpl MySQLImpl DB2Impl

See EMSBasicFactory.zip for implementation


8
What Are The Benefits?
 Encapsulate object creation
 Remove duplicate object creation code from clients
(see EMSNoFactory.zip and EMSBasicFactory.zip)
 Centralize class selection and object creation code

 Easy to extend, replace, or add new subclasses


 Replace MySQLImpl1 with MySQLImpl2
 Support new OracleImpl

 Easy to change object creation logic


 Support Singleton object (see EMSFactoryUsingSingleton.zip)
 Support lazy initialization (see EMSFactoryLazyInitialization.zip)

9
Can You Extend Eclipse IDE?
Can we add SE2006View to
Eclipse Eclipse IDE without modifying
Workbench a single line of Eclipse code?

views
ViewPart
createPartControl()

ProblemView OutlineView SE2006View

10
The Magic Power: Strategy Design +
Factory Design + Dynamic Loading
Eclipse
RegistryStrategyOSGI
Workbench

views create
ViewPart
createPartControl()

ProblemView OutlineView SE2006View

See YouExtendEclipse.zip for code example


11
Java Swing Framework Look & Feel
JavaSwing
UIManager
Application

views create
LookandFeel

Motif Metal Your


LookandFeel LookandFeel LookandFeel

Strategy Design + Factory Design + Dynamic Loading


12
JDBC Database Driver

Application java.sql.DriverManager

views create
java.sql.Connection

mysql. postgresql. yourdb.


ConnectionImpl JDBC4Connection yourjdbcconnection

Strategy Design + Factory Design + Dynamic Loading


13
Strategy + Factory + Dynamic Loading

 Create any subclass object without specifying


the class name in the code

 No need to change a single line of code to


use new classes

 Provide the foundation for modern software


frameworks to load application-specific
classes

See EMSFactoryDynamicLoading.zip for code example


14
Provides a unified interface to a set of interfaces in a
subsystem. Façade defines a higher level interface
that makes the subsystem easier to use.

University of Kansas 15
Design Principles
• Identify the aspects of your application that vary and separate them from
what stays the same
• Program to an interface, not an implementation
• Favor composition over inheritance
• Strive for loosely coupled designs between objects that interact
• Classes should be open for extension, but closed for modification

• Principle of least knowledge – talk only to your immediate friends

University of Kansas 3/20/2018


Façade – Class diagram

17
Façade - Problem

18
Façade - Solution
 Pros
 Makes code easier to use and understand
 Reduces dependencies on classes
 Decouples a client from a complex system

 Cons
 Results in more rework for improperly designed Façade class
 Increases complexity and decreases runtime performance for large
number of Façade classes

20
 Creational Patterns  Behavioral Patterns
▪ Abstract Factory ▪ Chain of Responsibility
▪ Builder ▪ Command
▪ Factory Method ▪ Interpreter
▪ Prototype ▪ Iterator
▪ Singleton ▪ Mediator
 Structural Patterns ▪ Memento
▪ Adapter ▪ Observer
▪ Bridge ▪ State
▪ Composite ▪ Strategy
▪ Decorator ▪ Template Method
▪ Façade ▪ Visitor
▪ Flyweight
▪ Proxy
Liu Yang
1
Interactive Event-Driven Systems
 UIs are prone to change
 The same data can be presented differently
 Changes to UI must be easy and even possible at
runtime
 The application display and behavior must reflect data
changes immediately
 The same presentation can have different look and feel
 The application reacts to user input differently

 UI should NOT be tightly coupled with core


functionality and data in order to allow for the above
changes
This is not a complete list of design challenges
2
for interactive event-driven systems!
Excel Conceptual Model
EditWS
sheetMgr enterData()
SheetManager 1 1 showWS()

updateCell() sheetMgr
getData()
1 * LineChart
sheetMgr

1
drawLine()

BarChart
*
drawBar()
data

WorkSheet Boundary? Control? Entity?


3
Update Worksheet – Sequence Diagram
EditWS SheetMgr BarChart LineChart

editData
updateCell

storeData
update
getData

newdata
drawBar

Update
getData

newdata drawLine

4
Excel Layered Architecture
Presentation
Edit Line Bar
Worksheet Chart Chart
editData getData getData
update update

App Logic
SheetManager

Persistent Data updateCell

Worksheet

5
Excel Layered Architecture

What’s wrong
Presentation with this
Edit Line Bar Layered
Worksheet Chart Chart Architecture?
getData
editData

App Logic
SheetManager
What kind of
coupling between
Presentation and
Persistent Data updateCell
App Logic?
Worksheet

6
What do We Really Need?
 We need many
views to receive
an update when
worksheet
changes Worksheet
Cell A10
changed

7
What are the Design Problems?
 Loose coupling between an worksheet
(subject) and its dependent views (observers)
 Worksheet wants to notify views the data change
once it occurs, but views of a worksheet can be
created/deleted freely and constantly.
 Views want to show the data change immediately
once it occurs, but they do not know when the
data change will occur.

What design pattern


8
can help?
Identify the Design Pattern
Subject
• I do not care in what format the data is
visualized and how many views are visualizing
the data
• I want to let whoever is visualizing the data
know the latest data change when it occurs
• It is up to views to decide what to do with the
data change
Observer
Loose coupling is a benefit for both sides!
Pattern!
Observer
• I can be created and deleted for data visualization
freely
• I want to update the chart with the latest data
change, but I do not know when the data change
will occur
• I cannot constantly check the data change because
I do not know how frequent I should check
10
Observer Pattern – Excel Worksheet – Views
WSSubject mgr views WSObserver
1 *
attach(WSObserver) update()
detach(WSObserver)
notify()
getData() :Details

EditWS
SheetMgr
update()
updateCell()
getData() :Details
sheetMgr.getData();
showWS();
LineChart
WorkSheet

See ExeclObserver.zip for BarChart


for each o in observers illustrative code example
o.update();
10
Excel Architecture
Apply
Observer
Pattern Presentation
Observer Edit Line Bar
Worksheet Chart Chart
getData
Notification
subscription

getData
editData update update

App Logic
SheetManager

Subject
Persistent Data updateCell

Worksheet
11
Observer Pattern – Update Worksheet
SheetMgr View
EditWS
:WSSubject :WSObserver

enterData
updateCell

storeData

loop [for each view]

update
getData
newdata

SheetManager (or other manager classes) and views


communicate as WSSubject and WSObserver objects,
not specific manager
12 classes or views!
All Problems Solved?
 UIs are prone to change
 The same data can be presented differently
 Changes to UI must be easy and even possible
at runtime
 The application display and behavior must
reflect data changes immediately

?  The same presentation can have different look


and feel – what pattern can be used here?
?  The application reacts to user input differently
– what pattern can be used here?
13
All Problems Solved?
 UIs are prone to change
 The same data can be presented differently
 Changes to UI must be easy and even possible
at runtime
 The application display and behavior must
reflect data changes immediately
 The same presentation can have different look
and feel – Strategy Pattern (interchangeability)
 The application reacts to user input differently
– Strategy Pattern (interchangeability)
14
What We Have Discovered
 One problem with layering (layered architecture) is that
many situations require up-calls from lower to higher
layers – dependency, e.g. Excel worksheet – update

 How do we allow up-calls without creating


dependencies between lower and higher layers?
 Apply design pattern – observer pattern
(loose coupling between two layers)

 Observer pattern enables loose coupling between


Excel worksheet and views, but it DOES NOT solve all
problems – may need more than one design pattern!
E.g. observer pattern + strategy pattern
15
Model-View-Controller (MVC) Architecture
 Main Goal
 To facilitate and optimize the implementation of
interactive intensive systems, particularly those that
use multiple synchronized presentations of shared
information.

 Key Idea
 The separation of the Model from View and
Controller components allows multiple Views of the
same Model – It separates presentation and
interaction from the data. If the user changes the Model
via the Controller of one View, all other Views dependent
on this data should reflect the changes.
16
Model-View-Controller (MVC) Architecture
 Separation of UI from the core data model
 Need to support multiple different user interface (e.g.
desktop GUI, web browser, PDA, cell phone, etc.) –
Core functionality should be reusable across all
different interfaces.
 Interface details changes frequently – Changing UI
details should not affect core functionality.
 It should be easy to add a new user interface.

Model-View-Controller (MVC) architecture model


describes separation of UI from core data model
17
Model-View-Controller (MVC) Architecture
Boundary? Control? Entity?
 MVC Components (View, Controller) ( Model )
 Encapsulate core Functionality (App Logic) + Data in Model.
 Implement UI in View (present data) + Controller (react to
user input).
Model Contains the processing (operations) and the data involved.
View Presents the output – Defines and manages how the data is
presented to the user; each View provides specific presentation
of the same Model. Each View “observes” the Model –
Whenever the data Model changes, all Views immediately
notified and so they can update their graphical presentation.
Controller Manages user interaction – Captures user input (events->
mouse clicks, key presses, etc.) and passes these interactions
to the View and the Model. Each View is associated to a
Controller that captures and processes user input and modifies
the data Model. The user interacts with the system solely
through Controllers. 18
Model-View-Controller (MVC) Architecture
 Controllers typically implement event-handling mechanisms that are
executed when corresponding events occur.
Update model

Change notification
(via notification mechanism of
Observer pattern)

User actions

 Changes made to the Model by the user via Controllers are directly
propagated to the corresponding Views. The change propagation
mechanism can be implemented using the observer pattern (via
subscribe/notify protocol). 19
Model-View-Controller (MVC) Architecture
 MVC architecture style is non-hierarchical
(triangular)
 View subscribes for changes to the Model (via
Observer subscription mechanism)
 Controller gathers input (or change) from the users
and updates the Model.
 Model updates the change and notifies all
subscribers (the Views) of the change (via Observer
notfication mechanism)
 View is notified and updates its display; the user
sees the change. 20
MVC Architecture
AppLogic + Data Presentation
(Model) (View + Controller)
model observers
Model 1 *
Observer
- data update()
service()

register(Observer) model <<create>>


unregister(Observer) Controller
1 *
notify() View
handleEvent()
getData() scroll()
update()
for each o in observers view
o.update();
model.service() model.getData();
app logic, update data; redraw view;

22
Observer + Strategy Patterns in MVC
 Observer Pattern (View–Model relationship):
 Model uses the Observer Pattern to keep the View(s) updated.
 When Model (Subject) data is changed, it updates all the Views
(Observers, via notification mechanism) – Allows multiple
Views to the same Model.

 Strategy Pattern (View–Controller relationship):


 View and Controller use the Strategy Pattern as the View is
concerned with the visual aspects (display data) and delegates
the interface behaviors to the Controller.
 The View (Context) uses the Controller (Strategy Interface) to
implement a specific type of response (or strategy objects).
The Controller can be changed to allow View to respond
differently to user input. 23
Excel MVC
WSSubject mgr views WSObserver
1 *
attach(WSObserver) update()
detach(WSObserver)
notify()
getData() :Details

EditWSCtrler <<create>>
sheetMgr EditWSView
SheetManager
1 * handleEnter() update()
showWS()
updateCell()
getData() :Details view

sheetMgr.updateCell()

WorkSheet LineChart
sheetMgr.getData();

BarChart
24
Model-View-Controller (MVC) Architecture
 Design patterns in MVC
 Observer Observer, Strategy
 View – Model; Controller - Model and Abstract
 Strategy Factory are the key
 View – Controller; View – Look & Feel patterns in MVC
 Abstract Factory
 Create controller or look & feel for a view
 Composite Other patterns are
 Nested views (e.g. Panel contains Button; also important for
Nested Panels) the design of
 Decorator interactive systems.
 Attach additional UI functionalities (e.g., scrolling) to a view
 Command
 Support undo/redo user actions 25
 Pros
 Simultaneous development
 Multiple views for a model – Models can have multiple views
 High cohesion
▪ MVC enables logical grouping of related actions on a controller together. The views for a
specific model are also grouped together.
 Low coupling
▪ The very nature of the MVC framework is such that there is low coupling among models,
views or controllers
 Cons
 Code navigability and pronounced learning curve
▪ The framework navigation can be complex because it introduces new layers of
abstraction and requires users to adapt to the decomposition criteria of MVC.
 Multi-artifact consistency
▪ Decomposing a feature into three artifacts causes scattering. Thus, requiring developers
to maintain the consistency of multiple representations at once.

25
 Problem
 Interactive Event-Driven Systems
 Solution (Pattern Composition)
 Observer Pattern + Strategy Pattern + …
 Popular patterns in many real frameworks
 Django, Reils, .NET MVC…
Liu Yang
1
SDLC Activities
Problem Solution
Requirements Requirements System Object Testing
Impls
Elicitation Analysis Design Design

Expressed in Structured By Realized By Implemented Verified By


Terms Of By

class...
class...
class... ?
Requirement
Specification Design Source Test Cases
Analysis SW Model
(SRS) Model Architecture Code Black Box tetsing
(More about custimers) (Detail) Source code (Ecs, BVs)
Func & non-func reqs Class diagram SW architecture Class diagram Working White Box testing
Use cases Sequence diagram Boundary, control, Sequence prototype (CFG, basis paths)
Use case model State machine entity classes diagram
Data dictionary Design 2patterns State machine
 In 1947 Harvard University was
operating a room-sized computer
Called the Mark II.
 mechanical relays
 glowing vacuum tubes
 technicians program the computer by reconfiguring it
 Technicians had to change the occasional vacuum tube.

 A moth flew into the computer and


was zapped by the high voltage when
it landed on a relay.
 Hence, the first computer bug!
Unexpected things happen!

A software bug is an error,


flaw, failure or fault in a computer
program or system that causes it to
produce an incorrect or unexpected result,
or to behave in unintended ways.

4
5
Can We Test Everything?
 A function is supposed to A buggy
program!
 Take an integer input value,
add 1 to the input, divide it
int blech(int input) {
by 30000 and return the input = input – 1;
value return input/30000;
}
 How many possible input
values for 16-bits integer?Can we test all the
 216 = 65536 possible inputs?
Yes, but TOO
6 COSTLY!
Can We Test Everything?
 A function is supposed to A “Black
 Take an integer input value, add Box”
1 to the input, divide it by 30000
and return the value

 Which input values do you


choose to test the program?
 1, 42, 32000, -31218, …

Are these good selection of inputs?


Can we detect the bug of the program?
7
Equivalence Class and Boundary
Value Testing
• Add1Divide30000 (-32768 ≤ input ≤ -30001) [return -1]
– Lower boundary -32768: -32769, -32768, -32767
– Upper boundary -30001: -30002, -30001, -30000

• Add1Divide30000 (-30000 ≤ input ≤ 29998) [return 0]


– Lower boundary -30000: -30001, -30000, -29999
– Upper boundary 29998: 29997, 29998, 29999

• Add1Divide30000 (29999 ≤ input ≤ 32767) [return 1]


– Lower boundary 29999: 29998, 29999, 30000
– Upper boundary 32766: 32766, 32767, 32768
8
Can We Test Everything?
A “White
 How many possible input Box”
values for 16-bits integer n?
doSomething(int n) {
 216 = 65536 1. int a = 0;
2. while(a < n) {
 Which input values do you 3. if(a < 3) {
choose to test the program? 4. print(“X);
5. } else {
 1, 42, 32000, -31218, …
6. print(“Y”);
7. }
 Can we cover all 8. a++;
statements, all branches, 9. }

or all execution paths? 10. return;


9 }
Basis Path Testing
 Basis Path Testing (or structured testing)
is a white box testing method used for
designing test cases intended to examine
all possible paths of execution in a
program at least once.
 Analyzes Control flow graph (CFG)
 Determines Cyclomatic Complexity (CC) value
 Obtains linearly independent paths
 Generates test cases for each path

10
Basis Path Testing
Control Flow Graph (CFG) • Three basis paths
I. 1, 2, 10
1
Cyclomatic Complexity II. 1, 2, 3, 4, 8, 2, 10
a = 0; (CC) = 3
III. 1, 2, 3, 6, 8, 2, 10
2 while
a<n
false • Three test cases
true I. n=0
3
false true II. n = 1
if a < 3
III. n = 4
6 4
print(“y”); print(“x”);
• Real execution paths
8 I. 1, 2, 10
a++;
II. 1, 2, 3, 4, 8, 2, 10

10
III. 1, 2, 3, 4, 8, 2, 3, 4,
return; 8, 2, 3, 4, 8, 2, 3, 6,
11 8, 2, 10
What is Testing?
 Testing == Debugging ?
 To show that software works ?
 To show that software doesn’t work ?
 To reduce the perceived risk of system not
working to an acceptable value

 To result in low-risk software without much


testing effort
12
Types Of Testing
 Black Box Testing
 What to analyze: Requirements and specifications
• E.g. “The income of an applicant must be between $1500 per
month and $8000 per month”
 Type of black box testing
• Equivalence class testing and boundary value testing
• State-based testing

 White Box Testing


 What to analyze: Implementation details, internal paths
and structure
 Type of white box testing
• Control flow testing
• Data flow testing 13
Levels Of Testing
 Unit testing (we learn in this course)
 Test an unit individually
 Integration testing
 Test units in combination
 System testing
 Test everything (functionality, usability, reliability,
performance, portability, security …)
 Acceptance testing (UAT User Acceptance
Testing)
 Customer accepts the software and give us
their money 14
Ingredients Of Test Case
Ingredient Description

Name Distinct name of test case

Location Path to test program and its inputs

Input Input data or commands

Oracle Expected test output

Log Actual output produced by the test

15
Test Cases for Mortgage
Application
Each row is a test case
Input Oracle Log

Income Number of Applicant Property Expected Test


mortgage Type Type Result Result

$5000 2 Person Cando Approval Approval

$30000 3 Person HDB Approval Approval

$15000 4 Person HDB Approval Approval

$100 1 Person HDB Reject Reject

$1501 8 Person Condo Reject Approval

$19845 3 Company Condo Reject Reject

$79999 2 Person Mobilehome Reject Reject


16
An Android Unit Test Case
package mortgageapplication.test;
Location
public class TestMortgageApplicationActity {
private MortgateProcessor processor;
public void testQualifiedApplication() {
int income = 5000;
int nummortage = 2;
Name
AppcantType applicant = ApplicantType.Person;
Input
PropertyType property = PropertyType.Cando;
ApplicationResult result = Log
processor.analyzeApplication( income,
numortgage, applicant, property);
assertEquals(result, ApplicationResult.Approval);
}
public void testLowIncome() {

Google
int income = 100; Oracle
int nummortage = 1;
“Android Testing AppcantType applicant = ApplicantType.Person;
Fundamentals” and PropertyType property = PropertyType.HDB;
“Android Activity ApplicationResult results=
Testing Tutorial” processor.analyzeApplication( income,
numortgage, applicant, property);
assertEquals(result, ApplicationResult.Reject);
} 17
}
Order Of Test Case Execution
 Cascading test cases, e.g.,
1. Create an order  Smaller and simpler test cases
2. Read the order  One fails, the subsequent test
3. Update the order may be invalid
4. Delete the order
5. Read the deleted order

 Independent test cases, e.g.,


 Self-contained test cases  Parallel test execution
for the above features  Larger and more complex
test cases
18
 Software testing is an investigation conducted to
provide stakeholders with information about the
quality of the software product or service under test.
 Dynamic execution
 To find bug, rather than to prove no bug
 Type of testing
 Whitebox vs Blackbox
 Level of testing
 Unit, integration, system and acceptance
 Test Case
 5 elements, and execution order

19
CZ2006/CE2006
Software Engineering

Lecture 16-17
Equivalence Class Testing
When I launch my app after several
hours of development
Unexpected things happen!

A software bug is an error,


flaw, failure or fault in a computer
program or system that causes it to
produce an incorrect or unexpected result,
2
or to behave in unintended ways.
Types Of Testing
 Black Box Testing
 What to analyze: Requirements and specifications
• E.g. “The income of an applicant must be between $1500 per
month and $8000 per month”
 Type of black box testing
• Equivalence class testing and boundary value testing
• State-based testing

 White Box Testing


 What to analyze: Implementation details, internal paths
and structure
 Type of white box testing
• Control flow testing
• Data flow testing 3
Levels Of Testing
 Unit testing (we learn in this course)
 Test an unit individually

 Integration testing
 Test units in combination

 System testing
 Test everything (functionality, usability, reliability,
performance, portability, security …)
 Acceptance testing (UAT User Acceptance
Testing)
 Customer accepts the software and give us
their money 4
Ingredients Of Test Case
Ingredient Description

Name Distinct name of test case

Location Path to test program and its inputs

Input Input data or commands

Oracle Expected test output

Log Actual output produced by the test

5
Black Box Testing Process
 The tester
1. Analyzes requirements or specifications The most
 equivalence classes and boundary values difficult
2. Chooses valid inputs and invalid inputs steps
3. Determines expected outputs (oracle) for chosen inputs
4. Constructs tests with the chosen inputs (e.g., write JUnit
program)
 The testing engine (e.g., JUnit)
1. Executes the tests
2. Compares actual outputs (log) with the expected outputs
(oracle)
3. Determines whether the SUT (System Under Test)
functions properly 6
Black Box Testing Pros and Cons
 Applicability
 All levels of system development (Unit, Integration,
System, Acceptance)
 Cons
 Cannot know how much of the implementation have
been tested
 No notion of testing coverage like in white box testing

 Pros
 Directs the tester to a very small subset of test
inputs that can highly likely find the bugs
7
We do Black Box Testing Often…

https://www.dpreview.com/galleries/6998361880/photos/1163297

8
Assumption #1
 Verifiable requirements and API specification
exists
 Make software more testable from its inception!

 A requirement like this is NOT verifiable!


 The company must not hire too-young or too-old
people
 The company can hire juniors on part-time basis
 The company can hire adult as full-time employees
Compare this with verifiable
requirements on Hire or Not slide!
9
Assumption #2
 Code must be testable!
 Examples that make black-box testing less effective
if (age==0) hire=NO; if (age>=0 && age <= 15) hire=NO;
if (age==1) hire=NO; if (age>=16 && age <= 18) hire=PART;

if (age>=18 && age <= 34) hire=FULL;
if (age==15) hire=NO;
if (age==16) hire=PART;
if (age==17) hire=PART; if (age==35 && name==“xingzc”)
if (age==18) hire=FULL; hire=CEO;
… if (age==35 && name!=“xingzc”)
if (age==54) hire=FULL; hire=FULL;
if (age==55) hire=NO;
if (age==56) hire=NO; if (age>=36 && age<=54) hire=FULL;

if (age>=55 && age<=99) hire=NO;
if (age==98) hire=NO;
if (age==99) hire=NO; 10
Motivating Example: Hire or Not?
 Test a module implementing the following
hiring requirements
 0 – 15, 55 – 99 Do not hire
 16 – 17 Part-time
 18 – 54 Full-time
Test …, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9,
10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, Test only one value for
21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, each range, one invalid
32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42,
43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, value below 0, and one
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, invalid value above 99
65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75,
76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86,
87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97,
98, 99, 100, 101, 102, …?
11
Equivalence Class Testing – Partition
Input Values into Equivalence Classes
 A set of input values forms an equivalence
class (EC) if
 They all are supposed to produce the same output
 If one value catches a bug, the others probably will
too
 If one value does not catch a bug, the others
probably will not either

12
A metaphor

http://web.1.c2.audiovideoweb.com/1c2web3536/lowcalrice.jpg

13
Equivalence Class Testing Process
 The tester
1. Identify the valid and invalid equivalence classes that partition
the input values
2. Choose at least one input value for each equivalence class of
each input parameter
3. Determines expected outputs (oracle) for chosen inputs
4. Constructs tests with the chosen inputs (e.g., write JUnit
program)

 The testing engine (e.g., JUnit)


1. Executes the tests
2. Compares actual outputs (log) with the expected outputs (oracle)
3. Determines whether the SUT (System Under Test) functions
properly 14
Range of Values
 ONE equivalence class of VALID values
 TWO equivalence classes of INVALID values
Mortgage –
Valid Income Range
1500≤ x ≤ 80000
Invalid Invalid
x ≤ 1499 x ≥ 80001
$1500/month $80000/month

Requirement: The system approves mortgage application


if income is between $1500/month and $80000/month
15
Range of Values – Exercise

Mortgage –
Number of Mortgages
Valid
0≤ x ≤ 5
Invalid Invalid
x ≤ -1 x≥6
0 5

Requirement: The system approves application if #mortgage


per applicant is between 0 and 5

16
Range of Values – Exercise

Length of Password

Valid
4≤ x ≤ 8
Invalid Invalid
x≤3 x≥9
4 8

Requirement: The password must contain 4-8 chars and


digits

17
Range of Values – Exercise
Hiring Rules
Valid equivalence classes
0 ≤ age ≤15 (do not hire)
16 ≤ age ≤17 (hire part-time)
18 ≤ age ≤54 (hire full-time)
55 ≤ age ≤99 (do not hire)

Invalid equivalence classes


age ≤ -1
age ≥ 100
Requirements: 0 – 15, 55 – 99 Do not hire
16 – 17 Part-time
18 – 54 Full-time

18
Discrete Values
 ONE equivalence class of VALID values
 ONE equivalence class of INVALID values
Mortgage –
Applicant Type
Valid Invalid
Trust
Person Company
Partnership

Requirement: The system approves only personal mortgage


applications
19
Discrete Values – More Examples

Mortgage –
Property Type

Valid Invalid
HDB Townhouse
Cando Mobilehome

Requirement: The system approves only HDB and Condo


mortgage applications

20
Discrete Values – More Examples

Character of Password

Valid Invalid
ab…z
AB…Z +-()…
012…9

Requirement: The password must be characters a-z, A-Z,


and 0-9

21
Design Test Cases Using ECs
1. Test VALID inputs of several parameters
 Test valid inputs of several parameters at the
same time (i.e. per test case)
 Choose one valid input for each input parameter
from an equivalence class

2. Test INVALID inputs of several parameters


 Test ONLY ONE INVALID input from an
equivalence class of one input parameter at the
same time (i.e. per test case)
 Choose valid inputs from an equivalence class of
all other input parameters
22
Test Valid Inputs Using ECs

 You may test valid input values of several


input parameters at the same time

 You may create test cases for all the values


in an valid equivalence class if the set of
valid values in the equivalence class is
small
e.g. The number of mortgages (0, 1, 2, 3, 4, 5)
Property type (HDB, Condo)
but not for income range, or characters of password
23
Test Valid Inputs – Example
Each row is a test case. As each parameter has only
For each test case, choose one valid one valid EC, this single
input value from a valid equivalence test case satisfies EC
class of each parameter testing principle

Income Number of Applicant Property Expected


mortgage Type Type Result
$1500 0 Person Condo Approval
$2000 1 Person Condo Approval
$5000 2 Person Condo Approval
$12345 3 Person HDB Approval
$76543 4 Person HDB Approval
$80000 5 Person HDB Approval
As #mortgage and PropertyType
Try to cover a few more valid have only 6 (0-5) and 2 (Condo,
income value when HDB) valid values, we create
enumerating #mortgage and several more test cases to cover
PropertyType values 24
all these values
Should We Test Invalid Inputs?
 Testing by Contract
 Create test cases only for valid inputs (i.e., the input values
that satisfy the pre-conditions)

 Defensive Testing
 Create test cases for BOTH VALID and INVALID inputs
 Do not assume that users will use your code the way it is
supposed to be used
 Test the module to see whether it behaves as expected for invalid
inputs, i.e. do not cause unforeseen errors or abnormal system
behavior (sudden program termination)

Which one does the testers prefer?


 If it does not work, who will get the blame? – the testers
 Testers prefer defensive testing
25
Test Invalid Inputs Using ECs
Why?
 You must test ONLY ONE INVALID input
value from an equivalence class of one input
parameter per test case i.e. each test case
should have no more than one invalid input
Income Number of Applicant Property Expected
mortgage Type Type Result

$100 8 Company Mobilehome Reject

Invalid input Invalid input Invalid input Invalid input

If we test only one invalid input for each test


case, then we can learn the error handling or
behavior for each 26
type of invalid input
Test Invalid Inputs Using ECs

 You may create test cases for all the values


in an invalid equivalence class if the set of
invalid values in the equivalence class is
small

27
Test Invalid Inputs – Example
Each row is a test case.
Test ONLY ONE INVALID
input value per test case

Income Number of Applicant Property Expected


mortgage Type Type Result
$100 1 Person Condo Reject
$81000 2 Person HDB Reject
$5000 -1 Person Condo Reject
$10000 8 Person HDB Reject
$12345 3 Company HDB Reject
$76543 4 Person Mobilehome Reject

Choose valid input values


for all other parameters
28
Quick Summary
A key aspect of black box testing is identifying
Equivalent Classes (EC).

Identifying ECs helps us test effectively with a


minimal set of inputs.

For equivalence classes (ECs), range of values –


• ONE VALID EC of VALID values
• TWO INVALID ECs of INVALID values
29
But, the Real World is Messy

http://mrmen.wikia.com/wiki/File:MR_MESSY_4A.jpg

30 …
Real World Requirements are
Messy Too 

Software Engineering: Concepts and Applications by Subhajit Datta (Oxford University Press, 2010)
31
A Key Skill is to Derive Verifiable
Requirements for Effective Black Box Testing

Software Engineering: Concepts and Applications by Subhajit Datta (Oxford University Press, 2010)
32
Liu Yang
1
Equivalence Class Testing – Partition
Input Values into Equivalence Classes
 A set of input values forms an equivalence
class (EC) if
 They all are supposed to produce the same output
 If one value catches a bug, the others probably will
too
 If one value does not catch a bug, the others
probably will not either

2
Equivalence Class Testing Process
 The tester
1. Identify the valid and invalid equivalence classes that partition
the input values
2. Choose at least one input value for each equivalence class of
each input parameter
3. Determines expected outputs (oracle) for chosen inputs
4. Constructs tests with the chosen inputs (e.g., write JUnit
program)

 The testing engine (e.g., JUnit)


1. Executes the tests
2. Compares actual outputs (log) with the expected outputs (oracle)
3. Determines whether the SUT (System Under Test) functions
properly 3
Range of Values
 ONE equivalence class of VALID values
 TWO equivalence classes of INVALID values
Mortgage –
Valid Income Range
1500≤ x ≤ 80000
Invalid Invalid
x ≤ 1499 x ≥ 80001
$1500/month $80000/month

Requirement: The system approves mortgage application


if income is between $1500/month and $80000/month
4
Discrete Values
 ONE equivalence class of VALID values
 ONE equivalence class of INVALID values
Mortgage –
Applicant Type
Valid Invalid
Trust
Person Company
Partnership

Requirement: The system approves only personal mortgage


applications
5
Design Test Cases Using ECs
1. Test VALID inputs of several parameters
 Test valid inputs of several parameters at the
same time (i.e. per test case)
 Choose one valid input for each input parameter
from an equivalence class

2. Test INVALID inputs of several parameters


 Test ONLY ONE INVALID input from an
equivalence class of one input parameter at the
same time (i.e. per test case)
 Choose valid inputs from an equivalence class of
all other input parameters
6
Test Valid Inputs Using ECs

 You may test valid input values of several


input parameters at the same time

 You may create test cases for all the values


in an valid equivalence class if the set of
valid values in the equivalence class is
small
e.g. The number of mortgages (0, 1, 2, 3, 4, 5)
Property type (HDB, Condo)
but not for income range, or characters of password
7
Test Valid Inputs – Example
Each row is a test case. As each parameter has only
For each test case, choose one valid one valid EC, this single
input value from a valid equivalence test case satisfies EC
class of each parameter testing principle

Income Number of Applicant Property Expected


mortgage Type Type Result
$1500 0 Person Condo Approval
$2000 1 Person Condo Approval
$5000 2 Person Condo Approval
$12345 3 Person HDB Approval
$76543 4 Person HDB Approval
$80000 5 Person HDB Approval
As #mortgage and PropertyType
Try to cover a few more valid have only 6 (0-5) and 2 (Condo,
income value when HDB) valid values, we create
enumerating #mortgage and several more test cases to cover
PropertyType values 8
all these values
Test Invalid Inputs Using ECs
Why?
 You must test ONLY ONE INVALID input
value from an equivalence class of one input
parameter per test case i.e. each test case
should have no more than one invalid input
Income Number of Applicant Property Expected
mortgage Type Type Result

$100 8 Company Mobilehome Reject

Invalid input Invalid input Invalid input Invalid input

If we test only one invalid input for each test


case, then we can learn the error handling or
behavior for each type
9
of invalid input
Test Invalid Inputs – Example
Each row is a test case.
Test ONLY ONE INVALID
input value per test case

Income Number of Applicant Property Expected


mortgage Type Type Result
$100 1 Person Condo Reject
$81000 2 Person HDB Reject
$5000 -1 Person Condo Reject
$10000 8 Person HDB Reject
$12345 3 Company HDB Reject
$76543 4 Person Mobilehome Reject

Choose valid input values


for all other parameters
10
Boundary Value Testing (BVT) –
Which Values to Test?
 BVT is only applicable to range of values
 Focus on boundaries of the equivalence classes
of range of values
 Select a minimal set of valid and invalid inputs (values
on-the-boundary, just-below, or just-above
boundaries) to test

 What is the boundary values of parameter


Property type?
 Do discrete values, such as property type, have
boundary values? NO
11
Boundary Value Testing (BVT) Process
 The tester
1. Identify the lower and upper boundaries of
equivalence classes of the range-of-values parameters
2. Choose three input values for each boundary
 One value on-the-boundary, one value just-below,
and one value just-above
 Just-below and just-above value depends on the value’s unit
 No need to duplicate the test cases if the just-below or
just-above values fall into other ECs (including current EC)

3. Determines expected outputs (oracle) for chosen inputs


4. Constructs tests with the chosen inputs (e.g., write
JUnit program) 12
Determine Boundary Values (BVs) – Example
 Income range valid equivalence class (1500 ≤ x ≤ 80000)
– Lower boundary 1500: 1499, 1500, 1501
– Upper boundary 80000: 79999, 80000, 80001
– Valid boundary values: {1500, 80000}
– Invalid boundary values: {1499, 80001}

 Number of mortgage valid equivalence class (0 ≤ x ≤ 5)


– Lower boundary 0: -1, 0, 1
– Upper boundary 5: 4, 5, 6
– Valid boundary values: {0, 5}
– Invalid boundary values: {-1, 6}

 Length of password valid equivalence class (4 ≤ x ≤ 8)


– Lower boundary 4: 3, 4, 5
– Upper boundary 8: 7, 8, 9
– Valid boundary values: {4, 8}
– Invalid boundary values: {3, 9}
13
Determine Boundary Values (BVs) – Example
 Hiring rules (0 ≤ age ≤ 15) (Do not hire)
Valid
– Lower boundary 0: -1, 0, 1
boundary
– Upper boundary 15: 14, 15, 16
values:
 Hiring rules (16 ≤ age ≤ 17) (Part time) {0, 15,
– Lower boundary 16: 15, 16, 17 16, 17,
– Upper boundary 17: 16, 17, 18 18, 54,
55, 00}
 Hiring rules (18 ≤ age ≤ 54) (Full time)
– Lower boundary 18: 17, 18, 19 Invalid
– Upper boundary 54: 53, 54, 55 boundary
values:
 Hiring rules (55 ≤ age ≤ 99) (Do not hire) {-1, 100}
– Lower boundary 55: 54, 55, 56
– Upper boundary 99: 98, 99, 100
14
Determine Boundary Values (BVs) – Example

 Add1Divide30000 (-32768 ≤ input ≤ -30001) (return -1)


– Lower boundary -32768: -32769, -32768, -32767
– Upper boundary -30001: -30002, -30001, -30000

 Add1Divide30000 (-30000 ≤ input ≤ 29998) (return 0)


– Lower boundary -30000: -30001, -30000, -29999
– Upper boundary 29998: 29997, 29998, 29999

 Add1Divide30000 (29999 ≤ input ≤ 32767) (return 1)


– Lower boundary 29999: 29998, 29999, 30000
– Upper boundary 32766: 32766, 32767, 32768
15
Design Test Cases Using BVs
1. Test VALID inputs of several parameters
 Test valid inputs of several parameters at the same time
 Choose one valid input from an equivalence class of each
input parameter
2. Test INVALID inputs of several parameters
 Test ONLY ONE INVALID input from an equivalence class
of one input parameter per test case
 Choose VALID inputs from an equivalence class of all other
input parameters

 Use the boundary values of the equivalence


classes of range-of-values parameters
 Value on-the-boundary as VALID input
 Just-below or just-above values (if not in other ECs, including
the current EC) as INVALID inputs
16
Black Box Testing – ECs and BVs
Range of Values Discrete Values
Equivalence ONE Valid EC ONE valid EC
Classes (ECs) TWO Invalid ECs ONE Invalid EC

Range of values Lower Boundary Upper Boundary


Boundary ONE value on-the- ONE value on-the-
Values (BVs) boundary boundary
(for each EC) ONE value just-below ONE value just-below
ONE value just-above ONE value just-above

Discrete Values
Boundary Values (BVs) NO Boundary Values
(for each EC)

17
Black Box Testing – ECs and BVs
For test cases (use boundary values) –
• Test combination of VALID inputs (i.e. value on-the-boundary), one
from each EC

• Test ONE INVALID input from an EC per test case, all others are VALID
inputs => One test case can contain AT MOST ONE invalid input

• Test combination of boundary values


Example: (two parameters, A and B of range of values)
1. Valid A + Valid B  combination of VALID inputs
2. Valid A + Invalid B 
combination of boundary values
3. Invalid A + Valid B 
• Note: For VALID EC: On-the-boundary: valid
Just-below and just-above: invalid
• Remove just-below or just-above values from the boundary values of
each EC (no need to duplicate the test cases) if the just-below or just-
18
above values fall into other ECs (including current EC)
Liu Yang
1
Black Box Testing Pros and Cons
 Applicability
 All levels of system development (Unit, Integration,
System, Acceptance)
 Cons
 Cannot know how much of the implementation have
been tested
 No notion of testing coverage like in white box testing

 Pros
 Directs the tester to a very small subset of test
inputs that can highly likely find the bugs
2
White Box Testing Process
The most difficult steps
 The tester
1. Analyzes SUTs (System Under Test) implementation
 Control Flow Graph or Data Flow Graph
2. Identify execution paths through the SUT
3. Chooses inputs to cause the SUT to execute selected paths
4. Determines expected outputs (oracle) for chosen inputs
5. Constructs tests with the chosen inputs (e.g., write JUnit
program)
 The testing engine (e.g., JUnit)
1. Executes the tests
2. Compares actual outputs (log) with the expected outputs
(oracle)
3. Determines whether the SUT (System Under Test) functions
properly 3
White Box Testing Pros and Cons
 Applicability
 All levels of system development (Unit, Integration, System,
Acceptance)
 Pros
 Ensure that every path through the SUT has been identified
and tested
 Cons
 Testing all execution paths is generally infeasible
 e.g., loop, #decision points
 May not detect data and arithmetic bugs
 e.g., a = a – 1 // should be a = a + 1; or
a/b // b cannot be zero
 Never find paths that are not implemented
 e.g., paths in requirements are missing in implementation
4
Control Flow Graph (CFG)

 A directed graph, consists of nodes and


edges, where:
 Each node represents a process block or a
decision point

 Each edge represents control flow (i.e.,


what happens after what)

5
Process Block
 A sequence of statements
Process Block execute sequentially

…  Does not contain if/while/for/


s1; switch/goto statements
s2; s1
 Contains any number of
… s2
sequentially executed statements
in the process block
 One control flow edge into the
process block
 One control flow edge out of
the process block
6
Binary Decision Point – if statement

Binary Decision Point  Control flow can


change at the decision
… point
if(a>0) { false
if(a>0)
s1;  One control flow edge
} true into the decision point
s2;
… s1  Two control flow edges
out of the decision
point
s2
 True branch
 False branch
7
Binary Decision Point – if-else statement
Binary Decision Point  Control flow can
change at the
… decision point
if(a>0) {
s1; if(a>0)  One control flow
} else { true false edge into the decision
s2;
} point
s1 s2
s3;  Two control flow

s3
edges out of the
decision point
 True branch
 False branch
8
Binary Decision Point – while statement
Binary Decision Point  Control flow can change
… at the decision point
while(a>0) {
s1; false
 One control flow edge
while(a>0) into the decision point
a--;
} true  Two control flow edges
s2;
… s1 out of the decision point
 True branch
 False branch
a--
 Loop back to the
decision point from the
s2
last statement
9
Binary Decision Point – for statement
Binary Decision Point

 Control flow can change
for(a=100;a>0;a--) { at the decision point
s1; a=100
}
 One control flow edge
s2; false into the decision point
… while(a>0)
 Two control flow edges
true out of the decision point
transform
into
s1  True branch
…  False branch
a=100;
while(a>0) { a--  Loop back to the
s1; decision point from the
a--; last statement
} s2
s2;
… 10
N-ary Decision Point – switch statement
N-ary Decision Point
 Control flow can
… change at the
switch(a) { decision point
case 1: switch(a)
s1;
a==1 a==2 default  One control flow
break;
case 2: s3
edge into the
s1 s2
s2; decision point
break;
default:  N control flow edges
s4
s3; out of the decision
} point
s4;

11
Control Flow Graph - Example
int computeP(int a, int b) {
1 int q, x, p;
2 q = 1; 2-3 q = 1;
x = 2;
3 x = 2;
4 if(a > 0) { true
4 If a>0
5 x = x + 1;
false x = x + 1; 5
6 }
7 p = q/x; 7 p = q/x;
8 if(b == 3) { true
8 if b==3
9 p = max(q, x);
10 } false p=max(q, x); 9
11 return p;
11 return p;
12 } 12
Execution Path Through the CFG

 A sequence of process blocks and


decision points through the CFG of the
program

13
Execution Path – computeP(int,int)
q = 1; q = 1;
2-3 x = 2;
2-3
x = 2;

true true
4 if a> 0 4 if a> 0
false 5 x = x + 1; false 5 x = x + 1;
7 p = q/x; p = q/x;
7

8 if b==3 true true


8 If b==3
9 p=max(q, x);
false 9 p=max(q, x);
false

11 return p; 11 return p;
Path#1: 2-3, 4, 7, 8, 11 Path#2: 2-3, 4, 5, 7, 8, 11
Other execution paths for14computeP(int,int)?
Execution Path – computeP(int,int)
q = 1; q = 1;
2-3 x = 2;
2-3
x = 2;

true true
4 if a> 0 4 if a> 0
false 5 x = x + 1; false 5 x = x + 1;
7 p = q/x; p = q/x;
7
true true
8 if b==3 8 If b==3
9 p=max(q, x); p=max(q, x);
false false 9

11 return p; 11 return p;
Path#3: 2-3, 4, 7, 8, 9, 11 Path#4: 2-3, 4, 5, 7, 8, 9, 11
Two decision points  Four execution
15 paths (22 = 4)
Level 1 - 100% Statement Coverage

 Create test cases such that all statements


are executed at least once under test
 Select execution path(s) to cover all the
CFG nodes at least once

16
Level 1 Coverage – computeP(a, b)
 Select execution path(s) to cover all the CFG nodes at least once

2-3 q = 1; 2-3 q = 1;
x = 2; x = 2;

4 if a> 0
true Have we 4 if a> 0
true

false 5 x = x + 1; missed false 5 x = x + 1;

7 p = q/x; anything? 7 p = q/x;

true true
8 if b==3 8 if b==3

9 p=max(q, x); 9
false false p=max(q, x);

11 return p; 11 return p;
Path: 2-3, 4, 5, 7, 8, 9, 11
 Choose input values to execute the selected path
e.g., a=1 and b=3, or a=10 and
17 b=3, etc ……
Level 2 – 100% Branch Coverage

 Create test cases such that all branches


out of the decision points are executed
at least once under test

 Binary decision point evaluates to TRUE


and FALSE outcome at least once

18
Level 2 Coverage – computeP(a, b)

Select execution paths to execute all branches of the decision
points at least once
2-3 q = 1; Path#1: 2-3 q = 1; Path#2:
x = 2; x = 2; 2-3, 4, 7, 8, 11
2-3, 4, 5, 7, 8, 9, 11
true
true
4 if a> 0
true
4 if a> 0
5 x = x + 1;
Have we false 5 x = x + 1;
false

7 p = q/x;
missed 7 p = q/x;
true
true
anything? true
8 if b==3 8 if b==3

false 9 false 9 p=max(q, x);


p=max(q, x);

11 return p; 11 return p;

 Choose input values to execute the selected path


e.g., a=1 (true), b=3 (true); and
19 a=0 (false), b=2 (false)
Level 4 – 100% Path Coverage
 Two more execution paths (from level 2) to achieve 100% path
coverage of all branches of the decision points at least once
2-3
q = 1; Path#3: 2-3 q = 1; Path#4:
x = 2; 2-3, 4, 5, 7, 8, 11 x = 2; 2-3, 4, 7, 8, 9, 11
true true
4 if a> 0 4 if a> 0

false 5 x = x + 1; 5 x = x + 1;
false
7 p = q/x; 7 p = q/x;

8
true true
if b==3 8 if b==3

false 9 p=max(q, x); false


p=max(q, x);
9
11 return p; 11 return p;
 Choose input values to execute the selected path
e.g., a=1 (true), b=2 (false); 20
and a=0 (false), b=3 (true)
Level 4 – 100% Path Coverage
 Create test cases such that all execution
paths are executed at least once under
test

 May not be feasible in general (we shall


see example later)
 Every decision point doubles the number of
paths (i.e., 2|𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑𝑑| )
 Every loop multiplies the paths by the number
of iterations
21
Level 3 – Basis Path Coverage
 Create test cases such that the minimum number
of basis paths are executed at least once under test.
 What is basis path (a.k.a. Linear Independent Path)?
 Each basis path traverses at least one new control flow
edge (i.e. at least one new node) that has not been
traversed before the path is defined.
 A set of basis paths (or basis set) is a set of linearly
independent paths.
 The basis set is not unique (we shall visit this point
later). Basis Path testing is an effective mechanism to
deal with exponential combination of branches.
22
Basis Path Testing
From Test Fundamentals lecture slide#11

 Basis Path Testing (or structured testing)


is a white box testing method used for
designing test cases intended to examine
all possible paths of execution in a
program at least once.
 Analyzes Control flow graph (CFG)
 Determines Cyclomatic Complexity (CC) value
 Obtains linearly independent paths
 Generates test cases for each path

23
Basis Path Testing Process
 The tester
1. Construct the control flow graph (CFG) of the SUT
(System Under Test)
2. Identifies execution paths through the CFG of the SUT
2.1 computes the CFG’s Cyclomatic Complexity (CC)
2.2 selects a set of #CC basis paths
3. … The rest of steps are the same as the slide #3
4. …
5. …
Basis Path testing guarantees
 The test engine 100% statement and branch
1. … coverage
2. …
3. … 24
Cyclomatic Complexity of a CFG
 CC measures how complex your
program is in terms of the number of
decision points (i.e., if/while/for/switch).

 The more decision points (i.e.,


if/while/for/switch) a program has → The
higher the CC → The more basis paths
you need to test.
E.g. if your program has CC value 6, then you’ve to
identify 6 basic paths to test.
25
Cyclomatic Complexity of a CFG
 Use the following two equations to
compute CC
 CC = |edges| - |nodes| + 2

 CC = |decisionpoint| + 1, if all decision


points are binary, i.e., one true branch + one
false branch

The two equations compute the same


value if all decision points are binary
26
Cyclomatic Complexity – Example
int computeP(int a, int b) {
1 int q, x, p; |edges| = 8
2 q = 1; q = 1; |nodes| = 7
3 x = 2; x = 2; CC = 8 – 7 + 2 = 3
4 if(a > 0) { true
if a> 0
5 x = x + 1; Or,
6 } false
x = x + 1;
7 p = q/x; |decisionpoint| = 2
p = q/x;
8 if(b == 3) { CC = 2 + 1 = 3
9 p = max(q, x); true
if b==3
10 } p=max(q, x);
false
11 return p;
} return p;
27
Select a Set of Basis Paths

 Pick a “baseline” path 2-3


q = 1;
x = 2;

 Reasonably true
true
4 if a> 0
“typical” path of
execution false
5 x = x + 1;

7 p = q/x;
 Most important path
from the tester’s view true
8 if b==3

Basis path#1 (baseline): false


false 9 p=max(q, x);
2-3, 4, 5, 7, 8, 11
11 return p;
28
Select a Set of Basis Paths
q = 1;
 Change the outcome 2-3 x = 2; First decision
of the first decision point
true
4
point if a> 0

false 5 x = x + 1;
false

 Keep the maximum 7 p = q/x;


number of other
true
decision points the 8 if b==3

same false 9 p=max(q, x);


Basis path#2:
2-3, 4, 7, 8, 11 11 return p;
29
Select a Set of Basis Paths
q = 1;
 Change the outcome of 2-3
x = 2;
the second decision
true
point 4 if a> 0

false 5 x = x + 1;
 Keep the maximum p = q/x;
7
number of other
true
decision points the 8 if b==3
true

same Second false 9 p=max(q, x);


decision
Basis path#3 : point 11 return p;
2-3, 4, 5, 7, 8, 9, 11
30
Create a Test Case for Each Basis Path

q = 1;
2-3
x = 2;
 One set of basis paths
Baseline
I. 2-3, 4, 5, 7, 8, 11
true
4 if a> 0
II. 2-3, 4, 7, 8, 11
5 x = x + 1;
false III. 2-3, 4, 5, 7, 8, 9, 11
7 p = q/x;
 Three test cases
true
8 if b==3
I. a = 4; b = 2
false 9 p=max(q, x); II. a = 0; b = 5
III. a = 7; b = 3
11 return p;

31
Basis Paths for computeP()
 One set of basis paths
2-3 q = 1; Original
x = 2;
baseline I. 2-3, 4, 5, 7, 8, 11
true
II. 2-3, 4, 7, 8, 11
4 if a> 0
III. 2-3, 4, 5, 7, 8, 9, 11
false 5 x = x + 1;

 Another set of basis paths


7 p = q/x;
Another
baseline
I. 2-3, 4, 7, 8, 11
true
8 if b==3 II. 2-3, 4, 5, 7, 8, 11
false 9 p=max(q, x); III. 2-3, 4, 7, 8, 9, 11
The third paths in the two
11 return p; sets are different
The basis set is not unique; but each basis set has
32
the same number of basis paths (i.e. 3 in this case)
Not All Basis Paths are Feasible
Consider another program logic
CC = 2+1=3  One set of basis paths
1 x = 0; Baseline
I. 1, 2, 3, 4, 5, 6, 8
true II. 1, 2, 4, 5, 6, 8 (infeasible)
2 if a>0

false 3 x = x + 1;
III. 1, 2, 3, 4, 5, 7, 8 (infeasible)
- Two infeasible paths
4 y = x*2;
 One test case
false 5 true I. a = 4
if x>0
II. Infeasible basis path
7 print(y); 6 print(x);
III. Infeasible basis path
8
return; Fail to test 2, 4, 5, 6, 8, and
5, 7, 8, branches
33
Minimize Infeasible Basis Paths
 Another set of basis paths
1 x = 0;
I. 1, 2, 3, 4, 5, 6, 8
true II. 1, 2, 4, 5, 6, 8 (infeasible)
2 if a>0
III.1, 2, 4, 5, 7, 8 (change both
false 3 x = x + 1; decision points at the same
time)
4 y = x*2; - One infeasible path
false 5 true
if x>0  Two test case
7 print(y); 6 print(x); I. a = 4
8 II. Infeasible basis path
return; III. a = 0
34
How to Deal with Loop?
 When selecting basis paths, select the loop only
zero and once (no need to consider iteration)

 When selecting baseline paths, select false


branch first at loop decision point, i.e., do not
enter the loop

 When choosing input values to execute the


path, the real execution path may execute loop
several times (see example next slide).
35
Exercise – Basis Path Testing
doSomething(int n) { 1 a = 0;
1 int a = 0;
2 false
2 while(a < n) { while a<n
3 if(a < 3) { true
4 print(“X); false 3
true
if a < 3
5 } else {
6 print(“Y”); 6 print(“y”); 4 print(“x”);

7 } 8
a++; a++;
8
9 }
10 return; 10 return;
11 } 36
Exercise – Basis Path Testing
CC = ??
2+1 = 3  Three basis paths
Select false branch Baseline
1 a = 0; first, i.e. do not I. 1, 2, 10
enter the loop II. 1, 2, 3, 4, 8, 2, 10
2 false
while a<n III. 1, 2, 3, 6, 8, 2, 10
true  Three test cases
3 I. n = 0
false true
if a < 3 II. n = 1
6 print(“y”); 4 print(“x”);
III. n = 4
 Real execution paths
8
a++; I. 1, 2, 10
II. 1, 2, 3, 4, 8, 2, 10
III. 1, 2, 3, 4, 8, 2, 3, 4, 8, 2,
10 return; 3, 4, 8, 2, 3, 6, 8, 2, 10
37
Testing – Both Testings are Important!
 Black Box Testing
 Equivalence class testing (range of values, discrete
values)
 Boundary value testing (only applicable to range of values)

 White Box Testing


 Control flow graph (CFG)
 Statement, branch, basis path, path coverage
 Basis path testing
 Cyclomatic complexity (how many basis paths you
need to test)
 Select basis paths
38
Liu Yang

1
White Box Testing Summary:
Control Flow Testing

2
Control Flow Graph - Example
int computeP(int a, int b) {
1 int q, x, p;
2 q = 1; 2-3 q = 1;
x = 2;
3 x = 2;
4 if(a > 0) { true
4 If a>0
5 x = x + 1;
false x = x + 1; 5
6 }
7 p = q/x; 7 p = q/x;
8 if(b == 3) { true
8 if b==3
9 p = max(q, x);
10 } false p=max(q, x); 9
11 return p;
11 return p;
12 } 3
Coverage Criteria

Full Path
Coverage
Basis
Path
Branch
Coverage
Coverage
Statement
Coverage

4
White Box Testing: Basis Path Testing
Process
 Construct control flow graph (CFG) from the program
(code fragment) of the SUT.

 Identifies execution paths through the CFG.


 Computes the CFG’s Cyclomatic Complexity (CC)
 Selects a set of #CC basis paths

 Choose input values to execute the paths.


 The CC value tells us the upper bound on the size of the
basis set, i.e. gives us the minimum number of linearly
independent paths (basis paths) we need to find. E.g. if
your program has CC value 6, then you’ve to identify six
basic paths to test.
Basis Path testing guarantees 1050% statement and branch coverage
White Box Testing: Cyclomatic
Complexity (CC) of a CFG
 Use the following two equations to
compute CC
 CC = |edges| - |nodes| + 2

 CC = |decisionpoint| + 1, if all decision


points are binary, i.e., one true branch + one
false branch

The two equations compute the same


value if all decision points are binary
6
White Box Testing: Cyclomatic
Complexity (CC) – Example
int computeP(int a, int b) {
1 int q, x, p; |edges| = 8
2 q = 1; q = 1; |nodes| = 7
3 x = 2; x = 2; CC = 8 – 7 + 2 = 3
4 if(a > 0) {
true
x = x + 1; if a> 0
5 Or,
6 } false
x = x + 1;
7 p = q/x; |decisionpoint| = 2
p = q/x;
8 if(b == 3) { CC = 2 + 1 = 3
9 p = max(q, x); true
if b==3
10 } p=max(q, x);
11 return p; false

} return p;
7
White Box Testing: Select a Set of
Basis Paths
 Choose a “baseline” path
 Reasonably “typical” path of execution
 Most important path from the tester’s view

 Change the outcome of the first decision point, keep


the maximum number of other decision points the same

 Change the outcome of the second decision point, keep


the maximum number of other decision points the same

 Change the outcome of the third decision point, and so


forth
8
White Box Testing: Select a Set of
Basis Paths
Change outcome of Change outcome of
Select baseline path first decision point second decision point

Basis path#1 (baseline): Basis path#2: Basis path#3 :


2-3, 4, 5, 7, 8, 11 2-3, 4, 7, 8, 11 2-3, 4, 5, 7, 8, 9, 11
9
White Box Testing: Basis Path Testing
For independent paths (Basis Paths) –
• The basis set is not unique
• There may be several different basis sets for the given
algorithm, based on the baseline path you’ve chosen. You may
have derived a different basis set
• The basis set “covers” all the nodes and edges in the CFG
(Basis Path testing guarantees 100% statement and branch coverage)

For test cases –


• Prepare test cases that will force execution of each path in the
basis set, i.e. choose input parameters (values) to execute each
path in the basis set.
• A basis path may not be feasible regardless of input parameters.
10
White Box Testing – Dealing with Loop
1. To choose basis path (for loop):
 When selecting basis paths, always execute the loop
zero and once (i.e. no need to consider iteration).
 When selecting baseline paths, select false branch
first at loop decision point, i.e., do not enter the loop.
 Then execute the loop ONE time (i.e. the TRUE
branch next, for one time).

1. For basis path testing (for loop), the test cases


may execute the loop multiple iterations.

11
Testing – Both Testings are Important!
 Black Box Testing
 Equivalence class testing (range of values,
discrete values)
 Boundary value testing (only applicable to range of values)

 White Box Testing Lecture#16 – Lecture#19


 Control flow graph (CFG) Tutorial#9 Q1, Tutorial#10 Q1

 Statement, branch, basis path, path coverage


 Basis path testing
 Cyclomatic complexity (how many basis paths you
need to test)
 Select basis paths
 Choose input values t1o2 execute the paths
Software Maintenance

13
Causes of Maintenance Problems

 It is estimated that there are more than


100 billion lines of code in production in
the world.*

 As much as 80% of it is unstructured,


patched, and badly documented.*

* Hans van Vliet “Software Engineering Principles and Practices” 3rd Edition

14
Causes of Maintenance Problems
 Unstructured code
 E.g. Numerous GOTO statements – hard to read, understand, and
maintain! (Spaghetti code)
– Improve by using structured programming such as IF-ELSE statements.
 E.g. Poor and inconsistent naming, long procedures, strong coupling,
weak cohesion, deeply-nested IF statements, etc.

 Insufficient domain knowledge


 To gain a sufficient understanding of a system from its source code.
 The more spaghetti-like this code is, the less easy it becomes to
disentangle it.

 Insufficient documentation
 No documentation, out-of-date documentation, or insufficient
documentation. 15
What is Software Maintenance?

 Software maintenance is defined as


(IEEE610, 1990)*:

“The process of modifying a software system


after delivery to correct faults, improve
performance or other attributes, or adapt
to a changed environment.”

* IEEE610 (1990). IEEE Standard Glossary of Software Engineering Terminology. IEEE Std 610.12.

16
What is Software Maintenance?
 Software maintenance is thus concerned
with:
 Correcting errors found after the software has
been delivered.
 Adapting the software to changing
requirements, changing environments, etc.

 Changes are implemented by modifying


existing system components and/or adding
new components to the system.
17
Types of Software Maintenance
 Fault repairs:
 Changing a system to fix bugs/vulnerabilities and
correct deficiencies in the way meets its requirements.
 Environmental adaptation:
 Maintenance to adapt software to a different operating
environment.
 Changing a system so that it operates in a different
environment (computer, OS, etc.) from its initial
implementation.
 Functionality addition/modification:
 Modifying the system to satisfy new requirements.
18
Maintenance Effort Distribution

Adapted from Ian Sommerville “Software Engineering” 9th Edition


19
Software Refactoring
 Refactoring is the process of making improvements
to a program to slow down degradation through
change. It means modifying (but not adding
functionality) a program to:
 Improve its structure
 Reduce its complexity
 Make it easier to understand

Refactoring does not change the behavior of the


software
20
Software Refactoring

 Refactoring is a continuous process of


improvement throughout the development
and evolution process.

 Refactoring is intended to avoid the structure


and code degradation that increases the
costs and difficulties of maintaining a system.

21
Program Code Improvements
 Situations (“bad smells”*) in which the code of a
program can be improved:
 Duplicate code
 Long methods
 Large class
 Temporary field
 Switch (case) statements
 Lazy class
 Data clumping (same group of data reoccur in several places)
 Tight coupling of two classes

* Fowler, M. (1999). Refactoring: Improving the Design of Existing Code. Addison Wesley.
22
Software Maintenance

23
Quiz
 Quiz format:
 Date: 18 Nov 2021 (Thursday)
 Time: 12 noon
 Duration: 1 hour
 Answer ALL questions
 Five (5) MCQ
 Five (5) short-answer questions
 Questions carry different marks
 Questions may have sub-questions
24
Quiz
 Open Book
 ONLY paper materials (not limited to cheat sheet and textbook)
 NO electronic devices allowed

25

You might also like