se_lectures/.DS_Store
__MACOSX/se_lectures/._.DS_Store
se_lectures/Day15/WeatherMonitoringSystem.docx
Weather Monitoring System
Requirements Definition
The system shall provide automatic monitoring of various weather conditions. Specifically, it must measure:
· Wind speed and direction
· Temperature
· Barometric pressure
· Humidity
The system shall also provide the following derived measurements:
· Wind chill
· Dew point temperature
· Temperature trend
· Barometric pressure trend
The system shall interface with the following hardware: keypad, wind-direction sensor, temperature sensor, clock (on-board clock), humidity sensor, wind-speed sensor, pressure sensor, and LCD display (capable of processing a simple set of graphics primitives, including messages for drawing lines and arcs, filling regions, and displaying text).
The system shall have a means of determining the current time and date, so that it can report the highest and lowest values of any of the four primary measurements during the previous 24-hour period. The sampling rates are: every 0.1 second for wind direction, every 0.5 seconds for wind speed, and every 5 minutes for temperature, barometric pressure, and humidity.
The system shall have a display that continuously indicates all eight primary and derived requirements, as well as the current time (hour, minutes, second) and date (day, month, year).
Through the use of a keypad, the user shall be able to direct the system to display the 24-hour high or low value of any one primary measurement, together with the time of the reported value.
The user shall be able to choose either a 12- or 24-hour format for the time.
The system shall allow the user to calibrate its sensors against know values, and to set the current time and date. The wind direction sensor requires neither calibration nor history.
Assume that each temperature sensor value is represented by a fixed-point number, whose low and high points can be calibrated to fit known actual values. Intermediate numbers shall be translated to their actual temperatures by simple linear interpolation between the two points.
Trends shall be expressed as a floating numbers between –1 and 1, representing the slope of a line fitting a number of values over some interval of time.
__MACOSX/se_lectures/Day15/._WeatherMonitoringSystem.docx
se_lectures/Day15/.DS_Store
__MACOSX/se_lectures/Day15/._.DS_Store
se_lectures/Day15/Collaborations and Hierarchies.pptx
Collaborations and Hierarchies
Outline
Collaborations
Identifying collaborations
Recording collaborations
Hierarchies
Hierarchy graphs
Venn diagrams
Continuing Practice
"Programming today is a race between software engineers striving to build bigger and better idiot-proof programs, and the Universe trying to produce bigger and better idiots. So far, the Universe is winning."
-Rich Cook
Motivation for Collaborations
Two ways a class performs responsibilities
Knows something
Does something
Collaboration is
Request f ...
1. se_lectures/.DS_Store
__MACOSX/se_lectures/._.DS_Store
se_lectures/Day15/WeatherMonitoringSystem.docx
Weather Monitoring System
Requirements Definition
The system shall provide automatic monitoring of various
weather conditions. Specifically, it must measure:
· Wind speed and direction
· Temperature
· Barometric pressure
· Humidity
The system shall also provide the following derived
measurements:
· Wind chill
· Dew point temperature
· Temperature trend
· Barometric pressure trend
The system shall interface with the following hardware: keypad,
wind-direction sensor, temperature sensor, clock (on-board
clock), humidity sensor, wind-speed sensor, pressure sensor,
and LCD display (capable of processing a simple set of graphics
primitives, including messages for drawing lines and arcs,
filling regions, and displaying text).
The system shall have a means of determining the current time
and date, so that it can report the highest and lowest values of
any of the four primary measurements during the previous 24-
hour period. The sampling rates are: every 0.1 second for wind
2. direction, every 0.5 seconds for wind speed, and every 5
minutes for temperature, barometric pressure, and humidity.
The system shall have a display that continuously indicates all
eight primary and derived requirements, as well as the current
time (hour, minutes, second) and date (day, month, year).
Through the use of a keypad, the user shall be able to direct the
system to display the 24-hour high or low value of any one
primary measurement, together with the time of the reported
value.
The user shall be able to choose either a 12- or 24-hour format
for the time.
The system shall allow the user to calibrate its sensors against
know values, and to set the current time and date. The wind
direction sensor requires neither calibration nor history.
Assume that each temperature sensor value is represented by a
fixed-point number, whose low and high points can be
calibrated to fit known actual values. Intermediate numbers
shall be translated to their actual temperatures by simple linear
interpolation between the two points.
Trends shall be expressed as a floating numbers between –1 and
1, representing the slope of a line fitting a number of values
over some interval of time.
__MACOSX/se_lectures/Day15/._WeatherMonitoringSystem.do
cx
se_lectures/Day15/.DS_Store
__MACOSX/se_lectures/Day15/._.DS_Store
3. se_lectures/Day15/Collaborations and Hierarchies.pptx
Collaborations and Hierarchies
Outline
Collaborations
Identifying collaborations
Recording collaborations
Hierarchies
Hierarchy graphs
Venn diagrams
Continuing Practice
"Programming today is a race between software engineers
striving to build bigger and better idiot-proof programs, and the
Universe trying to produce bigger and better idiots. So far, the
Universe is winning."
-Rich Cook
Motivation for Collaborations
Two ways a class performs responsibilities
Knows something
Does something
Collaboration is
Request from one object to another in order to fulfill a
responsibility.
Motivation (Cont.)
Why identify collaborations?
Collaborations represents the flow of control and information
4. through the system.
May identify misplaced responsibilities, and
May identify missing responsibilities.
In sum, shows dynamics of the system.
Finding Collaborations
Look at each responsibility of each class:
Is the class capable of fulfilling this responsibility by itself?
If not, where can it get what it needs?
Look at each class:
What other classes need what this class does or knows?
Leverage the “Purpose” sentence of the class
Role-play scenarios, which class talks to which class to get the
information?
Finding More Collaborations
Examine relationships between classes, especially:
The “is-part-of” relationship.
The “has-knowledge-of” relationship.
The “depends-on” relationship.
Where do these relationships come from?
“Is-part-of” Relationship
May imply responsibilities for maintaining information.
May fulfill responsibilities by delegating them.
Two relationships (containment):
Composite
Aggregate
5. Which relationship is more likely to require collaborations?
7
Relationships in General
May know other classes that are not in part-of relationships
(i.e., associations in UML).
May imply responsibilities to know information, and thus
collaborations.
Can you think of an example?
Person
Phone book
8
Recording Collaborations
Write the name of the server (or helper) class on the CRC card
of the client.
Write the name directly to the right of the responsibility the
collaboration fulfills.
Class: Person
6. Responsibilities Collaborations
Knows name
Knows address AddressBook
Knows phone number PhoneBook
…
Client
Server
(or helper)
Collaborations
Is there a way to visualize the connections that classes have?
Collaboration Model
Graphical representation of collaborations
Arrow from client to a “contract” of the server, denoted by a
semicircle
Contract: group of responsibilities (more on this later)
Person
AddressBook
1
PhoneBook
2
7. Other Tools - UML
UML interaction diagrams
Sequence diagram (Chapter 10)
Communication diagram (Chapter 15)
Sequence Diagram Example
message
lifetime
control
object
Sequence Diagram
Collaboration
Communication Diagram
object
link
message
8. 15
Communication Diagram
Collaboration
16
Outline
Collaborations
Hierarchies
Hierarchy graph
Venn diagram
Continuing Practice
Review of CRC Process
Exploratory phase
Identify a preliminary list of classes, responsibilities and
collaborations.
Analysis phase
Obtain a more global understanding of the design, e.g., by using
tools such as:
Hierarchy graphs,
Venn diagrams, and
Contracts.
Hierarchy Graph
9. A graphical representation of inheritance between related
classes.
A hierarchy graph is a general tree.
The nodes are classes and the arcs represent inheritance.
Ancestor nodes are superclasses of descendent nodes, which are
subclasses.
As a heuristic, I recommend delaying the identification of
hierarchies until identification of classes is mostly complete.
Example – Hierarchy Graph
CRC notation
Leaf nodes are often concrete classes.
Non-leaf nodes are often abstract classes.
PartTime
FullTime
Employee
All classes can be designated as either abstract or concrete.
Concrete is the default. This means that the class can have
(direct) instances.
In contrast, abstract means that a class cannot have its own
(direct) instances.
10. Abstract classes exist purely to generalize common behavior
that would otherwise be duplicated across (sub)classes.
Ask the question: will the class become alive (as an object)
during runtime? If so, then it should be a concrete class,
otherwise it will be an abstract.
20
In UML …
PartTime
FullTime
Employee
Abstract Classes
Classes that cannot be instantiated.
Designed only to be inherited from, thus allowing reuse and
avoiding duplication.
Used to factor common behaviors among classes.
Finding Abstract Classes
At the exploratory stage, all identified classes are probably
concrete
A few may have been identified as abstract.
But, do you have all your abstract classes? That is, have you
used the power of abstraction (factoring behavior)?
Another Example of Hierarchy Graph
12. Thus, an intersection among classes:
Denotes common responsibilities, and thus
May indicates an abstract superclass
25
Example
PartTime
FullTime
Employee
PartTime
set of responsibilities
Employee
set of classes
PartTime
FullTime
Employee
FullTime
26
Exercise - 5 Minutes!
15. In Sum, Hierarchies …
Facilitate the review of inheritance relationships.
Use hierarchy graphs and Venn diagrams as a notation and an
analysis tool
29
How to build Good Hierarchies?
Model “is-a” relationships.
Factor common responsibilities as high as possible.
“Push” them up
Make sure abstract classes do not inherit from concrete classes.
Eliminate classes that do not add functionality.
Example – Using Venn Diagram To Check a Hierarchy
If B supports only a part of responsibilities defined for A, what
does the Venn diagram look like? How to fix this?
Hint: Model each Venn diagram class as a set of responsibilities
A
B
A
B
A
B
Which is it?????
31
16. The point here is: DON’T FORCE IT
Fixing the Problem
Create an abstract class with all responsibilities common to both
A and B, and have them both inherit from it.
This is called “Factoring”
Not to be confused with “Refactoring”
A
B
C
A
B
C
32
Example – Factoring Responsibilities
You will need at least 2 subclasses to inherit this responsibility
or might as well not even bother.
20. Design Introduction
Outline
Software Design Overview
High-Level
Low-Level
CRC
Identifying Classes
Identifying Responsibilities
Practice
Design Overview
What is Software Design?
Deals with transforming the requirements specifications into a
model that can be implemented using programming languages.
Can be broken down into two types
High-level (i.e., Architecture Design)
Low-level (i.e., Detailed Design)
Software Architecture
What is a Software Architecture?
High Level Design: Software Architecture
The primary way to implement nonfunctional requirements
Requires a deep understanding of the desired quality attributes
of the system, might necessitate negotiation and prioritization
with the stakeholders.
21. Can be difficult to guess right under an agile method.
High-level Vs Low-level
Architecture Design:
High-level deals with overarching nonfunctional goals of the
system.
Requires a complete understanding and prioritization of
nonfunctional requirements.
Detailed Design:
Focuses on the bridge between the functional requirements and
the actual implementation of the system.
Main concern is the maintainability and easy of implementation
of the system.
Software Architecture Issues
Architectures are strictly influenced by the desired
nonfunctional requirements.
Requires a complete understanding of the requirements for the
best architecture selection.
You can’t have your cake and eat it too..
Some quality attributes are mutually exclusive to a certain
degree
e.g., high performance and security, scalability and
availability..
This is why it is so important to prioritize and be able to
negotiate nonfunctional requirements with stakeholders.
Changing an architecture once it is installed is very difficult
Often times it is better to redo the system.
High-level Vs Low-level
Architecture Design:
22. High-level deals with overarching nonfunctional goals of the
system.
Requires a complete understanding and prioritization of
nonfunctional requirements.
Detailed Design:
Focuses on the bridge between the functional requirements and
the actual implementation of the system.
Main concern is the maintainability and easy of implementation
of the system.
Detailed Design
We need a method to convert requirement specifications into an
actual implementation of a software system
There are multiple ways, the book focuses on one approach.
In addition to this, I’ll teach you a different approach.
Class, Responsibility, and Collaborator (CRC) Cards
Invented in 1989 by Kent Beck and Ward Cunningham
A simple yet powerful object-oriented (analysis/design)
technique
Uses a collection of (standard index) cards that are divided into
three sections:
Class
Responsibility
Collaborator
Class, Responsibility, and Collaborator
A class represents a collection of the same objects.
A responsibility is anything that a class knows or does, a
23. service that it provides for the system.
A collaborator is another class that is used to get information
for, or performs actions for the class at hand to support a
responsibility.
Example
More on CRC Cards
3x5 (or 4x6) index cards, post-its, etc.
One class per card
In addition, you can also write superclasses and subclasses.
More on this later..
On the back, write a description of purpose of the class.
It should be one sentence.
Example: The purpose of this class is to represent a person in
the system.
Question
Why use index cards?
Advantages
Portable: cards can be used anywhere, even away from the
computer or office
Anthropomorphic: no computer program can capture the essence
of the interactions forced by passing the cards
Level of involvement felt by each team member increases
Useful throughout the life cycle
24. More Advantages
Provides a basis for a formal analysis and a design method
Serves as input to a formal method (i.e., a starting point)
Ease the transition from process orientation to object
orientation
Most of us (still?) think in a process oriented manner
Provides a general bound on the size of a class
A card
CRC Approach – The Process
Exploratory phase (Today)
Find classes
Determine operations and knowledge for each class
(responsibilities)
Determine how objects collaborate to discharge responsibilities
Analysis phase (Later)
Collect into subsystems
Improve design
How to Find Objects and Their Responsibilities?
Use nouns and verbs in requirement documents as clues
Noun phrases leads to objects
Verb phrases lead to responsibilities
Determine how objects collaborate to fulfill their
responsibilities
To collaborate, objects will play certain roles
Why is this important?
Objects lead to classes
Responsibilities lead to operations or methods
Collaborations and roles lead to associations
25. Identifying Objects (Classes)
Start with a set of requirement specifications
Look for noun phrases.
Separate into obvious classes, uncertain candidates, and
nonsense
Refine to a list of candidate classes.
Guidelines for Refining Candidate Classes
Model physical objects – e.g., disks, printers, station.
Model conceptual objects – e.g., windows, files, transaction,
log.
Choose one word for one concept – what does it mean within
the domain?
Be wary of adjectives – does it really signal a separate class?
Guidelines for Refining (Cont.)
Be wary of missing or misleading subjects – rephrase in active
voice.
Model categories of classes – delay modeling of inheritance.
Model interfaces to the system – e.g., user interface, program
interface.
Model attribute values, not attributes – e.g., customer vs.
customer address.
Example: Mail-Order Software
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
26. ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Example: Mail-Order Software
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Candidate Classes
Candidate Classes (Cont.)
Expect the list to evolve as design proceeds
Record why you decided to include or reject candidates
Candidate class list follows configuration management and
version control
27. A Good Class …
Has a clear and unambiguous name
Has a name that is recognizable by domain experts/stakeholders
Is a singular noun
Has responsibilities
May actively participate in the system
What Are Responsibilities?
The public services that an object may provide to other objects:
The knowledge an object maintains and provides
The actions that it can perform
That is they
Convey a sense of purpose of an object and its place in the
system
Record services that a class provides to fulfill roles within the
system
Record knowledge and manipulation of information in the
system
Knowledge and Action
Knowing responsibilities
Knowing about private encapsulated data
Knowing about related objects
Knowing about things it can derive or calculate
Doing responsibilities
Doing something itself, such as creating an object or performing
a manipulation
Initiating action in other objects
Controlling and coordinating activities of other objects
Identifying Responsibilities
Use mixtures of:
Verb phrase identification. Similar to noun phrase
28. identification, except verb phrases are candidate
responsibilities.
Scenarios and role play. Perform scenario walk-through of the
system where different persons “play” the classes, thinking
aloud about how they will delegate to other objects.
Class enumeration. Enumerate all candidate classes and come
up with an initial set of responsibilities.
Class relationship examination. Examine all classes and their
relationships to compare how they fulfill responsibilities.
Example of Verb Phrase Identification
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Example of Verb Phrase Identification
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
29. The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Candidate Responsibility
Responsibility Types
Identify the types of responsibilities for each class
Behavior – Describes what a class does (i.e. things that meets
the requirements of the system)
Knowledge – Describes what the class knows about itself (i.e.
attributes of the class)
Example
Knowledge or Behavior?
Know balance?
Verify customer?
Know account number?
Authorize transaction?
Track activity?
Last page visited?
Late fee amount?
Print layout?
Assigning Responsibility Types
For knowledge types
30. Match the responsibility with the class who owns the
information
For behavior types
Match the responsibility with the class who can do this
Look at the name and purpose of the class as a guideline
Practice!
ATM Example specifications
Cards
Read
Chapter 12, 13 & 14
Further readings
B. Beck and W. Cunningham, A Laboratory for Teaching
Object-Oriented Thinking, OOPSLA ’89, October 1-6, 1989.
R. Wirfs-Brock, B. Wilkerson and L. Wiener, L., Designing
Object-Oriented Software, Prentice Hall, 1990. (Chapters 3 and
4)
Hans Van Vliet, Software Engineering, Principles and
Practice,3rd edition, John Wiley & Sons, 2008. Sections 10.1.4
& 12.3
__MACOSX/se_lectures/Day14/._Design & Architecture.pptx
se_lectures/Day22/.DS_Store
__MACOSX/se_lectures/Day22/._.DS_Store
se_lectures/Day22/Weather.pptx
31. Weather Monitoring System
Classes
Classes
Sensors
Wind Speed
Wind Direction
Barometric Pressure
Humidity
Derived Measurements
Wind Chill
Dew Point Temp
Trends
Temp Trend
Barometric Trend
Continous Data
Specific Data
Time
Clock
Keypad
LCD
Graphics
Line
Arc
Region
Text
History Logs
Wind Speed
Wind Direction
Barometric Pressure
Humidity
32. Weather Monitoring System
Collaboration Graph
Weather Monitoring System
Contracts
Simple Contracts
Monitor Weather
Get current weather data
Query specific sensor 24 hour hi-lo data
Display graphic data
Capture user input
Get current time and date
Set time and date
Get sensor data
Get derived measurement
Calibrate sensor
Get 24 hour hi-lo for sensor
Generate graphic
36. Low Coupling
Abstractions
A plan for building a system
?
Building a bridge to code
How do we map the work we have done with our detailed
designs into actual code?
We can build classes (we have the cards with the names)
And we have our contracts.
How do we implement these?
Contracts describe interfaces
Classes provide interfaces for other classes to interact through
There are multiple ways to build classes and their routines
Traditional Building of Classes and Routines
Approaches
Ways to plan for implementation of contracts:
Pseudocode Programming Process (PPP)
Design by contract
Test-first
Pseudocode Programming Process
(PPP)
Approach based on using English-like statements to describe
code logic
Language independent
Less training required:
37. We all know English somewhat..
Can be verified without implementing anything
i.e. can be reviewed.
PPP-Design the routine
This can be guided by what we have designed, for example:
Your CRC contract from your detailed design can be the starting
point.
Write Pseudo-code that fulfills that contract.
Review!
PPP-Implement
Write code following your pseudocode.
You don’t have to think much, just read along.
Thoughts?
PPP-Review
Check the code
Can be a review, or be done by unit testing.
PPP-Repeat as necessary
You might encounter optimizations or you might need to clean
up the code.
Might identify factoring out, i.e. identifying new routines to be
extracted out.
PPP
Seems silly
Who needs pseudocode??
38. Only dumb programmers!
Thoughts?
PPP
Seems silly
Who need pseudocode??
However it isn’t just about you
Others can review before you implement potentially finding
issues
Others can understand what you’re going to do and therefore
accommodate their work to match yours
You can build test cases much easier this way
Design by Contract
A different approach:
“Applying Design by Contract,” B. Meyer, IEEE Computer, pp.
40-51, October 1992
Design by Contract
The next logical step after you have created your CRC
contracts.
Enhance them by adding:
Pre-conditions
Post-conditions
What are pre and post conditions?
Pre: What must be true to guarantee the execution of this
contract
Post: What is guaranteed to be true after the execution of this
contract
39. Pre-Condition
Capture the conditions that must be true in order for the method
to execute correctly
Describe the required state of the ADT or object before entering
the function
Written as an expression that is true or false
May consist of statements connected by logical operators (AND,
OR)
Use true when no pre-condition exists – should be rare.
15
Post-Condition
Must clearly state what is true when the method completes
execution
Describe the expected state upon exiting the function
Should be strong enough so that only correct implementations
will satisfy the condition
Think of an evil programmer.
16
Example
40. 17
Example Continued
18
Design by Contract
Pre an post conditions can be written
Use formal methods like
using a specification language
such as:
Z
JML
OCL
And others..
Informally, using English as a language
Pre: The internal private list will not empty and only contain
positive integers.
Post: The Sum() method will iterate through the private list, and
return the addition of all elements within that list.
Semi-formally, using a combination of the above.
Drawbacks of each?
Design by Contract
By writing pre and post conditions we gain the following
benefits:
41. We don’t have to be so defensive on production code (defensive
programming)
We have precise contract agreements that must be fulfilled
We can generate unit and integration testing much easier
Good Pre and Post Conditions
States
What (properties), e.g.,
The property of being square roots
The property of being sorted
The property of appearing in an array
Not how (algorithms), e.g.,
Not how to calculate square roots (linear, binary, Newton)
Not how to sort (bubble, insertion, quick)
Not how to decide whether an item appear in an array
21
21
Test-first
Produce automated tests before you code.
Test-first
Wait.. What?
Create tests and execute them without code??
Test-first
42. Produce automated tests before you code
Start with a small focused unit test
At first it will fail (it should fail, if it doesn’t then something is
already wrong)
Minimally develop code to pass this test
Refactor
Reorganize code without changing it’s behavior.
Repeat with the next test
Where do tests come from?
What is automated testing?
Test-first
Tests come from
Use Cases and Scenarios
CRC contracts
Automated testing is a way to create unit tests that can be
automatically tested
Such tools as NUnit, JUnit
Are a great tool for regression testing (regre-what?)
Benefits of this approach?
Test-first
Benefits:
You are testing as you go
You can fix issues faster because you’re closer to the code
Your testing becomes your abstract pseudocode.
But your code is only going to be as good as your testing
And a lot of effort will be invested in refactoring.
Approaches
43. All 3 approaches are valid
They all serve a purpose
Add …
se_lectures/.DS_Store
__MACOSX/se_lectures/._.DS_Store
se_lectures/Day15/WeatherMonitoringSystem.docx
Weather Monitoring System
Requirements Definition
The system shall provide automatic monitoring of various
weather conditions. Specifically, it must measure:
· Wind speed and direction
· Temperature
· Barometric pressure
· Humidity
The system shall also provide the following derived
measurements:
· Wind chill
· Dew point temperature
· Temperature trend
· Barometric pressure trend
The system shall interface with the following hardware: keypad,
wind-direction sensor, temperature sensor, clock (on-board
clock), humidity sensor, wind-speed sensor, pressure sensor,
and LCD display (capable of processing a simple set of graphics
primitives, including messages for drawing lines and arcs,
filling regions, and displaying text).
The system shall have a means of determining the current time
and date, so that it can report the highest and lowest values of
44. any of the four primary measurements during the previous 24-
hour period. The sampling rates are: every 0.1 second for wind
direction, every 0.5 seconds for wind speed, and every 5
minutes for temperature, barometric pressure, and humidity.
The system shall have a display that continuously indicates all
eight primary and derived requirements, as well as the current
time (hour, minutes, second) and date (day, month, year).
Through the use of a keypad, the user shall be able to direct the
system to display the 24-hour high or low value of any one
primary measurement, together with the time of the reported
value.
The user shall be able to choose either a 12- or 24-hour format
for the time.
The system shall allow the user to calibrate its sensors against
know values, and to set the current time and date. The wind
direction sensor requires neither calibration nor history.
Assume that each temperature sensor value is represented by a
fixed-point number, whose low and high points can be
calibrated to fit known actual values. Intermediate numbers
shall be translated to their actual temperatures by simple linear
interpolation between the two points.
Trends shall be expressed as a floating numbers between –1 and
1, representing the slope of a line fitting a number of values
over some interval of time.
__MACOSX/se_lectures/Day15/._WeatherMonitoringSystem.do
cx
se_lectures/Day15/.DS_Store
45. __MACOSX/se_lectures/Day15/._.DS_Store
se_lectures/Day15/Collaborations and Hierarchies.pptx
Collaborations and Hierarchies
Outline
Collaborations
Identifying collaborations
Recording collaborations
Hierarchies
Hierarchy graphs
Venn diagrams
Continuing Practice
"Programming today is a race between software engineers
striving to build bigger and better idiot-proof programs, and the
Universe trying to produce bigger and better idiots. So far, the
Universe is winning."
-Rich Cook
Motivation for Collaborations
Two ways a class performs responsibilities
Knows something
Does something
Collaboration is
Request from one object to another in order to fulfill a
responsibility.
Motivation (Cont.)
46. Why identify collaborations?
Collaborations represents the flow of control and information
through the system.
May identify misplaced responsibilities, and
May identify missing responsibilities.
In sum, shows dynamics of the system.
Finding Collaborations
Look at each responsibility of each class:
Is the class capable of fulfilling this responsibility by itself?
If not, where can it get what it needs?
Look at each class:
What other classes need what this class does or knows?
Leverage the “Purpose” sentence of the class
Role-play scenarios, which class talks to which class to get the
information?
Finding More Collaborations
Examine relationships between classes, especially:
The “is-part-of” relationship.
The “has-knowledge-of” relationship.
The “depends-on” relationship.
Where do these relationships come from?
“Is-part-of” Relationship
May imply responsibilities for maintaining information.
May fulfill responsibilities by delegating them.
Two relationships (containment):
47. Composite
Aggregate
Which relationship is more likely to require collaborations?
7
Relationships in General
May know other classes that are not in part-of relationships
(i.e., associations in UML).
May imply responsibilities to know information, and thus
collaborations.
Can you think of an example?
Person
Phone book
8
Recording Collaborations
Write the name of the server (or helper) class on the CRC card
of the client.
Write the name directly to the right of the responsibility the
collaboration fulfills.
48. Class: Person
Responsibilities Collaborations
Knows name
Knows address AddressBook
Knows phone number PhoneBook
…
Client
Server
(or helper)
Collaborations
Is there a way to visualize the connections that classes have?
Collaboration Model
Graphical representation of collaborations
Arrow from client to a “contract” of the server, denoted by a
semicircle
Contract: group of responsibilities (more on this later)
Person
AddressBook
1
PhoneBook
2
49. Other Tools - UML
UML interaction diagrams
Sequence diagram (Chapter 10)
Communication diagram (Chapter 15)
Sequence Diagram Example
message
lifetime
control
object
Sequence Diagram
Collaboration
Communication Diagram
object
link
51. Hierarchy Graph
A graphical representation of inheritance between related
classes.
A hierarchy graph is a general tree.
The nodes are classes and the arcs represent inheritance.
Ancestor nodes are superclasses of descendent nodes, which are
subclasses.
As a heuristic, I recommend delaying the identification of
hierarchies until identification of classes is mostly complete.
Example – Hierarchy Graph
CRC notation
Leaf nodes are often concrete classes.
Non-leaf nodes are often abstract classes.
PartTime
FullTime
Employee
All classes can be designated as either abstract or concrete.
Concrete is the default. This means that the class can have
(direct) instances.
In contrast, abstract means that a class cannot have its own
52. (direct) instances.
Abstract classes exist purely to generalize common behavior
that would otherwise be duplicated across (sub)classes.
Ask the question: will the class become alive (as an object)
during runtime? If so, then it should be a concrete class,
otherwise it will be an abstract.
20
In UML …
PartTime
FullTime
Employee
Abstract Classes
Classes that cannot be instantiated.
Designed only to be inherited from, thus allowing reuse and
avoiding duplication.
Used to factor common behaviors among classes.
Finding Abstract Classes
At the exploratory stage, all identified classes are probably
concrete
A few may have been identified as abstract.
But, do you have all your abstract classes? That is, have you
used the power of abstraction (factoring behavior)?
53. Another Example of Hierarchy Graph
Ordered
Collection
Indexable
Collection
Magnitude
Array
Matrix
String
Date
Abstract class
Venn Diagram
Another tool to understand inheritance relationships.
A Venn diagram views a class as a set of responsibilities, then
What does an intersection mean?
Common responsibilities
What might an intersection lead to?
54. Abstract classes
Thus, an intersection among classes:
Denotes common responsibilities, and thus
May indicates an abstract superclass
25
Example
PartTime
FullTime
Employee
PartTime
set of responsibilities
Employee
set of classes
PartTime
FullTime
Employee
FullTime
26
55. Exercise - 5 Minutes!
Ordered
Collection
Indexable
Collection
Magnitude
Array
Matrix
String
Date
Draw a Venn diagram for the following hierarchy graph.
27
Draw a Venn diagram for the following hierarchy graph
57. 28
In Sum, Hierarchies …
Facilitate the review of inheritance relationships.
Use hierarchy graphs and Venn diagrams as a notation and an
analysis tool
29
How to build Good Hierarchies?
Model “is-a” relationships.
Factor common responsibilities as high as possible.
“Push” them up
Make sure abstract classes do not inherit from concrete classes.
Eliminate classes that do not add functionality.
Example – Using Venn Diagram To Check a Hierarchy
If B supports only a part of responsibilities defined for A, what
does the Venn diagram look like? How to fix this?
Hint: Model each Venn diagram class as a set of responsibilities
A
B
A
B
A
B
Which is it?????
58. 31
The point here is: DON’T FORCE IT
Fixing the Problem
Create an abstract class with all responsibilities common to both
A and B, and have them both inherit from it.
This is called “Factoring”
Not to be confused with “Refactoring”
A
B
C
A
B
C
32
Example – Factoring Responsibilities
You will need at least 2 subclasses to inherit this responsibility
or might as well not even bother.
62. se_lectures/Day14/Design & Architecture.pptx
Design Introduction
Outline
Software Design Overview
High-Level
Low-Level
CRC
Identifying Classes
Identifying Responsibilities
Practice
Design Overview
What is Software Design?
Deals with transforming the requirements specifications into a
model that can be implemented using programming languages.
Can be broken down into two types
High-level (i.e., Architecture Design)
Low-level (i.e., Detailed Design)
Software Architecture
What is a Software Architecture?
High Level Design: Software Architecture
The primary way to implement nonfunctional requirements
Requires a deep understanding of the desired quality attributes
of the system, might necessitate negotiation and prioritization
63. with the stakeholders.
Can be difficult to guess right under an agile method.
High-level Vs Low-level
Architecture Design:
High-level deals with overarching nonfunctional goals of the
system.
Requires a complete understanding and prioritization of
nonfunctional requirements.
Detailed Design:
Focuses on the bridge between the functional requirements and
the actual implementation of the system.
Main concern is the maintainability and easy of implementation
of the system.
Software Architecture Issues
Architectures are strictly influenced by the desired
nonfunctional requirements.
Requires a complete understanding of the requirements for the
best architecture selection.
You can’t have your cake and eat it too..
Some quality attributes are mutually exclusive to a certain
degree
e.g., high performance and security, scalability and
availability..
This is why it is so important to prioritize and be able to
negotiate nonfunctional requirements with stakeholders.
Changing an architecture once it is installed is very difficult
Often times it is better to redo the system.
64. High-level Vs Low-level
Architecture Design:
High-level deals with overarching nonfunctional goals of the
system.
Requires a complete understanding and prioritization of
nonfunctional requirements.
Detailed Design:
Focuses on the bridge between the functional requirements and
the actual implementation of the system.
Main concern is the maintainability and easy of implementation
of the system.
Detailed Design
We need a method to convert requirement specifications into an
actual implementation of a software system
There are multiple ways, the book focuses on one approach.
In addition to this, I’ll teach you a different approach.
Class, Responsibility, and Collaborator (CRC) Cards
Invented in 1989 by Kent Beck and Ward Cunningham
A simple yet powerful object-oriented (analysis/design)
technique
Uses a collection of (standard index) cards that are divided into
three sections:
Class
Responsibility
Collaborator
Class, Responsibility, and Collaborator
65. A class represents a collection of the same objects.
A responsibility is anything that a class knows or does, a
service that it provides for the system.
A collaborator is another class that is used to get information
for, or performs actions for the class at hand to support a
responsibility.
Example
More on CRC Cards
3x5 (or 4x6) index cards, post-its, etc.
One class per card
In addition, you can also write superclasses and subclasses.
More on this later..
On the back, write a description of purpose of the class.
It should be one sentence.
Example: The purpose of this class is to represent a person in
the system.
Question
Why use index cards?
Advantages
Portable: cards can be used anywhere, even away from the
computer or office
Anthropomorphic: no computer program can capture the essence
of the interactions forced by passing the cards
66. Level of involvement felt by each team member increases
Useful throughout the life cycle
More Advantages
Provides a basis for a formal analysis and a design method
Serves as input to a formal method (i.e., a starting point)
Ease the transition from process orientation to object
orientation
Most of us (still?) think in a process oriented manner
Provides a general bound on the size of a class
A card
CRC Approach – The Process
Exploratory phase (Today)
Find classes
Determine operations and knowledge for each class
(responsibilities)
Determine how objects collaborate to discharge responsibilities
Analysis phase (Later)
Collect into subsystems
Improve design
How to Find Objects and Their Responsibilities?
Use nouns and verbs in requirement documents as clues
Noun phrases leads to objects
Verb phrases lead to responsibilities
Determine how objects collaborate to fulfill their
responsibilities
To collaborate, objects will play certain roles
Why is this important?
Objects lead to classes
Responsibilities lead to operations or methods
Collaborations and roles lead to associations
67. Identifying Objects (Classes)
Start with a set of requirement specifications
Look for noun phrases.
Separate into obvious classes, uncertain candidates, and
nonsense
Refine to a list of candidate classes.
Guidelines for Refining Candidate Classes
Model physical objects – e.g., disks, printers, station.
Model conceptual objects – e.g., windows, files, transaction,
log.
Choose one word for one concept – what does it mean within
the domain?
Be wary of adjectives – does it really signal a separate class?
Guidelines for Refining (Cont.)
Be wary of missing or misleading subjects – rephrase in active
voice.
Model categories of classes – delay modeling of inheritance.
Model interfaces to the system – e.g., user interface, program
interface.
Model attribute values, not attributes – e.g., customer vs.
customer address.
Example: Mail-Order Software
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
68. Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Example: Mail-Order Software
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Candidate Classes
Candidate Classes (Cont.)
Expect the list to evolve as design proceeds
Record why you decided to include or reject candidates
Candidate class list follows configuration management and
version control
69. A Good Class …
Has a clear and unambiguous name
Has a name that is recognizable by domain experts/stakeholders
Is a singular noun
Has responsibilities
May actively participate in the system
What Are Responsibilities?
The public services that an object may provide to other objects:
The knowledge an object maintains and provides
The actions that it can perform
That is they
Convey a sense of purpose of an object and its place in the
system
Record services that a class provides to fulfill roles within the
system
Record knowledge and manipulation of information in the
system
Knowledge and Action
Knowing responsibilities
Knowing about private encapsulated data
Knowing about related objects
Knowing about things it can derive or calculate
Doing responsibilities
Doing something itself, such as creating an object or performing
a manipulation
Initiating action in other objects
Controlling and coordinating activities of other objects
Identifying Responsibilities
70. Use mixtures of:
Verb phrase identification. Similar to noun phrase
identification, except verb phrases are candidate
responsibilities.
Scenarios and role play. Perform scenario walk-through of the
system where different persons “play” the classes, thinking
aloud about how they will delegate to other objects.
Class enumeration. Enumerate all candidate classes and come
up with an initial set of responsibilities.
Class relationship examination. Examine all classes and their
relationships to compare how they fulfill responsibilities.
Example of Verb Phrase Identification
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Example of Verb Phrase Identification
Imagine that you are developing order-processing software for a
mail order company, a reseller of products purchased from
various suppliers.
Twice a year the company publishes a catalog of products,
which is mailed to customers and other interested people.
Customers purchase products by submitting a list of products
71. with payment to the company. The company fills the order and
ships the products to the customer’s address.
The order processing software will track the order from the time
it is received until the product is shipped.
The company will provide quick service. They should be able to
ship a customer’s order by the fastest, most efficient means
possible.
Candidate Responsibility
Responsibility Types
Identify the types of responsibilities for each class
Behavior – Describes what a class does (i.e. things that meets
the requirements of the system)
Knowledge – Describes what the class knows about itself (i.e.
attributes of the class)
Example
Knowledge or Behavior?
Know balance?
Verify customer?
Know account number?
Authorize transaction?
Track activity?
Last page visited?
Late fee amount?
Print layout?
72. Assigning Responsibility Types
For knowledge types
Match the responsibility with the class who owns the
information
For behavior types
Match the responsibility with the class who can do this
Look at the name and purpose of the class as a guideline
Practice!
ATM Example specifications
Cards
Read
Chapter 12, 13 & 14
Further readings
B. Beck and W. Cunningham, A Laboratory for Teaching
Object-Oriented Thinking, OOPSLA ’89, October 1-6, 1989.
R. Wirfs-Brock, B. Wilkerson and L. Wiener, L., Designing
Object-Oriented Software, Prentice Hall, 1990. (Chapters 3 and
4)
Hans Van Vliet, Software Engineering, Principles and
Practice,3rd edition, John Wiley & Sons, 2008. Sections 10.1.4
& 12.3
__MACOSX/se_lectures/Day14/._Design & Architecture.pptx
se_lectures/Day22/.DS_Store
__MACOSX/se_lectures/Day22/._.DS_Store
73. se_lectures/Day22/Weather.pptx
Weather Monitoring System
Classes
Classes
Sensors
Wind Speed
Wind Direction
Barometric Pressure
Humidity
Derived Measurements
Wind Chill
Dew Point Temp
Trends
Temp Trend
Barometric Trend
Continous Data
Specific Data
Time
Clock
Keypad
LCD
Graphics
Line
Arc
Region
Text
History Logs
Wind Speed
Wind Direction
Barometric Pressure
Humidity
74. Weather Monitoring System
Collaboration Graph
Weather Monitoring System
Contracts
Simple Contracts
Monitor Weather
Get current weather data
Query specific sensor 24 hour hi-lo data
Display graphic data
Capture user input
Get current time and date
Set time and date
Get sensor data
Get derived measurement
Calibrate sensor
Get 24 hour hi-lo for sensor
78. A well designed system
High Cohesion
Low Coupling
Abstractions
A plan for building a system
?
Building a bridge to code
How do we map the work we have done with our detailed
designs into actual code?
We can build classes (we have the cards with the names)
And we have our contracts.
How do we implement these?
Contracts describe interfaces
Classes provide interfaces for other classes to interact through
There are multiple ways to build classes and their routines
Traditional Building of Classes and Routines
Approaches
Ways to plan for implementation of contracts:
Pseudocode Programming Process (PPP)
Design by contract
Test-first
Pseudocode Programming Process
(PPP)
Approach based on using English-like statements to describe
code logic
79. Language independent
Less training required:
We all know English somewhat..
Can be verified without implementing anything
i.e. can be reviewed.
PPP-Design the routine
This can be guided by what we have designed, for example:
Your CRC contract from your detailed design can be the starting
point.
Write Pseudo-code that fulfills that contract.
Review!
PPP-Implement
Write code following your pseudocode.
You don’t have to think much, just read along.
Thoughts?
PPP-Review
Check the code
Can be a review, or be done by unit testing.
PPP-Repeat as necessary
You might encounter optimizations or you might need to clean
up the code.
Might identify factoring out, i.e. identifying new routines to be
extracted out.
PPP
80. Seems silly
Who needs pseudocode??
Only dumb programmers!
Thoughts?
PPP
Seems silly
Who need pseudocode??
However it isn’t just about you
Others can review before you implement potentially finding
issues
Others can understand what you’re going to do and therefore
accommodate their work to match yours
You can build test cases much easier this way
Design by Contract
A different approach:
“Applying Design by Contract,” B. Meyer, IEEE Computer, pp.
40-51, October 1992
Design by Contract
The next logical step after you have created your CRC
contracts.
Enhance them by adding:
Pre-conditions
Post-conditions
What are pre and post conditions?
Pre: What must be true to guarantee the execution of this
contract
Post: What is guaranteed to be true after the execution of this
contract
81. Pre-Condition
Capture the conditions that must be true in order for the method
to execute correctly
Describe the required state of the ADT or object before entering
the function
Written as an expression that is true or false
May consist of statements connected by logical operators (AND,
OR)
Use true when no pre-condition exists – should be rare.
15
Post-Condition
Must clearly state what is true when the method completes
execution
Describe the expected state upon exiting the function
Should be strong enough so that only correct implementations
will satisfy the condition
Think of an evil programmer.
16
Example
82. 17
Example Continued
18
Design by Contract
Pre an post conditions can be written
Use formal methods like
using a specification language
such as:
Z
JML
OCL
And others..
Informally, using English as a language
Pre: The internal private list will not empty and only contain
positive integers.
Post: The Sum() method will iterate through the private list, and
return the addition of all elements within that list.
Semi-formally, using a combination of the above.
Drawbacks of each?
Design by Contract
83. By writing pre and post conditions we gain the following
benefits:
We don’t have to be so defensive on production code (defensive
programming)
We have precise contract agreements that must be fulfilled
We can generate unit and integration testing much easier
Good Pre and Post Conditions
States
What (properties), e.g.,
The property of being square roots
The property of being sorted
The property of appearing in an array
Not how (algorithms), e.g.,
Not how to calculate square roots (linear, binary, Newton)
Not how to sort (bubble, insertion, quick)
Not how to decide whether an item appear in an array
21
21
Test-first
Produce automated tests before you code.
Test-first
Wait.. What?
Create tests and execute them without code??
84. Test-first
Produce automated tests before you code
Start with a small focused unit test
At first it will fail (it should fail, if it doesn’t then something is
already wrong)
Minimally develop code to pass this test
Refactor
Reorganize code without changing it’s behavior.
Repeat with the next test
Where do tests come from?
What is automated testing?
Test-first
Tests come from
Use Cases and Scenarios
CRC contracts
Automated testing is a way to create unit tests that can be
automatically tested
Such tools as NUnit, JUnit
Are a great tool for regression testing (regre-what?)
Benefits of this approach?
Test-first
Benefits:
You are testing as you go
You can fix issues faster because you’re closer to the code
Your testing becomes your abstract pseudocode.
But your code is only going to be as good as your testing
And a lot of effort will be invested in refactoring.
85. Approaches
All 3 approaches are valid
They all serve a purpose
Add …
Name:
________________________________________________
_______________________________
Design of Software
Systems
The following specifications are to be used for
developing a design in this examination:
You have been recently hired by an online company to
develop and implement an online scientific
calculator. The following specifications describe the
initial delivery of the desired system.
The system’s user interface shall be graphical based.
The system’s user interface shall be accessible via an
online webpage.
The system’s user interface shall display buttons to
represent the elements of the calculator, such as
numbers and operations.
The system’s functionality will support entering
numeric digits in the range of 0-9 and up
86. to 32 digits.
The system’s functionality will allow entering decimal
numbers using the “.” to delimit the whole
number
from the fractional number.
The system’s functionality will support the following
arithmetic operations:
• Addition
• Subtraction
• Multiplication
• Division
The system’s functionality will support the following
advanced scientific operations:
• �" • �� • �& • � • log x
• sin x • cos x • tan x • n! • 10"
• arcsin x • arccos x • arctan x • mod x •
inv x
The system’s functionality will support two buttons to
reset operations and clear the transcript:
1. A button labeled “C” which will clear all
operations.
2. A button labeled “CE” which will clear the
last entered operation.
87. The system will display a textbox with a
scrollable bar containing the transcript of
operations as they
execute.
The system will provide a means to email a
transcript of operations to the user’s desired
email address.
1) Why is cohesion and coupling important with respect
to the design of a system? Fully justify
your answer. Take into consideration this answer when
answering the remainder of the exam.
2) Using the CRC Process, create at least 4 classes
(including responsibilities and collaborations) for
the desired system as described above.
88. 3) Define 3 Contracts for 3 different classes that
you created in question 2.
4) Create a collaboration diagram for the classes
you created in questions 2 and 3.
5) Using either a top-down approach or a bottom-
up approach (but just one, and state which one
you are using), sketch a high-level subsystem
collaboration graph.
89. 6) In class we discussed Protocols (Detailed Design) for
contracts. What is their purpose and why
do we do them? For the contract of
multiplication, writethe pre and post conditions.
7) Recall the Strategy Design pattern as shown
below:
What is the problem that this design pattern is
aiming to solve? How will this work with the
implementation of the calculator. Explain using
concrete examples, i.e. you may draw the UML
for this.
8) In class we discussed MVC. What benefits
90. can this provide to us in our calculator
implementation? Justify.