test questions
se_lectures/.DS_Store
__MACOSX/se_lectures/._.DS_Store
__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 from one object to another in order to fulfill a responsibility.
Motivation (Cont.)
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):
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.
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
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
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
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.
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
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?
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
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
Ordered
Collection
Indexable
Collection
Magnitude
Array
Matrix
String
Date
magnitude
Date
string
Array
Ordered collection
Indexable collection
Matrix
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?????
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.
Ellipse
Element
Text
Element
Line
Element
Rectangle
Element
Group
Element
Drawing
Element
How many responsibilities do you need in order to create an abstract class?
Answer: 1, but there’s a catch!!!
33
Factoring (Cont.)
Rectangle
Element
Ellipse
Element
Text
Element
Line
Element
Group
Element
Drawing
Element
Linear
Element
Rectangle
Element
Ellipse
Element
Text
Element
Line
Element
Group
Element
Drawing
Element
Linear
Element
Filled
Element
34
Outline
Collaborations
Hierarchies
Continuing Practice
Add Collaborations
Identify Hierarchies
Finish Reading if you haven’t
Chapter 17 and 18
__MACOSX/se_lectures/Day15/._Collaborations and Hierarchies.pptx
se_lectures/Day14/.DS_Store
__MACOSX/se_lectures/Day14/._.DS_Store
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 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.
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
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.
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
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
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 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
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 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.
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
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
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
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
Weather Monitoring System
Subsystem Graph
Graphics
Query
WeatherMonitor
CurrentData
1
2
10
3
12
WeatherMonitor
1
CurrentData
2
10
Query
3
Graphics
12
__MACOSX/se_lectures/Day22/._Weather.pptx
se_lectures/Day18/Detailed Design.pptx
Detailed Design
1
Detailed Design
Following the CRC process we have modeled a detailed design for a system.
What is the purpose of creating this?
To create a well-designed system.
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
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
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
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
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:
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
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
All 3 approaches are valid
They all serve a purpose
Add structured detail
Manage complexity
Create a process to replicate
Act as the bridge between CRC and the Implementation.
Practice writing protocols
Try the pseudocode approach.
Do pre/post conditions for some contracts.
Define some test cases that could be automated.
3/28/2019
28
__MACOSX/se_lectures/Day18/._Detailed Design.pptx
se_lectures/Day18/.DS_Store
__MACOSX/se_lectures/Day18/._.DS_Store
se_lectures/Day20/Design Patterns.pptx
Design Patterns
Medical Doctors
You go to the doctor
You tell list your symptoms
Doctor looks back at what s/he knows and matches the symptoms with the treatment
Who figured out this stuff?
Other doctors who researched/stumbled on the same diseases
Other doctors who figured out the effects of certain medicines on these diseases
The Dream
Optimally we’d like to:
You see a software requirement
You look at it’s needs
You look back at what you know and match the needs with the problem solution
Goal
So wouldn’t it be nice if someone came to us with a problem..
..and we could just open a book or a repository, and tweak an existing solution for this need?
Design Pattern
Describes
problem that occurs repeatedly
the core of the solution to that problem
Solution can be reused
not necessary to implement it the same way
Patterns
Proven solutions to recurring software problems.
Architecture
Design
Architectural patterns are beyond the scope of this class
But let’s view a very common and important one
MVC
Model-View Separation
Model: The domain layer of objects. (objects that contain data and operations).
View: The presentation layer of objects (windows, applets, reports).
Separation of Concerns
Domain vs View
Design Heuristics – 1
So far we have talked about:
High Cohesion
Low Coupling
This is Separation of Concerns
Separate focused cohesive elements into modules
This lowers coupling
It all boils down to high cohesion/low coupling.
The Nature of Software
Software Changes
If a piece of software is being used it is being changed:
Bugs are found that need to be corrected or
Improvements found with use are being requested
Change in software is not trivial
Can introduce bugs, or affect non-functional requirements (security, performance, portability)
All good software will change; if it’s not being changed it’s not being used
Design Heuristics – 2
Design for Change
Notion to structure and organize your software system to facilitate and minimize the impact of change
How is it done?
Separate and Encapsulate elements that are likely to change.
View of a System
Is the view of a system likely to change?
What is the difference between the following software systems?
Windows 8 vs Windows 10
NFL Madden 2016 vs NFL Madden 2019
IOS 7 vs IOS 10
Your credit card’s website in 2014 vs 2019
Answer: Looks different!
Model-View
Window
Configuration
display( )
addEntry( )
query( )
Model
View
Goal: Classes in Model should not have direct visibility to classes in View.
Model-View Separation Motivation
Motivation
Focus more on the domain processes rather than on computer interfaces.
Allow separate development of the model and user interface layers.
Minimize the impact of changes in the interface upon the domain layer.
Allow new views to be easily connected to an existing domain layer.
Problem
Window
Configuration
display( )
addEntry( )
query( )
Model
View
Model classes know about View classes.
Worse
displayMessage ( )
Model-View Separation Pattern
Window
Configuration
display( )
addEntry( )
query( )
Model
View
query( )
View classes know about Model classes.
Better
Model-View Separation Pattern
Configuration
Old Window
display( )
addEntry( )
query( )
Model
View
query( )
New Window
display( )
The View Layer can be modified without affecting the Model layer.
Model-View Separation Pattern
Configuration
addEntry( )
query( )
Model
View
query( )
New Window
display( )
When the Window needs to display data it queries the Model objects “Polling Model”
Model-View Separation Pattern with Indirect Visibility
Configuration
Window
display( )
addEntry( )
query( )
Model
View
Model View
Controller
post Update Message
tells Window to Update
query( )
MVC
MVC is an architecture pattern
An architecture is the higher level design of a system
Meaning it’s the way a software system is structurally organized, and the communication paths between components is defined
Other examples include: Layered, Client-Server, Pipe and Filter, N-Tier, Event-driven...
Patterns
Proven solutions to recurring software problems.
Architecture
Design
So patterns we will see are at the detailed design level..
Design Patterns
First recognized by the Gang of Four
Erich Gamma
Richard Helm
Ralph Johnson
John Vlissides
Published a book with 23 patterns
These have become the foundations of all other patterns
GoF 23
Are categorized into three groups
Creational
Structural
Behavioral
The whole list:
Abstract Factory, Builder, Factory Method, Prototype, Singleton, Adapter, Bridge, Composite, Decorator, Façade, Flyweight, Proxy, Chain of Responsibility, Command, Interpreter, Iterator, Mediator, Memento, Observer, State, Strategy, Template Method, Visitor
Where do you see Design Patterns?
Seminars and conferences
Technical journals
Text books and trade journals.
Existing well designed systems
A good software engineer knows design patterns.
Because he/she doesn’t want to reinvent the wheel
And make the wheel a square.
Where did they come from?
Patterns start with a premise and answer two questions:
Premise: the goodness of a design is objective: not entirely in the eyes of the beholder.
Q1: What is present in good designs that is not present in poor ones?
Q2: What is present in poor designs that is not present in good ones?
Description of patterns:
Name What it’s commonly called.
Intent What it does.
Problem What problem addresses.
Solution How does the pattern solve the problem
Participants Objects interacting
Consequences Investigate forces at play
Implementation Note: this is not the pattern itself.
References Where it comes from.
Elements
Pattern name
Becomes part of our vocabulary
Allows abstract discussion of problem and approaches
Allows discussion of issues instead of implementation
Problem
Solution
Consequences
Vocabulary Example : find number in sorted list
Find middle value and compare value we are looking for to that one. If found, we’re done. Otherwise, if we are looking for something bigger, set the new bottom to the current middle. Otherwise, set the new top to the current middle.
Repeat the above step until the list can’t be divided further. If it’s not in the last two positions, it’s not in the list.
Vocabulary Example 2: find number in sorted list
Use binary search.
Discussion
This assumes that you know what binary search is.
But if you know what binary search is, the discussion is greatly simplified.
Algorithms are not patterns. Patterns are not algorithms.
Elements
Pattern name
Problem
Explains the problem and its context
may include a list of conditions needed before application of the solution makes sense
Solution
Consequences
Elements
Pattern name
Problem
Solution
Describes elements of design, relationships, responsibilities, and collaborations
Does not describe a particular implementation
Abstract description and how a general arrangements of objects solves problem
UML
Consequences
Elements
Pattern name
Problem
Solution
Consequences
Results and trade-offs of applying pattern
Needed to evaluate tradeoffs between solutions.
Frequently time/space trade-offs
Why use patterns?
Reuse existing, high-quality solutions to common problems
Incorporates a great deal of experience
May describe things often overlooked or subtle that prevent good solutions
Focus on issues not implementation
Shift thinking to higher level
Decide if design is right, not just working
Assists you in learning how to design well
Improves code: smaller hierarchies, more modifiable code.
General Strategies suggested by patterns
Design to interfaces
Favor composition over inheritance
Find what varies and encapsulate it.
Consider what should vary in your design.
Consider what you want to be able to change without redesign (as opposed to what might force you to redesign)
Then encapsulate it
34
(Encapsulation is hiding: not just data, but data, implementation, interface, anything.)
Solving Problems
Patterns help you identify non-obvious abstractions
e. g., Strategy describes pattern for interchangeable families of algorithms
Patterns can guide decisions about what should be an object
How to Select a Design Pattern
Consider how design patterns solve design problems
Scan Intent sections
Study how patterns interrelate and patterns of like purpose
Consider what should be variable in your design
How to use a pattern
Read the pattern paying attention to Applicability and Consequences
Study the Structure, Participants, and Collaborations
Look at Sample Code
Choose good names for participants
Define the classes, interfaces, and operations
Implement the operations to carry out the responsibilities and collaborations
Design Pattern Examples
Let’s look at a couple of design patterns in detail.