Object Oriented Software Engineering Practical software development using UML and Java By Timothy C Lethbridge and robert Laganiere McGraw-Hill 2001 Intemational ISBN 0-07-709761-0 US ISBN0-07-283495-1 Public Answers to Selected Exercises- Version 1.9(August, 2002) o 2002 Timothy C Lethbridge and Robert Laganiere The following contains answers to a subset of the 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 The answers provided here are publicly available on the website so as to enable students to practise. Generally speaking, the answers given here are parts a of multi-part questions; in exercises with many parts, answers may also be given to parts c and e. The full set of answers is only available to instructors as a separate password-protected document le update these answers from time to time, adding improved explanations, altemative answers, and extra exercises. You can contact us at tcl@site. ottawa. ca with suggestions. Items which we plan to complete or augment at a later date are marked in green Pleaselookatourwebsite(www.llosengcom)forotherinformationaboutthisbookincluding a knowledge base containing many of the basic facts from the book Videos of Tim Lethbridge presenting lectures based on the book The slides that have been prepared for professors who teach using the book
O bj ect O ri e ntedSo ftw ar e E ng in e er in g : P ra cti ca l softw a red e ve lo p me nt usin gU MLan d Java By Timothy C. L e thbr idge a nd Robe rt La ga niè re McG ra w -H ill 2001 I nter national I SBN0- 07-709761- 0 U S ISBN 0- 07- 283495- 1 PublicA ns wer s t o Se lec te d Exe r cise s–Ve rs ion 1 .9(A ugust , 2 00 2) © 2002 T imothy C. Le thbridgea nd Rober t L aganièr e T he f ollow ing c ontains answe rs to a subse t of t hee xer cises in the book, a long w ith e xpla nations of some aspe c ts of the a nswe r s. I n somec ase s theprovided answ e rs a r e mor e de taile d those tha t would bee xpe cted fr om stude nts. Also notethat some que stions a resubjec tive, so r e ader s may ha vere sponses diff e re nt fr om those w ritte n her e. T hea nsw er s provided he re ar e public ly a vaila ble on the we bsite so a s to ena ble stude nts to pra c tise . G ene ra lly spe a king, the a nsw er s give n he r e ar e par ts a of multi-pa rt questions; in exe rc ise s with ma ny pa r ts, a nswe r s ma y a lso be given to par ts c and e . T hef ull se t ofansw e rs is only a va ila bleto instr uctor s a s asepa ra tepa ssw or d- prote c te d doc ume nt. W e update the se answ e rs f r om time to time , adding improved e xplana tions, alter na tive a nswe r s, a nd extrae xer cises. Y ou c an c ontac t us a t tcl@site .uottaw a .c a with sugge stions. I tems w hich we plan to c omple te or a ugment a t a late r da te ar e mar ke d in gre en. Ple aselook a t ourw e b site (w ww .lloseng.c om)f orothe rinf ormation a bout this book, inc luding: • Aknow le dgeba sec ontaining many of thebasic fa c ts f r om the book • V ide os ofT im Le thbridgepre senting le c ture s base d on the book. • T heslide s tha t ha ve be e n pr e pa re d f orpr of e ssor s w ho te ac h using thebook
PUBLIC ANSWERS TO EXERCISES Chapter 1. Software and Software Engineering El.1 p 5 Classifying software a)*Custom; real-time c)Generic; real-time(but soft real-time El.2 p. 10 Stakeholder reactions to situations particular type of work. On the other hand, he or she may be relieved about not being put out of wort i a)*. The user may be disappointed, since he or she might be looking forward to no longer having to do ince 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 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 today's 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 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 ify mistakes. Usability of the bills themselves will be important because ordinary people have to derstand them Efficiency should not be a concern THESE ANSWERS SUPPORT THE BOOK OBJECT ORIENTED SOFTWARE ENGINEERING
PUBLI C A NSW ERS T O EX E RCISE S PA2 T HE SEAN SW E RS SU PPORTT HEBO OK O BJ ECT O RI E NTEDSO FTW AR E E NG INE ER ING : Chapt er 1. Soft w ar e and Soft war e Engineer ing E 1.1 p. 5 Classify ing software . a )*Custom; re a l- time. c )*G ener ic; r e al-time( but soft re al- time ) . E 1.2 p. 10 Stak e holde r re actions to situations. a )*• T he use r ma y be disappointed, sinc e he orshe might belooking f or wa r d to no longer ha ving to do this par tic ulartypeofw ork. O n theothe r ha nd, heor shema y bere lie ve d a bout not being put out ofw or k. • T he c ustom er ma y be disappointed at not be ing a ble to save mone y; he or she ma y also be surpr ised, since ma ny pe ople be lie ve that softw ar e syste ms ar e e asy to develop; they unde re stima te the c omple xity of ta sks tha t a reto be a utoma te d. The c ustomermight c onsultsome other softwa r e enginee r to obtain asec ond opinion. • T he develope rs will pr oba bly move on to othe rw or k. • T he de ve lopme nt m anage rs ma y be disappointed at not ha ving the opportunity to do f ur the r w or k on thepr ojec t. E 1.3 p. 12 Prioritizing qualityattribute s a )*R eliabilit y will bepa ra mount f or thespa c ec ra f t sof tw ar e . It would be sad ifthe spac e cr af t did not make it into orbit af te r a ll that time , a lthough no live s w ould be lost. Eff ic iency might be impor tant since proce ssors fr om 20 ye ar s e ar lie r ar e f ar slow e r tha n today’s de vic es. U sabilit y will like ly not be a n issue since the sof tw a re w ill r un autonomously and r epor t a ny fe edbac k to exper ts; f ur the rmore the sof tw ar e c annot be inter a ctivesinc e it ta ke s c onsider a ble time to se nd signa ls to a nd fr om Pluto a t thespee d of light. M aint ainability is a lso like ly to be a minima l c onc er n since this softw ar e is likely to only be used once . H ow eve r, ther e r emains thepossibility that the sof tw ar ec ould beused on othe r syste ms, orw ill nee d to be c ha nge d as la st- minute bugs ar ef ixe d. c )*M aint ainability will like ly be the most impor tant c once r n since da tapr oc essing sof tw a rete nds to evolve. R eliabilit y will also beofc onsider a ble impor tance : Bill printing must be a c cura te, sinc e it ca n be c ostly to r ec tif y mista ke s. U sabilit y of the bills themse lve s w ill be impor ta nt be c ause or dinar y people have to under sta nd them. Eff ic iency should not be ac onc er n
PA3 PUBLIC 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 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) e)"Instance of Person 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 c)*Bad. The word" is inappropriate in a class name. Call it simply sleepingCar e)*Bad. It should not be plural: Route would be bette E2.3 P 33 Naming different classes derived from words with multiple English meanings. vofritle a)*Title: Describes published books independently of the number of copies Copyofritle: or perhaps LibraryItem: Represents physical books(as well as other things, such as videos )that the library places on its shelves c)*RegularlyScheduledFlight: has a flight number, departure time, origin and destination and is flown every day; SpecificFlight: flies on a particular day 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 ometimes certain attributes could be represented as associations instead -these are shown in parentheses a)*name, description, (producer, distributer) c)*date, startTime, endTime, description, soundAlarmWhenstarting,(room) e)'callerNumber, calledPartyNumber, isConnected, startTime, currentcell signalStrength, totalCost E2.5 p 35 Identifying associations a)boughtFrom ProductionCompany, produced By: Producer, episodes Episode leadActors Actor c)*meetingRoom: MeetingRoom e)*caller: CallParty, called: CallParty E2.6 P. 35 Differentiating between variables and objects E2.7 p. 36 ldentifying 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 E2.8 p. 40 Identifying poor generalizations a)*Bad: You can't say 'A Canadian dollars is a money'; also CanadianDollars should be an instance of Currency c)*Probably OK e)"Bad: Account12876 would be instance of BankAccount(or some subclass of BankAccount) E2.9 No public C 2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIERE
PA3 PUBLI C A NSW ERS T O EX E RCISE S © 2002 T IMO TH Y C. LE T HBRI D GEA N D RO BERT L AG AN I ÈRE Chapt er 2. Revi ew of object or i entat ion E 2.1 p. 32 Distinguishing am ong c lasse s and instanc es T he c lass names in the following answe rs could var y slightly. T he points in pa r enthe se s a re of lesser impor tance , a nd ar e f orthose w ho ha ver e ad Chapte r5. a )*I nsta nceof AutomobileCompany. ( orpe rha ps just Company) c )*Cla ss, subc la ss of Person. ( In Chapter s 5 a nd 6, w ew ill seethat it might be be tte r to ma ke this a subcla ss of PersonRole) e )*I nsta nceof Person. E 2.2 p. 33 De te c ting bad c lass name s and im proving them a )*Bad. I s this a par tic ular ve hic le ( w hich might better be c alled some thing like Locomotive, or RollingStockConfiguration) or a sche dule d r un (RegularlyScheduledRun) tha t c ould use a ny ve hicle , orthe r un on apa rtic ula r day ( SpecificRun) ? Wewill disc uss this kind ofproble m in mor e detail in Cha pte r 6 in thec ontext of theA bstra ction O c curr e nc e patte r n. c )*Bad. T hew ord ‘ D ata’is inappr opr ia te in a cla ss na me . Call it simply SleepingCar. e )*Bad. I t should not beplur al: Route would be bette r . E 2.3 p. 33 Naming diffe re nt classes de riv ed fromwords with m ultiple E nglish m eanings. a )*Title: D esc ribe s publishe d books independently of the number of c opies CopyOfTitle: or per ha ps LibraryItem: Repr esents physica l books (a s w ell a s other things, such a s vide os) tha t thelibr ar y pla c es on its she lve s. c )*RegularlyScheduledFlight: has a flight numbe r , de par tur e time, or igin and destination a nd is f lown ever y day; SpecificFlight: f lie s on a pa r ticularda y. E 2.4 pp. 34-35 I de ntify ing attribute s I n this que stion a nd the next, ther e a re ma ny alte r na tives, a f ew possibilitie s a re show n her e. In pa rtic ula r sometime s c er ta in attributes c ould be re pre se nte d a s assoc ia tions inste ad – thesea reshow n in par enthe se s. a )*name, description, ( producer, distributer) c )*date, startTime, endTime, description, soundAlarmWhenStarting, ( room) e )*callerNumber, calledPartyNumber, isConnected, startTime, currentCell, signalStrength, totalCost E 2.5 p. 35 Identifying assoc iations a )*boughtFrom:ProductionCompany, producedBy:Producer, episodes:Episode, leadActors:Actor c )* meetingRoom: MeetingRoom e )*caller:CallParty, called:CallParty E 2.6 p. 35 Diffe re ntiating betwee n v ariable s and obje cts a )*O bjec t E 2.7 p. 36 Identifying ope rations I n thef ollow ing, ope ra tions tha t w ould pr oba bly be polymor phic a reshow n in ita lics, how e ve r, exac tly w hic h ope ra tions ar e polymorphicw ould de pend on the design. a )*getArea, getPerimeterLength, getPoints, move, resize, rotate, flipHorizontally, flipVertically E 2.8 p. 40 Identifying poor ge neralizations a )*Bad: Y ou c a n’ t say ‘ A Cana dian dolla rs is a mone y’ ; a lso CanadianDollars should be an instanc e of Currency c )*Proba bly O K . e )*Bad: Account12876 would be insta nceof BankAccount (or some subcla ss of BankAccount) E 2.9 No public answe r
PUBLIC ANSWERS TO EXERCISES 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 a)*In this problem we create two separate hierarchies, Vehicle and Partofvehicle. These could also ave something like Machine as a common superclass, although the problem suggested creating separate Vehicle Landvehic⊥e( Added) Car SportscAr B AirVehicle(Added) Aeroplane Amphibious vehicle artofvehicle Engine JetEngine ElectricMotor Cansmlss1。n Vehicle could instead be divided into PoweredVehicle and Unpoweredvehicle; multiple inheritance could be then used for superclasses of the vehicle leaf classes 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) ActualTrip( Runs at a given time on a given day; could also be called Run) CharteredTrip(Renamed for clarity) (Added to properly compl 1P UnscheduledTrip(Runs on a route, but not at the normal time) BusVehicle(Renamed from busto distinguish different types of bus) LuxuryBus e)*Currency( Canadian Dollars and US Dollars are Instances) ExchangeRate(Attributes or associations could be fromCurrency, tocurrency, rate FinancialInstitution(Added) Credi tunion Creditcardcompany(Visa and Master Card are instances) FinancialInstrument ReusableFinancialInstrument(Added) Creditcard Debitcard SingleTransactionInstrument (Added) BankAccount ElectronicDevice (Added) AutomaticTellerMachine(better than BankMachine) BankBranch THESE ANSWERS SUPPORT THE BOOK OBJECT ORIENTED SOFTWARE ENGINEERING
PUBLI C A NSW ERS T O EX E RCISE S PA4 T HE SEAN SW E RS SU PPORTT HEBO OK O BJ ECT O RI E NTEDSO FTW AR E E NG INE ER ING : E 2.10 pp. 41-42 A rranging potential c lasse s into inheritanc e hie rarchie s ( Se ealso E 5.21, p. 189) I n thef ollow ing, thehie r ar chies a r e shown using indented te xt to savespa c e. W hethe rit w ould bea ppr opr ia te to ac tua lly inc lude a ll the cla sses in agive n system w ould depend on thea pplic a tion’ s re quire ments. T he r e ar e many possible va riations on the se a nsw er s. Note: Se e also E5.21 f or additional e xer cises ba se d on the se proble ms. a )*I n this pr oblem we c r ea te tw o separ a te hier ar c hies, Vehicle and PartOfVehicle. T he se could a lso have something like Machine as a common super cla ss, a lthough the pr oblem sugge sted cr ea ting separ a te hie ra r chie s. Vehicle LandVehicle (A dde d) Car SportsCar Truck Bicycle AirVehicle (A dde d) Aeroplane AmphibiousVehicle PartOfVehicle Engine JetEngine ElectricMotor Wheel Transmission Vehicle could instea d be divided into PoweredVehicle and UnpoweredVehicle; multiple inher ita nc ec ould bethen used for super c la sse s ofthe vehic le le a f cla sses. c )*Schedule (W e w ill lea rn la te rtha t this may not be ne e de d sincethe w holesyste m store s thesc he dule) RegularlyScheduledTrip (A dde d as a super cla ss r e pr ese nting some thing tha t r uns a t agive n time) RegularlyScheduledExpressBus (r ena me d f orc lar ity) BusRoute ActualTrip (Runs a t agive n time on a given da y; c ould a lso be ca lle d ‘ Run’ ) CharteredTrip (Rena me d f orc lar ity) ScheduledTrip (A dde d to pr ope rly c omple me nt unscheduledTrip) UnscheduledTrip (Runs on ar oute, but not a t thenormal time ) BusVehicle (Rena me d f rom ‘ bus’to distinguish diff e re nt type s of bus) LuxuryBus TourBus e )*Currency (Cana dian Dolla rs a nd US Dolla rs a r e Insta nc e s) ExchangeRate (A ttr ibute s orassoc ia tions c ould be fromCurrency, toCurrency, r ate ) FinancialInstitution ( Adde d) Bank CreditUnion CreditCardCompany (V isaa nd Ma ste rCar d a reinsta nc es) FinancialInstrument ReusableFinancialInstrument ( Adde d) CreditCard DebitCard SingleTransactionInstrument ( Adde d) Cheque BankAccount Loan ElectronicDevice ( Adde d) AutomaticTellerMachine (betterthan BankMachine) BankBranch
PAS PUBLIC ANSWERS TO EXERCISES 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 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 iangles(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*radius E2. 12 No public answer 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 E2. 14 No public answer E2. 15 No public answer E2. 16 No public answer 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 ectangle 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 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 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 availabl E2. 19 p. 53 Using documentation to look up library classes and thus better understand a prog This is a purely practical exercise. Its purpose is to encourage students to get in the habit of using documentation E2.20 No public answer E2.21 No public answer E2. 22 No public answer E2.23 No public answer E2. 24 No publi c answe C 2002 TIMOTHY C. LETHBRIDGE AND ROBERT LAGANIERE
PA5 PUBLI C A NSW ERS T O EX E RCISE S © 2002 T IMO TH Y C. LE T HBRI D GEA N D RO BERT L AG AN I ÈRE E 2.11 p. 47 De sc ribing how poly m orphic im ple me ntations of c ertain shapeoperations would work. a )*translate: I n SimplePolygon (a s inher ite d by Rectangle and RegularPolygon) , and EllipticalShape (a s inher ite d by Circle) , themethod translate would movethe center. c )*getArea: I n Rectangle, the me thod getArea would r eturn height * width. I n RegularPolygon, it w ould compute the ar e a by dividing the polygon into numPoints individua l triangle s ( se e thea nsw er to E 2.30 f orthe de taile d a lgorithm). O ncethis a r eais c alc ulate d, the total a r eaof the RegularPolygon would be c alculated by multiplying the a re a of ea c h tr iangle by numPoints. I n Circle, theme thod getArea would r eturn pi * radius2 . E 2.12 No public answe r E 2.13 p. 47 Incorporating new c lasse s into an e xisting c lass hie rarchy that c ontains c onside rablepoly morphism. a )*IsoscelesTriangle: O ne might think of ma king this a subcla ss of ArbitraryPolygon, how e ve r tha t w ould be inappr opr ia te since you don’t w a nt it to inher it me thods such as addPoint and removePoint. A be tter solution is to ma ke it a subc lass of SimplePolygon. A s a ttributes you w ould have to storethe baseLength and height, or e lse you c ould store one of thetwo va lue s fora ngles a nd the le ngth of one of the sides, letting the othe r a ngle va lue a nd side be c omputed w hen ne eded. A s methods, you would ne ed changeScale, setBaseLength, setHeight, getArea, getPerimeterLength, getVertices, getBoundingRect, getBaseAngle, getTopAngle, a nd pe rhaps setBaseAngle and setTopAngle. E 2.14 No public answe r E 2.15 No public answe r E 2.16 No public answe r E 2.17 p. 49 De te rmining whe n dy nam icbinding is nee ded in a se t of poly m orphic me thods. T his e xe rc ise ha s tur ne d out to be par tic ular ly use ful to ensur e stude nts r e ally unde r stand the implic ations of polymorphism. Be fore assigning this exer c ise, it ha s pr ove d to be ne ce ssa ry to e xplain the ma te r ia l on pa ges 48 and 49 par tic ular ly ca r ef ully, w ith se ve ra l e xa mples. N ote tha t the exer c ise has the assumption, “ that the c ompilerknow s tha t no ne wc la sse s or me thods ca n be added to thehier a rc hy” ; it is w orth r eminding stude nts tha t this is not gene ra lly true in Java ( you c an a dd a subcla ss unle ss the c la ss is de clar e d final, a nd you c annot dec lar e anon- le afclass to be final) . a )*I nvoking getPerimeterLength on a Rectangle va ria ble: No dyna mic binding is ne e de d since Rectangle is a le af class a nd so the va r ia ble c ould only eve r conta in an instanc e of that class. Theloc a l method in Rectangle would a lw a ys bec alled. c )*I nvoking getBoundingRect on a Polygon va ria ble: Dyna mic binding w ould be ne ede d, sinc e e ithe r the me thod in Polygon or the one in Rectangle might have to be exe cute d depe nding on w hich class of objec t is pla ce d in thevar iableat r un time. E 2.18 p. 51 Re se arc hing products that c laim to beobje ct- orie nte d to de termine if theyre ally are . T hea nsw erto this question will va r y ove r time, de pe nding on w ha t produc ts ar e a va ila ble. E 2.19 p. 53 Using doc ume ntation to lookup library c lasse s and thus better unde rstand a program. T his is a pur ely pra c tica l e xe r cise . I ts purpose is to e nc our age stude nts to get in the ha bit of using doc ume ntation. E 2.20 No public answe r E 2.21 No public answe r E 2.22 No public answe r E 2.23 No public answe r E 2.24 No public answe r