SWE Full Notes
SWE Full Notes
CE2006/CZ2006
Software Processes
Requirements specification
Software discovery and evaluation
Requirements refinement
Application system configuration
Component adaptation and integration
Agile methods
Agile development techniques
Agile project management
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.
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.
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.
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.
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.
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.
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.
Prioritized
Useful to
prioritize the
near-term
items that
are destined
for the next
few Sprints
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.
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.
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.
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.
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.
• Programme of Study
• Course
• Degree Programme
Requirements Elicitation 2 of 3
Discussion Topics
• 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.
Structure Behavior
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
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
Withdraw
money
Verify
Customer Customer Bank
Check
Balance
Use Case Associations
Manage Incident
<<include>> <<include>>
<<include>>
Create Handle Close
Incident Incident Incident
<<include>>: Reuse Existing Functionality
• Problem: There are overlaps among use cases.
• 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.
Help
<<extend>>
Report
Emergency
Include, extend associations
.
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
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
• Reading
– Bruegge Chap 4.4
– Fowler Chap 9
Use Case Model
• 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
Select Find
Courses Course
<<include>> Schedule
Student Professor
Login <<include>>
<<include>>
Manage Manage
Billing of Students Curriculum
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.
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 ……..)
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.
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
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
TarifSchedule
TripLeg
Price
Enumeration getZones()
Price getPrice(Zone)
* * Zone
Many-to-Many Associations
Person 1 1 Head
Point
Polygon 1
* x: Integer
1-to-many association
y: Integer
draw()
Class Relationships
1
aggregation: "is part of" aggregation
1
symbolized by a clear white diamond
Engine
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
FingerprintReader EntryGate
FacilityAccessSystem Employee
(Fingerprint?)
Stereotyping to Indicate
Class Responsibilities
<<read>>
Employee
Usage dependency
EntryGate
Summary
• Analysis Modelling
• Class Diagram
Software Engineering
CE2006/CZ2006
• 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
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. ...
<<singal>>
Boundary Object
How to visualize the
Controller Object workflow
EntryGate
Entity Object
Sequence Diagram: Definitions
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:
scan Interaction
frame
validate(image)
find(image)
Frame found
label
alt [found==true]
unlock(image)
invaliduser [else]
Types of Interaction Frames
sd sequence diagram
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
<<singal>>
Boundary Object
How to visualize the
Controller Object workflow
EntryGate
Entity Object
Communication diagram
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
• 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.
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).
insert(c:Coin)
Accumulate insert(c:Coin)
entry / amount := amount+c.amount
do / display(amount)
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
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
Time Paused
Click Close
Window
UML Activity Diagram
• Activities are the execution of one or more basic
operations. Represented by a rounded rectangle.
• Forks are when control flow has one input and two or more
outputs (go to concurrent activities).
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.
• Interaction Diagrams
– State Machine Diagrams
– Activity Diagrams
UML Review 1
Lesson Objectives
Review UML with an example
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
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:
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
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
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:
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>>
Flow of Events:
1. Employee presses finger on FingerprintReader. User
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?
UML Review 2
Lesson Objectives
Review UML with an example
[Initial Requirements
elicitation Agreed]
5. Identify Classes <<include>>
Scan
fingerprint
Entry Gate
Validate
ValidateDoorEntry Use Case Description DoorEntry
User
Fingerprint EntryGate
Reader
FAMgr
FASMgr
Validate(Img)
GateOpened()
Entry Log
:FingerprintReader :Fingerprint :EntryGate
:User Interface Interface
:FASMgr
Press
Validate(img)
Lock()
RecordEntry()
Example: FingerprintReader Functionality
Ready
entry / initialize scanner
press
/send image
WaitConfirmation [invaliduser=tr
ue]
Example: Validate Door Entry System
Third Step – Refine Class (& Use Case) Diagrams
Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By
class...
class...
class... ?
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
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.
Connectors
Interactions among components:
communication, coordination, or cooperation among components.
WWW Client
CGI
Presentation UI WWW Server
Manager Manager
Path
Resolver
Access
Manager
Cache HTTP Access
Manager Protocol Server List
Manager
13
14
Architecture is abstract
The details of the components and connectors are hidden
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
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
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
Implemented
Expressed in By
Structured By Realized By
Terms Of Verified
By
class...
class...
class... ?
WWW Client
CGI
Presentation UI WWW Server
Manager Manager
Path
Resolver
Access
Manager
Cache HTTP Access
Manager Protocol Server List
Manager
4
Interface specification:
Reuse: Existing libraries and
operations, arguments, type
Design Patterns
signatures, and exceptions
Object Design
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
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()
ConcreteStrategyA ConcreteStrategyB
11
Pros
Provides encapsulation
Hides implementation
Allows behavior change at runtime
Cons
Results in complex, hard to understand code if overused
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
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
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
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
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.
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)
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);
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);
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();
- 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
register( unregister(
YrAcct,tutorial) YrAcct,tutorial)
addtoList( rmfromList(
YrAcct,tutorial) YrAcct,tutorial)
- 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
41
Event Handling & Observer Pattern –
Design Problems
Loose coupling between an event source (subject)
and its dependent event handlers (observers)
Event Handling
MyActionListener
JButton JMenuItem
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
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
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
DataStoreFactory
Resource + getDatastore() : DataStoreInterface
Manager
<<create>>
datastore
DataStoreInterface
retrieveMap()
createIncident()
dispatchResource()
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()
10
The Magic Power: Strategy Design +
Factory Design + Dynamic Loading
Eclipse
RegistryStrategyOSGI
Workbench
views create
ViewPart
createPartControl()
views create
LookandFeel
…
Application java.sql.DriverManager
views create
java.sql.Connection
…
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
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
updateCell() sheetMgr
getData()
1 * LineChart
sheetMgr
1
drawLine()
BarChart
*
drawBar()
data
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
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.
EditWS
SheetMgr
update()
updateCell()
getData() :Details
sheetMgr.getData();
showWS();
LineChart
WorkSheet
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
update
getData
newdata
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.
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()
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.
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
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.
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
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
15
Test Cases for Mortgage
Application
Each row is a test case
Input Oracle Log
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
19
CZ2006/CE2006
Software Engineering
Lecture 16-17
Equivalence Class Testing
When I launch my app after several
hours of development
Unexpected things happen!
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
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!
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)
Mortgage –
Number of Mortgages
Valid
0≤ x ≤ 5
Invalid Invalid
x ≤ -1 x≥6
0 5
16
Range of Values – Exercise
Length of Password
Valid
4≤ x ≤ 8
Invalid Invalid
x≤3 x≥9
4 8
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)
18
Discrete Values
ONE equivalence class of VALID values
ONE equivalence class of INVALID values
Mortgage –
Applicant Type
Valid Invalid
Trust
Person Company
Partnership
…
Mortgage –
Property Type
Valid Invalid
HDB Townhouse
Cando Mobilehome
…
20
Discrete Values – More Examples
Character of Password
Valid Invalid
ab…z
AB…Z +-()…
012…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
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)
27
Test Invalid Inputs – Example
Each row is a test case.
Test ONLY ONE INVALID
input value per test case
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)
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
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)
5
Process Block
A sequence of statements
Process Block execute sequentially
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
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
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
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
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
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
11 return p; 11 return p;
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
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).
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
false 5 x = x + 1;
false
false 5 x = x + 1;
Keep the maximum p = q/x;
7
number of other
true
decision points the 8 if b==3
true
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;
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)
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)
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.
} 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
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)
13
Causes of Maintenance Problems
* 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 documentation
No documentation, out-of-date documentation, or insufficient
documentation. 15
What is Software Maintenance?
* 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.
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