Anda di halaman 1dari 86

Object Oriented Software Engineering:

Practical software development using UML and Java


By Timothy C. Lethbridge and Robert Laganire
McGraw-Hill 2001
International ISBN 0-07-709761-0
US ISBN 0-07-283495-1

Answers to Exercises Version 1.9 (August, 2002)


2002 Timothy C. Lethbridge and Robert Laganire
The following contains answers to exercises in the book, along with explanations of some aspects of the answers. In some
cases the provided answers are more detailed those that would be expected from students. Also note that some questions
are subjective, so readers may have responses different from those written here.
In order to ensure that answers to exercises assigned for credit remain unavailable to students, this document is be
to be made available only to instructors (and their teaching assistants) who have adopted the book.
Some of the answers (marked *) are to be made publically available on the books web site. Such answers are
intended for public discussion by instructors and for readers working through the book on their own. Most parts
a, c and e of multi-part exercises (not involving programming) are the ones that have public answers.
Other than those marked *, please do not provide answers to others, particularly by posting them on nonpassword-protected web sites.
We suggest that in order to provide answers without making it easy for the students to distribute them to others, you post
printouts of selected answers in a glass display case for a short period of time or show them during lectures or tutorials.
We update these answers from time to time, adding improved explanations, alternative answers, and extra exercises. You
can contact us at tcl@site.uottawa.ca with suggestions. Added exercises are intended to be used for examinations etc. This
version contains many, but not all of the answers. We are working on completing the remainder. Please email us,
quoting the above version number and date, to obtain the latest answers when available. Items which we plan to
complete or augment are marked in green. Changes from the previous version will have a change bar in the margin.
Please look at our web site (www.lloseng.com) for other information about this book.

Accompanying zip file


Accompanying this file, you should also have been sent a zip file containing Java code for answers that require
programming. You will find the following in the file:
Code for exercises regarding the postal code system (E2.20, E2.21, E2.23, pp. 53-54)
Code for exercises regarding the polar and Cartesian co-ordinates (E2.24, E2.26, E2.27, E2.28, E2.29, pp. 55-56)
Code for the exercise regarding the shape hierarchy (E2.30, p. 59)
Code for the exercise regarding the performance analysis of Java classes (E2.31, p. 59)
Code for the various versions of SimpleChat built as a result of project exercises
Version 2: Adding simple improvements: P3.2, P3.3 and P3.4, pp. 97-99.
Version 3: Security and channels: P4.2, p. 149.
Version 4: Observable layer: P6.1, p. 227.
Version 5: User interface: P7.2, p. 266.
Version 6: Transmitting vector graphics using DrawPad: P7.3, p. 266.
Code for the Small Hotel Reservation System
We ask you to please protect the above code with the same diligence as this answer manual.
For convenience, the zip file also contains copies of SimpleChat version 1, OCSF, Drawpad, OCSF and the postal code
and point examples, which are also freely available on the web.

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A2

Chapter 1. Software and Software Engineering


E1.1

p. 5 Classifying software.
a)*Custom; real-time.
b) Embedded; real-time.
c)*Generic; real-time (but soft real-time).
d) Custom; data-processing.

E1.2

p. 10 Stakeholder reactions to situations.


a)* The user may be disappointed, since he or she might be looking forward to no longer having to do this
particular type of work. On the other hand, he or she may be relieved about not being put out of work.
The customer may be disappointed at not being able to save money; he or she may also be surprised,
since many people believe that software systems are easy to develop; they underestimate the
complexity of tasks that are to be automated. The customer might consult some other software engineer
to obtain a second opinion.
The developers will probably move on to other work.
The development managers may be disappointed at not having the opportunity to do further work on
the project.
b) The users will be frustrated if they are forced to use the system anyway. The users may refuse to use
the system, or may just ignore it, so it becomes shelfware.
The customer will probably be surprised, and then will request changes.
The developers and managers may feel intense pressure to change the system so that it does solve the
customers problem. Hopefully, both groups will realise that it would have been better if they had not
blindly followed the customers specification, but had instead done their own analysis and corrected the
specification at the time the project started.

E1.3

p. 12 Prioritizing quality attributes


a)*Reliability will be paramount for the spacecraft software. It would be sad if the spacecraft did not make it
into orbit after all that time, although no lives would be lost. Efficiency might be important since
processors from 20 years earlier are far slower than todays devices. Usability will likely not be an issue
since the software will run autonomously and report any feedback to experts; furthermore the software
cannot be interactive since it takes considerable time to send signals to and from Pluto at the speed of light.
Maintainability is also likely to be a minimal concern since this software is likely to only be used once.
However, there remains the possibility that the software could be used on other systems, or will need to be
changed as last-minute bugs are fixed.
b) Usability will be a key concern for shopping-mall software since it will be used by all kinds of people,
without a manual. Reliability will also be reasonably important, although occasional down-time would not
have dire consequences. Maintainability will also be reasonably important since it is likely that the
software will be enhanced gradually over many years. Efficiency will probably be of low importance since
todays hardware is so fast that the kinds of computations required should not tax it.
c)*Maintainability will likely be the most important concern since data processing software tends to evolve.
Reliability will also be of considerable importance: Bill printing must be accurate, since it can be costly to
rectify mistakes. Usability of the bills themselves will be important because ordinary people have to
understand them. Efficiency should not be a concern.
d) Reliability of automatic-transmission software will be of utmost importance, since some kinds of failure
would be life-threatening. Usability would not be a concern to the driver, since controls are standardized
and rather simple; however, the usability of a diagnostic subsystem used by mechanics would be
important. Efficiency might be important if a very simple CPU and a small amount of memory were used
to save money. The system, once installed in a vehicle, would not be changed; however, maintainability
might be reasonably important so that the software can be adapted to other vehicles.
e) Income tax software is another application domain in which maintainability will be a big concern since
tax regulations tend to change frequently. Usability will also be important so the auditors can do their job
efficiently. Reliability will be of moderate importance (accuracy of results, however, will be very
important). Efficiency will be of minimal importance.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A3

ANSWERS TO EXERCISES

Chapter 2. Review of object orientation


E2.1

p. 32 Distinguishing among classes and instances


The class names in the following answers could vary slightly. The points in parentheses are of lesser
importance, and are for those who have read Chapter 5.
a)*Instance of AutomobileCompany. (or perhaps just Company)
b) Class, subclass of Company. (Or perhaps instance of CompanyType).
c)*Class, subclass of Person. (In Chapters 5 and 6, we will see that it might be better to make this a subclass
of PersonRole)
d) Class, subclass of Student (although as you will learn later in the book, it is probably best not to create a
class as specific as this).
e)*Instance of Person.
f) Class. (Or instance of ProductCategory).
g) Class, subclass of Game. (Or instance of ProductCategory.)
h) Instance of BoardGame (or perhaps just an instance of Game if there is no BoardGame class)
i) Class, subclass of Vehicle. (Or instance of ProductCategory).
j) Class, subclass of Car. (although as we will see, you should probably not create a class as specific as this)
k) Instance of GameOfChess.
l) Instance of Car.

E2.2

p. 33 Detecting bad class names and improving them


a)*Bad. Is this a particular vehicle (which might better be called something like Locomotive, or
RollingStockConfiguration) or a scheduled run (RegularlyScheduledRun) that could use
any vehicle, or the run on a particular day (SpecificRun)? We will discuss this kind of problem in more
detail in Chapter 6 in the context of the Abstraction Occurrence pattern.
b) Bad. Is this a place where a train stops (TrainStation, Station, StoppingPlace) or the event of
a particular train stopping on a particular day (StopOccurrence)
c)*Bad. The word Data is inappropriate in a class name. Call it simply SleepingCar.
d) Bad. It should not start with a lowercase letter: Passenger would be better.
e)*Bad. It should not be plural: Route would be better.
f) Bad. This is clearly a verb, and it also starts with a lower-case letter. Departure would be better.
g) Bad. The word Info is inappropriate in a class. Call it SpecialTrain, CharteredTrain or
SpecialRun.

E2.3

p. 33 Naming different classes derived from words with multiple English meanings.
a)*Title: Describes published books independently of the number of copies CopyOfTitle: or perhaps
LibraryItem: Represents physical books (as well as other things, such as videos) that the library places
on its shelves.
b) VideotapeRecording; CopyOfRecording; VideotapePlayer (the latter meaning of Video
is only used in certain parts of the English-speaking world).
c)*RegularlyScheduledFlight: has a flight number, departure time, origin and destination and is
flown every day; SpecificFlight: flies on a particular day.
d) Series: has a name, description, producer, set of regular actors, etc.; Episode: has a length, a plot, and
other information that differs from episode to episode in a series; ShowingOfEpisode: has a start time
and date.

E2.4

pp. 34-35 Identifying attributes


In this question and the next, there are many alternatives, a few possibilities are shown here. In particular
sometimes certain attributes could be represented as associations instead these are shown in parentheses.
a)*name, description, (producer, distributer)
b) name, address, telephoneNumber, frequentFlierNumber, passportNumber,
specialNeeds
c)*date, startTime, endTime, description, soundAlarmWhenStarting, (room)
d) roomNumber, desiredTemperature, currentTemperature, heatingOn,
airConditioningOn

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A4

e)*callerNumber, calledPartyNumber, isConnected, startTime, currentCell,


signalStrength, totalCost
f) lineNumber, isOperating
E2.5

p. 35 Identifying associations
a)*boughtFrom:ProductionCompany, producedBy:Producer, episodes:Episode,
leadActors:Actor
b) bookings:Booking
c)* meetingRoom: MeetingRoom
d) building:Building
e)*caller:CallParty, called:CallParty
f) productBeingProduced:Product,

E2.6

p. 35 Differentiating between variables and objects


a)*Object
b) Object
c) Variable

E2.7

p. 36 Identifying operations
In the following, operations that would probably be polymorphic are shown in italics, however, exactly which
operations are polymorphic would depend on the design.
a)*getArea, getPerimeterLength, getPoints, move, resize, rotate,
flipHorizontally, flipVertically
b) getName, getDepartment, getWard (except Doctor), getRoom (Patient only),
getDiagnosis (Patient only), getSpecialty (Doctor and Nurse only)
c) getName, getNumberOfPages (except Videotape), getRunningTime (Videotape only)

E2.8

p. 40 Identifying poor generalizations


a)*Bad: You cant say A Canadian dollars is a money; also CanadianDollars should be an instance of
Currency
b) Bad: You cant say An account is a bank
c)*Probably OK.
d) Bad: You cant say A chequing account is a savings account
e)*Bad: Account12876 would be instance of BankAccount (or some subclass of BankAccount)
f) Bad: You cant say A customer is a people. The word people is either used in the plural, or else means
nationality.
g) Acceptable for now, however we will learn later that there are some problems with this type of
generalization GraduateStudent might be better as a subclass of a class called StudentRole
h) Bad: You cant say A country is a continent
i) May be OK. Whether a city can be defined as a special kind of region depends on the political structure of
each particular country.

E2.9

p. 41 Analysing the consequence of making Quadrilateral & Rectangle subclasses of Polygon


The same problems arise as when you make Circle a subclass of Ellipse: Some things you can do with a
Polygon, such as moving an arbitrary point, you cannot do with a Rectangle; also, while you might be
able to add or delete a point from a Polygon, you wouldnt want this capability to be inherited by
Quadrilateral. One solution is not to have a separate Rectangle or Quadrilateral class at all,
and just use instances of Polygon that happen to be constrained appropriately. Another, probably superior,
approach is to make Polygon abstract, and make separate subclasses of it: such as Quadrilateral and
ArbitraryPolygon. This is the solution taken in Figure 4.3.

E2.10 pp. 41-42 Arranging potential classes into inheritance hierarchies (See also E5.21, p. 189)
In the following, the hierarchies are shown using indented text to save space. Whether it would be appropriate
to actually include all the classes in a given system would depend on the applications requirements. There are
many possible variations on these answers. Note: See also E5.21 for additional exercises based on these
problems.
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A5

ANSWERS TO EXERCISES

a)*In this problem we create two separate hierarchies, Vehicle and PartOfVehicle. These could also
have something like Machine as a common superclass, although the problem suggested creating separate
hierarchies.
Vehicle
LandVehicle (Added)
Car
SportsCar
Truck
Bicycle
AirVehicle (Added)
Aeroplane
AmphibiousVehicle
PartOfVehicle
Engine
JetEngine
ElectricMotor
Wheel
Transmission
Vehicle could instead be divided into PoweredVehicle and UnpoweredVehicle; multiple
inheritance could be then used for superclasses of the vehicle leaf classes.
b) This problem is trickier than the last, since most students will initially not figure out the distinction among
the first three hierarchies.
EditionOrIssue (Added to represent members of a series, these can have copies)
EditionOfBook
IssueOfNewspaper
IssueOfMagazine
Copy (Added to represent physical things one can check out of a library)
CopyOfBook
CopyOfIssueOfMagazine
Publication (The general things that can have editions or issues)
WorkOfLiterature
Periodical
Magazine
Newspaper
PartOfPublication (Added)
VolumeOfBook (Changed name to make clearer)
Chapter
Author
Publisher
Author and Publisher could perhaps be given a common superclass such as LegalEntity
c)*Schedule (We will learn later that this may not be needed since the whole system stores the schedule)
RegularlyScheduledTrip (Added as a superclass representing something that runs at a given time)
RegularlyScheduledExpressBus (renamed for clarity)
BusRoute
ActualTrip (Runs at a given time on a given day; could also be called Run)
CharteredTrip (Renamed for clarity)
ScheduledTrip (Added to properly complement unscheduledTrip)
UnscheduledTrip (Runs on a route, but not at the normal time)
BusVehicle (Renamed from bus to distinguish different types of bus)
LuxuryBus
TourBus
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A6

d) ElectronicDevice (Added)
RecorderOrPlayer (Added)
VideoRecorderOrPlayer (Added)
VideoCassetteRecorder (Avoid 3-letter class names)
AudioRecorderOrPlayer (Added)
AudioTapeDeck
RemoteControl
TelevisionSet
WorkOfArt (Added)
Film (More general word than Movie, Sound Of Music would be an instance)
Song (Added for consistency)
VersionOfSong
RecordingMedium (Independent of the individual items recorded on it)
Cassette (Added, but may not be necessary)
VideoCassette (Added to complement AudioCassette)
AudioCassette
CompactDisc (Avoid 2-letter class names)
DigitalVideoDisc (Avoid 3-letter class names)
CopyOfRecording (Better name than item on tape; several could be on any RecordingMedium)
CopyOfFilm (Renamed for consistency)
CopyOfSong (Better name than song on CD)
The hierarchy of Cassette could be a hierarchy of Tape instead.
e)*Currency (Canadian Dollars and US Dollars are Instances)
ExchangeRate (Attributes or associations could be fromCurrency, toCurrency, rate)
FinancialInstitution (Added)
Bank
CreditUnion
CreditCardCompany (Visa and MasterCard are instances)
FinancialInstrument
ReusableFinancialInstrument (Added)
CreditCard
DebitCard
SingleTransactionInstrument (Added)
Cheque
BankAccount
Loan
ElectronicDevice (Added)
AutomaticTellerMachine (better than BankMachine)
BankBranch
f) HotelCompany (Hilton is an instance)
Hotel (Ottawa Hilton is an instance)
RentableSpace (Added)
HotelBedroom (Renamed from hotel room for clarity)
MeetingRoom (probably same as conference room)
Ballroom
Suite
Person (Added)
MeetingOrganizer
Guest
Booking (same as Reservation)
Event (Added)
CateredFunction
Meeting
Conference
ItemOnBill
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A7

ANSWERS TO EXERCISES

g) InsurancePolicy
AutomobilePolicy
HomePolicy
LifeInsurancePolicy (Renamed for clarity)
Transaction (Added)
Claim
PolicyRenewal
Deductable (Could also simply be an attribute)
Person (Added)
InsuranceClient (Could also simply be an attribute)
Beneficiary (Could also simply be an attribute)
InsuredProperty
h) ElectronicDevice (Added)
Telephone
PhoneLine
DigitalPhoneLine (Renamed for clarity, but digital may work better as an attribute)
ExtensionLine (Renamed for clarity)
PhoneCall
ConferenceCall
Feature
CallWaiting (Could be an instance of Feature instead)
CallForwarding (Could be an instance of Feature instead)
VoiceMail (Could be an instance of Feature instead)
CallStatus (Added)
CallOnHold (on hold may work better as an attribute of PhoneCall)
ForwardedCall (Forwarding information may be better as attributes of PhoneCall)
Caller
TelephoneNumber
VoiceMailMessage
VoiceMailBox
E2.11 p. 47 Describing how polymorphic implementations of certain shape operations would work.
a)*translate: In SimplePolygon (as inherited by Rectangle and RegularPolygon), and
EllipticalShape (as inherited by Circle), the method translate would move the center.
b) changeScale: In Rectangle, the method changeScale would multiply the height and width
by its argument. In RegularPolygon it would multiply the radius by the argument. In
EllipticalShape (as inherited by Circle) it would multiply the semiMajorAxis (which acts as
the radius) by the argument.
c)*getArea: In Rectangle, the method getArea would return height * width. In
RegularPolygon, it would compute the area by dividing the polygon into numPoints individual
triangles (see the answer to E2.30 for the detailed algorithm). Once this area is calculated, the total area of
the RegularPolygon would be calculated by multiplying the area of each triangle by numPoints. In
Circle, the method getArea would return pi * radius2.
d) The getCenter method inherited by Shape2D would always be used. No overriding methods would be
needed.
E2.12 p. 47 Incorporating new polymorphic operations into an existing class hierarchy.
There would be an abstract methods in Shape2D, since flipHorizontally and flipVertically
would make sense for all classes. There would have to be specific concrete methods in the following classes:
Ellipse (would just adjust the orientation since an ellipse is symmetrical)
Circle (would do nothing)
SimplePolygon (would simply adjust the orientation appropriately)
ArbitraryPolygon (would have to move each of the points)
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A8

E2.13 p. 47 Incorporating new classes into an existing class hierarchy that contains considerable polymorphism.
a)*IsoscelesTriangle: One might think of making this a subclass of ArbitraryPolygon, however
that would be inappropriate since you dont want it to inherit methods such as addPoint and
removePoint. A better solution is to make it a subclass of SimplePolygon. As attributes you would
have to store the baseLength and height, or else you could store one of the two values for angles and
the length of one of the sides, letting the other angle value and side be computed when needed. As
methods, you would need changeScale, setBaseLength, setHeight, getArea,
getPerimeterLength, getVertices, getBoundingRect, getBaseAngle, getTopAngle,
and perhaps setBaseAngle and setTopAngle.
b) Square: This should probably not be a subclass of Rectangle, since a Square can have a simpler
implementation than a Rectangle. One solution is to make a new sub-hierarchy with
RectangularShape as the abstract superclass (a subclass of SimplePolygon), and make
Rectangle and Square subclasses of this. However, it turns out that there will be almost no shared
attributes or methods between Rectangle and Square, except for those inherited from
SimplePolygon and above. Therefore, Square can be simply made a subclass of SimplePolygon.
In this case it would have a sideLength attribute, and methods changeScale, setSideLength,
getArea, getPerimeterLength, getVertices, getBoundingRect and getSideLength.
E2.14 p. 47 Designing the details of shape operations.
Methods addPoint and removePoint would have to maintain the points in order, since depending on
the order of the points, different shapes would result. Also, it is important to note that changing a point
would affect the geometric center(to visualize this, imagine adding some points far from the existing
points). The addPoint and removePoint methods would therefore either have to modify the center
instance variable, or else adjust all the other points so that the center remains the same.
E2.15 p. 47 Determining the methods needed to polymorphically implement an operation.
There would be separate getEnclosingCircle methods in each leaf class, and an abstract
getEnclosingCircle operation in Shape2D. Here are descriptions of the implementation of
getEnclosingCircle in the various leaf classes:
In Circle, the method getEnclosingCircle would simply return itself.
In the other leaf classes, the methods would compute the radius of the new Circle as the distance to the
farthest point from the centre; they would use the same centre as in the original shape.
The radius used for the enclosing circle of an Ellipse would be the semiMajorAxis.
The radius used by Rectangle would be sqrt((height/2)2 + (width/2)2).
The radius used by RegularPolygon would be the same radius as the original shape.
To compute the enclosing circle of an ArbitraryPolygon, it would be necessary to compute the
distance of each point from the centre and find the maximum of those distances.
E2.16 p. 48 Determining immutable operations that may return instances of a different class.
You might add a changeScale(x,y) method to several classes; this would distort a shape by a
different amount in the x and y dimensions. In RegularPolygon such a method would return an
ArbitraryPolygon (since the result would no longer be regular). Similarly, distorting a Rectangle
that was rotated would result in an ArbitraryPolygon.
The addPoint and removePoint methods of ArbitraryPolygon could be made to determine
whether the resulting shape was now in fact a Rectangle or a RegularPolygon, and return an
instance of the appropriate class.
Similarly, the changeNumPoints method of RegularPolygon might be made to return a
Rectangle if the number of points was set to four.
If you made either of the above two changes, you should presumably add changeNumPoints to
Rectangle that would convert one into a RegularPolygon or an ArbitraryPolygon.
(However, if the rectangle is not square, it is be unclear exactly where the extra point should be added.)
You would also need to add addPoint and removePoint methods to Rectangle and
RegularPolygon that would return instances of ArbitraryPolygon.
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A9

ANSWERS TO EXERCISES

E2.17 p. 49 Determining when dynamic binding is needed in a set of polymorphic methods.


This exercise has turned out to be particularly useful to ensure students really understand the implications of
polymorphism. Before assigning this exercise, it has proved to be necessary to explain the material on pages
48 and 49 particularly carefully, with several examples. Note that the exercise has the assumption, that the
compiler knows that no new classes or methods can be added to the hierarchy; it is worth reminding students
that this is not generally true in Java (you can add a subclass unless the class is declared final, and you
cannot declare a non-leaf class to be final).
a)*Invoking getPerimeterLength on a Rectangle variable: No dynamic binding is needed since
Rectangle is a leaf class and so the variable could only ever contain an instance of that class. The local
method in Rectangle would always be called.
b) Invoking getCenter in a SimplePolygon variable: No dynamic binding is needed since there is only
one getCenter method in the hierarchy of SimplePolygon (the one inherited from Shape2D).
c)*Invoking getBoundingRect on a Polygon variable: Dynamic binding would be needed, since either
the method in Polygon or the one in Rectangle might have to be executed depending on which class
of object is placed in the variable at run time.
d) Invoking getScale on an ellipticalShape variable: This is a misprint that we will try to correct in
a future printing. Actually, we meant to say changeScale. In that case, dynamic binding would be
needed to choose between the changeScale methods in Circle and Ellipse.
e) Invoking translate on a RegularPolygon variable: No dynamic binding is needed since
Rectangle is a leaf class (the method inherited from SimplePolygon would always be called).
E2.18 p. 51 Researching products that claim to be object-oriented to determine if they really are.
The answer to this question will vary over time, depending on what products are available.
E2.19 p. 53 Using documentation to look up library classes and thus better understand a program.
This is a purely practical exercise. Its purpose is to encourage students to get in the habit of using
documentation.
E2.20 p. 53 Fixing an inconsistency in the Postal Code program.
Java code is provided in the accompanying zip file. In this exercise, there were two simple changes that could
have been made to either the PostalCode or CanadianPostalCode classes. Both would have resulted
in a correct answer.
In PostalCode, one can change the constructor so that it transforms the code parameter to upper case.
This is done by calling the toUpperCase method located in java.lang.String.
In CanadianPostalCode, the solution is equally simple. In its validate method, it is only
necessary to remove the calls to the isUpperCase from the java.lang.Character utility class
from the if block..
E2.21 pp. 53-54 Designing modifications to the postal code program.
a) It is only necessary to add the length method to PostalCode. It would return the value returned by the
length method from the java.lang.String class.
b) It is only necessary to modify the PostalCode class. The exercise suggested the
java.io.FileInputStream be used, therefore the solution was implemented using that class.
The way this method works is that it opens a file and then reads one byte at a time until it reaches a
newline character, which is the delimiter of a postal code. After that, it creates a String object from the
characters read and compares it with the code contained inside the PostalCode object. If they are equal,
the method exits the loop and returns true, otherwise it will keep reading a single line at a time until it
either finds a match or reaches the end of the file. If the end of the file is reached and no match is found,
the method returns false.
There is a simpler way to implement a solution to this exercise using a combination of the
java.io.BufferedReader
and
java.io.FileReader
classes.
By
using
the
java.io.FileInputStream class, we are limited to reading a single character at a time. The
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A10

java.io.BufferedReader and java.io.FileReader classes have methods that allow reading


an entire line at a time from the file.
c) You have to modify every subclass of PostalCode to add a call to a method that opens a file containing
destinations. This method is located in PostalCode. As with part b, we used
java.io.FileInputStream to read from the destinations file. We then proceed to separate the
prefix from the actual destination. The prefix indicates the destination, therefore we only need to check if a
postal code starts with the prefix we just read from the file. This is done with the call to the
startsWith() method located in the java.lang.String class. If the prefix matches, we return the
destination; otherwise, we continue to attempt to find a match until one is found or the end of the file is
reached. In the latter case, if no known prefix is found, an exception is thrown. This exception is dealt with
by PostalCodes subclasses. Note that throwing the exception was not the only way to deal with an
unknown destination. Other solutions such as returning null are also valid ways to deal with such an
occurrence.
E2.22 p. 54 Implementing modifications to the postal code program.
Java code is provided in the accompanying zip file.
E2.23 p. 54 Designing and implementing a new subclass in the existing Postal Code hierarchy.
To add the Ootumlia postal codes, we added a class called OotumliaPostalCode and made it a subclass
of PostalCode. We followed the model of all the other classes when implementing the constructor and the
getCountry() method. Validating the code was similar to validating the British postal codes. We simply
read each character and verify that it is something that could be expected at this position. Modifying the
PostalTest class only involved adding a block of code to attempt to generate this class of object as was
done with the pre-existing classes. The oocodes.txt file contains prefixes for the Ootumlia codes and the
destination associated with them. Java code is provided in an accompanying zip file.
E2.24 pp. 55-56 Evaluating and implementing design alternatives for the PointCP class hierarchy.
a) If a programmer knows that his or her program is going to be doing a lot of operations that would access
Cartesian co-ordinates (x and y) then it would be much more efficient to have the internal storage in
Cartesian form, rather than forcing each access to convert from Polar form. Similarly if the programmer
knows, in another part of the program, that a lot of access will be done to the polar co-ordinates, then it
would be better to convert to that format in advance.
b) The problem arises because floating point numbers are often imprecise approximations of real numbers. In
general, if you convert data from back and forth from one format to another, you run the risk of losing
accuracy, since small rounding errors can occur in each conversion.
c) Complete code is provided in the accompanying zip file.
We first generate a random Cartesian point. Methods are provided in PointCP to transform a point
from Cartesian to polar and vice-versa. Using these methods, we convert the point into polar form and
attempt to calculate the X and Y co-ordinates of the point. We compare these values to the original ones,
which are stored in variables. We issue a warning if these values are not identical. We then reconvert the
point from polar form back to Cartesian form and compare the original values with the ones we now have.
If these values are not identical, we issue an error message along with the differences involved.
The answer to this should, ideally, be the same in each Java VM. We have, howeer, heard reports that
some operating systems and Java versions give different results.
More details to be added regarding the conclusions from running the above program.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A11

ANSWERS TO EXERCISES

E2.25 p. 56 Tabulating the pros and cons of design alternatives.


Design 1: Store one type of coordinates using a single pair of
instance variables, with a flag
indicating which type is stored.

Design 2: Store polar co-ordinates


only

Advantages
Allows the programmer to easily
optimize his or her program if there is a
need to use both types of co-ordinate
system in different parts an algorithm
the programmer can quickly experiment
with the co-ordinate storage format of
each object to determine which gives the
best results.
Very simple; uses the least memory.

Design 3: Store Cartesian coordinates only


Design 4: Store both types of coordinates, using four instance
variables

Same as above.

Design 5: Abstract superclass with


design 2 and 3 as subclasses

Uses the least memory; allows the


designer to optimize the case where one
type of access is performed most
frequently; allows the programmer to
take advantage of polymorphism,
although it is unclear whether this would
be used much. Has simple constructors
(no need for the p or c flag).

Very fast access guaranteed


particularly useful when computations
are performed that need both types of
co-ordinates frequently.

Disadvantages
Somewhat complex; could give bad
performance if the wrong type of
data is stored and the programmer
does not optimize.

Makes inefficient use of CPU if the


other type of co-ordinates is most
often needed.
Same as above.
Uses the most memory; makes
inefficient use of CPU if new objects
are created frequently and then
discarded without taking advantage of
the ability to access both types of coordinate. This inefficiency would
result from the need to always
compute the other type of coordinate when creating an object.
Dynamic binding might slow
computations somewhat if variables
were declared as the type of the
superclass.

E2.26 p. 56 Implementing an alternative design for the PointCP class hierarchy.


Full Java code is provided in the accompanying zip file.
In implementing Design 5, we created a Point class and two other classes PPoint and CPoint, which
are subclasses of Point, to deal with polar and Cartesian co-ordinates respectively. By doing so, we
eliminated the need for the typeCoord variable which contained the type of co-ordinate. The third argument
in the constructor, which was the initial value of typeCoord is no longer necessary.
The Point class is abstract and contains abstract versions of all the methods originally implemented in
the PointCP class. CPoint and PPoint classes will have different implementations of these methods, but
the code for each remains the same as in the PointCP class. The subclasses only contain the block of code
referring to their specific type.
The following are examples of how parts of the code have been transformed:
Design 1:
public double getX()
{
if (typeCoord == 'C')
return xOrRho; // Now in CPoint
else
return (Math.cos(Math.toRadians(yOrTheta)) * xOrRho);
}
Design 5: (PPoint.java)
public double getX()
{
return (Math.cos(Math.toRadians(theta)) * rho);
}

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

// Now in PPoint

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A12

Design 5: (CPoint.java)
public double getX()
{
return x;
}

E2.27 p. 56 Conducting a performance analysis.


Full Java code is provided in the accompanying zip file.
In this exercise, the objective is to run a performance analysis to compare Designs 1 and 5 of the Point
example.
The first class we wrote, PointTest, contains only a main method designed to execute the analysis. To
do this, it creates 100,000 instances of both Cartesian and polar points using the implementation of Design 1.
It then performs all the possible operations on each of these points while keeping track of the necessary time
in milliseconds. We restart the whole operation with 100,000 instances of both PPoint and CPoint.
Currently, keeping track of time in milliseconds is accomplished by the use of the getTimeInMillis
method from java.util.GregorianCalendar class. However, this method is protected, meaning that
it can only be accessed from within the class in which it is contained or a subclass. Therefore, to be able to
access it, we write a class, ExtendedCalendar, which extends java.util.GregorianCalendar
and create a method within this class whose only purpose is to access the protected getTimeInMillis
method. Note that a perfectly good alternative solution would have been to use
System.currentTimeMillis() to get the times. We plan to modify the code to reflect this
improvement.
E2.28 p. 56 Improving the clarity of a design.
a) The method getInput is excessively complex for several reasons:
It has too much nesting, relative to the simple function it is performing. At its deepest it has an if
within an if within a try within a while within a for.
Each time through the outer for loop, the code behaves differently depending on the value of the
variable i. This is not clear programming because the reader cannot see at a glance what the outer loop
is supposed to do. It would perhaps be better if the variable i was named something like inputStep,
but that is only a partial solution.
b) To simplify the code, we only needed to change the static method getInput to remove the complex pair
of loops and replace it with 3 do-while loops. Each of these loops prompts the user to enter a certain value
and then validates the data. If the data that was entered is found to be invalid, either because an exception
was thrown, or because the data was not in the proper range, the loop is repeated until valid input is
obtained. The commands that create the PointCP object that is returned remain unchanged.
c) Complete code is provided in the accompanying zip file.
E2.29 p. 56 Designing, implementing and evaluating a design that makes use of interfaces.
Complete code is provided in the accompanying zip file.
There is not much difference between this solution and the solution to exercise 2.26. The most important
difference lies in the elimination of the Point superclass. Since all the methods in Point were abstract,
there was not much difference between it and the new PointCP interface. By definition, an interface is a
collection of abstract methods and constants. Any class which implements a particular interface must provide
a concrete implementation of all the methods defined within that interface or else must be declared abstract.
In the case of this example, the PPoint and CPoint classes both implement the PointCP interface and
provide concrete implementations of the methods defined within the interface. The implementation of these
methods are identical to the ones in exercise 2.26. Slight modifications were made to some of the method
headers and to the PointTest class. The methods which used to return a Point object now return a
PointCP object and the PointTest class was modified to create PointCP objects instead of Point
objects.
Further evaluation to be provided.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A13

ANSWERS TO EXERCISES

E2.30 p. 59 Implementing a complete class hierarchy of shapes.


Complete code is provided in the accompanying zip file.
This exercise is an implementation of the geometric shapes hierarchy discussed in Section 2.6. All the
operations defined within this class are basic mathematical operations such as rotation, translation, resizing,
etc. Formulae for these can be obtained from a basic geometry textbook.
Worth mentioning is the fact that in the ArbitraryPolygon class, all points are relative to the
center. In this case, the center of the shape is treated as the intersection of the x and y axis in the Cartesian
system. Therefore, when rotation of the shape is demanded, we rotate the points around the center as though
we were rotating them around the origin.
Note that two methods were left incomplete. These are the getArea of ArbitraryPolygon and
getBoundingRect of Ellipse. To calculate the surface of an ArbitraryPolygon, it is first
necessary to divide it into triangles and then calculate the area of each of these triangles and sum them
together. This has not been implemented. The second method, calculating the bounding rectangle of an ellipse
is quite a challenge when the ellipse is rotated at angles which are not multiples of 90 degrees. To accomplish
this, it is first necessary to use numerical methods to calculate the maximal and minimal values of x and y.
E2.31 pp. 59-60 Formal laboratory experiment: Conducting a performance analysis of Java classes.
Code for this is provided in the accompanying zip file.
This exercise is another performance analysis exercise. Four classes were necessary to complete it, These
are named CollectionTestVersionX, where X is from 1 to 4. Each contains the solution to part X of
the exercise.
Some points to note regarding the implementation:
All the Java collection classes can only accept objects that are subclasses of java.lang.Object.
Therefore, the primitive types, such as int, could not be added and must therefore be transformed into
their corresponding type. For an int, the corresponding type was java.lang.Integer, for
float it would be java.lang.Float.
Part iii) made use of an Iterator. However, part iv) does not. The reason is that when using an
Iterator, the collection cannot be modified by anything other than the Iterator. Since the
Iterator interface does not provide an add method, we cannot use it without causing a
ConcurrentModificationException to be thrown.
To generate pseudo-random numbers, Java uses the java.util.Random class. An object of this
class must be instantiated and methods such as nextInt must be called upon it in order to generate
the numbers.
Additional discussion of results to be provided.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A14

Chapter 3. Basing software development on reusable technology


E3.1

p. 63 Researching resources on the Internet that discuss aspects of reuse.


The answer to this question will vary since web pages are continually being added, deleted and changed.

E3.2

p. 63 Analysing information about reuse.


For discussion only.

E3.3

pp. 69-70 Determining the services that should be present in a framework.


a)*Reservation framework.
Add an instance of whatever that can be reserved (e.g. a book, a place on a flight, a seat in a theatre)
Add an instance of whatever the reservation is made on behalf of (e.g. a library patron, a passenger, a
theatre-goer).
Make a reservation
Delete a reservation
b) Scheduling framework.
Add a scheduled event (e.g. a meeting, a run of a bus along its route)
Add a regularly scheduled event (e.g. a meeting held at the same time each week, or a run of a bus that
occurs at the same time each day)
Delete an event
Change the time of an event
Change the description of an event
Add an object that will attend or make the event operate properly (e.g. a person attending a meeting, a
physical bus vehicle that will pick up passengers as scheduled)
c) Language-processing framework. (This part would only be appropriate for students familiar with
parsing)
Add a definition for a pattern (e.g. grammar rule) that will be used to match specific input, and will add
objects to a data structure representing the input.
Add a definition for the action to perform in response to the input, once it is processed.
Process a unit of input from some source, taking the appropriate action.

E3.4

p. 70 Determining differentiating features of framework-based applications, as well as its hooks and slots.
a)*Reservation framework.
Differentiating features:
- The classes of objects that can be reserved and their attributes, associations and other operations
- The attributes of the reservation itself, and perhaps subclasses representing different types of
reservation
- The classes of objects that a reservation can be made on behalf of
- The user interface
- Rules regarding the reservation, such as who can make one, whether the item can be reserved, etc.
Hooks:
- A function that would be called when a reservation is complete (e.g. to send an email)
- An function to call when reservations are full that could be used, for example, to add a waiting list,
or to give some form of notification to the user.
- A function called to load a reservation from a database.
- A function called to save a reservation.
Slots:
- There may be no slots in this system.
b) Scheduling framework.
Differentiating features:
- The classes of events to be scheduled
- The classes of objects that will be attend/operate the event
- Rules for how scheduling is managed
- Automatic scheduling algorithms
- The user interface

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A15

ANSWERS TO EXERCISES

Hooks:
- A function to be called when an the time for an event arrives (e.g. to sound an alarm or send an
email)
- A function to be called when a reservation changes (e.g. to notify people of changes)
- A function to be called when an event is complete
Slots:
- There may be no slots in this system.
c) Language-processing framework.
Differentiating features:
- The grammar or patterns
- The actions to be taken
- The feedback on inappropriate input
- The sources of input
- The destinations of output
- The chunk size of input (whether the input is processed one token at a time, one line at a time or a
file at a time, before any actions can be taken).
Hooks:
- A macro pre-processor that would be invoked prior to processing input.
- A post-processor that could do extra processing on the output.
- A logging mechanism that would count the commands, statements, etc. processed.
- Code to generate understandable output when certain kinds of standard errors are encountered (e.g.
nothing matches the input, end-of-file, etc.). Most of the time, you would expect these hooks to be
filled, but there may be certain applications where the default do-nothing response is needed.
Slots:
- There may actually be no slots. This would mean that the basic system could function by having a
user interface simply call the services.
E3.5

p. 70 Determining the range of applications that might benefit from a framework.


a)*Reservation framework.
A library system, where you can reserve items that are already checked out
Reservation of seats on any kind of transportation system
Reservation of entertainment tickets
b) Scheduling framework.
Scheduling people to attend events
Personal calendar application
Scheduling vehicles to provide transportation services
c) Language-processing framework.
A programming language of any kind
A command language, e.g. for commands sent to a server, which could include doing database queries

E3.6

p. 70 Evaluating alternative approaches to designing a framework.


a)*If you started with a vertical framework for a frequent flier program, you would have a lot of facilities
already developed, some of which would be quite specific to the frequent flier domain. The following
gives some ideas of the services, slots and hooks that might be provided; many variations on this answer
are possible.
i. Services:
Maintenance of frequent flier accounts to which points (miles) can be added and redeemed (i.e.
adding new accounts; deleting accounts)
Keeping of basic personal information (name, address, points) about each frequent flier, with
methods to update this information (which would call the first hook below to allow managing of
additional information)
Keeping of a log of flights to be used when producing reports (would also be capable of recording
other transactions, e.g. points awarded for renting a car).
Methods to add, delete and query the number of points in the account.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A16

Generic mechanism, given two cities, that would calculate how many points would be required to
fly between them for free for a given user. This would be called when customers are doing queries,
and also when a person actually books a free flight to determine how many points to deduct. This
would call the first slot below to do detailed calculations.
Generic mechanism, given two cities, that would calculate how many points to credit to a particular
frequent flier who pays for a ticket. It would be called when the user is making queries, and also
when a person actually takes a flight, in order to credit points. This would call the second slot below
for detailed calculations.
Generic mechanism that runs every month, calling the slot (below) for producing reports, and the
hooks (below) for deleting inactive accounts, and perhaps promoting users to different classes.
ii. Slots (code that must be provided)
A method to evaluate rules regarding how many points are required to fly certain routes for free.
A method to evaluate rules regarding how many points are obtained from flying certain routes
(might be specific to certain classes of frequent flier, certain times, etc.)
A method to produce a formatted printout of a frequent fliers account (each airline may want to
make these appear stylistically different from other airlines). Note that instead of creating a slot, this
functionality could be left out of the framework entirely.
Note that the user interface would have to be provided, but would probably not actually appear as
slots in the basic system; the user interface would be a separate subsystem that would simply call the
services.
iii. Hooks (places where optional add-ons can easily be plugged in)
Ability to manage additional types of information about frequent fliers (e.g. work address, email,),
beyond the basic minimum information. Different airlines might want to keep different kinds of
information for use in marketing etc.
Ability to have different classes of users (e.g. prestige users who have accumulated large numbers of
points)
Mechanism to delete accounts after a certain time period with no activity (this might be activated by
the monthly run that prints reports)
Ability to add different kinds of points to be used for different purposes (e.g. some airlines, in
addition to miles, also keep track of a separate count of miles flown in first class; such points might
have different rules, such as expiring after the end of a year).
b) If you wanted to create a horizontal framework that would work for any kind of frequent buyer program,
your framework would be much more basic and generic. For example, it would not have such specific
classes as Flight, instead you would have more general superclasses of these such as Purchase. Such
a framework would require considerably greater effort to turn into a frequent flier application.
i. Services:
Maintenance of accounts to which points can be added and redeemed (same as in part a, above)
Maintenance of basic personal information (same as in part a)
Keeping a record of transactions (unlike part a, this would not have any specialized knowledge of
flights with origins and destinations)
Methods to add, delete and query the number of points (same as in part a)
ii. Slots (code that must be provided)
A very simple framework such as this may not have any slots it might simply provide the above
services that could be used by any software that wants to add and delete points.
iii. Hooks (optional add-ons)
Ability to add extra details to each transaction (e.g. so that each transaction could track the flight
number, origin and destination city)
Ability to add extra details to the personal information (similar to part a)
E3.7

p. 70 Evaluating whether or not one should first develop a framework when designing an application.
a)* Arguments in favour of developing a full frequent flier framework:
Developing the framework improves your overall design. Since you would have to build flexibility into the
framework to allow it to be used by others, you would benefit from that flexibility when you have to make
changes yourself.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A17

ANSWERS TO EXERCISES

As a consequence of the above, you would expect maintenance costs to be reduced; you would also expect
to be able to respond faster to market-driven requirements changes.
You might be able to sell your framework to others, or to provide frequent-flier services to other smaller
airlines.
Should two airlines using the same framework decide to work together in an alliance (or to merge) their
systems would be more compatible with each other, reducing costs.
b) Arguments against developing a frequent flier framework:
The time to develop a framework, although an investment, might somewhat delay the day when the first
release is available. This is probably the biggest obstacle.
The total amount of code might be greater than if you did not use a framework, so if you do a bad job of
designing the framework and have to abandon it, you have lost more.
It might require greater effort to convince management that framework-development is the best approach.
E3.8

p.74 Evaluating whether an application should be designed as a client-server system or not.


a)*Word processors are not normally designed using a client-server architecture. The following are some of
the reasons why not:
People typically use word processors on laptop computers or other machines that may not be connected
to any network.
Although people do share word-processed data, most people work on their own local copy and then
share it when they are finished.
It might be beneficial to allow a word processor to optionally connect to a server to do such things as load
and save data, or to enable two people to edit the same document concurrently. However it would still be
necessary to ensure that the user could operate the program while not connected.
b) Like a word-processor, it would be important to allow the user to use his or her personal calendar
program while disconnected from the network. However it would also be very useful if, while connected,
the program could communicate with other programs. This could enable several people to automatically
co-ordinate a time when they are both available. It could also permit the user to be notified of changes in
schedule such as meetings booked by his or her manager or secretary, or event cancellations. The personal
calendar program, running on a personal digital assistant, could also act as a client to a desktop version.
c) A home alarm system could be configured as a client that is constantly connected to a server. In an
alternative design, the client could connect to the server only if some emergency were detected. However,
an advantage of maintaining a constant connection would be that if that connection were severed, this
would be a sign of trouble.

E3.9

p.74 Determining the services to be provided by a server.


a)*An airline reservation server would be expected to do some of the following activities:
Maintain the list of flights along with basic details of each flight (and allow changes)
Maintain the prices (and allow changes, special offers etc.)
Maintain the bookings (allow bookings to be made, changed and deleted)
Allow people to query all of the above
b) A toll-free number server might do the following:
Map a toll-free number into a normal toll number. The mapping might depend on the calling number or
area, the time of day, and the availability of various actual numbers (whether they are busy or not).
Track the number of mappings performed and allow queries about this information.
Allow queries about the customer to whom a toll free number belongs, and to whom bills will be sent.
This information might be used when producing a directory, or when a member of the public does an
on-line query. The information would also be used by the telephone companies for billing purposes.
c) The server at the centre of a building alarm system would do such things as the following:
Take pre-programmed actions (e.g. sounding an alarm, calling the fire department) in response to
signals received from various sensors.
Report on the status of the system, to allow either remote monitoring displays of where trouble exists.
Configure new devices on the system.
Set up specific actions to be taken in response to particular signals.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A18

E3.10 p. 79 Evaluating the balance of work on the client and server side of a system.
a)*For an airline reservation system:
i. Server work: See exercise E3.9.
ii. Client work:
Enter queries about available flights and display the results.
Enter bookings
Display and print itineraries
iii. Information transmitted from server to client:
Results of queries (relatively simple text)
iv: Information transmitted from client to server:
Simple commands and their arguments.
v: How the clients work could be minimized or maximized:
The client might be interacting with several different reservation systems, producing overall
itineraries that would combine the results from several servers. A server could be developed to
provide this function interacting with other servers and managing itineraries.
The client could, on the other hand, be given a lot of intelligence to work out itineraries and good
deals. It could find the best prices, and even run a bidding mechanism that would try to get airline
servers to give better deals.
The client could simply be a web browser with no intelligence at all about the frequent flier domain.
vi: Network effects of changing the clients workload:
Putting more intelligence into the server (such as having the server interact with other servers)
would have only a moderate effect on the quantity of information transmitted in the network as a
whole.
Adding extra intelligence to the client might result in large numbers of queries being transmitted,
and large numbers of replies returned. The client would need to perform these queries in order to
marshal the information it needs to make decisions.
Having the client become nothing more than a web browser, would probably increase network
traffic from the server to the client, since now the server would have to transmit images and all the
other information that will make the UI of the client look nice.
b) For a toll-free number server:
i. Server work: See exercise E3.9.
ii. Client work:
Making calls (it asks the server for the actual toll number to call and bill)
Presenting statistical information to phone company systems.
iii. Information transmitted from server to client:
Very simple pieces of data (primarily phone numbers)
iv: Information transmitted from client to server:
Very simple commands
v: How the clients work could be minimized or maximized:
For this application, the client could cache the mappings so that if telephone users repeatedly dial
the same toll free number within a specified period of time, the client would not have to repeatedly
query the server.
The database of mappings could be distributed to several sites so that the impact on any one server is
reduced.
vi: Network effects of changing the clients workload:
Caching would reduce the total number of queries needed.
Distributing the database would mean that queries could be made locally if there was a local server.
c) For a central building alarm server:
i. Server work: See exercise E3.9.
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A19

ANSWERS TO EXERCISES

ii. Client work:


Some clients may simply send messages (e.g. alarms) to the server, and receive nothing in response.
Others might communicate with the server in more sophisticated ways.
Clients might check in to the server periodically, reporting their status. In other cases, the server
may poll, clients regularly asking them to report their status; in that case the clients are acting like
servers since the central system is now initiating the communication.
There might be a separate client (i.e. an end-user configuration and query console, as opposed to a
sensor) that allows updating of configuration information and permits queries about the system.
iii. Information transmitted from server to client:
For the clients that provide information to the server, there may be no communication to the client,
or merely simple data to do such things as confirm that messages have been received.
For a configuration/query client, the data would be lists of status information.
iv: Information transmitted from client to server:
Alarms.
Status information.
Requests for information and updates to the configuration data
v: How the clients work could be minimized or maximized.
The configuration/query client could be a web browser.
vi: Network effects of changing the clients workload:
Making a client into a web browser would increase network load a little, however the overall load
on a network from an alarm system would normally be so small, that network load would not be an
issue.
d) For the web:
i. Server work:
Sending static pages or applets to clients
Computing dynamically the contents of pages (the programs that generate dynamic content might be
passed data from forms, information from cookies and entire URLs examples of systems for
computing dynamic content include ColdFusion , JSP, ASP etc.).
Handling http uploads and downloads (and perhaps uploads using ftp as well)
Handling ftp requests
ii. Client work:
Rendering (computing how to display) output sent from the server
Managing a client-side cache
Managing bookmark/favourites lists
Transmitting URL requests and http upload/download requests to the server
iii. Information transmitted from server to client:
Information formatted as html, jpeg, Java classes, etc. This could be quite bulky.
iv: Information transmitted from client to server:
URLs and the contents of forms
Large files in the case of http-upload
v: How the clients work could be minimized or maximized:
Web protocols are well-defined and dont give much leeway for adjusting the kind of information a
client should transmit or receive. However, if the client allows for options such as switching off
image display, this can help the end-user to decide on amount of network resources consumed.
Some text-based browsers designed to run on cell-phones or old-fashioned textual terminals
automatically ignore graphical content.
The biggest opportunity for impact on network usage is in the hands of web site designers, who tend
to design pages that transmit overly bulky images.
vi: Network effects of changing the clients workload:
Removing or simplifying graphical content tends to have a dramatic effect on reducing network
resource usage.
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A20

e) For an email system:


i. Server work:
Receiving emails from the network and holding them until a client connects
Providing received emails to clients when a client connects
Sending emails
Managing folders (some clients do this themselves, but you can configure servers to manage your
folders so that they are available no matter which client you use)
Filtering undesirable email (viruses and spam)
ii. Client work:
Composing emails (including specialized functions such as forwarding, replying etc.)
Handing emails to a server to be sent to the destination
Connecting to a server to receive emails
Displaying received emails
Managing local folders
iii. Information transmitted from server to client:
Simple messages (e.g. that no messages have arrived)
Lists of emails
Emails received (could be lengthy if there are attachments)
iv: Information transmitted from client to server:
Emails to be sent (could be lengthy if there are attachments)
Simple commands (e.g. to get emails)
v: How the clients work could be minimized or maximized:
Simply make the client a web browser (decreasing intelligence)
Have the client handle all the folder management
Avoiding uploading attachments to the client unless they are explicitly requested.
vi: Network effects of changing the clients workload:
Making the client a web browser could increase or decrease total traffic to the client, depending on
the type of emails received. It would increase traffic if the user will tend to read all emails anyway,
including attachments. The increase would be due to the extra work of sending the pretty html
layout and images required by the user interface. On the other hand, if the user tends to get a lot of
junk mail, then the total network load may be reduced, since most of what would be transmitted to
the client would be the lists of emails, not the bulky emails themselves.
Having the client handle folder management would reduce network load substantially.
Avoiding uploading attachments unless requested would also reduce network load.
E3.11 p. 80 Writing protocols for a client-server system.
There are clearly many possible protocols for these systems; the level of complexity could become substantial.
the following shows some basic sets of messages that could be exchanged.
a)*Airline reservation system. Note that a real system can be extremely complex; the following represents a
simplified view of the kinds of messages that such a system would need to exchange.
Messages to server
Possible replies to client
addRegularFlight number planeType effectiveDate
confirmFlightAdded number
flightNumberAlreadyExists
addFlightLeg flightNumber origin leaveTime destination arriveTime
confirmLegAdded
flightTimeConflictsWithAnotherLeg
deleteRegularFlight number effectiveDate
confirmDeletion
flightNumberDoesNotExist
addFareClass fareCode
confirmFareClass
fareClassAlreadyPresent
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A21

ANSWERS TO EXERCISES

setFare origin destination classCode startDate endDate


confirmFare
addBooking name date flight originCity destinationCity fareClass
confirmBooking confirmationNumber seat
bookingCannotBeMade reason
deleteBooking confirmationNumber
confirmBookingDeletion
bookingNotCancelled reason
confirmationNumberInvalid
queryFlightAvailability date origin destination fareClass earliestDepTime latestArrTime
availableFlight date flightNumber fareClass
noMatchingAvailableFlight
queryBookings name date
confirmBooking confirmationNumber seat
queryBookingsByNumber confirmationNumber
bookingInfo flightNumber date name origin
destination fareClass seat
queryPassengers flightNumber date
bookingInfo flightNumber date name origin
destination fareClass seat

b) Toll-free-number server
Messages to server
queryNumber tollFreeNumber
mapNumber tollFreeToMap callerNumber
usageCount tollFreeNumber

Possible replies to client


queryReply name address billingNumber
mappedNumber tollNumber
usageReply numberOfCalls

c) Building alarm system. Note that if this system was set up on the Internet, it would be a prime target for
hackers. Such a system needs to be either on a dedicated network, or to incorporate sophisticated
encryption and other security features.
Messages to server
Possible replies to client
alarm unitNumber alarmType
acknowledge
- Signals that an alarm condition has been detected by a sensor
statusReport unitNumber status
acknowledge
- Reports that the sensor is working well (or not); if a server does not receive such a message at a
specified interval, it might display a trouble signal.
listStatus
statusReply unit status unit status
- Used by the systems main console client to obtain information about all the sensors
addUnit type description address responseNum unitAdded assignedUnitNumber
- Used to add a new sensor, whose input the server should expect, and to specify what response to
take when the server receives an alarm from this sensor.
removeUnit unitNumber
acknowledge
- Used to indicate that a sensor is no longer part of the system
addResponse responseNum phoneNum action acknowledge
- Used to specify one of several possible responses to different types of alarm

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A22

Chapter 4. Developing requirements


E4.1

p. 106 Listing information to be consulted when performing a domain analysis.


a)*Police information system
Police officers and staff (interviews, brainstorming and observing work)
Police training and procedures manuals
Documentation of existing software and equipment used by the police (including competing products)
Books about police methods
Similar information about related activities such as court procedures, etc.
b) Household alarm system
Personnel at alarm companies, emergency-response dispatching organizations, alarm equipment
manufacturers
Procedures manuals at alarm companies and emergency-dispatching organizations
Documentation and web sites about alarm hardware and existing alarm systems
Experience using actual existing alarm systems
Documentation about the network and other hardware that would be connected to the alarm system
Potential end users and customers of the alarm system
c) GANA system. Developing this system involves considering a surprising number of issues.
Literature about existing vehicle-based information and telematics systems in general
Potential end-users of the system
Automobile companies in whose vehicles the systems would be installed
Suppliers of map databases (information about the kinds of maps they can provide)
Suppliers of wireless services (information about how information can be transmitted to the GANA
system)
Safety studies, regulations and laws regarding usage of in-car telematics systems, as well as people who
have studied or have strong views about these issues
Experience using competing systems
Literature about the GPS satellite system and GPS devices
Psychologists and psychology literature regarding driving skills, driver reaction time navigation skills,
fear of being lost or confused, etc.
Literature and experts regarding voice output
User interface literature regarding UIs of small devices
d) Investments system. Of the four parts of this question, developing this system probably requires the
broadest and deepest amount of domain knowledge. Probably the team should include people who have
taken university degrees in business, or at least who took many business courses. That said, many readers
of this book will have enough knowledge to be able to make a useful first approximation for some aspects
of this system.
Information about securities and other investments that would be typically found in training courses for
investment dealers.
Potential end-users of the system.
Information about work practices obtained by talking to various investment dealers.
Existing software and web sites for managing and tracking portfolios
Literature from mutual fund companies.

E4.2

p. 106 Writing a short domain analysis for a system.


We will not be providing any answers to this exercise since the answers will depend too much on the
information consulted, the country in which the reader resides, and the date the information is gathered.

E4.3

p.110 Defining and narrowing the scope of a system.


In this following answers, a reasonably complete set of possible system functions is listed. The functions in
bold are the ones that represent the minimal requirements of a first release. Of course, each persons answer
will be somewhat different; however, the sample answers suggest the scope of good answers to this question.
(See E9.1 for additional exercises based on these systems)

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A23

ANSWERS TO EXERCISES

a)*Police information system


Managing personnel information about officers and staff (note that a generic personnel management
system could also be used to do this, although it would have to be hooked to the police system to enable
some of the other functions mentioned below).
Managing basic information about areas and events to be patrolled
Facilitating the manual scheduling of the duties of officers and staff
Automatically proposing schedules for some of the duties of officers and staff
Managing basic information about each case being investigated
Managing the documents that have to be written regarding each case, and following each shift
Generating statistics and trend information about crime rates etc.
Managing detailed information about suspects, witnesses and other people relevant to cases
Providing links to drivers licenses and other databases to help police find information
Providing links to court and criminal records
b) Record company web site
Listing the catalogue of available music for browsing
Searching for music by various criteria
Displaying details about a particular CD in detail
Providing profiles of musicians or groups
Selling music on-line (to be shipped to the buyer)
Playing samples of music streamed live over the web to entice purchasers
Selling music online to be electronically downloaded with copy-protection features
Allowing purchasers to put together their own custom CD composed of items from various sources
Selling spin-off products (e.g. clothing with the names of musicians or groups)
Taking surveys about the tastes and preferences of site visitors
Providing message boards for fans of particular musicians or groups
Providing lists of retail stores where this companys music is distributed
Providing information about the corporation (e.g. for investors, or musicians and groups
interested in having their work recorded)
c) Public library system
Adding and deleting of material held by the library
Checking out and returning of material
Browsing through lists of material (by subject, title, author etc.)
Searching for specific items
Handling inter-library loans
Connecting to other libraries databases to allow searches there
Allowing clients to look up the status of their accounts
Managing fines (keeping records of money owing)
Providing librarians with lists of overdue items
Sending out overdue notices
Placing items on hold (reserving them when they are already checked out by someone else)
Ordering books on-line from publishers
Generating statistics about which items have been borrowed, and which patrons do the borrowing
d) Taxi company system
Adding and deleting taxis and drivers from the system
Tracking which taxis are currently in operation, and where they are going (with information
entered manually by the dispatcher)
Automatically tracking taxis using GPS technology
Recording information from people who request a taxi by phone
Automatically obtaining address information about callers using caller-id and a telephone company
database.
Allowing ordering of a taxi on the web
Automatically determining which taxi should respond to a call based on their location, destination of
the trip and other information.
Managing the personnel information about each taxi driver and dispatcher
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A24

Centrally managing the money received from each trip


Tracking the usage of each vehicle, and scheduling maintenance
E4.4

p. 110 Giving precise problem statements, considering high-level goals.


a)*The new police information system will make operations of the police department more efficient by
reducing the time and effort required to plan and execute work, as well the time required to enter and find
information required in routine police work.
b) The record company web site will help to maximize sales by attracting potential purchasers, making it
easy for them to make purchases, and giving them an experience that will make them want to repeatedly
visit the site, more so than competitors sites.
c) The new public library system will help to reduce the costs of running the library while at the same time
making it as easy as possible for clients to meet their information and entertainment needs by finding and
checking out material.
d) The taxi company system will improve the profitability and efficiency of corporate operations by
increasing response time to clients, reducing the idle time of taxis, and reducing the number of dispatchers
needed.

E4.5

p. 115 Describing functional requirements of a system.


These build on the answers to E4.3 and E4.4 above.
a)*Police information system
To be provided in a later version of this document
b) Record company web site
To be provided in a later version of this document
c) Public library system
To be provided in a later version of this document
d) Taxi company system
To be provided in a later version of this document

E4.6

p. 118 Classifying requirements into functional or non-functional.


a)*F.
Describes the computation to be performed (some security requirements are non-functional, but this
one seems to be in the functional category)
b) F.
Describes a response (output) to a situation.
c)*NF. Constrains response time.
d) F.
Indirectly specifies the output needed (the output must be in the format accepted by this particular
plotter). Some people might argue that this is a constraint on technology, and hence non-functional;
however, the technology here is part of the external world, not the internal world, as in the case of a
program language or database system.
e ) X.
Requirements should not constrain design to this level of detail. This is a design detail.
f) NF. Allowances for future enhancement; constrains design.
g) NF. Constrains resource usage (but not platform).

E4.7

p. 118 Rewriting requirements so they are verifiable.


In each part of this questions, we would expect an answer similar to one of the bulleted points. Some of the
bulleted points show that there should be two or more separate requirements.
a)*Constraint on technology to be used:
The C++ programming language must be used
A strongly typed, block-structured programming language must be used that does not allow unrestricted
access to memory.
b) Constraint on development process:
The development process to be used shall be compliant with the norms established at CMM-level 3;
furthermore the development organization must be certified at CMM level 3.
Development methodology XYZ must be used.
Extreme programming must be used, following the methodology defined at
www.extremeprogrammming.org

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A25

ANSWERS TO EXERCISES

c)*Constraint on availability and throughput


- The system will accept connections 24 hours a day, every day, with a maximum downtime of 5
minutes a month, which can occur only between 12:30 a.m. and 1:30 a.m. North American Eastern
Time.
- When available, the system will at all times be able to manage 200 simultaneous connections, and
process 2000 transactions per minute.
d) Constraint on cost (could also be in project plan)
The final polished system (including all documentation and fixing of all defects reported in the first
month of use) must be delivered at a cost of under 200,000.
e) Constraint on response time (Aalthough it is ambiguous what this is actually constraining)
- The automated teller machine should at all times respond to user input with feedback in 0.5s,
- All debit, deposit and balance inquiries to the customers own bank must be completed in 5s.
- All transactions made by interacting with another bank must be completed in 10s
E4.8

p. 118 Writing non-functional requirements for the microwave oven system.


The following is an example of a possible answer.
The system shall respond to all specified events in less than 0.1s
The software shall fit within 500K of PROM
No failure may cause the motor to run indefinitely.
The software shall be designed such that new cooking modes, sensors, cooking mechanisms and special
functions can be readily added without having to significantly change the software written for this basic
version of the system.
The software will be written in C.
The software will be initially targeted to the PowerPC 604 processor, but shall be written in such a way
that minimal change would be required to run it on a different processor.

E4.9

p. 119 Writing non-functional requirements.


These build on the answers to E4.3 - E4.5 above.
a)*Police information system
When the user is connected to the over a local area network, the system shall respond with complete
responses to all inputs within 0.5s at peak system load.
When the user is connected over a wireless connection at 9600bps, the system shall respond with
complete responses to all inputs within 3s at peak system load.
The system shall be capable of handling 50 simultaneously connected users, and 300 user interactions
(events originating from users) per minute.
The system shall not consume more than 200MB of RAM while running at peak capacity.
The system shall not consume more than 56Kbps of bandwidth per connected user (averaged over any
1s time period)
The system shall achieve a reliability level of no more than 1 failure per 10 user hours, with none of
those failures rendering the system totally inoperable.
The system shall be available 99.9% of the time with no period of down time exceeding 2 minutes.
The system shall be designed so that large numbers of additional functions can be added with little
reprogramming.
The system shall be designed so that it could be adapted to the needs of other police departments with
minimal reprogramming.
The server shall be able to run on a Windows 2000 (or higher) equipped system, with a 1.4 GHz or
faster Intel processor, 300MB or more of RAM, and 15GB or more of disk space.
The client software shall be able to run on EMP-4500 police car terminals, as well as on EMP-4500
emulators running on desktop computers.
b) Record company web site

To be provided in a later version of this document

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A26

c) Public library system

To be provided in a later version of this document


d) Taxi company system

To be provided in a later version of this document


E4.10 p. 122 Practising interview techniques.
This is a purely practical exercise.
E4.11 p. 124 Practising brainstorming techniques.
This is a purely practical exercise.
E4.12 p. 126 Creating a list of actors for a mail-order company.
Shipper (puts together orders and sends them to customers)
Receiver (puts items on shelves that arrive from suppliers)
Warehouse supervisor (co-ordinates the work of shippers and receivers)
Inventory taker
Telephone operator
Telephone operator supervisor
Product orderer (plans the products that should be in the warehouse and orders them)
Catalogue editor
Returns handler (deals with items sent back by customers, or which could not be delivered)
Corporate finance and accounting official (needs to examine warehouse and sales data)
Corporate executives (need management information from the system)
E4.13 p. 126 Creating a list of use-cases.
All actors
- Sign in
- Sign out
- Change password
Shipper
- Display next order to fulfil
- Check off item prepared for shipment
- Display location in warehouse where item should be located
- Completed shipment
Receiver
- Enter shipment in database
- Display location in warehouse where item should be located
Warehouse supervisor
- All shipper, receiver and inventory taker functions
- Display statistics about shipping and receiving performance
- Assign shipment to shipper
- Assign delivery to receiver
- Add shipper or receiver
Inventory taker
- Display location in warehouse where item should be located
- Enter count of items of a certain category
- Display inventory statistics
Telephone operator
- Pick up call automatically routed to operator
- Look up existing customer records
- Search for item in catalogue
- Display technical information about item
- Display availability and pricing information about an item
- Add item to sale
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A27

ANSWERS TO EXERCISES

- Complete sale
Telephone operator supervisor
- All telephone operator functions
- Display statistics about operators
- Override default pricing
E4.14 p. 126 Creating a list of use-cases for the microwave oven system.
Open door, halting cooking
Set cooking by time
Set cooking by auto-reheat without temperature
Set cooking by auto-reheat with temperature
Set cooking by auto-defrost without weight
Set cooking by auto-defrost with weight
Set time of day
Start cooking
Press start while door is open
E4.15 pp. 129-130 Describing the type of requirements document needed.
a)*Software controlling a manned spacecraft sent to Mars
There would need to be a considerable amount of detailed technical requirements documentation.
Technical terminology could be used since all readers would be expected to have a technical
background. There would probably initially be a very high-level description of the missions overall
objectives used to obtain funding for the mission. Then there would be a requirements document for the
high-level system requirements of the combined hardware-software system. Next, the system would be
allocated into hardware and software subsystems, which in turn would each be divided into several
subsystems. At each level there would probably be general and detailed requirements documents. The
rationale for this level of detail is that a spacecraft is novel, is technically complex, will involve many
different people with different types of expertise to develop, is difficult or impossible to change once
launched, and is expensive (with high failure cost and hence a high level of required reliability).
b) Payroll software for a large company
This will require somewhat less documentation than the spacecraft, but since the company is large, it
will probably involve significant complexity in its payroll (perhaps several different unions, stock
options, different pension plans etc.). There will thus need to be a high level requirements document, as
well as requirements for several different lower-level subsystems. Readers of these documents may no
little or nothing about computers (they will typically be managers, human resources staff etc.)
c) Computer game software for a cell phone
Computer game software in general can be quite complex with many different subsystems. However,
on todays cell-phones the amount of functionality is likely to be rather limited, hence the game will
probably be quite simple. Probably just one reasonably detailed requirements document will be needed.
d) Software to search email folders
This is probably a rather simple function that might be developed for personal use with little need for
formal process. However, if the function is to be part of a larger system, a single short requirements
document would probably suffice.
E4.16 pp. 135-136 Finding problems in requirements statements.
a)*Simple interest calculation program
The requirements are not separated into individual points
This is a handy utility is too informal
It is not clear whether the fields are updated upon every keystroke, or whether the user has to hit enter
or click on some button to cause an update of the fields.
It is not clear whether the monthly payments are at the start or end of each month (this effects the
computation).
(The computations themselves are well-known by accountants, so it is legitimate to exclude them)
There is no information about the platform on which the program runs,
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A28

Maximum and minimum dollar amounts and interest rates that can be handled should be specified.
Precision of calculations should be specified.
What happens if the user enters invalid keystrokes?
It would be desirable to describe the user interface in a little more detail.
b) Dispatcher automation system (this is a particularly atrocious requirements statement for such a critical
system!)
The requirements are not separated into individual points
It doesnt seem even remotely realistic that a voice recognition system could classify cases; this has to
be a human function.
What happens to non-urgent cases?
How can, in general, the ambulance dispatcher receive the patients record? The patient may not have a
record on the system or may be too badly sick to provide sufficient information to look up the record.
What information is in the record?
How is the summary of the conversation with the operator created, and what is in this summary?
It is unclear the difference between the dispatcher and the operator. And the fact that there is a
difference seems confusing and likely to result in dangerous delays.
In what format is all the information about the case made available to the ambulance operator? And
what constitutes all the information?
c) Inventory recording system
This requirements documents delves into the design aspects of the UI and the exact naming of the
fields. This offers way too little flexibility when actual design is to take place.
The word number is ambiguous. Does it mean the number of items, or some kind of identifier.
Inconsistency between the terms product id and product code.
A dialog box with list of product ids would be impractical in a warehouse with thousands of product
types.
What does add a product code mean. Does it mean entering an existing product code by searching for
a matching description? Or does it mean adding a totally new type of product. Probably the latter, but
you have to be crystal clear in requirements.
Inconsistency between Clerk and Staff member.
After the system prints out the sticker with the bar code, it clears the fields. But what if there was no
paper in the printer, and so the sticker was not actually printed? If the staff member tries again, the
system will record that an extra item is in inventory! Also, there needs to be better feedback that the
sticker has printed more than simply clearing the fields; this does not tell the user anything
informative.
What happens if barcode is illegible?
What happens when two identical products are in the warehouse but have different codes due to user
error?
No non-functional requirements described.
E4.17 p. 136 Rewriting requirements to remove defects.
a)*Simple interest calculation program
Functional Requirements
- When the system starts, a window appears, whose content and function is describe below.
- The window has the title Simple Interest Calculation, as well as standard close and minimize icons
in the title bar.
- The window has labels Principal:, Annual interest rate:, Interest paid at the end of each month:.
The right edges of these are vertically aligned, and each is followed on the right by an input field
- The principal and interest fields are capable of accepting 10 characters of input, the interest rate field
is capable of containing 8 characters.
- The user may enter numeric values in each field; as each key is typed (including the delete key), the
other fields are updated instantly. An empty field is taken as having the value zero.
- Editing the interest rate causes a change to the monthly payment.
- Editing the monthly payment causes a change to the interest rate
- Editing the principal causes a change to the monthly payment
- The user may use the mouse to move the insertion point or select characters in any field, as in
standard Windows applications.
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A29

ANSWERS TO EXERCISES

- The system can handle dollar amounts from -999999.99 to 9999999.99, and interest rates from 999.99% to 999.99%. The percent symbol is automatically added if the user does not specify it.
- All calculations are rounded to the nearest cent. Two decimal places are always shown in all three
places.
- Any edit to a field that would result in an invalid input, or a computed result that could not be
displayed in the other fields, will not be accepted the system will beep and display an error
message at the bottom of the window describing the error. Error messages include:
The largest value accepted for <field> is xxx
The smallest value accepted for <field> is xxx
Input must be numeric
Input is only accepted to two decimal points
A <field> input value of xxx would result in an invalid value for <field>
Non-functional Requirements
- The program will run on all Microsoft Windows operating systems starting with Windows 95 and
Windows NT 4.0 (on all CPUs of at least 33Mhz).
- Response time will appear instantaneous to users.
b) Dispatcher automation system
To be provided at a later date.
c) Inventory recording system
Functional requirements:
- When system starts, a window appears with contents and functions as described below:
- The window has title Warehouse management system and the standard window icons
- At the top of the window are two fields identified as Product Code and Number of Items
- Below this is a button labelled Record arrival of items. This button is emphasized in the standard
way to show that pressing return will activate its function.
- Below this button, separated visually from the above, is a field marked 'Description of new product
that lacks a code'
- Below this is a button marked Create a new product code with the above description, and record
arrival of items'
- Each of the labels is right-aligned and each is followed by a text field
- The Product Code field is capable of accepting text of unlimited length, but displays at least 25
characters (the user has to use the mouse to scroll the field left or right if there are more than 25
characters in it.
- The Number of items field is capable of accepting a positive integer up to 6 digits. Attempts to
enter non-digits into this field will result in the computer issuing a sound and not accepting the
pressed key.
- The Description ... field is capable of accepting any string up to 500 characters long.
- When the user clicks on the Create a new product code button, a new product code appears in the
product code field.
- When either button is entered
- A set of products is considered to be entered into the database and stored inside the warehouse.
- Barcodes labels are then printed for use at retrieval of the product from the warehouse and
removal from the database.
- The number of barcode labels printed equals the value of the number of items field.
- If the user omits the Product Code when clicking the Record arrival button, then the system will
display a scrollable list of all currently valid product codes along with their description for the user
to select.
- Upon selection from this list, the product code appears on the first screen, ready for the user to
click the 'Record arrival' button.
- If the user types a Description when clicking the Record arrival button, the system will display a
message indicating that the description is not needed and will take no action. The description is
highlighted so the user can press the delete key to remove it if he or she wants to do that.
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A30

- If the user omits the Description when pressing the Create new product code button, a
message will be displayed prompting the user to provide a description, and no change is made to the
database.
- If the user omits the Number of items field, it defaults to 1.
- When the system reads a barcode, one item of the specified product code is removed from the
database. If the barcode is unreadable, the system will ask the user to input the barcode number into
a dialogue box.
Non-Functional Requirements
- The program will run on all Intel based processors having a processor speed of at least 100MHz, and
having at least 32MB of RAM.
- Response times to user input are no more than 0.1s at any time
- Response times when reading the barcode are no more than 0.2s at any time
E4.18 p. 136 Reviewing requirements for the microwave oven system.
Here are a few possible flaws in the microwave oven example:
According to the requirement 2, the user can not interchangibly press the power button while setting the
time. Yet, these two have no impact on each other theoretically.
Entry of time of day in requirement 4 requires four digits (i.e. the user has to enter a zero, prior to entering
1-9). This is awkward; the system should allow the entry of times up to 9:59 using 3 digits.
Should consider the option of allowing a 24 hour clock instead of imposing 12 hour clock in requirement
5.
Requirement 7: Would you want to display invalid sequences, or just valid ones?
Requirement 10:
- Is the amount of steam really a good indicator of the fact that the food is warmed up properly. (eg. The
outside is nice and cooked, but the inside of the food may still be frozen solid!)
- A tone could perhaps be emitted when the system updates the time estimate for auto-reheat
We would like the input of readers in case there are additional comments. Email us at tcl@site.uottawa.ca
E4.19 p. 141 Reviewing requirements for the GANA system.
Here are some possible issues, we invite readers to send us others:
The system should perhaps automatically adjust the brightness according to the ambient lighting conditions
so that it is always readable.
There is no way to completely turn the system off.
E4.20 p. 146 Reviewing requirements for SimpleChat.
We invite the comments of readers.
P4.1

p. 148 Requirements for additional features of SimpleChat


An overview of these is provided in the accompanying source code in the rationale.html file. A full
requirements document will be provided in a later release of the answers.

P4.2

p. 149 Implementation of additional features of SimpleChat


See the accompanying source code zip file.

P4.3

p. 149 Domain analysis for hotel reservations.


We may provide this at some point in time.

P4.4

p. 149 Requirements document for Small Hotel Reservations System


Small Hotel Reservations System (SHORS)
Requirements Document
A. Problem:

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A31

ANSWERS TO EXERCISES

The proposed software system will be used to manage the front-desk activities of a hotel. It will be able to
accept reservations, to record information about the hotel guests, to verify room availability, and to allocate
rooms to guests.
B. Background information:
See Lethbridge and Laganire Object-oriented Software Engineering page 149 for a short description of the
problem. Note that the writing of this document would normally have been preceded by a sound domain
analysis.
C. Environment and system models:
In its first version, the SHORS will be a simple application to be run from a single computer. The second
version should be a client/server system where the client component is used to manage the reservations and
the server centralizes the corresponding data. A third version is also envisaged where guests will be able to
make their reservations from the Internet.
D. Functional requirements:
`

1. Guest
1.1.
1.2.
1.3.
1.4.
1.5.
1.6.

The information associated with each guest is: name, address and phone number.
The full name of a guest is represented by a single string of characters.
Guests are searched using a substring, any guest name that contains that substring is returned by the
search operation.
The address of a guest is represented by a single string of characters. This contains the complete
address (street, city, postal code, )
The phone number is represented by a string of characters.
An account can be printed and contains the information about a guests stay and the amount to be paid.
The printed account also includes the name of the hotel and the date at which it has been issued.

2. Room
2.1.
2.2.
2.3.
2.4.
2.5.
2.6.
2.7.
2.8.
2.9.
2.10.
2.11.
2.12.
2.13.
2.14.

Each room has a number. Some of them are also designated by a special name.
A quality level is associated with each room.
A quality level is identified by a number. Standard rooms usually have quality number 0. This number
increases as the quality of the associated increases.
Quality level can also be given a name.
A list of characteristics is associated with each quality level. It describes the equipment common to the
room having this quality level as well any other special elements such as location, views or privileges.
All rooms having the same quality level have the same maximum daily rate.
The maximum daily rate is for one person. There may be an additional charge for each extra person.
The room charge per night can be less than the specified daily rate.
A room is either smoking or non-smoking.
A room contains a certain number of beds, all of the same type. Typical configurations are 2 Queen
beds or 1 King bed.
Some rooms can adjoin 1 or 2 other rooms.
Adjoining rooms always belong to the same quality level.
Equivalent rooms are said to belong to the same category. When a guest makes a reservation, recording
the room category is sufficient. On check-in, any available room of the required category can be
assigned to the guest.
Two rooms are equivalent if they belong to the same quality level, they have the same smoking status
and they have the same type and number of beds.

3. Reservation
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

3.1.
3.2.
3.3.
3.4.
3.5.
3.6.
3.7.

A32

To make a reservation, the guest must specify the arrival date and the departure date (or the number of
nights) for the proposed stay.
Normally, a room is not allocated when a guest makes a reservation, the room allocation being made
only when the guest checks in.
A reservation is accepted only if rooms are available.
A room is available if the total number of rooms of the required category is greater than the number of
rooms of that category requested by the reservations, throughout the specified period.
When a reservation is made for a suite (i.e. two or more adjoining rooms), the room allocation must be
done immediately.
A reservation is for one guest, for one sequence of consecutive nights for rooms of one category.
A reservation can be cancelled at any time.

E. Non Functional Requirements


1 Although this project has been undertaken to satisfy the needs of a particular hotel, it should be built with
enough flexibility such that it can be used by a wide variety of hotels.
2. In its client/server version, the amount of information sent to the client should be minimized.
3. The user interface of the system does not have to allow a user to enter and modify information concerning
the hotel configuration (number of rooms, room descriptions, etc.). However, there should exist a simple
means by which the hotel can be described (such as a text file).
4. Information concerning guests and their reservations must be persistent.

Some comments concerning the requirements:


Req. 1.1: Credit card information is not included here. Card type, number and expiration date is the
information generally associated with a credit card. This information could also be associated with
each stay. Sometimes a guest can provide more than one credit card. Adding this information is left
to a future release.
Req. 1.2: Having first name and last name as separate attributes would be a better choice. This would be
required, for example, if one wants to display the list of guests in alphabetical order of their last
names. However, using a single attribute simplifies the implementation, and gives more flexibility in
case of unusual name formats.
Req. 1.4: For more flexibility, each component of the address could be a separate attribute.
Req. 1.6: The guest account is used here only to produce a bill concerning a guests stay. More investigation
should be done to determine what information should be recorded here. It should also be possible to
include the various items that can also appear on a hotel bill such as food, movie rental, purchases at
hotels boutique, etc.
Req. 2.6: Note that in most hotels, the actual rates charged depend on time of year, whether the hotel is near
capacity, day of the week etc.
Req. 2.12: The quality level restriction on adjoining rooms has been added for simplicity. A good domain
analysis would confirm if this assumption is realistic.
Req. 2.13: Even if this requirement is not explicit in the project description, any quick domain analysis would
reveal the necessity of introducing the concept of equivalent rooms. Indeed, even if rooms are not
allocated at reservation time, the fact that this guest wants, lets say, a two- queen-bed smoking
room must be recorded to make sure that such a room will be available when the guest arrives.
Req. 3.5: This restriction must be added to reduce the complexity of the room availability and room allocation
procedures. One can verify that it would be quite complex to guarantee that two adjoining rooms
will be available without actually allocating them at reservation time.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A33

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A34

Chapter 5. Modelling with classes


E5.1

p. 160 Analysing an association and considering alternative multiplicities


As written the association says the following:
A SpecificFlight can have any number of Bookings, including zero. This seems reasonable: When
first created the SpecificFlight will be no bookings; also, no upper bound should be specified since
we do not know the largest capacity plane that will ever be used.
A Booking is for exactly one SpecificFlight. Firstly, this means that you can never have a
Booking that doesnt indicate any SpecificFlight. This might be reasonable, but it might also be
possible to design systems that use a different approach. For example, some systems might create a
Booking in advance of deciding which flight will be used; or maybe a booking could involve something
other than a flight (e.g. a hotel room). Secondly, this association makes it clear that a Booking can never
involve more than one SpecificFlight. Clearly, when you fly you often have to change planes and
take several different SpecificFlights to your destination, so another alternative would be to make
this association many-to-many. However, the many-to-one approach shown here remains valid: You would
have to have a series of Bookings that are tied together into an itinerary.

E5.2

p. 160 Designing associations among classes


Note that the exercise says take care to specify labels for the associations; however, we have only shown
labels where the default has would not suffice. In many of the following, differences in class names are
possible.
a)*We will see later on that aggregation could be used here; however, at this point in the book the following
would be a reasonable answer. Making the multiplicity on the Vehicle end 0..1 might be even better,
allowing for wheels to exist on their own, without being attached to vehicles.
*

Vehicle

Wheel

b) In the following, there could also be a class VideoRentalShop that might have one-to-many
associations to both RentableItem and Member. We will see in Chapter 6 that such a class is a
Singleton class; often when drawing domain diagrams we do not need to explicitly show it, since its
presence is understood, and it makes the diagram more complex. The following diagram could also have
been shown as an association class (as in Figure 5.7). Many students will think that there should be an
association called purchase; this is a common error, since purchase is an action, not an association.
Adding a class Membership (as distinct from Member, or in place of Member) is another possible
variant.
RentableItem

Rental

Member

c) A one-to-one solution might seem obvious for this exercise, however we have chosen a * to 0..1
multiplicity pattern for the following reasons: The 0..1 multiplicity is used because there might be cases
where you know a country, but do not know the head of state, or perhaps the head of state has been
deposed and no new one has been appointed/elected. The * multiplicity at the Country end accounts for
those situations where two independent countries have the same person as the head of state (e.g. Queen
Elizabeth II is formally head of state of several countries). The 0..1 at the HeadOfState end could
perhaps be changed to 1..* since it seems reasonable that a head of state must have some state of be head
of!
Country

* HeadOfState
0..1

There is another issue which could give rise to a different answer to this exercise. If the system in question
was describing the history of various countries, rather than the current status of each country now, then the
multiplicity might be * to * (or 1..* to *).
d) This answer is actually shown on page 161! If you flip the diagram so Student is on the right ad
CourseSection is on the left, you will see that the answer is also analogous to part b. Those readers
who bother to read ahead and make the appropriate connections will benefit. There could also have been a
School singleton class. CourseSection could also have been called CourseOffering. However,
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A35

ANSWERS TO EXERCISES

Course on its own would have been a much weaker choice since it is important to distinguish the
multiple offerings of a particular course. Registration could have been shown as an association class,
as in Figure 5.7.
Student

Registration *

CourseSection

e) This is largely analogous to parts b and d. You could conceivably leave out the class Registration if
you did not need to store information such as whether a particular member has paid for the particular
activity. Also, we have not given the class Activity the name ActivityOffering, although this
would be a valid alternative.
Member

Registration *

Activity

f) This is analogous to part b, d and e. Class LibraryItem could also be called BorrowableItem,
CopyOfPublication etc.
LibraryItem

Loan

Patron

g) We have shown the TheatreCompany singleton in the following, but it could be omitted. A
presentation could also theoretically involve many plays, so the right-hand association could be many to
many.
TheatreCompany

E5.3

* Presentation *

Play

p. 160 Explaining the consequences of associations in terms of creation and destruction of instances
This exercise has several parts that are strongly analogous to each other, and which turn out to be candidates
for association classes, which are described on page 161.
a)*A Vehicle could exist, and then a Wheel could be created and associated with it; conversely, the wheels
could exist first. Similarly, the order in which these associated objects are destroyed does not matter.
b) The RentableItem would be expected to exist before it is rented i.e. before an associated Rental
object is created. A Member, on the other hand might be created at the time of rental, if this is the first
rental. If a Rental is destroyed, then it would not automatically have an impact on instances of Member
or RentableItem. However, if a RentableItem or Member is destroyed, it makes no sense to keep
associated instances of Rental, so these should either be destroyed first, or at the same time as the
destruction of the Rental. Of course, you may prevent a Member from being removed while he or she
still has some Rentals.
c)*Under normal circumstances in the real world, a country exists over a longer period of time than any of its
heads of state. However, if we imagine an information system storing biographical information, then a
person might be created in the system who later on is recorded as the head of state of a country. So there
are no necessary constraints on the order of creation or destruction of these instances.
d) This part is similar to part b. The Registration would be created after both the Student and he
CourseSection, and would have to be destroyed first, or at the same time as its Student or
CourseSection.
e)*This is similar to parts b and d. The Registration would be created after the Member and the
Activity, and would have to be destroyed no later than these associated instances. (In some
circumstances, the Member and the Registration could be created together).
f) This is also similar to parts b, d and e. The Loan would be created after the Patron and the
LibraryItem, and would be destroyed no later than these. (In some circumstances, the Patron and the
Loan could be created together).
g) This would typically be handled in the same way as parts b, d, e and f in the sense that a Presentation
should require the prior existence of a TheatreCompany and Play. However, you could imagine a
situation where the Presentation is planned first (i.e. a time-slot in a theatre schedule), and then a
TheatreCompany is booked to perform in that time slot. In that latter circumstance, the theatre

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A36

company could be disbanded, without requiring the destruction of the Presentation (some other
company could take its place).
E5.4

p. 160 Reading associations in both directions.


The exact phrasing of answers to this question will, of course, vary considerably. This exercise has proven
particularly valuable at getting students to check their work and detect errors in their class diagrams. Creating
these answers even helped us make improvements to our answers to E5.2. Different answers to E5.2 would
result in different answers to this question.
a)* A Vehicle can have no Wheels, or an unspecified number of Wheels.
A Wheel always belongs to exactly one Vehicle.
b) A RentableItem can be rented any number of times (can be involved in any number of Rentals,
including zero).
Each Rental is always involves renting exactly one RentableItem to exactly one Member.
A Member can have any number of Rentals (can rent any number of items)
c)* A Country has either zero or one known HeadOfState.
A HeadOfState can head any number of Countrys
d) A Student can register in any number of course sections (can have any number of
Registrations)
Each Registration involves registering exactly one Student in exactly one CourseSection
A CourseSection can have an arbitrary number of Registrations
e)* A Member can register in any number of activities (can have any number of Registrations)
Each Registration involves registering exactly one Member in exactly one Activity
An Activity can have an arbitrary number of Registrations
f) A LibraryItem can be loaned any number of times (can be involved in any number of Loans,
including zero).
Each Loan is always involves loaning exactly one LibraryItem to exactly one Patron.
A Patron can have any number of Loans (can be loaned any number of items)
g) The TheatreCompany can put on any number of Presentations.
Each Presentation is put on by just one TheatreCompany and involves just one Play.
A Play can be presented at any number of Presentations, including zero.

E5.5

p. 162 Adding association classes.


The question doesnt require a list of attributes, but we show attributes below to help explain the purpose of
the association class.
a)*A reasonable association class might be called PlayingRecord or something similar. The attributes
needed would depend on the type of sport, but might include positionPlayed, goalsScored,
penalties and timeOnField
Player

SportGame

PlayingRecord
positionPlayed
goalsScored
penalties
timeOnField

b) The association class Ticket might include attributes seatNumber, ticketNumber, price, and
dateBought.
Spectator

Show

Ticket
seatNumber
ticketNumber
price
dateBought

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A37

ANSWERS TO EXERCISES

c) The
association class Stay might
plannedDepartureDate, and roomRate.

include

Guest

attributes

such

as

dateArrived,

HotelRoom

Stay
dateArrived
plannedDepartureDate
roomRate

E5.6

p. 162 Adding association classes with attributes to reflexive associations.


The successor-prerequisite association might have an association class called
PrerequisiteReason, the main attribute of this could be simply called description. (Also shown
below is a one-to-many association to a class Topic that would list the topics taught in the
prerequisite that are needed by the successor; this is not a required part of the answer).
The
isMutuallyExclusiveWith
association
might
have
an
association
class
MutualExclusionReason, also with a description attribute. (Also shown below is an
association to a list of topics that are duplicated in the two mutually exclusive courses).
successor
* Course

*
isMutuallyExclusiveWith

*
prerequisite

PrerequisiteReason

MutualExclusionReason

description

description

*
materialNeededBySuccessor

E5.7

*
overlappingMaterial

Topic

p. 162 Transforming association classes and their associations to regular associations and classes.
This is a surprisingly tricky question. Firstly, students have to realize that, unlike in Figure 5.7, for each
association there will only be two classes involved, instead of three.
For the prerequisite-successor association, the transformation is then relatively straightforward: it becomes
a pair of associations (each PrerequisiteReason has two separate many-to-one associations with the
Course class.
The isMutuallyExclusiveWith association, on the other hand, represents a symmetric relationship.
It is therefore unreasonable to give MutualExclusionReason two separate but identical many-to-one
associations to Course; instead, the two associations should be merged into a single many-to-two
association!
After making these transformations, advanced readers might realize that the class names
PrerequisiteReason and MutualExclusionReason should perhaps be changed to the simpler
namesPrerequisite and MutualExclusion.
mutuallyExclusivePair

successor

Course

prerequisite
*

PrerequisiteReason
description

description

*
*
materialNeededBySuccessor

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

MutualExclusionReason
*

Topic

*
overlappingMaterial

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

E5.8

OrganizationalUnit

Department

E5.9

A38

p. 167 Creating a class diagram with more than one generalization.

Division

Employee

ProfessionalEmployee

TechnicalEmployee

SupportEmployee

p. 168 Drawing a class diagram corresponding to an instance diagram (See also E6.3, p. 208).
PoliticalEntity
name
borders
*

Territory

Country

isMemberOf *

InterGovernmentalOrganization

*
StateOrProvince
isPartOf

E5.10 p. 172 Distinguishing among ordinary associations, aggregations and compositions.


a) Aggregation. The handset is clearly part of the telephone, but if removed would still exist independently.
b) Ordinary association. The teachers may colloquially be called part of the school, but the school doesnt
control the teachers entire lives (we hope), so they should be considered completely independent entities.
c) Composition. Normally if a book ceases to exist in the system, we would not want to keep track of a set of
loose chapters. However, if your system allows chapters to exist independently, then use an ordinary
aggregation instead (this might be the case for electronic books whose chapters are independently
distributed)
E5.11 p. 175 Writing constraints about shapes, and converting these to OCL.
The existing constraints on LineSegment and LinearShape in Figure 5.22 say, A line-segment must
have non-zero length, and, Two line segments may not lie on top of each other. However there are several
other constraints that should be imposed. In the following we stick to the simple OCL that is introduced in the
book; readers may be able to think of other constraints that could be added, and advanced readers might use
more advanced OCL.
There cannot be more than two edges sharing the same point
context LinearShape inv:
edge->forAll(e1,e2,e3 |
(e1.endPoint = e2.startPoint
and e1 <> e3 and e2 <> e3)
implies
(e3.startPoint <> e1.endPoint
and e3.endPoint <> e1.endPoint))
Explanation: For any triplet of edges, where two (e1 and e2) meet at a point,, then the third (which differs
from e1 and e2) cannot also start or end at this meeting point.
If there is more than one segment, then each segment must be attached to some other segment
context LinearShape inv:
edge->size > 1 implies
edge->forall(e1 |
edge->exists(e2 |
e1.startPoint = e2.endPoint
or e1.endPoint = e2.startPoint))
E5.12 p. 175-176 Writing OCL constraints.
a)*Referring to Figure 5.11, p. 164
context RecordingCategory inv:
subcategory->forAll(r |
self <> r)
b) Referring to Figure 5.8, p. 162
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A39

ANSWERS TO EXERCISES

context Course inv:


isMutuallyExclusiveWith->forAll(cm |
successor->forAll(cs |
cm <> cs)
and
prerequisite->forAll(cp |
cm <> cp))
c) context Course inv:
successor->forAll(cs |
prerequisite->forAll(cp |
cs <> cp))
E5.13 p. 178 Designing how operations would be performed
a)*In this example it is ambiguous whether getSiblings should include half siblings or just full siblings;
we assume the former.
getSiblings (a method of Person) would be performed as follows:
1 Obtain the parents (a Union), by following the association
2. For the femalePartner of the Union:
2.1 For each of her Unions
2.1.1 Put the children of the Union in the result set
(excluding duplicates and the self object)
3. Repeat step 2 for the malePartner
4. Return the result set
b) Half siblings are those that share one parent but not both.
getHalfSiblings (a method of Person) would be performed as follows:
1 Obtain the parents (a Union we will call mainUnion), by following the association
2. For the femalePartner of the mainUnion:
2.1 For each of her Unions other than mainUnion
2.1.1 Put the children of the Union in the result set
(duplicates should never occur)
3. Repeat step 2 for the malePartner
4. Return the result set
c)*Step siblings are children of a persons step-parent which are not half-siblings. To solve this problem we
will first define a method of Person called getStepParents, as follows:
1. Obtain the parents (a Union we will call mainUnion).
2. For the femalePartner of the mainUnion:
2.1 For each of her Unions other than the mainUnion
2.1.1 Put the malePartner in the result set
3. Repeat step 2 inverting femalePartner and malePartner
4. Return the result set
Now we can define the getStepSiblings method of Person:
1. For each stepParent obtained by calling getStepParents
1.1 Add each of the children of the stepParent to the result set
2. Call getSiblings to obtain the set of siblings
3. Subtract the siblings and self from the result set
4. Return the result set
d) The isMarried method of Person would operate as follows (note that this would give inaccurate
results if information is missing)
1. For each of the Persons Unions
1.1. If the dateOfMarriage is set
and the dateOfDivorce is not set
and the dateOfDeath of neither malePartner nor femalePartner is set
then return true
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A40

e) The getNumberOfMarriages method of Person would operate as follows:


1. For each of the Persons Unions
1.1 If the dateOfMarriage is set
then increment the result counter
2. Return the result counter.
E5.14 p. 178 Writing OCL constraints for the genealogical example.
a)*context Person inv:
dateOfDeath =
or dateOfBirth =
or dateOfBirth <= dateOfDeath
b) context Union inv:
dateOfMarriage =
or dateOfDivorce =
or dateOfMarriage <= dateOfDivorce
E5.15 p. 178 Comparing advantages and disadvantages of two class diagrams solving the same problem.
Advantages of part c versus part d
There are two fewer classes and one fewer association, simplifying some aspects of implementation
The notion of male and female partners are less tightly embedded in the system, allowing for the
possibility of other types of union (as permitted in some jurisdictions)
There are situations in genealogy where you know that a person exists but you do not know their sex. In
part d, you would not be able to represent this cleanly.
Advantages of part d, as opposed to part c (these are mentioned in the text on page 178)
There is one fewer attribute, slightly simplifying some aspects of the implementation.
There is one fewer OCL constraint, simplifying some aspects of implementation.
E5.16 p. 178 Evaluating a change to a class diagram.
a) The essential difference between a Union and a Marriage is that the latter is formalized by a state or
religion and hence has official documentation. If one makes the design change suggested in this question,
then the Marriage class could have special attributes such as certificateNumber, officiant
(clergy or judge), and divorceCertificateNumber; there could also be an association listing the
witnesses, if any. The original dateOfMarriage and dateOfDivorce attributes might be
changed to dateStarted and dateEnded, to make them apply equally well to both a simple Union
and a Marriage. The placeOfMarriage attribute ought to be moved from Union to the new
Marriage class.
b) Advantages of the new design (shown below) as opposed to the original design (Figure 5.23 (c))
The attributes in the old design all had the word marriage in them, even though some Unions are not
marriages. The attributes therefore had to be unused or else used in a slightly confusing way. The new
design reduces this confusion.
The new design allows more specialized marriage-specific attributes and associations to be added.
Advantages of the original design:
It is simpler (it may suffice, but that would depend on the system requirements)

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A41

ANSWERS TO EXERCISES

Person
name
sex
placeOfBirth
dateOfBirth
placeOfDeath
dateOfDeath

*
witnesses
child

partner
* 0..2
{partner->forAll(p1,p2 |
p1 <> p2
implies p1.sex <> p2.sex)}
*

Union
dateStarted
dateEnded

0..1
parents

Marriage
placeOfMarriage
certificateNumber
officiant
divorceCertificateNumber

E5.17 p. 179 Extending a class diagram to handle new requirements.


a) Adoptive parents can be handled in at least two ways:
1. A reflexive association on Person it would be many to 0..2, and have roles adoptedChild and
adoptiveParents. This simple solution is shown on the left below; it does not involve the Union
class and hence accounts for the fact that it may not require two people for an adoption to occur (e.g. an
aunt may adopt a child after the childs parents die).
On the right below is a variant in which we have added an Adoption class with its own
dateOfAdoption attribute. This variant is superior in that now a person can be adopted more than
once (can have more than one adoption, each with its own adoptive parents).
adoptiveParents 0..2

adoptiveParents 0..2

Person

Person
*

name
adoptedChild
sex
placeOfBirth
dateOfBirth
placeOfDeath child
dateOfDeath *
partner
* 0..2
{partner->forAll(p1,p2 |
p1 <> p2
implies p1.sex <> p2.sex)}
*

dateOfMarriage

*
name
adoptedChild
sex
placeOfBirth
dateOfBirth
placeOfDeath child
dateOfDeath *

Adoption
dateOfAdoption

partner
* 0..2
{partner->forAll(p1,p2 |
p1 <> p2
implies p1.sex <> p2.sex)}
*

Union
placeOfmarriage

*
0..1

Union
0..1
parents

dateOfDivorce

placeOfmarriage
dateOfMarriage

0..1
parents

dateOfDivorce

2. A significantly different approach is to make the Union be the entity doing the adopting. This makes
adoptions more similar in implementation to ordinary parent-child relationships, but requires a fake
union to be created in the case of single-parent adoptions.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A42

Person
name
sex
placeOfBirth
dateOfBirth
placeOfDeath
dateOfDeath

0..1

adoptedChild

Adoption
dateOfAdoption
*

child

partner
* 0..2
{partner->forAll(p1,p2 |
p1 <> p2
implies p1.sex <> p2.sex)}
*

Union
placeOfmarriage
dateOfMarriage
dateOfDivorce

0..1
parents

0..1
adoptiveParents

b) This exercise may be slightly offensive to certain cultures, although omitting the exercise may be offensive
to other cultures; in software we try to model reality.
The simplest way to change Figure 5.23 (c) to account for same-sex unions is to change the constraints.
The existing OCL constraint can be moved to the Person class, and modified slightly as follows:
context Person inv:
parents.partner.forAll(p1,p2 |
p1 <> p2
implies p1.sex <> p2.sex)
E5.18 p. 184 Making a preliminary list of classes by listing noun phrases in requirements.
In the following, we simply list a reasonable initial set of classes based on a first scan of the nouns in the
problem descriptions. Other lists are possible. Not all the nouns shown will end up in the final answers, shown
in the answer to E5.20. Classes where there is some initial doubt are marked ??.
a)*Bank account management system (p. 448)
Service ??
BankAccount
Branch
Client
MortgageAccount, ChequingAccount, CreditCardAccount
Property ??
CreditCard
JointAccount ??
Privilege ??
Division, SubDivision ??
Manager, Employee ??
Nouns not on the list because they will probably not be classes in the system:
System (because it is not part of the domain)
OOBank (an instance)
address, branch number (attributes)
account number, balance, credit limit, overdraft limit (attributes)
interest rate, monthly fee (attributes)
husband, wife (information in an example only)
cheque, insurance (possibly beyond the scope, may become classes later)
Planning, Investments, Consumer, Consumer Division (instances)
personal banker (association)
b) Election management system (p. 448)
To provide later.(but see diagram at E5.20)
c) Geographical information system (pp. 448-449)
To provide later (but see diagram at E5.20)
d) Investments system (p. 449)
To provide later (but see diagram at E5.20)
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A43

ANSWERS TO EXERCISES

e) Manufacturing plant controller (pp. 449-450)


To provide later.(but see diagram at E5.20)
E5.19 p. 187 Identifying attributes and associations and drawing a preliminary class diagram.
We will not provide an explicit answer to this exercise. The answers to E5.20 show a suitable set of attributes
and associations in the final answer.
E5.20 p. 189 Adding generalizations or interfaces to a class diagram.
a)*Bank account management system: See 5.21e for a related problem.
worksFor

Person
subdivision
*

name

OrganizationalUnit 0..1

manager

0..1

Employee

interestRate
monthlyFee
checksAllowed
insuranceAvailable

personalBanker

Branch
address
number

0..1

AccountType

Customer
*

1..2

accountHolder

*
*

Account

number
balance
creditOrOverdraftLimit

CreditCard
name
1..*

ChequingAccount

MortgageAccount
collateralProperty

CreditCardAccount
expiryDate

The distinction between AccountType and Account is important (so that each Account does not
need to store its own interest rate). There is a good chance, however, that students will not make this
distinction in their initial answers.
The following are some variations:
A customer is not always a person, so the generalization here may need to be changed so the top class is
LegalEntity, which has Customer as a subclass (or the generalization can be removed entirely)
There can be separate Department and Division classes, although the solution shown, using
OrganizationUnit is more flexible). It is important, however, not to add a separate class for each
division, as that would be very inflexible.
Each individual credit card may have its own number.
CollateralProperty and Address may be classes instead of simple attributes
You might add a separate Privilege class associated to AccountType, instead of the attributes
checksAllowed and InsuranceAvalable.
b) Election management system: The first diagram below (which is not the correct answer) shows the
central core of a very simple election system. We often use this as a starting point for discussion.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A44

Voter
name
address

CandidateForPosition
Position

isIncumbent
totalVotes
isWinner

title

The following is a more complete answer that accounts for the following:

The fact that voters might be able to run for more than one position
Keeping a record of different elections that occur on different dates
Tracking where each voter is supposed to vote.
Different positions on different elected bodies (e.g. school boards or city councils)

Take note of the following points that might not be so obvious:


1. We associate instances of CandidateForPosition with a Voter instead of making
CandidateForPosition a subclass. This is more flexible since it allows a voter to be a candidate
more than once.
2. Areas can be contain and be contained in sub-areas. For example a city might be divided into wards or
boroughs. Some positions represent a large area such as a city, while other positions represent a smaller
area.
Election
date

CandidateForPosition
*

isIncumbent
totalVotes
isWinner
*

runsAs

Voter

Position

name
address
*

ElectionForPosition

ElectedBody
name

title
*

votesAt

represents

Poll
location
number

locatedIn

Area
containedIn

description
*

c) Geographical information system: The association between the Feature and the FeatureType is
important (as will be discussed in Chapter 6, this is an example of the Abstraction Occurrence pattern).
However, you could instead have three associations between each feature subclass and its respective
feature type subclass, although this would be more complex to code (code for manipulating the
relationships would be the same in every pair). The association between Feature and FeatureType
could be one-directional. Making RegionFeature a subclass of CurveFeature is not the only
possibility; it could be made a direct subclass of Feature (same for the corresponding types).

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A45

ANSWERS TO EXERCISES

Map
scale
name
lattitide
longitude
height
width

*
Feature
name

FeatureType
description

CurveFeatureType
colour
thickness
dashLength
gapLength

PointFeatureType
*

symbol
PointFeature

Bitmap 0..1
fillPattern
bits

CurveFeature

Point *

RegionFeatureType
colour

RegionFeature

d) Investments system: The key insight in this question is to realize that mutual funds are, themselves,
investors. If multiple inheritance were to be used, MutualFund could be made a subclass of Investor.
InvestmentAdvisor
name
specialty
advises

arranged

Transaction
shares
pricePerShare
date
commissionRate
*

Investor
name

owner

actsAs

Investment
sharesOwned
*
amountInvested

MutualFund

Security
name
currentPricePerShare

Stock

Bond

* manager

FundCompany
name

e) Manufacturing plant controller: This is a particularly challenging problem simply because of the large
number of classes and associations. We will solve the problem paragraph by paragraph, showing at each
stage the new additions to the class diagram.
Paragraph 1: This is the central core of the system.
The manufacturing plant itself is a singleton and can be left out.
The class ProductType has been used instead of DeviceType or MechanicalDeviceType;
this generalizes the model.
Assembly step and manufacturing step are the same thing
ProductType
description
*
*
AssemblyLine
number

Paragraph 2 (changes are shown in red below)

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ProductRun
timePeriod
numUnits

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A46

{ordered}
AssemblyStep requiredToProduce
*
description
*
RobotAllocation
*
timePeriod
Robot
number

ProductType
description
*
*
AssemblyLine
number

ProductRun
timePeriod
numUnits

Paragraphs 3 (green) and 4 (blue):


We now have to distinguish between the ProductTypes that have parts (e.g. in general, cars have
wheels), and the specific Products that have specific parts. The reflexive aggregation between
instances of ProductType is many-to-many (a ProductType can be used as a part of many other
different ProductTypes). On the other hand, the reflexive aggregation between instances of
Product is one-to-many (a specific machine can be a part of only one other specific machine).
Assembly and Completed assembly are just synonyms for product.
The 0..1 multiplicity in the madeDuring and obtainedFrom associations is used to distinguish
circumstances when a Product is made by this plant or purchased.
The name of the class BillOfMaterialsLineItem is a standard term in production management.
Note that an AssemblyStep can put together several instances (numberRequired) of several
ProductTypes.
*

BillOfMaterialsLineItem
Bin
numberRequired

putTogetherDuring
{ordered}
requiredToProduce
AssemblyStep
*
description
*
RobotAllocation
*
timePeriod
Robot
number

Bin
number
*
keptIn

Supplier
obtainedFrom
name
0..1
*
* *
* availableFrom
ProductType
* Product*
description
0..1
ProductRun
* serialNumber
*
madeDuring
timePeriod
* *
*
numUnits
fulfilledBy
AssemblyLine
number
OrderLineItem

E5.21 p. 189 Additional exercises in drawing class diagrams, based on E2.10 (p. 41).
Since each of these lacks detail regarding the requirements, we have had to suggest the attributes and
associations that should be present. Note that each of these represents only part of a final system many
details (e.g. additional classes) have been omitted.
a)*Vehicles: We assume data is being maintained for hobbyists interested in data about a wide variety of
vehicles and their parts. In this answer, we decided to follow the pattern found in Figure 5.12 creating a
VehicleCategory class instead of modelling each type of vehicle as its own class. Students who
created the class hierarchy in E2.10 might simply transcribe it here; however, it is a good learning exercise
to show that although the hierarchy of E2.10 might have been good for preliminary domain modelling, the
answer below is much more flexible (it allows new vehicle types to be added without extra programming).
Note also that question E6.2 is related to this.
VehicleCategory
description
powerSource

isOfCategory
*

*
*
subcatgegory

Vehicle
name
* manufacturer

hasParts

VehiclePart
description
typicalNumber
*
subparts

b) Library: We assume a system for a university or city library. Note the following points:
The classes IssueOfNewspaper and IssueOfMagazine have been merged.
Similarly, the subclasses of Copy, Periodical and PartOfPublication have been eliminated
(the superclass suffices in each case)
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A47

ANSWERS TO EXERCISES

The author, publisher and part of publication have all been attached to EditionOrIssue instead of
Publication, since they can change from one issue/edition to another.
See Figure 6.1 on page 204 for a related problem; the answer given here has the additional concept of
edition or issue that Figure 6.1 lacks.
subparts
{ordered}

PartOfPublication
title
pageNumber

Publisher

tableOfContents *
{ordered}

Author

name

name
*

EditionOrIssue

Copy
*

issueNumber
publishedDate

barCodeNumber

Publication

hasEditionsOrIssues

name

{ordered}

EditionOfBook

IssueOfPeriodical

Periodical

isbn

volume

issn

libOfCongress

Book

frequency

c)*Bus scheduling: We assume a system for a bus company that runs regular routes as well as charters. This
has much in common with the Airline system (see the answer to E5.26). Note the following points:
The subclasses of BusVehicle have been merged, and the attribute category is used to determine
whether the bus is a luxury one or not.
Although it would seem that TripOnRoute would have no distinguishing features, and thus not need
to exist as a separate class, in fact it could contain the abstract operation getRoute, which would be
implemented differently in its two subclasses.
Information about bus stops not included in this model, but would be rather important.
BusVehicle
model
category
yearMade
identificationNumber

ActualTrip
*
date

CharteredTrip
startPoint
charterer
startTime
expectedReturnTime

TripOnRoute

ScheduledTrip
*

RegularlyScheduledTrip
depTime

UnscheduledTrip
*

BusRoute
routeNumber
origin
destination
normalRunningTiime

d) Video store: We assume a system for a store that sells music and videos as well as equipment for playing
the such works. Note the following points:
Many classes have been removed for flexibility: The different types of ElectronicDevice are now
represented using instances of the ProductCategory class; the media on which recordings are
available are represented using RecordingMedium (the type of music or film can be represented
using ProductCategory)
The individual copies of recordings have been left out since in a video store application, it would not be
conventional to keep track of each copy (unlike in a library). However, the expensive electronic
devices, which have serial numbers, are separately tracked.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A48

Many more attributes (and associated classes) could be attached to Work.


subcatgegory
*

Product

isOfCategory

ProductCategory
description

name

ElectronicDevice

Recording

* Work

name

*
*

SpecificDevice

RecordingMedium

serialNumber

description

e)*Financial institution: See 5.20a for a similar problem (that also includes the notion of customers which
are omitted here). Note the following points about this answer:
We have decided to make BankAccount a kind of FinancialInstrument; this is a bit different
from what we did in the answer to E2.10e, but has the advantage that it allows the denomination
association to inherit nicely.
It is well known that debit cards have PINs. Some have argued that credit cards dont. In fact they do
but the PINs are not used in some jurisdictions.
FinancialInstitution
name
Branch
CreditCardCompany

hasBranches

Bank

name
address

Currency
issuer

FinancialInstrument

denomination
*

code
exchangeRate

ReusableFinancialInstrument

Cheque

BankAccount

number
PIN

drawnAgainst
amount
date
*
sequenceNumber

accountNumber
balance
overdraftOrCreditLimit
1..*

CreditCard
creditLimit
name

DebitCard

connectedAccounts

Loan
monthlyPayment

f) Hotel: Note the following points:


We decided, when creating this answer, that there was little difference between a meeting, a catered
function and a conference.
We also decided that there is not sufficient difference between a meeting room and a ballroom to justify
having a separate Ballroom class.
We also eliminated the two subclasses of Person

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A49

ANSWERS TO EXERCISES

* subsidiaryBookings

ItemOnBill
HotelCompany

owns *

name

Hotel

description
charge

name
address
*

assignedSpace

composedOfRooms

Booking
*

RentableSpace
costPerDay
floorArea

startDate
endDate
startTime
endTime
* bedroomsRequired
creditCardToBill

responsablePerson

Person
name
address

Event
description

HotelBedroom

MeetingRoom

roomNumber
qualityLevel
isSmoking

name
maxSeatingCapacity

Suite

g) Insurance company. Note that this drastically oversimplifies the insurance industry!

Transaction
date

InsurancePolicy
policyNumber
monthlyPremium
startDate
endDate
insuredValue

Renewal

Claim
description
amountClaimed

*
holder

LifeInsurancePolicy

beneficiary

InsuredProperty

Person
name
address
dateofBirth

PropertyInsurancePolicy

yearBuilt

insuredLife

Vehicle

Building

identificationNumber
manufacturer
model

address
floorArea

h) Telephone system. We assume a system for a Central Office (telephone exchange) or PBX (private branch
exchange). Note the following points:
Telephone systems are some of the most complex pieces of software ever written. The answer given
below is an extreme over-simplification.
All of the generalizations have been removed because they did not add any apparent benefit in the final
class diagram.
The notion of call status is captured by examining the attributes and associations of a telephone call. No
separate class is therefore needed. Similarly, the notion of conference call is captured by examining the
number of telephone numbers connected to the call.
forwardedTo
*

originator

PhoneCall
isOnHold
startTime
duration

0..1

ringsOn

TelephoneNumber
parties
*

digits
*

hasWaiting

digitizedSound

VoiceMailBox

E5.22 p. 192 Determining responsibilities for each class.


2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

location
digOrAnalog

subscribesTo

belongsTo
*

VoiceMailMessage

PhoneLine
*

0..1

attachedTo

Feature

Telephone

description

model

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A50

It is important that these be simple phrases. Suitable classes for the responsibilities are given in parentheses. In
some cases the word singleton is used to indicate that the responsibility could be added to a singleton class
not shown in the answer to E5.20. There are sometimes several choices for suitable classes; all suitable
choices are listed, with the suggested one in italics. The plus symbol indicates that there should be several
polymorphic implementations in subclasses
a)*Bank account management system.
Adding a new customer (singleton, static Customer)
Changing details of a customer (Customer)
Opening an account (static Account +)
Crediting an amount to an account (Account)
Debiting an amount from an account (Account)
Changing the credit or overdraft limit on an account (Account)
Issuing a new credit card (CreditCardAccount)
Adding a new employee (OrganizationalUnit)
Changing details of an employee (Employee)
Assigning a personal banker to a customer (Customer, Employee)
Adding a new branch (singleton, static Branch)
Changing the address of a branch (Branch)
Changing an employees reporting relationship (Employee)
Changing the divisional structure in the organization (OrganizationalUnit)
Adding a new account type (singleton, static AccountType)
Changing details of an account type (AccountType)
b) Election management system (class allocation to be done)
Add election
Add elected body
Add area
Add position
Add election for position
Add voter
Change voter information
Delete voter
Add candidate for position
Add poll
Change poll location
c) Geographical information system
To be done
d) Investments system
To be done
e) Manufacturing plant controller
To be done
E5.23 p. 192 Determining responsibilities in the genealogical example.
The same notation is used here as was used in the last exercise.
Add person (singleton, static Person)
Remove person (Person)
Change person name (Person)
Change person attribute details (Person)
Add union (Person)
Remove union (Union)
Add a partner to a union (Union)
Change marriage details (Union)
Change divorce details (Union)
Create parent-child relationship (Person, Union)
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A51

ANSWERS TO EXERCISES

Remove parent-child relationship (Person, Union)


E5.24 p. 194 Adding operations to a class diagram.
These could be listed inside class boxes; however, we have just shown them as simple lists following each
class.
a)*Bank account management system
Account
Account(overdraftLimit, accountType)
credit(amount)
debit(amount)
changeOverdraftLimit(amount)
ChequingAccount
ChequingAccount(overdraftLimit, accountType)
MortgageAccount
MortgageAccount(initialBal, accountType, propertyDescription)
CreditCardAccount
CreditCardAccount(accountType)
addCard(name)
AccountType
changeInterestRate(newRate)
changeMonthlyFee(newFee)
changeChequingPrivilege(checksAllowed)
changeInsuranceDetails(insuranceDescription)
Person
(no operations at this level of analysis)
Employee
changeName(name)
changeOrganizationalUnit(newOrganizationalUnit)
Customer
assignPersonalBanker(employee)
Branch
changeAddress(newAddress, newPhoneNumber)
OrganizationalUnit
addEmployee(name)
changepParentUnit(newParentUnit)
b) Election management system
To be added
c) Geographical information system
To be added
d) Investments system
To be added
e) Manufacturing plant controller
To be added
E5.25 p. 194 Adding operations in the genealogical example.
Note that operations for getting attributes have been omitted to shorten the list. A legitimate argument cound
be made for not allowing the deletePerson and deleteUnion operations, on the grounds that once a
person is created it should not be possible to erase all trace of her or him. This, however, is an issue that
requires more analysis.
Person
deletePerson()
changeName(newName)
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A52

changeSex(newSex)
changePlaceOfBirth(newPlaceOfBirth)
changeDateOfBirth(newDateOfBirth)
changePlaceOfDeath(newPlaceOfDeath)
changeDateOfDeath(newDateOfDeath)
addUnion(person)
Union
deleteUnion()
changePlaceOfMarriage(newPlaceOfMarriage)
changeDateOfMarriage(newDateOfmarriage)
changeDateOfDivorce(newDateOfDivorce)
createChildRelationship(childPerson)
addPersonToUnion(person)
E5.26 p. 194-195 Extending the airline system to add new features.
The following is the complete class diagram incorporating the added features. Explanations of the features
follow. An alternative solution is also presented at the end.
PersonRole 0..2

Person

Airline

name
idNumber

PlannedLeg

EmployeeRole

PassengerRole

jobFunction

points

plannedStartTime
plannedEndTime

*
supervisor

origin

1..*

PlannedFlight

time
flightNumber

destination

AirportTerminal *
*

Booking
seatNumber
*
*0..1

Ticket

City

name

name

SpecificLeg

from

actualStartTime
actualArrivalTime

to

**

Fare

1..* *

0..1

number

price
class
distance
*

SpecificFlight
date

a) Flights fly from one airport terminal to another, but may also have several intermediate stops. A passenger
can be booked onto one or more of the legs of a flight.
Split flights up into legs;
Each leg has an origin and destination AirportTerminal;
Multiplicity from Booking to SpecificLeg is many to many.
Alternatives:
You could have omitted AirportTerminal, and instead had an Airport class or even simply had
origin and destination attributes. A string describing the terminal could then be stored in the
PlannedFlight class.
You could have both an Airport and an AirportTerminal classs.
You could have decided that every Booking will be for just one SpecificLeg, although the above
solution is probably better.
b) Passengers can query the system to determine at what times flights are available from their desired origin
city to their desired destination city (assume they do not care, within a city, about which terminal or
airport is used by the airline)
Added a City class, which can have several airport terminals.
It is important not to have classes called Query (because it is not part of the domain),
DestinationCity or OriginalCity (because they are just ordinary cities).
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A53

ANSWERS TO EXERCISES

c) Flights have scheduled departure and arrival times, but they can be late, so they have actual departure and
arrival times as well.
Actual times added to SpecificLeg.
d) The airline may add charter flights that are not regularly scheduled.
RegularFlight name changed to PlannedFlight, since there may only be one occurrence.
You might have considered subclassing this into CharterdFlight and RegularFlight, but you
would have had to show that there are different attributes, in that case. An attribute of
CharteredFlight might be charteringOrganization.
e) The airline publishes prices that apply between any pair of cities to which it flies. Business class, regular
and seat-sale fares are available.
Added a Fare class to capture this information. Note that the fare type is typically called class in the
airline industry.
You do not need a separate classes called BusinessClass, Regular or SeatSale. These are just
values of the class attribute of Fare.
Alternatives
The attributes in Fare could be businessClassFare, economyClassFare.
You could associate Fare with individual specific flights (there are various advantages and
disadvantages to this). You could also have a start and end date for each fare.
f) Passengers buy tickets and are charged the prices in effect when their tickets were booked. Each ticket
involves a complete itinerary, composed of a sequence of one or more legs. The fare type is not necessarily
the same for each leg of the flight.
Added a Ticket class. A ticket is for zero or more bookings. Zero bookings is possible in the case of
an open return, or if a ticket is issued from one city to another that is valid at any time. A Booking may
not yet have a Ticket issued for it. A ticket has a specific set of Fares.
A ticket has to be linked to both Booking and to PassengerRole. It has to be linked to Booking
since it must list all the legs (if any) that are booked.
g) Passengers are automatically part of a frequent-flier plan. They accumulate points based on the distance
they flew and their class (business class or not).
Added a points attribute to the PassengerRole class. Distance information is recorded in the
Fare class.
The following is an alternative answer. Instead of using legs (the edges of the graph designating a flights
route) it uses instances of AirportVisit (the vertices of the graph). The drawback to this is that the
starting point of a flight would only use the depTime while the ending point of a flight would only use the
arrTime.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)
PersonRole 0..2

Person

Airline

name
idNumber

AirportVisit

EmployeeRole

PassengerRole

plannedArrTime
plannedDepTime

*
2..*
1..*

PlannedFlight

supervisor

jobFunction

points

A54

origin

time
flightNumber

destination

AirportTerminal *
*

Booking
seatNumber

from

to

name

SpecificAirportVisit

from

Fare

2..**

0..1

Ticket

to

**

actualArrTime
actualDepTime

*
*0..1

City

name

price
class
distance

number

SpecificFlight
date

E5.27 p. 195 Adding responsibilities and operations for new features of the airline system.
To be provided
P5.1

p. 199 Class diagram for Small Hotel Reservation System


QualityLevel

Hotel
name
addQualityLevel
getQualityLevel
getQualityLevels
getGuestList
getRoom
addGuest
removeGuest
searchForGuest
saveGuestData
readDescriptionFile

name
level
characteristics
maximumPrice
pricePerExtraPerson
numberOfCategories
getNumberOfRooms
getPrice
getRooms
addCharacteristic
removeCharacteristic
getNumberOfAvailableRooms
getNonAssignedRooms
addRoo
removeRoo
getCategoryDescription

name
roomNumbe
numberOfBeds
typeOfBeds
smoking
category

Guest
name
address
phoneNumbe
createReservation
cancelReservation
getListOfStays

*
*

Stay
id
arrivalDate
numberOfNights
roomChargePerNigh
numberOfPersons
categoryNumber

Room

adjoin

0..2

0..2

getQualityLevel
getAssignedStays
getDescription
adjoinRoo
unadjoinRoo

getDepartureDate
assignRoom
getRoomCategory
getRooms
inConflict
inConflict

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A55

ANSWERS TO EXERCISES

Chapter 6. Using design patterns


E6.1

p. 206 Applying the Abstraction-Occurrence pattern.


a)*
Periodical
name
publicationFrequency
issn

* PeriodicalIssue

volumeNumber
issueNumber
publicationDate
numPages

b) The following assumes what is being developed is a library system. In this library each copy is stamped
with a different bar code number (distinct from the bar code number printed by the publisher which would
be the same for all copies).
PeriodicalIssue

* CopyOfPeriodicalIssue

volumeNumber
issueNumber
publicationDate
numPages

barCodeNumber

If, instead, the system being developed was a publishers distribution system, the diagram might look like
this:
PeriodicalIssue

* CopyOfPeriodicalIssue

volumeNumber
issueNumber
publicationDate
numPages

subscriberName
subscriberAddress

c)
TelevisionEpisode
name
producer
director
summary
runningTime
contentRating

E6.2

startTime
televisionStation

p. 208 Representing a hierarchy of parts using the Composite pattern.


All the actual parts shown in the original figure (Figure 5.20) would be instances of the classes shown here.
Vehicle

* VehiclePart
*

VehicleCompositePart

E6.3

* ShowingOfTVEpisode

VehicleAtomicPart

p. 208 Ensuring that the General Hierarchy pattern is applied in E5.9 (p. 168).
There are several ways of naming the non-superior and superior nodes in this exercise. Below is one way. As
an extension, the class Country could be made a subclass of SubdividedTerritory. As shown, the
class diagram would allow gteneration of an instance hierarchy, part of which might include, for example:
that, for example, European Union -> United Kingdom -> (England, Scotland, Wales and Northern Ireland),
and within each of those, various levels of counties and municipalities. The lowest level municipalities would
be the only instances of class UnsubdividedTerritory.
The question required the use of the general hierarchy pattern. However, in a real system it might be better
to remove the SubdividedTerritory and UnsubdividedTerritory classes and represent the partof relation as a reflexive association of Territory. This might be a bit more flexible.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A56

PoliticalEntity
name
borders
*

Territory

isMemberOf *

InterGovernmentalOrganization

SubdividedTerritory

UnsubdividedTerritory

E6.4

p. 215 Finding applications for the delegation pattern in the genealogical example.
While there are many situations in Figure 5.23 (c) where a method would call a method in a neighbouring
class, there are actually relatively few opportunities where the calling method only call a neighbouring method
(and do nothing else). Two notable exceptions are listed below. The reason for the shortness of this list is that
there is only one association with a 1 or 0..1 end; it is such associations that tend to give rise to
opportunities for pure delegation.
It would be reasonable to have a method getMother in class Person. This would delegate through the
child-parents association to a method of Union called getFemalePartner.
There would presumably be a similar method getFather that would delegate to a method of Union
called getMalePartner.

E6.5

p. 221-222 Determining the pattern(s) that would apply in specific design circumstances.
a)*Adapter (in your inheritance hierarchy create an adapter class that whose methods delegate to those in the
class you want to reuse)
b) Immutable (RegularPolygons distortion operations return new instances of some other class that is
probably not a RegularPolygon)
c) Proxy (Most of the time a ProxyImage exists in memory; methods in this class cause the
HeavyWeightImage to be loaded when required)
d) Faade (Create a Faade class in the subsystem that has a public interface with only the 5 key methods;
these will delegate to the other methods inside the subsystem, which would not be public)
e) Observer (The StockQuoter is the Observable; the other classes observe it)
Note, parts a, c and d also use delegation, but this is not the dominant pattern here.

E6.6

p. 222 Writing a description of the Iterator pattern that is already implemented in Java.
The Iterator pattern
Context: Collections (lists, arrays, sets etc.) are very common data structures. It is also common when
designing algorithms to want to visit every element of a collection (or to visit every element up to a certain
point, at which time you decide to stop); this might be for the purposes of searching for a particular element,
extracting information from each element, or performing some computation such as summing the elements.
Problem: How do you best allow for an operation to be performed on every element of a collection?
Forces: You want the code to be simple; you want to protect the internals of the collection classes, and permit
the internals to be changed without affecting the code that accesses each element; you want to reduce the
chances of errors among those who use the mechanism. Extreme efficiency is not a concern.
Solution: Create an interface called Iterator with next as its main operation. Then, in every collection
class, create an inner class that implements the Iterator interface, as well as a method iterator that
returns an instance of this inner class. When an algorithm needs to process the elements of a collection, it
simply calls the iterator method, and then repeatedly calls next on the result. To allow for efficient
detection of the end of the collection, provide a hasNext operation in the Iterator interface that will
return true only when next has not reached the end of the collection and will hence return a result.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A57

ANSWERS TO EXERCISES

interface
Collection

interface
Iterator

iterator

next
hasNext

ConcreteCollection

ConcreteIterator
*

iterator

next
hasNext

Antipattern: Loop through the elements using a while or for loop. This has several disadvantages: It is
bug prone (the starting or terminating condition may be coded incorrectly); the code is less abstract; it requires
knowledge of the internal structure of the collection class; there will have to be a separate loop for every
algorithm that needs to visit the elements (multiplying the chance of bugs and multiplying the exposure to the
internals of the collection), and the loops may have to be changed if the data structure is changed.
References: This pattern was derived from the code implementing the Java Iterator interface.
E6.7

p. 222 Writing a pattern representing the concept of a Cache.


a) The Cache pattern
Context: A computational element often needs to make requests of another. The elements in question could
be as diverse as a client obtaining information from a server, or a CPU accessing memory. If identical requests
will result in identical responses, then there may be a waste of computational and/or network resources in
repeatedly computing and returning the same answer.
Problem: How do you prevent repetition of some computational operation, in circumstances when an
identical request may be made repeatedly.
Forces: You want to maximize the overall efficiency of the system. The aspects of efficiency to be balanced
include network bandwidth and computational power. You also want to reduce the time it takes the requestor
to obtain the desired result.
Solution: Create a cache that will store the results of recent requests. When a new request is to be made, a
check is first made to see if that request has recently been made, and hence the result is still in the cache. If a
valid result is still in the cache, then this result is returned. The client or the server can manage the cache, or it
can be a separate component.
Client

Cache
request

Server
request

There must also be a mechanism to limit the size of the cache. This can be done by defining recent in
terms of a limited period of time, a specific number of requests, and/or the frequency with which a particular
request is made.
There will often also be a need for a way to invalidate a cached result in circumstances when the request
to the server would return a different result from what was previously returned (and is in the cache).
Antipattern: Sometimes the time taken to search the cache can exceed the time taken to service the request;
hence the cache must be significantly more efficient than the request server, and/or must be kept at a
reasonable size.
Related pattern: The Proxy pattern is similar in the sense that access is made to the cache (proxy) by default,
and only to the server (heavyweight) when needed.
b) This is a practical exercise only.
E6.8

p. 224-225. Analysing designs to determine the extent to which a pattern applies.


In the following, we consider only the client side; the server side operates analogously.
ObservableClient acts as an adapter in the sense that it is a member of an inheritance hierarchy (of
Observable) that accesses the services of AdaptableClient. The latter class cannot be put in the same
hierarchy because it already has a superclass. However, there are some important differences from the classic
adapter pattern:

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A58

Delegation does not only occur from adapter to adaptee, but in the other direction as well: The three
methods connectionEstablished, connnectionClosed and handleMessageFromServer
call the corresponding methods in ObservableClient.
Some key methods that are being delegated to AdaptableClient (openConnection,
closeConnection, etc.) are not polymorphic in the hierarchy of Observable.
A classic adapter is often written to access code written by a third party (e.g. the Torus class accessing
TimsTorus in Figure 6.10). In the case of ObservableClient, all the classes have been written by
the same developers.
E6.9

p. 225 Summarizing the advantages and disadvantages of the Observable layer of OCSF.
The main trade-off is increasing flexibility at the cost of efficiency and complexity.
Advantages:
Users of the ObservableClient and ObservableServer can create many different observer
classes in their system that independently react to different messages. Adding new observers is very easy
and does not require changing any of the code related to other observers. Without the observable layer, it
would
be
necessary
to
edit
handleMessageFromServer
(and
perhaps
also
connectionEstablished and connectionClosed) whenever new functionality is to be added.
Disadvantages:
The OCSF framework is more complex. Originally there were just three classes; now there are eight.
The Observable pattern is not particularly efficient when there are many observers interested in different
messages. This is because the notifyObservers message causes all the observers to receive a message
they ignore messages they are not interested in.

P6.1

p. 227 Applying the OCSF observable layer to SimpleChat to produce version 4


See the accompanying source code.

P6.2

p. 227 Applying patterns to the Small Hotel Reservations System.


The Hotel class can be designed as a singleton. This way, the important functionalities of the system,
such as access to guests and rooms will be publicly accessible through it.
The QualityLevel and Room classes could be made immutable. This would ensure that their
configuration would not be changed after a reservation has been made. However, in some cases, more
flexibility might be required where, for example, the manager may want to change the beds in a room.
However, allowing this kind of modifications can be tricky, since this will affect the room availability.
In the case of the client/server version of the system, a proxy for the Stay class would have to be created.
This lightweight version of the class would simply replace the associations with the Room and
QualityLevel classes by room number and level number attributes. This would ensure that when a
Stay instance is sent to a client, then all the associated objects do not have to be sent with it.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A59

ANSWERS TO EXERCISES

Chapter 7. Focusing on users and their tasks


E7.1

p. 232 Reflecting on the usability and usefulness of everyday software.


This exercise is highly subjective; answers will depend on the software chosen, the version of the software and
the readers personal experience with the software.

E7.2

p. 234 Determining the types of users who will use systems.


a)*An air traffic control system would be used by highly trained air-traffic controllers and their managers.
They would be using the system intensively throughout their working day. Some aspects of the system
might also be used by pilots, government aviation authorities and airport administrators.
b) The GANA system would be used by anyone who drives a car, as well as other people sitting in the
passenger seat of a car (i.e. teenagers and anyone older). The users might speak different languages, and
might be deaf or have certain physical disabilities. They would not necessarily have any knowledge of
navigation or computers.
c) A microwave oven would be used by practically anybody, including relatively young children. Such a
system should be as accessible as possible to the disabled.
d) The configuration and data-entry aspects of a payroll system would probably be handled by people with
expertise in human-resources and finance. However, they would not necessarily have any computer
expertise. Some outputs of a payroll system, including the printed cheques and pay stubs, might be used by
all employees.

E7.3

p. 237 Writing use cases


a)*The sequence of operations could differ from bank to bank.
Use case: Pay bill at ATM.
Actors: Any member of the general public with a bank account and bills to pay (minimum likely age is
16)
Goals: To efficiently and accurately pay his or her bill
Preconditions: The actor must have an account at the bank. The bank must accept the bill in question
for payment. The actor must have their bank card and know their PIN. The actor must have
sufficient funds in their account.
Steps:
Actor actions
1. Insert card.
3. Enter PIN.
5. Specify pay bill.
7. Enter details of bill.
9. Deposit bill.

11. Indicate no other transaction.


13. Take card.

System responses
2. Prompt for PIN.
4a. Display list of possible transactions.
4b. Prompt for desired transaction.
6. Prompt for details of bill.
8. Prompt to deposit bill using an envelope.
10a. Accept deposit.
10b. Debit account.
10c. Print receipt.
10d. Prompt to see if there is another transaction.
12. Eject card.
14. Display welcome message.

Postconditions: The system has stored the bill physically, and has a record of the transaction. The actor
has a receipt for the transaction.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A60

b) The following has been based on Microsoft Word (although is as user-interface independent as possible).
The sequence could differ in other word processors.
Use case: Create a table in a word processor.
Actors: Any member of the general public with a basic knowledge of how to operate a word prcessor.
Goals: To create a table as quickly as possible
Preconditions: The actor must be running the word processor and have in mind the information to be
placed in the table. The actor must have positioned the cursor at the spot where the table is to be
inserted.
Steps:
Actor actions
1. Select the insert table command.
3a. Specify the requested information.
3b. Indicate that the information is correct.

System responses
2. Prompt for the number of rows and columns, as well as
the format.
4. Insert a table.

Postconditions: The table appears in the document as specified. The cursor is positioned in the first
cell of the table.
c) We have tried to be as user-interface independent as possible, but there are a number of different sequences
in which the following actions could be taken.
Use case: Program a microwave oven to turn on at a future time
Actors: Any member of the general oven preparing a meal in advance; minimum likely age is 12.
Goals: To set up the microwave as easily and quickly as possible to start cooking at a future time.
Preconditions: The food must be in the oven. The oven is idle.
Steps:
Actor actions
1. Press the delayed cooking button.
3. Enter the start time.
5. Specify the cooking duration.
7. Enter start.

System responses
2. Prompt for the start time.
4. Prompt for the cooking duration.
6. Prompt to enter start.
8. Display indication that it is waiting to start cooking.

Postconditions: The oven starts cooking at the specified start time, and cooks for the specified
duration.
d) There are several sequences in which voice mail systems system can be used. Some systems will not delete
messages as the default. Others will play all messages, not just new ones.
Use case: Listen to voice mail messages.
Actors: Any member of the general public, including children as young as about 5.
Goals: To listen to all messages waiting.
Preconditions: The system has been set up to take messages.
Steps:
Actor actions
1. Initiate the play new messages operation.
3. Indicate that he or she wants to listen to the next
message.
5. Indicate that he or she wants to delete the
message and proceed.

System responses
2a. Indicate number of new messages.
2b. Prompt the user to proceed.
4a. Play the next message (if any).
4b. Prompt the user to delete and proceed.
6a. If there are more messages repeat at step 4).
6b. If there are no more new messages, notify the user.

Postconditions: The user has listened to all the new messages. The new messages have been deleted.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A61

E7.4

ANSWERS TO EXERCISES

p. 238 Drawing use case diagrams


a)*Library system (based on example 4.9, page 126) We give two answers for this: The first does not use
generalization, which had not yet been discussed in the text in the context of use case diagrams. This
diagram is excessively complex so would not be worth drawing in a real software engineering project.
Search for
items by
title

Search for
items by
author

Borrower

Search for
items by
subject

Add a
new item
Delete
an item

Place a
book on
hold

Change
an item's
information

Librarian
Check
personal
information

Check out
an item

Checkout Clerk

Check in
an item
Renew
an item

Update a
borrower's
information

Record
fine
payment

Obtain
overdue fine
amount

Add a
borrower
Accounting System

The second version of the answer uses generalization, showing how the diagram can be simplified (fewer
lines)
Place a
book on
hold

Search for
items by
title

Check
personal
information
Borrower
Check out
an item

Search for
items by
subject

Accounting System
Update a
borrower's
information

Check in
an item
Renew
an item

Search for
items by
author

Checkout Clerk

Add a
new item

Add a
borrower

Obtain
overdue fine
amount

Record
fine
payment

Change
an item's
information
Delete
an item

Librarian

b) Mail order system (based on exercises E4.12 and E4.13, page 126). As with part a, above, we have also
used generalization here to reduce the complexity. However, students who did not read ahead would not be
expected to do so.
Note that use case diagrams can be clumsy; the answer to E4.13 seems a clearer expression of this
information. The only information that is expressed more clearly is the generalizations among different
actors.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A62

Change
password

Sign in
Sign out
Inventory
system user
Display next
order

Confirm
shipment
completed

Enter
received
shipment
Shipper

Display
location of
item

E7.5

Receiver

Inventory
Taker

Display
inventory
statistics

Assign
delivery to
receiver

Display
performance
statistics
Assign
shipment to
shipper

Enter item
count

Warehouse
Supervisor

Add
personnel
member

Answer
call

Display
customer
info

Add item
to sale
Complete
sale

Display
operator
statistics

Telephone
Operator

Telephone
Operator
Supervisor

Search
catalogue
Display item
technical
info
Display item
avail & price
info

Override
price

p. 240-241 Writing use cases for the car park system.


a)*
Use case: Exit car park by paying using a debit card.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A63

ANSWERS TO EXERCISES

6.2c. Raise barrier.


8. Lower barrier.

7. Drive through barrier, triggering a sensor.

The above does not deal with the situation where the driver runs out of money and has to cancel the
operation. That would be a separate use case.
c) This is mostly the same as Example 7.2, with a few minor generalizations.
Use case: Exit car park.
Actors: Car drivers.
Goals: To leave the car park after having paid the amount due.
Preconditions: The driver must have entered the car park with his or her car and must have picked up a
ticket upon entry.
Summary: When a driver wishes to exit the car park, he or she must bring his or her car to the exit
barrier and interact with the machine to pay the amount due.
Related use cases:
Generalization of: Exit car park, paying cash and Exit car park by paying using debit card.
Steps:
Actor actions
1. Drive to exit barrier, triggering a sensor.

System responses
2a. Detect presence of a car.
2b. Prompt driver to insert his or her card.
4. Display amount due.
6a. Acknowledge payment.
6b. Raise barrier.
8. Lower barrier.

3. Insert ticket.
5. Make payment.
7. Drive through barrier, triggering a sensor.

Postconditions: The driver has exited the car park.


E7.6

p. 241 Drawing use case diagrams involving extension and specialization.


Exit Car
park

Driver
Exit car park,
paying cash

extend

Attempt to exit car


park without initially
entering enough
money

E7.7

p. 242 Listing use cases and prioritizing them.


a)*A telephone answering machine.
Record outgoing message
Record incoming message
Listen to incoming messages
Skip back to previous message
Erase a message
Skip to next message
Record a conversation

b)

The GANA navigation system.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

Exit car park by


paying using a
debit card

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A64

Set destination
Start navigating
Change scale
Scroll map
Display current location
Display destination location
Navigate to destination
Change to setup mode
Obtain constant spoken directions
Obtain a single spoken direction
c) A video-cassette recorder.
Play tape
Stop playing
Start recording
Stop recording
Rewind
Eject tape
Fast forward
E7.8

p. 257 Creating error messages for a user interface.


a)*There are unlikely to be any error messages on this screen!
b) You must provide your name
You must provide at least one address
You must specify the street in your {home/work/mailing} address
You must specify the municipality in your {home/work/mailing} address
You must specify the postal code in your {home/work/mailing} address
c)* Your credit card number has only {n} digits; it must have {at least} {m} digits
The expiration month {mm} is not in the range 01 to 12
You must specify an expiration date
You must specify your credit card number if you wish to register.
d) Sorry, but your credit card transaction was not accepted by the credit card company.
Sorry, but the system was not able to process your transaction because {the credit card companys
system was temporarily unavailable}

E7.9

p. 257 Determining whether response time is adequate at a web site.


The answer to this exercise depends on the design of the web site chosen (and that web sites response time
may change from time to time).

E7.10 p. 257 Preparing a paper prototype.


This a practical exercise with no specific right answer.
E7.11 p. 257 Preparing a prototype UI for the GANA system.
An example UI will be provided in a future version.
E7.12 p. 258 Performing heuristic evaluations of user interfaces.
The answers to this exercise depend on the programs chosen, the versions of those programs, and the parts of
the programs evaluated.
E7.13 p. 258 Performing a heuristic evaluations of a web site.
The answers will depend on the web site chosen.
E7.14 p. 258 Having multiple people conduct separate heuristic evaluations.
This is another subjective exercise.
E7.15 p. 259 Performing heuristic evaluation of a GANA prototype and updating the UI.
THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A65

ANSWERS TO EXERCISES

This is another subjective exercise.


E7.16 p. 260 Performing an evaluation of a UI by observing users.
This is another subjective exercise.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A66

Chapter 8. Modelling interactions and behaviour


E8.1

p. 273 Drawing sequence diagrams.


a)*Library example: This assumes that there is a Library singleton class acting as a Faade.
foundBook:
CopyOfBook

:Library

foundBook :=
search(title)

:Loan
borrow
[available] create

b) Genealogy example (based on Figure 5.23(c). This problem is surprisingly time-consuming, and would be
complex if drawn as one large diagram. Rather than doing that we developed three simpler ones. The first
makes use of getSiblings, and getChildren, which are described in the second and third diagrams
respectively. Note that a good answer to this problem should reduce the necessity for an object to access
non-neighbours, and should instead make as much use of delegation as possible. For example,
getCousins does not directly compute the cousins; instead, it asks the parents to compute their nephews
and nieces.
:Person

getCousins

parentUnion:
Union

parents:
Person

parents.siblings:
Person

parentUnion :=
getParentUnion
parents :=
getParents
* [for all parents]
nephnieces

siblings :=
getSiblings
* [for all siblings]
getChildren

:Person

getSiblings

parentUnion:
Union

parents:
Person

parentUnion :=
getParentUnion
parents :=
getParents
* [for all parents]
getChildren

:Person

getChildren

unions:
Union

unions :=
getUnions
* [for all unions]
getOffspring

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A67

ANSWERS TO EXERCISES

c) Banking example
:Bank
client: Client

client :=
find(name)

[not found] create


:BankAccount

createAccount

create
deposit(amount)

E8.2

p. 275 Drawing collaboration diagrams.


1:*[for all Purchase] getSubtotal

2:getUnitPrice

:Bill

:Purchase

:Item

3:computeTotal

E8.3

p. 275 Drawing more collaboration diagrams


These correspond to the answers to E8.1
a)*Library example
GUI

1:foundBook :=
search(title)

:Library

2:borrow

3:[available] create

foundBook:
CopyOfBook

:Loan

b) Genealogy example (based on Figure 5.23(c), and in three parts as in E8.1b)


2:parentUnion :=
getParentUnion

GUI

1:getCousins

:Person

3:parents :=
getParents

parentUnion:
Union

4:* [for all parents]


nephnieces
6:* [for all siblings]
getChildren

parents:
Person

parents.siblings:
Person

5:siblings :=
getSiblings

2:parentUnion :=
getParentUnion
1:getSiblings
:Person

3:parents :=
getParents

4:* [for all parents]


getChildren

parents:
Person

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

parentUnion:
Union

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A68

2:unions :=
getUnions
1:getChildren
:Person

3:* [for all unions]


getOffspring

unions:
Union

c) Banking example
1:find(name)
GUI

:Bank
3:createAccount

2:[not found] create

5:deposit(amount)
client: Client
:BankAccount

E8.4

4:create

p. 279 Adding conditions to a state diagram.


Note that we have also shown conditions on the transitions between XTurn and OTurn, even though the
question did not require it.
[3 X in sequence]

XTurn
[not
3 X in sequence]

[not
3 O in sequence]

[impossible to get 3 in
sequence]

[impossible
to get 3 in sequence]

OTurn

E8.5

XWin

Tie

OWin

[3 O in sequence]

p. 279 Determining the state the system would be in after a sequence of events.
a)*It would be in state Cancelled.
Rationale:
Initial = Planned;
openRegistration -> OpenNotEnoughStudents (classSize=0);
requestToRegister -> OpenNotEnoughStudents (classSize=1);
requestToRegister -> OpenNotEnoughStudents (classSize=2);
cancel->Cancelled
b) It would be in state Closed
Rationale:
Initial = Planned;
openRegistration -> OpenNotEnoughStudents (classSize=0);
requestToRegister(twice) -> OpenNotEnoughStudents (classSize=2);
requestToRegister -> OpenEnoughStudents (classSize=3);
requestToRegister -> OpenEnoughStudents (classSize=4);
requestToRegister -> Closed (classSize=5)
requestToRegister (3 more times ignored since no outgoing transition)
closeRegistration (ignored since no outgoing transition)

E8.6

p. 280 Adding transitions to a state diagram.


The following changes were made to develop this answer:
Two new cancel transitions were added, one of which has a [not taught] condition.
Three requestToDrop transitions were added. These were made conditional on the student actually
being registered. In the case of the transition from Closed, we also want to ensure that the course has not
already been taught before allowing a drop.
A classSize < minimum transition was added to account for the case where dropping should cause a
transition to OpenNotEnoughStudents.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A69

ANSWERS TO EXERCISES

Planned
cancel

openRegistration

closeRegistration

OpenNotEnoughStudents

Cancelled
cancel
[not taught]
cancel

[not taught]
cancel

closeRegistration

Closed
classSize >= maximum

[isRegistered(aStudent)]
requestToDrop(aStudent)
/deleteRegistration
requestToRegister(aStudent)
/createRegistration

classSize <
minimum

classSize >= minimum


[isRegistered(aStudent)]
requestToDrop(aStudent)
/deleteRegistration
OpenEnoughStudents
requestToRegister(aStudent)
/createRegistration

[notTaught and
isRegistered(aStudent)]
requestToDrop(aStudent)
/deleteRegistration

E8.7

p. 280 Creating a state diagram for a traffic light.


There are two reasonable ways to answer this. The first approach involves mostly re-labeling the states
according to what the light at point 1 is doing. However, we have to change the position of the
YellowLight states, and the timing of the transitions surrounding these.
after(5s)

RedLightNoTrigger

YellowLight

vehicleWaitingToTurn

RedLightChangeTriggered
after(30s since exit from
state GreenLight)

after(25s)

GreenLight

The second approach is to label the states according to what both lights are doing at any given point in time. In
that case, there will be one extra state. This is actually a nicer answer, and is also the style requested for E8.8
below.
after(5s)

1Red2Green

vehicleWaitingToTurn

1Yellow2Red

1Red2GreenChangeTriggered
after(25s since exit from
state 1Green2Red)

1Red2Yellow

after(25s)

after(5s)

1Green2Red

Note that the state 1Red2Yellow might be better called 1Changing2Yellow, since in some countries
(e.g. the UK), when a traffic light is about to go green, it displays red and yellow at the same time.
E8.8

p. 280 Creating a state diagram for a four-way intersection.


NSRed-EWGreen

after(5s)

after(25s)

NSChanging-EWYellow

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

NSYellow-EWChanging
after(25s)

after(5s)

NSGreen-EWRed

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

E8.9

A70

p. 280 Creating a state diagram for an intersection with turning signals.


Note that the details of the answer to this question will depend on the traffic rules of the jurisdiction in
question, as well as the details of the individual intersection. In the following, there is a 2s interval during
which all lights are red; this allows turning vehicles to clear the intersection.
NSRed-EWGreen

after(5s)

NSYellow-EWChanging

after(25s)

NSRed-EWYellow

after(25s)
[not vehicleWaitingToTurn]
after(5s)

[vehicleWaitingToTurn]
after(5s)

NSGreen-EWRed
after(2s)

after(12s)

NSTurningEWRed

NSRedEWRed

E8.10 p. 280 Creating a state diagram for a vending machine.


This problem is best solved after students learn about guard conditions. Given that guard conditions are only
discussed on page 283, we give here two answers. The first just uses simple conditions:
notEnoughMoney and pressSelection
/displayNotEnoughMoney
enterCoin
/displayTotal

Waiting

returningComplete

noChangeRequired
and deliveryComplete

ReceivingMoney

enterCoin
/displayTotal

enoughMoney and
pressSelection

pressReturn

ReturningMoney

changeRequired and
deliveryComplete

DeliveringItem

The second version uses guard conditions:


[not enoughMoney]pressSelection
/displayNotEnoughMoney
enterCoin
/displayTotal

Waiting

returningComplete

[not
changeRequired]
deliveryComplete

ReceivingMoney

enterCoin
/displayTotal

[enoughMoney]pressSelection

pressReturn

ReturningMoney

[changeRequired]
deliveryComplete

DeliveringItem

E8.11 p. 283 Finding a missing transition in the automatic transmission state diagram.
The missing transition is selectDrive from the unnamed drive state to itself. This enables the driver to
shift the control from First or Second to Drive. This change is reflected in the answer to E8.12, below.
E8.12 p. 283 Adding the Park control to an automatic transmission state diagram.
This is actually a very simple change. As with Reverse, we assume that you cannot suddenly jump to or
from Park, but must shift through Neutral.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A71

ANSWERS TO EXERCISES

Park
selectNeutral

selectPark
selectReverse

Neutral

Reverse
selectNeutral

selectFirst

selectDrive

selectSecond

reachSecondSpeed
[driveSelected]

selectNeutral
reachThirdSpeed
[driveSelected]

First

Second
dropBelowSecondSpeed
[driveSelected]

selectFirst

selectDrive

Third
dropBelowThirdSpeed

selectSecond

E8.13 p. 283 Learning about the history state.


The history state is a circle containing an H that is found within a state that has substates. Any transition to
the history state from outside causes a transition to the most recently visited substate (that was active before
the main state was last exited).
E8.14 p. 283-284 Drawing and extending state diagrams.
a)*Jukebox.
[not enoughMoney]pressSelection
/displayNotEnoughMoney
enterCoin
/displayTotal

ProposeSelection

AcceptingMoney
pressReturnMoney
/returnMoney

enterCoin
/displayTotal

[enoughMoney]pressSelection
/returnChangeIfNecessary

MusicPlaying
do:
play chosen
selection

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A72

b) Microwave oven. (based on Example 4.6, page 112-114). Note that this answer corresponds to the
specifications as given; students may have a different answer of they made improvements following the
review conducted in E4.18. Note that the low-pitched tone following input of an invalid key has not been
modelled here.
pressCancel

AcceptingInput
[validTime]pressTimeOfDay

pressTimeOfDay

[<4 digits]
pressDigit

AccumulatingTimeOfDayDigits

Idle
pressDigit

do:
display
timeOfDay

[<4 digits]
pressDigit
[4 digits] pressDigit

AccumulatingCookingTimeDigits
pressPowerLevel

CookTimeSpecificationComplete
pressAutoDefrost

AccumulatingCookingWeightDigits

[<1 digit]
pressDigit

[1 digit] pressDigit

CookWeightSpecificationComplete
pressAutoReheat

AwaitingTemperatureButton
pressATemperatureButton

CookReheatSpecificationComplete

[doorClosed] pressStart
sufficientSteam
/soundThreeBeeps

[doorClosed] pressStart

Cooking
AutoReheatCooking

cookingTimeLimitReached
/soundThreeBeeps

TimeBasedCooking
H

do: cookFood
openDoor

Suspended

[doorClosed] pressStart

c) VCR. There are many possible answers to this, depending on the VCR; the one shown below is a good
solution
endOfTape
powerUp

StandbyForAutomatic
Recording

Off

on

On

[tapeInserted & notAtEnd]


recordTimeReached

AutomaticRecording

programEnd
[noProgramScheduledNow]
standby

on

[programScheduledNow]
standby

ShowingTVChannel
ManualRecording
[tapeInserted]record

stop

[tapeInserted]rewind

Rewinding

Idle
endOfTape

[tapeInserted]fastForward

FastForwarding

[tapeInserted]play

PlayingTape
fastForward FastFwdingSlowly
PlayingTapeNormally
WhilePlaying
play
rewind

play

RewindingSlowly
WhilePlaying

rewind
fastForward

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A73

ANSWERS TO EXERCISES

Some comments about the above:


It is important to show some substates to reduce the total number of transitions. For example, the
endOfTape event can occur in so many states that it is important to group many of these states in the
On superstate.
The eject event has not been modelled, but could be. In this model, we could imagine that eject
has the same effect as stop, but also sets tapeInserted to false.
In ShowingTVChannel, it might be possible to jump directly from FastForwarding to
Rewinding etc. The VCR modelled here requires you to stop first. However in PlayingTape
state, you can jump directly from any substate to any other substate.
d) VCR user interface. As with part c, the answer to this question depends heavily on the VCR chosen.
upArrow
/moveToLineAbove
downArrow
/moveToLineBelow

SelectRecordingDataLine

leftArrow

rightArrow
upArrow
/incrementCurrentDigit

EnterRepeatFrequency
leftArrow

rightArrow

downArrow
/decrementCurrentDigit

EnterChannel
leftArrow

digit
/editCurrentValue

rightArrow

EnterStartTime
leftArrow

rightArrow

EnterEndTime
leftArrow

rightArrow

EnterRecordingSpeed

upArrow
/toggleRecordingSpeed
downArrow
/toggleRecordingSpeed

cancel

rightArrow

E8.15 p. 289 Studying the implications of a change to a state diagram.


If closeRegistration or cancel are invoked from the Planned (initial) state, the code given results
in a transition to Cancelled state. A modified state diagram, shown below, has these two extra
transitions.
Planned
cancel

Cancelled
do:
unregister
students

openRegistration

closeRegistration

Open

cancel

NotEnoughStudents
closeRegistration
classSize >= minimum
classSize >= maximum

Closed

EnoughStudents
closeRegistration

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

requestToRegister(aStudent)
/createRegistration

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

P8.2

A74

p. 291 Drawing state diagrams of OCSF and SimpleChat


a)*ConnectionToClient in the OCSF Framework: Note that events such as setHost have not been
modelled here.
Running
/clientConnected

message/
receiveMessageFromClient

Initializing
AcceptingMessages
IOException
sendToClient/
send

exception/
clientException

Terminating

ReadyToTransmit

close/
clientDisconnected

b) A client in Phase 5 of SimpleChat


Connected
connectionEstablished

loginReceived

InitializingConnection
AwaitingPassword

TryingToConnect
connectionAttempt
Failed

connect

Idle

LoggedIn
NotForwarding

logout

cancelForward
networkDisconnection

P8.3

passwordReceived

forward

Forwarding

p. 291 Interaction diagrams and other work for the Small Hotel System
a) Responsibilities. To be provided in a later release.
b) Interaction diagrams
GUI

:Hotel

:Guest

s:Stay

:QualityLevel

r:Room

:Stay

searchForGuests(string)

getListOfStays

getQualityLevel

getNonAssignedRooms(s)
getRoomCatgory()
getRooms(category)
*[for all rooms] getAssignedStays()

*[for all stays] inConflict(s)

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A75

ANSWERS TO EXERCISES

GUI

:Guest

s:Stay

:QualityLevel

:Stay

:Room

getNumberOfAvailableRooms
(nights,arrival,category)

*[for all stays] inConflict(date,nights)

getRooms()

[no rooms] getRoomCategory()

*[for all rooms] getCategory()

createReservation
(qualityLevel,category)
create

addStay(s)

addStay(s)

c) State diagrams. We have not found the need to create any so far for this system. We may add some in a
future version of this document
d) This is a practical exericise requireing students to improve their previous work

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A76

Chapter 9. Architecting and designing software


E9.1

p. 299 Dividing a system into subsystems (see also E4.3, p. 110).


There will be several ways of dividing these into separate systems. The following systems suitable for the
requirements for are expressed as a simple hierarchical list.
a)*Police information system
User interface layer/client
Main functional layer/server
Scheduling subsystem
Case management subsystem
Personnel management subsystem
Statistics subsystem (may not be implemented in early releases)
Document repository
Database subsystem
Subsystem providing interfaces to other systems
b) Record company web site
User interface generation subsystem (generates html etc.)
Main functional layer (performs computational functions)
Searching subsystem
Sales subsystem
Surveys subsystem (may not be implemented in early releases)
Online-content subsystem (may not be implemented in early releases)
Message-board subsystem (may not be implemented in early releases)
Database subsystem
Music repository (may not be implemented in early releases)
c) Public library system
User interface layer
Main functional layer
Searching subsystem
Checkout subsystem
Administration subsystem
Overdue notice subsystem
Database layer
d) Taxi company system
User interface layer
Main functional layer
Dispatch subsystem
Automatic dispatch (may not be implemented in early releases)
Administration subsystem
Radio communications layer (may not be implemented in early releases)
Database subsystem

E9.2

p. 304 Categorizing designs according to the types of cohesion they should exhibit.
a) Booking class: Communicational cohesion
b) bmptojpg executable program: Functional cohesion (assuming it doesnt actually modify the bitmap, but
produces an entirely new output). You could also argue that there might only be communicational
cohesion here, or perhaps even only sequential cohesion for the different steps of the process.
c) GenerateStatistics executable program: Temporal cohesion. However, although it would be a
stretch, one can also imagine this being implemented as a functionally cohesive module that would output
a structure with the results, that could be printed or displayed by another module.
d) AnalyseData: Sequential cohesion (procedural would be OK too)

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A77

ANSWERS TO EXERCISES

E9.3

pp. 304-305 Determining flaws in designs with respect to cohesion.


a) Both of these subsystems do both user interface work and other work. Layer cohesion is therefore lacking.
Subsystem A is particularly bad in the sense that in addition to doing functions for the end-user, it also
does system-administration work such as backing up the database. In general, there seems to have been no
reasonable criteria for deciding what to put in each subsystem. The solution to this is major re-architecting:
Among the key changes: i) The database backup functions should be in their own subsystem. ii) The UI
should be separated from the rest.
b) As with part a) above, the criteria for dividing this system into subsystems seem arbitrary: Both
subsystems involve adding items to the shopping basket, yet the second subsystem also does an odd
selection of other things, including displaying on the screen and sending emails. It would seem reasonable
to separate out the functions that have to do with generating displays from the functions that have to do
with responding to commands (adding to the shopping basket etc.).

E9.4

p. 305 Determining the kinds of cohesion present in the design of SimpleChat.


To be provided.

E9.5

p. 309 Evaluating Javas reflection mechanism with respect to coupling.


To use reflection, you can change handleMessageFromClient to call methods that have the name of
whatever message is received. You would have to deal with cases where an invalid message is received by
handling the appropriate exception.
The central Java class to look at is java.lang.Class. You call this classs static method forName to
obtain a Java object representing the class whose method is to be called. Then you call getMethod to obtain
a Java object representing the appropriate method. Finally, you call invoke on this method. The method
getMethod will throw a NoSuchMethodException if an invalid command (method name) is passed.
Some of the benefits of using reflection in this context:
The total volume of code in handleMessageFromClient is vastly reduced; in effect, the same
benefits are achieved as would be achieved by using polymorphism.
Adding a new command only requires adding a new method; you no longer have to change
handleMessageFromClient.
Some of the drawbacks of using reflection:
There will be a performance degradation; in a heavily-used server, this could pose a problem.
The code may appear complex to people who are not used to reflection. The use of reflection discussed
here is relatively simple, but some reflective applications become very hard to understand and can give rise
to security defects.

E9.6

p. 312 Categorising aspects of designs according to the coupling they exhibit.


a)*Common coupling (all methods that access the variables are coupled)
b) Import coupling (all the imported classes are coupled to the class that does the importing)
c) There is content coupling here (the classes that manipulate instances of Address are coupled to it); there
is also stamp coupling (the methods that use Address as arguments are coupled to Address)

E9.7

p. 313 Determining ways to reduce coupling.


a)*It would be better to have methods getMinClassSize and getMaxClassSize available in
CouseSection this is probably a reasonable place to use static methods, even though we recommend
in general that they be avoided. Access to the static variables should not be public.
b) It is difficult to reduce import coupling if you really need to use the imported classes. However, excessive
importing is a common problem, so in this case you should double-check to make sure all the imported
classes are actually being used.
c) The content coupling can be eliminated by accessing the address using methods only. The stamp coupling
may be unavoidable. A possible solution would be to eliminate the class entirely and just use a string
containing the address, but this has drawbacks that must be weighed against the benefits.

2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A78

E9.8

p. 313 Determining the kinds of coupling present in the design of SimpleChat.


SimpleChat has the following examples of coupling:
Control coupling: The clients directly control what the server does via the messages; the strength of this
coupling could be reduced using reflection, as discussed in E9.5
Import coupling: The SimpleChat classes all have necessary import statements.
There is obviously routine call coupling, data coupling and stamp coupling due to various necessary
method calls.

E9.9

pp. 321-322 Choosing an architecture, basing the decision on quality requirements.


In parts a and b, the objectives are not met by any of the architectures; this raises some debate since we have
to choose which requirements to relax; we really need further study and discussion with the stakeholders.
a)*Choose architecture A, although architecture C might also be a reasonable choice further study is
probably needed. Rationale:
Runs on windows: Clearly eliminates D (A, B, C left)
Works on a 30 Kbps connection or faster: Eliminates B and perhaps eliminates A, however we will
leave A under consideration for now since it is close to this threshold (A, C left)
Works on a 500 MHz machine or faster: Clearly eliminates C. Leaving only architecture A even
though it does not quite meet the highest priority objective: bandwidth efficiency.
b) Given that bandwidth is the lowest priority now, we should keep architecture B under consideration. Given
that architecture B beats architecture A in the top-priority quality (CPU efficiency) it should probably be
our choice.
c) Choose architecture A again: Rationale:
Runs on Unix: Eliminates B and C (A, D left)
A and D satisfy all three of the other objectives.
A has the highest maintainability, so since maintainability is the highest general priority, we choose A.

E9.10 p. 331 Dividing a video game system into layers.


The following diagram shows one possible architecture:
To be provided
E9.11 p. 333 Studying architectures of peer-to-peer systems to determine how they can dispense with a server.
Discussion to be provided.
E9.12 p. 334 Studying the differences between CORBA and COM.
Discussion to be provided.
E9.13 p. 337 Designing a pipe-and-filter system to process stock quotations.
The following diagram shows one possible architecture:
To be provided
E9.14 p. 339 Designing the architecture of systems.
a)*A corporate payroll system.
To be provided.
b) A stock trading system.
To be provided.
c) The GANA system.
To be provided.
d) A distributed system for analysing radio-telescope signals.
To be provided.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A79

ANSWERS TO EXERCISES

Chapter 10. Testing and inspecting to ensure high quality


E10.1 pp. 348-349 Categorizing situations into failure, defect or error categories.
a) Error (resulting in a defect and failures)
b) Failure (a situation arising from a defect)
c) Defect
d) Defect
E10.2 p. 353 Determining equivalence classes for testing purposes.
a)*Telephone number. Note that it is good practice in software engineering to not require telephone numbers
to be in any particular format; this is because telephone number formats can change over time, and because
formats differ from country to country. Also, people need to enter strings such as ext to specify an
extension; therefore in the following we are being very liberal about what could be entered. You may
choose to be more restrictive.
Equivalence classes of valid data
1 Any string of printable ASCII characters (including letters, numbers and special symbols)
Equivalence classes of invalid data
2 The empty string (assuming the input is required)
b) A persons name in a Latin character set:
Equivalence classes of valid data
1 Strings of alphabetic characters of length 2-30 (assuming 30 is the maximum reasonable length - you
may pick a different reasonable length or not limit the length)
2 Strings of alphabetic characters of length 2-30 with one or more single spaces in them but not at the
start or end.
3 Strings of alphabetic characters of length 2-30 including an apostrophe (to allow for names such as
OToole)
4 Strings of alphabetic characters with accents and other diacriticals of length 2-30.
Equivalence classes of invalid data:
5 An empty string (assuming input is required)
6 Single alphabetic characters (presumably too short)
7 Strings of characters from non-Latin character sets, of length 2-30
8 Strings with numbers and special symbols, other than apostrophe.
9 Strings with whitespace (tabs, spaces etc.) other than single internal spaces.
c)*A time zone (numeric or alphabetical)
Equivalence classes of valid data:
1 Any sequence of three upper-case letters (time zones can be specified in many different ways
depending on the country; we are thus being liberal about allowed input)
2 A string of the format shh[:]mm, where
s can be + or -,
hh can be 00 to 14 (time zones near the date line can sometimes be greater than 12 hours from UTC)
mm can be 00 or 30
Equivalence classes of invalid data:
3 An empty string (assuming input is required)
4 A string of length 1 or 2
5 A numeric time zone without the + or -
6 A numeric time zone where the hour is greater than 14
7 A numeric time zone where the minutes range from 01 to 29
8 A numeric time zone where the minutes are other than 00 or 30
9 A sequence of alphabetic characters of length greater than 3
10 A character string mixing digits and letters
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A80

12 A character string with characters other than digits, letters or :, + and - in the appropriate spots.
d) The speed of a vehicle optionally followed by units.
Equivalence classes of valid data:
1 A sequence of digits of length 1 to 3 (the problem said 3-digit; we assume this included 1 and 2 digit
integers)
2 A sequence of digits of length 1 to 3 followed by one of the strings km/h, m/s or mph.
Equivalence classes of invalid data:
1 The empty string (assuming input is required)
2 A sequence of digits of length greater than 3
3 A string with characters other than digits and the sequences km/h, m/s and mph
e) A credit card number. The major credit cards have standard formats, however these are subject to
change. Also, additional credit cards might be introduced. Most systems should therefore not place undue
restrictions on the input format. In the following, we assume, however, that no credit card number could be
less than 7 digits.
Equivalence classes of valid data:
1 A string of 7 or more digits with optional single spaces separating groups of digits.
Equivalence classes of invalid data:
2 The empty string (assuming the information is required)
3 Strings with characters other than digits and spaces.
4 Strings shorter than 7 digits.
f) An FM broadcast radio frequency: Such frequencies can vary from 87.5 to 108 MHz. In some countries
(e.g. North America), the spacing between frequencies is 0.4 MHz. In other countries, the spacing is
different. If the computer system was unquestionably country-specific, then it could use knowledge about
frequency spacing to be very specific about what frequencies are allowed as input. In the following, we
assume that the system must allow frequencies as used in any country.
Equivalence classes of valid data:
1 Any value from 87.5 to 108, with up to two decimal place specified, but where the second decimal
place can only be 0 or 5. Note that for proper international input, the decimal point might be
specified as a . or a , or several other possibilities.
Equivalence classes of invalid data:
2 A value less than 87.5
3 A value greater than 108
4 A value with more than two decimal places specified
5 A value with a second decimal place that is other than 0, 5.
6 The empty string (assuming the input is required)
7 A string containing non-numeric values.
g) A URL: This is actually quite a tricky question, since the space of possible URL formats is unlimited,
given that new protocols can be created. However, a program that accesses a URL would only be expected
to be able to access URLs with protocols that are known at that time. In this answer, we therefore assume
that the program can only access http, https, file and ftp URLs.
Equivalence classes of valid data:
1 A string having the format: http://{domain}, including domains in non-western character sets.
1a Class 1 followed by /
1b Class 1 followed by arbitrary text of indefinite length
2 As with class 1, except https
3 As with class 1, except ftp
4 As with class 1, except file

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A81

ANSWERS TO EXERCISES

Equivalence classes of invalid data:


1 A string starting with a sequence other than http://, https://, ftp:// or file://
E10.3 p. 355 Determining equivalence classes when there are multiple inputs.
The following also incorporates the answer to E10.4 (marked - Boundary cases)
a)*Personal information form
Date of Birth: We will consider this as three separate inputs with a required format of yyyy/mm/dd; you
may have picked a different format.
Year
1 Valid: integers from 1880 to 9999 (Assume this is a system for people alive at the time the system is
used
- Boundary cases: 2000, 2001, 1880, 9999
2 Invalid: Integers from 0 to 99 (we treat this as a separate case since there may be some code that
incorrectly handles 2-character dates, which we have decided not to allow)
- Boundary cases: 0, 1, 99
3 Invalid: Integers from 100 to 1879
- Boundary cases: 100, 1879
5 Invalid: Empty string
6 Invalid: String with non-numeric characters
Month
1 Valid: 01 to 12
- Boundary cases 01, 12
2 Invalid: 1 to 9 (assume we explicitly require two digits)
- Boundary cases 1, 9
3 Invalid: 00 and 0
4 Invalid: 13 to 99
- Boundary cases 13, 99
5 Invalid: Empty string
6 Invalid: String with non-numeric characters
Day
1 Valid: 01 to 28
- Boundary cases 01 and 28
2 Valid: 29 in February of a leap year, or in any other month any year.
3 Invalid: 29 in Frebruary of a year other than a leap year.
4 Invalid 30 (in February)
5 Valid: 30 (in some month other than February)
6 Invalid: 31 (in a 30-day month or in February)
7 Valid: 31 (in a 31-day month)
8 Invalid: 32-99
- Boundary cases 32, 99
9 Invalid: 00 and 0
10 Invalid: 1 to 9 (2 characters required)
- Boundary cases 1, 9
11 Invalid: Empty string
12 Invalid: String with non-numeric characters
Street Address:
Valid: Character strings of length 2-40 (assumed limits) containing upper and lower case characters,
numbers, comma, period, hyphen, single spaces, accents and diacriticals
Boundary case: Strings of length 2 and 40
Invalid: Character strings containing non-printable characters
Invalid: Character strings with more than one embedded space
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A82

Invalid: Strings of length 0-1


City, Country and Postal code
Same as street address, except that country and postal code can have 0 characters
Home Telephone Number
Valid: Empty string
Valid: String of characters including digits, +, ( ), -, x and space
Invalid: Other strings of characters
b) SimpleChat Phase 2 commands
To be provided.
c) The GANA system
To be provided.
E10.4 p. 355 Determining boundary values.
See the lines marked boundary cases in the answer to E10.3
E10.5 p. 358 Java code and test harness for the landing gear example.
To be provided.
E10.6 p. 358-359 Tables of conditions for testing purposes.
a)*Message forwarding
To be provided.
b) Forms to be completed by different classes of people: It is easiest to rewrite the requirements first in
pseudocode, then consider each type of form separately.
If (disabled and not socialAssistance)
use form C
Else
If (underAgeOf18) then
use form A
Else
use form B
Endif
Endif
If (socialAssistance)
use form D
Endif
If (seniorCitizen and not (socialAssistance or subsidizedNursingHome))
use form E
If (not disabled and not seniorCitizen and earnHighIncome)
use form F

Table for forms A, B and C (? means either Y or N)


Disabled?
Social Assistance?
Under 18?
N
?
N
N
?
Y
Y
N
?
Y
Y
N
Y
Y
Y
Table for form D
Social Assistance?
Y
N

Form
B
A
C
B
A

Form D
Y
N

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A83

ANSWERS TO EXERCISES

Table for form E


Senior Citizen?
N
Y
Y
Y

Social Assistance?
?
N
?
Y

Table for form F


Disabled?
Senior Citizen?
Y
?
?
Y
N
N
N
N

Subsidized Nursing Home?


?
N
Y
?

High Income?
?
?
Y
N

Form E
N
Y
N
N

Form F
N
N
Y
N

c) Navigation system that gives warnings about required turns


To be provided.
d) Determining when the burglar alarm should sound
To be provided.
E10.7 p. 363 Stability and efficiency of Java sorting in Arrays and Collections.
To be provided.
E10.8 pp. 365-366 Classifying and testing for numerical defects.
a)*Assuming a floating point value will be exactly equal to 3.0, when it might be slightly different from this.
b) Not using enough bits to store maximum values: Total corporate assets could conceivably exceed the
largest number that can be stored in an int. To test for this defect, simply supply a very large value of
corporate assets. Note that some people might want Euro cents to be stored, however, most corporations
would not record their total assets to that level of precision.
c) Not using enough bits to store maximum values. The price of oil could rise indefinitely.
d) The most obvious defect here is storing the total money in a float value. When a page has a very large
number of hits, the float value will stop recording additional amounts of money because you would be
adding a very small integer to a large float, leaving that large float unchanged.
E10.9 p. 369-370 Writing a program to test for a critical race situation.
To be provided.
E10.10 p. 372 Testing for whether SimpleChat works sensibly when a resource is locked.
To be provided.
E10.11 p. 372 Designing stress and unusual-situation tests.
a)*A new web browser
Loading a truly massive web page full of complexity.
Loading a web page containing a large amount of JavaScript.
Loading a web page containing several large Java applets.
Loading a web page full of html errors
Loading a web page with obsolete html constructs
Loading a web page with the latest complex html and cascading style sheet constructs
Loading a web page that contains an extremely large number of levels of nested html tags.
Loading a web page containing tables with an extremely large number of columns and rows.
Loading a web page demanding a lot of width of the resulting output
Loading a very large web page that contains a large number of embedded objects.
Testing the browser on an extremely slow connection.
Loading a very large number of web pages at once in multiple windows.
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A84

Running on a variety of different versions of the target operating system.


Running on a machine with too little memory
Running on a machine with too little disk space for caching purposes.
Loading random pages over and over again for a long time (using a driver)
Running on a very small screen
Dealing with repeated failures of connections

b) A flight simulator
Running on a CPU with minimal speed and memory
Running on a variety of different operating systems and graphics cards
Running for a very long period of time (to check for memory leaks)
Running on a display screen with a particularly large number of pixels (or, as allowed in some
operating systems) several screens put together to create one large virtual screen.
Running on a very small display screen
(for flight simulators that can operate with several users each flying their own plane) Running with a
large number of planes.
c) The SimpleChat system
Having an extremely large number of clients connect to a given server.
Having a driver push an extremely large number of messages through the system at one time.
Running on as many different operating systems as possible.
d) The GANA navigation system
Dealing with errors in the mapping information.
Navigating while moving rapidly through very complex and dense cities
Dealing with intermittent internet connection for map loading
Dealing with intermittent GPS input due to tall buildings and tunnels
Navigating over a very large distance through a very complex route
E10.12 p. 376 Writing test cases.
a)*Message forwarding
To be provided.
b) Forms to be completed by different classes of people
To be provided.
c) Navigation system that gives warnings about required turns
To be provided.
d) Determining when the burglar alarm should sound
To be provided.
E10.13 p. 376 Creating a complete test plan from information in a table.
To be provided.
E10.14 p. 383 Planning for integration testing, including determining needed stubs and drivers.
To be provided.
E10.15 p. 387 Conducting code inspections.
This is a purely practical exercise

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

A85

ANSWERS TO EXERCISES

Chapter 11. Managing the software process.


E11.1 p. 401 Reviewing group work in order to improve process.
This is practical work only
E11.2 p. 414 Finding sources of error in cost estimates.
General sources of error: Estimates could vary greatly depending on the quality of the software
engineering team, the quality of the design of the existing system and many other factors.
Sources of error in requirements gathering: Working out the detailed requirements could take considerably
longer than anticipated.
Sources of error in prototyping: This will have to be prototyped repeatedly with real users in cars (or in
simulations of cars) since usability will be very important. It could take more iterations than expected, and
it may be time-consuming to organize enough tests in enough realistic situations. In particular, ensuring the
time estimates are accurate, and the map scales to the most reasonable scale for the driver will take a lot of
tuning.
Sources of error in design: The algorithms for estimating time of arrival and scaling the map will be
complex, and could take more time than expected to develop. Developing the database that stores
information about travel speeds on the roads, and rush-hour periods will take work that may not have been
anticipated in the original cost estimate.
Reliability will be important, so repeated testing and inspection may consume considerable time if a
higher-than expected defect level is encountered.
E11.3 p. 415 Cost estimation for release 1 of GANA.
To be provided.
E11.4 p. 419 Creating a team structure for different software projects.
a)*Replacement of the income tax system of a country (unless the country is a tiny island nation) would be a
very big undertaking, requiring hundreds of people. Some kind of hierarchy would certainly be required.
There would probably be a group of system architects and overall project planners who would divide the
system into its parts, and plan the interfaces among the parts. Then there would be a variety of subprojects. Some of the sub-projects might be managed using the chief-programmer or egoless style.
b) The GANA software is technically challenging due to its real-time nature, and the high need for usability.
An egoless approach might be used, although there would probably need to be several teams working on
different aspects of the software. This is because GANA might be too big for one egoless team, and an
egoless team cannot be allowed to get too big otherwise there will be too much time wasted
communicating among all the members. A chief programmer team would also be a good choice.
c) The control software for an interplanetary probe will probably be very complex, and will certainly require
high reliability. Once the system has been divided into its parts, egoless teams would probably be a good
choice.
d) A new front-end for a university registration system probably is a relatively small enhancement project. A
chief-programmer or egoless approach should work well.
E11.5 p. 419 Detailed design of the team structure for GANA Release 1
As determined in the last exercise, we will base the following on an egoless approach.
Number of people and evolution of the team:
To be provided.
Skills needed by team members:
To be provided.
E11.6 p. 422 PERT and Gantt charts for GANA Release 1.
PERT chart to be provided.
2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIRE

ANSWERS TO EXERCISES (Those marked * are to be publicly available on the books web site)

A86

Gantt Chart to be provided.


E11.7 p. 422 Changes to cost estimate following production of PERT and Gantt charts
To be provided.
E11.8 p. 424 Improvement of process by applying project management techniques
To be provided.

THIS DOCUMENT IS FOR INSTRUCTORS USING OBJECT ORIENTED SOFTWARE ENGINEERING: DO NOT GIVE TO OTHERS.

Anda mungkin juga menyukai