Transcript Chapter 13

Designing applications
5.0
Main concepts to be covered
•
•
•
•
Discovering classes
CRC cards
Designing interfaces
Patterns
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
2
Analysis and design
• How do we attack the analysis and
design of a software system?
• A large and complex problem area
with many different methodologies
• The verb/noun method is suitable
for relatively small problems
• CRC cards support the initial design
process
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
3
The verb/noun method
• Nouns in a description refer to things
– Such as people, buildings, etc…
– Corresponds to classes and objects
• Verbs refer to actions or behaviors
– Such as writing, eating, etc…
– Interactions between the objects
– Corresponding to methods
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
4
A problem description
The cinema booking system should store seat
bookings for multiple theaters. Each theater has
seats arranged in rows. Customers can reserve
seats and are given a row number and seat number.
They may request bookings of several adjoining
seats.
Each booking is for a particular show (i.e. the
screening of a given movie at a certain time).
Shows are at an assigned date and time, and
scheduled in a theater where they are screened.
The system stores the customer’s phone number.
What nouns and verbs can you identify in this example?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
5
A problem description
The cinema booking system should store seat
bookings for multiple theaters. Each theater has
seats arranged in rows. Customers can reserve
seats and are given a row number and seat number.
They may request bookings of several adjoining
seats.
Each booking is for a particular show (i.e. the
screening of a given movie at a certain time).
Shows are at an assigned date and time, and
scheduled in a theater where they are screened.
The system stores the customer’s phone number.
How are the nouns and verbs related?
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
6
Nouns and verbs
Cinema booking system
Stores (seat bookings)
Stores (phone number)
Theater
Has (seats)
Movie
Customer
Reserves (seats)
Is given (row number, seat number)
Requests (seat booking)
Time
Date
Show
Is scheduled (in theater)
Seat
Seat number
Telephone number
Row
Row number
Seat booking
• At first, use EACH noun as a class … even “bad” ones
• ALL nouns are represented as a singular class name
• Multiplicity is achieved with multiple instance objects
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barneads, Michael Kölling
7
Using CRC cards
• Class – Responsibilities - Collaborators
• Use one index card to represent each
class (important here to use real, physical cards)
• Each index card records:
– The class name
– The class’s responsibilities
– The class’s collaborators
(classes that this one uses)
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
8
A CRC card
Class name
Collaborators
Responsibilities
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
9
Scenarios
• The classes are approximated with a
physical representation by the CRC cards
• Use scenarios to figure out necessary
interactions between our classes
• Each scenario is an example of an activity
that the system has to carry out or support
– Sometimes known as use cases
• Used to discover and record object
interactions (collaborations)
• Scenarios performed best through a group
– Each person assigned one class
– Plays role by saying what that class is doing
– During the scenario, responsibilities and
collaborators are recorded on the CRC card
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
10
Scenario example
A customer calls the cinema and wants to make a reservation for two seats
tonight to watch the classic movie The Shawshank Redemption. The cinema
employee starts using the booking system to find and reserve a seat.

User finds all Shawshank Redemption showings for tonight
o
o

How does system find the show? Who does it ask? In a collection
o
o

Show responsibility: Can reserve seat.
Show stores seat reservations with link to a Theater object
o

CinemaBookingSystem responsibility: Accepts seat reservations from user.
Seat reservation task for particular show is delegated to Show class
o

CinemaBookingSystem responsibility: Retrieves and displays show details.
Show responsibility: Provides details about theater and number of free seats.
Assume customer chooses specific seats and user makes reservation
o

CinemaBookingSystem responsibility: Stores collection of shows.
CinemaBookingSystem collaborator: Collection (of Shows)
System retrieves & displays a detailed show list for user to give choices
o
o

CinemaBookingSystem responsibility: Can find shows by title and day.
CinemaBookingSystem collaborator: Show
Show responsibility & collaborator: Stores theater. & Theater
Theater makes a seat reservation in a collection of seats or row-seats?
o
o
o
o
o
Theater responsibility & collaborator : Stores rows. & Row
Row responsibility & collaborator : Stores collection of seats. & Seat
Row responsibility: Accepts reservation request for seat.
Row responsibility: Can find seats by number.
Seat responsibility: Accepts reservation. & Stores reservation status.
11
A partial example
CinemaBookingSystem
Can find shows by title and day.
Stores collection of shows.
Retrieves and displays show details.
Accepts seat reservations from user.
Collaborators
Show
Collection
...
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
12
Multiple scenarios necessary
Scenarios dealing with user and customer requests:
• Customer requests 5 seats together
• Customer requires lookup of forgotten seat numbers
• Customer cancels with only his name and show
• Customer wants additional seats near existing seats
• Cancelled show and all customers need to be called
Scenarios dealing with user and customer requests:
• New cinema setup with multiple theaters in varying
sizes of rows and seats
• New movie scheduled at various times and dates in
a particular theater
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
13
Scenarios as analysis
• Helps check that the problem
description is clear and complete
• Sufficient time should be taken to
execute as many scenarios as possible
• Ensure every detail is recorded
• No shortcuts should be taken!
• The analysis will lead into design
– Spotting errors or omissions here will
save considerable wasted effort later
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
14
Class design
• Scenario analysis helps to clarify the
application structure
– Each card maps to a class
– Collaborations reveal class cooperation
and object interaction
• Responsibilities reveal public methods
– Sometimes instance fields
– e.g. “Stores collection ...”
• Class responsibilities should be
evaluated using good design principles
– Responsibility-driven design
– Coupling
– Cohesion
15
Designing class interfaces
• Replay scenarios in terms of method
calls, parameters and return values
• Note the resulting method signatures
& instance fields this time (new cards)
• Create outline classes with method
stubs (empty body) for all public methods
◦ Seems tedious but is very valuable
• Careful design is a key to successful
implementation
Code mistakes can usually be fixed fairly easily later, BUT …
design mistakes can be very expensive, fatal or even unfixable
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
16
Documentation
• Write class comments
• Write method comments
• Describe the overall purpose of each
• Documenting now ensures that:
– The focus is on what rather than how
– That it doesn’t get forgotten!
In real-life applications, a good programmer understands
that documentation focusing on what a class/method
does is just as important as its implementation.
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
17
Cooperation
• Team-working is likely to be the
norm not the exception
• Documentation is absolutely essential
for team working
• Clean object-oriented design with
loosely-coupled components supports
cooperation
• Initial design best done in a group
• Then separation of classes may be
implemented independently
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
18
Prototyping
• Supports early investigation of a system
– Early problem identification
• Incomplete components can be simulated
– e.g. always
returning a fixed result
– Avoids random behavior which is difficult
to reproduce
• Useful with team development
– Continuation of development and testing
when not all classes are completed
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
19
Several models to build software
Waterfall model
• Traditional & conservative with widespread use
• No looking back approach with work on current and
previous phases
• Fixed sequence of several phases
–
–
–
–
–
–
Analysis of the problem
Design of the software
Implementation of components
Unit testing
Integration testing
Delivery of system to the client
• Flaws causing problems with this model
– Assumes developers fully understand system’s functionality
– Assumes that the system does not change after delivery
• No provision for iteration
20
Iterative development
Addressing problems with waterfall
• Use early prototyping to give impressions
• Frequent client interaction & feedback
• Iterate several times thru the cycle:
–
–
–
–
Analysis
Design
Prototype implementation
Client feedback
Growth model
• A growth model is the most realistic:
–
–
–
–
Design/implement a small, clean system
Add additional features gradually (grow it)
Deliver usable systems repeatedly/frequently
Notion of a complete system does NOT exist!
–
–
–
–
–
Software maintenance
Code reading
Designing for extendibility
Documentation
Coding for understandability
• Some tasks & skills become more important
21
Using design patterns
• Inter-class relationships are important and can
be complex
• Some relationships recur in different applications
• Design patterns help clarify relationships and
promote reuse
– Describes a common problem that occurs regularly in
software development
– Then describes a general solution that can be used in
many different contexts
o Typically description of a small set of classes and their
interactions
• Helps our task by providing:
– Good, reusable solutions (in class structure, not code)
– Established, common vocabulary for team designing
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
22
Pattern structure
Template for design patterns
• Pattern name
• Problem addressed and split into:
– Intent, motivation and applicability
• Solution description listing:
– Structures, participants, and collaborations
• Consequences of usage:
– Results and trade-offs
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
23
Decorator
• Augments functionality of an existing object to
respond to the same methods & additional ones
• Decorator object wraps another object
– Decorator usually has a similar interface
– Clients now interact with Decorator instead of original
– Decorator will now:
o … pass the method call to the enclosed object
o … but the decorator may also perform additional actions
• Example: java.io.BufferedReader
–
–
–
–
Wraps and augments an unbuffered Reader object
BufferedReader implements the same interface
Can be used instead of Reader
Adds to basic behavior of Reader
24
Singleton
• Ensures only a single instance of a class exists with
unified access to it
– All clients use the same object
– i.e. IDE has only 1 compiler or 1 debugger
• Private constructor prevents external instantiation
– Ensures no outside calls to it
– Client classes can not create new instances
• An instance obtained via static getInstance()
public class Parser
{
private static Parser instance = new Parser();
public static Parser getInstance()
{
return instance;
}
}
private Parser()
{
…
}
Parser parser = Parser.getInstance();
25
Factory method
• Provides the interface for creating objects, but
allows subclasses to decide which specific class
• Clients expect superclass or dynamic type interface
• A factory method is free to return an
implementing-class object or subclass object
• Exact type returned depends on context
• Example: iterator methods of collection classes
public void process(Collection<Type> collection)
{
Iterator<Type> it = collection.iterator();
…
}
– Client deals with objects of type Collection & Iterator
– In reality, dynamic type of collection (maybe ArrayList) returns
an ArrayListIterator when iterator method is called
Factory method specialized in subclasses tor return
specialized instances to the official return type. 26
Observer
• Supports separation of internal model from a
view of that model (i.e. GUI)
• Observer defines a one-to-many relationship
between objects
– Object-observed notifies all Observers of any state change
– Achieved with a low degree of coupling between them
– Allows for multiple views (alternatives or simultaneously)
• Example: foxes-and-rabbits SimulatorView
– Presented populations on screen as 2D animated grid
– Other possibilities include timeline graph and bar chart
27
Observer pattern structure
Uses Observable & Observer classes
• Observable entity (i.e. Field) extends Observable
• Observer (i.e. SimulatorViewer) implements Observer
– Provides methods for observers to attach themselves to the
observed entity
– Ensures that observers’ update method called when observed
entity invokes its inherited notify method
– Actual observers then get updated state from field to redisplay
28
Review
• Class collaborations and object
interactions must be identified
– CRC analysis supports this
• An iterative approach to design,
analysis and implementation can be
beneficial
– Regard software systems as entities
that will grow and evolve over time
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
29
Review
• Work in a way that facilitates
collaboration with others
• Design flexible, extendible class
structures
– Being aware of existing design
patterns will help you to do this
• Continue to learn from your own
and others’ experiences
Objects First with Java - A Practical Introduction using BlueJ, © David J. Barnes, Michael Kölling
30