Object-Oriented Software Engineering - WordPress

Transcription

Lethbridge.book Page i Tuesday, November 16, 2004 12:22 PMObject-Oriented Software EngineeringPractical software development using UML and JavaSecond edition

Lethbridge.book Page ii Tuesday, November 16, 2004 12:22 PM

Lethbridge.book Page iii Tuesday, November 16, 2004 12:22 PMObject-Oriented SoftwareEngineeringPractical Software Development using UML and JavaSecond editionTimothy C. LethbridgeRobert LaganièreLondon Burr Ridge, IL New York St. Louis San Francisco AucklandBogotá Caracas Lisbon Madrid Mexico Milan Montreal New DelhiPanama Paris San Juan São Paulo Singapore Tokyo Toronto

Lethbridge.book Page iv Tuesday, November 16, 2004 12:22 PMObject-Oriented Software EngineeringTimothy C LethbridgeRobert LaganièreISBN 0-07-70109082Published by McGraw-Hill EducationShoppenhangers RoadMaidenheadBerkshire SL62QLTelephone: 44 (0) 1628 502 500Fax: 44 (0) 1628 770 224Website: http://www.mcgraw-hill.co.ukBritish Library Cataloguing in Publication DataA catalogue record for this book is available from the British LibraryLibrary of Congress Cataloguing in Publication DataThe Library of Congress data for this book has been applied for from the Library ofCongressPublishing Director: Catriona KingDevelopment Editor: Karen MosmanMarketing Manager: Alice DuijserSenior Production Manager: Max ElveyText Design by Mike CotterellCover design by Ego CreativeTypeset at Neuadd Bwll, Llanwrtyd WellsPrinted and bound in the UK by Bell & Bain Ltd, GlasgowPublished by McGraw-Hill Education (UK) Limited an imprint of The McGraw-HillCompanies, Inc., 1221 Avenue of the Americas, New York, NY 10020. Copyright 2005by McGraw-Hill Education (UK) Limited. All rights reserved. No part of thispublication may be reproduced or distributed in any form or by any means, or stored ina database or retrieval system, without the prior written consent of The McGraw-HillCompanies, Inc., including, but not limited to, in any network or other electronicstorage or transmission, or broadcast for distance learning.ISBN 0-07-70109082 2005. Exclusive rights by The McGraw-Hill Companies, Inc. formanufacture and export. This book cannot be re-exported from the country to which itis sold by McGraw-Hill.

Lethbridge.book Page v Tuesday, November 16, 2004 12:22 PMiContentsForewordPrefaceGuided tourTechnology to enhance learning and teachingxixvxxiixxiv1 Software and software engineering1.1 The nature of software1.2 What is software engineering?1.3 Software engineering as a branch of the engineering profession1.4 Stakeholders in software engineering1.5 Software quality1.6 Software engineering projects1.7 Activities common to software projects1.8 The themes emphasized in this book1.9 Difficulties and risks in software engineering as a whole1.10 Summary1.11 For more information116810111416202426262 Review of object orientation2.1 What is object orientation?2.2 Classes and objects2.3 Instance variables2.4 Methods, operations and polymorphism2.5 Organizing classes into inheritance hierarchies2.6 The effect of inheritance hierarchies on polymorphism and variable declarations2.7 Concepts that define object orientation2.8 A program for manipulating postal codes2.9 Classes for representing geometric points2.10 Measuring the quality and complexity of a program2.11 Difficulties and risks in programming language choice and OO programming2.12 Summary2.13 For more information2929313638394552555760626363

Lethbridge.book Page vi Tuesday, November 16, 2004 12:22 PMviContents3 Basing software development on reusable technology3.1 Reuse: building on the work and experience of others3.2 Incorporating reusability and reuse into software engineering3.3 Frameworks: reusable subsystems3.4 The client–server architecture3.5 Technology needed to build client–server systems3.6 The Object Client–Server Framework (OCSF)3.7 Basic description of OCSF – client side3.8 Basic description of OCSF – server side3.9 An instant messaging application using the OCSF3.10 Difficulties and risks when considering reusable technology andclient–server systems3.11 Summary3.12 For more information676869717787919295991011021034 Developing requirements4.1 Domain analysis4.2 The starting point for software projects4.3 Defining the problem and the scope4.4 What is a requirement?4.5 Types of requirements4.6 Use cases: describing how the user will use the system4.7 Some techniques for gathering requirements4.8 Types of requirements document4.9 Reviewing requirements4.10 Managing changing requirements4.11 GPS-based Automobile Navigation Assistant (GANA)4.12 Requirements for a feature of the SimpleChat instant messaging program4.13 Difficulties and risks in domain and requirements analysis4.14 Summary4.15 For more 1641651665 Modeling with classes5.1 What is UML?5.2 Essentials of UML class diagrams5.3 Associations and multiplicity5.4 Generalization5.5 Object diagrams5.6 More advanced features of class diagrams5.7 The basics of Object Constraint Language (OCL)5.8 A class diagram for genealogy5.9 The process of developing class diagrams5.10 Implementing class diagrams in Java5.11 Difficulties and risks when creating class diagrams5.12 Summary5.13 For more 219

Lethbridge.book Page vii Tuesday, November 16, 2004 12:22 PMContents6 Using design patterns6.1 Introduction to patterns6.2 The Abstraction–Occurrence pattern6.3 The General Hierarchy pattern6.4 The Player–Role pattern6.5 The Singleton pattern6.6 The Observer pattern6.7 The Delegation pattern6.8 The Adapter pattern6.9 The Façade pattern6.10 The Immutable pattern6.11 The Read-Only Interface pattern6.12 The Proxy pattern6.13 The Factory pattern6.14 Enhancing OCSF to employ additional design patterns6.15 Difficulties and risks when using design patterns6.16 Summary6.17 For more 2432462502512517 Focusing on users and their tasks7.1 User-centered design7.2 Characteristics of users7.3 The basics of user interface design7.4 Usability principles7.5 Evaluating user interfaces7.6 Implementing a simple GUI in Java7.7 Difficulties and risks in user-centered design7.8 Summary7.9 For more information2532542562582622732762802802818 Modeling interactions and behavior8.1 Interaction diagrams8.2 State diagrams8.3 Activity diagrams8.4 Implementing classes based on interaction and state diagrams8.5 Difficulties and risks in modeling interactions and behavior8.6 Summary8.7 For more information2852852923013023063073079 Architecting and designing software9.1 The process of design9.2 Principles leading to good designDesign Principle 1: Divide and conquerDesign Principle 2: Increase cohesion where possibleDesign Principle 3: Reduce coupling where possibleDesign Principle 4: Keep the level of abstraction as high as possible309310314314315321329vii

Lethbridge.book Page viii Tuesday, November 16, 2004 12:22 PMviiiContentsDesign Principle 5: Increase reusability where possibleDesign Principle 6: Reuse existing designs and code where possibleDesign Principle 7: Design for flexibilityDesign Principle 8: Anticipate obsolescenceDesign Principle 9: Design for portabilityDesign Principle 10: Design for testabilityDesign Principle 11: Design defensively9.3 Techniques for making good design decisions9.4 Model Driven Development9.5 Software architecture9.6 Architectural patternsThe Multi-Layer architectural patternThe Client–Server and other distributed architectural patternsThe Broker architectural patternThe Transaction Processing architectural patternThe Pipe-and-Filter architectural patternThe Model–View–Controller (MVC) architectural patternThe Service-Oriented architectural patternThe Message-Oriented architectural pattern9.7 Writing a good design document9.8 Design of a feature for the SimpleChat instant messaging application9.9 Difficulties and risks in design9.10 Summary9.11 For more 35135235335535836036236536636736810 Testing and inspecting to ensure high quality10.1 Basic definitions10.2 Effective and efficient testing10.3 Defects in ordinary algorithms10.4 Defects in numerical algorithms10.5 Defects in timing and co-ordination: deadlocks, livelocks and critical races10.6 Defects in handling stress and unusual situations10.7 Documentation defects10.8 Writing formal test cases and test plans10.9 Strategies for testing large systems10.10 Inspections10.11 Quality assurance in general10.12 Test cases for phase 2 of the SimpleChat instant messaging system10.13 Difficulties and risks in quality assurance10.14 Summary10.15 For more 42042142211 Managing the software process11.1 What is project management?11.2 Software process models425425428

Lethbridge.book Page ix Tuesday, November 16, 2004 12:22 PMContents11.311.411.511.611.711.811.912 t estimationBuilding software engineering teamsProject scheduling and trackingContents of a project planDifficulties and risks in project managementSummaryFor more information435445449452453455456Theme 1: Understanding the customer and userTheme 2: Basing development on solid principles and reusable technologyTheme 3: Object orientationTheme 4: Visual modeling using UMLTheme 5: Evaluation of alternatives in requirements and designTheme 6: Incorporating quantitative and logical thinkingTheme 7: Iterative and agile developmentTheme 8: Communicating effectively using documentationTheme 9: Risk management in all software engineering activitiesWhere next?459459459464464465465466467467469Appendix A: Summary of the UML notation used in this book471Appendix B: Summary of the documentation types recommended in this book475Appendix C: System descriptions479Glossary485ix

Lethbridge.book Page x Tuesday, November 16, 2004 12:22 PM

Lethbridge.book Page xi Tuesday, November 16, 2004 12:22 PMiiForewordIf a builder build a house for someone, and does not constructit properly, and the house which he built falls in and kills itsowner, then that builder shall be put to deathArticle 229 of the Code of Hammurabi (1780 BC).This earliest recorded attempt to regulate the engineering profession remindsus, in the bluntest way possible, that the paramount purpose of engineering andengineering design is to serve the user. One would assume that the engineer’sresponsibility to users is so self evident that it goes without saying. Variousprofessional engineering societies have inculcated this into the core of the rulesthat regulate the conduct of their members.However, in the relatively young discipline of software engineering, this hasnot yet fully permeated the professional culture. Part of it is due to the essentialnature of the software: like no other engineering medium, software provides theshortest path from concept to reality. With no metal to bend, heavy weights tolift, or large teams of people to mobilize, creativity is practically unhampered. Inthe heady and seductive process of embodying ideas through software, users areoften forgotten or relegated to secondary status. In some cases, they are evenseen as a distraction whose idiosyncrasies merely get in the way of ‘elegant andclean’ design. Software developers are notorious for their impatience withanything that separates them from programming – the medium has become themessage. Symptomatically, the terms ‘hacking’ and ‘hacker’ have no equivalentin any other engineering discipline.It is interesting to note the dramatic impact that the concept of ‘use case’ hashad on the software community. This idea, introduced by Ivar Jacobson and hiscolleagues a little over a decade ago, was lauded as revolutionary. Its essence liesin the formal introduction of the concept of a user (an ‘actor’) into the softwaredesign process. (The layperson can hardly be blamed for wondering ‘what tookthem so long?’ Hammurabi knew this almost 4000 years ago.)

Lethbridge.book Page xii Tuesday, November 16, 2004 12:22 PMxiiForewordClearly, there is an imbalance of motivations here that needs to be set right:the creative urge needs to be made subservient to the need to support the user.This is something that has to be instilled from the first steps in a softwareengineering education, and the book by Tim Lethbridge and Robert Laganièreis an important contribution to this.The authors build the book around nine ‘themes’, auspiciously starting with‘understanding the customer and user’. (Many software practitioners do noteven differentiate between customers and users.) The themes are not drytheorems but distillations of practical and proven domain knowledge drawnfrom a wealth of experience in industrial software development. The bookabounds with pragmatic detail that is rarely found in textbooks. In fact, it is thekind of textbook that, as a young engineering student, I wished I had, because itdescribes the proverbial ‘real world’.The book does not shirk theory, quite to the contrary. However, the theorycomes alive because it is set in its full and proper context, comprising not onlythe technical but the social and cultural aspects that often play an important rolein molding the theory. The reader not only learns why a particular technologicalapproach is good, but also its drawbacks and, perhaps equally importantly, itshistory. (Some things – like the QWERTY keyboard – can only be understoodproperly if one is familiar with their history.) They carefully point out thecontroversial issues in modern software engineering without taking sides,meticulously listing the arguments for each viewpoint.The ‘engineering’ side of software engineering is extremely well representedhere and not just because the authors emphasize a user-centric approach.Themes such as ‘incorporating quantitative thinking’, ‘evaluation of alternativesin requirements and design’, ‘risk management’, or ‘communicating effectively’are all proven and effective techniques evolved from centuries of engineeringexperience and which, unfortunately, are still not adequately applied in softwareengineering. Yes, software is different from other forms of engineering in many,many ways, but not so different that it cannot benefit from these lessons learned.For example, the lack of quantitative thinking, including elementary riskanalysis, is probably one of the most common causes of software project failures.And, no matter which statistics you read, more software projects fail thansucceed. (Thankfully, the engineers who design buildings and airplanes have amuch better record than their software counterparts.)Model-driven development is another important thread throughout thebook. This relatively new approach to software development, which promisesto be the first true technological generational advance since the invention ofthe compiler, is covered in detail, from the basic principles of objectorientation to the latest modeling languages and their use. The way of thefuture lies here.So, from the nuts and bolts of objects to the high vistas of softwarearchitecture, from writing code to testing, from software development processesto project management – it’s all gathered here. The breadth and depth of thematerial covered is striking and impressive, yet it has been brought together

Lethbridge.book Page xiii Tuesday, November 16, 2004 12:22 PMForewordquite seamlessly, all the pieces in their rightful places, in balance. Althoughprimarily conceived as a textbook, it will undoubtedly serve its readers as areference for years to come.If a builder build a program for someone, and does notconstruct it properly Bran SelicAugust, 2004Ottawa, Canadaxiii

Lethbridge.book Page xiv Tuesday, November 16, 2004 12:22 PM

Lethbridge.book Page xv Tuesday, November 16, 2004 12:22 PMiiiPrefaceOur focus in this book is software engineering knowledge and skills that readerscan put into immediate practical use. The book is designed to be used in secondyear post-secondary software engineering courses, although it has been used inintroductory software engineering courses at all levels. It will also be valuable toprogramming practitioners who want to develop a better understanding ofmodern software engineering.We have taught software engineering courses for fourteen years, and haveattempted to tune the book so that it is both useful and enjoyable to students.Feedback from former students has been gratifying – some have reported that theyregularly use it as a reference in their jobs. Our industrial experience performingsoftware development, consulting and professional training has also allowed us tofocus on material that is important to the employers of these students.Using the book in a software engineering degree programSoftware engineering is becoming an established discipline, separate fromcomputer science and computer engineering. As a witness to this, in 2004 TheIEEE Computer Society and the ACM approved Software Engineering 2004(SE2004), a document outlining what should be taught in any undergraduatesoftware engineering program. Timothy Lethbridge played a leading role in thatproject, and this book is specifically designed as a textbook for SE2004 courseSE201. See the web site http://sites.computer.org/ccse.At the University of Ottawa, we teach the material in this book over a 12-weekperiod during the first semester of the second year. By that time, students havecompleted two semesters of computer science – including object-orientedprogramming in Java. They take a course in data structures and algorithms inparallel with this course, and subsequently take advanced software engineeringcourses that expand their knowledge of the material we introduce here.Students who have studied the material in this course should be particularlyemployable in summer jobs, co-op and sandwich work terms, and other formsof industrial placement. Employers are looking for students who understandwhat constitutes a good requirement, can apply fundamental design principles,

Lethbridge.book Page xvi Tuesday, November 16, 2004 12:22 PMxviPrefacecan use UML properly, can translate requirements and designs into good qualityprograms, and can effectively test those programs. This book gives a practicalgrounding in all of these skills.The book is structured so that in a 12-week course or unit, it can be taughtusing three hours a week of classroom instruction, plus regular supervised andunsupervised laboratory time. Each year we assign a selection of the exercises,many of which students work on in groups. This second edition of the bookupdates many exercises and introduces many new ones.Suggested backgroundPrior to studying this book, readers should understand the basic notions ofobject-oriented programming, although Chapter 2 gives a brief review of theseconcepts. We have selected Java as the language used for programming examplessince it is a complete, simple and popular object-oriented language. Motivatedreaders who know other object-oriented languages should be able to pick up thenecessary Java from the material provided in Chapter 2 and the book’s web site,and as they work through the exercises.Material on the web siteWe have prepared a web site with many resources to support readers andteachers. The address is http://www.lloseng.com.Here you will find sets of presentation slides, source code, answers to exercises,links to all the web-based references, a knowledge base summarizing many of theconcepts presented, videotapes of lectures, and various other learning aids.There is also a publisher’s website at http://www.mhhe.com/lethbridge, whereyou will find lecturer’s password-protected resources.Themes taught throughout the bookWoven throughout the book are nine themes that we believe are basic tocontemporary software engineering. Each of these themes is revisited in manychapters, and is taught in the context of concrete examples and exercises.1. Understanding the customer and the user. We emphasize domain analysis aswell as gathering and validating requirements. We place these in the context ofuse case analysis and usability. Readers are asked to think in terms of what thecustomer’s problem really is, what is realistic, etc. The purpose of softwareengineering is described at the beginning of the book as solving customers’problems, rather than developing software for its own sake.2. Basing development on solid principles and reusable technology. Weemphasize the necessity for software engineers to understand design principlesand have a thorough grasp of suitable technology before embarking on aproject. To ensure this is the case for the design work in this book, we firstreview object-oriented principles. Later we discuss frameworks, a series ofdesign principles, and many design and architectural patterns.

Lethbridge.book Page xvii Tuesday, November 16, 2004 12:22 PMPreface3. Visual modeling using UML. We present key elements of UML, particularlyclass, interaction and state diagrams. We do not cover all of UML and we donot restrict our discussion to UML alone since it does not cover all of softwareengineering. We emphasize that UML diagrams do not solve problems bythemselves, but are one of the many tools that software engineers should use asa regular part of their work. For the second edition, we have updated the bookso that it is compliant with UML 2.0.4. Evaluation of alternatives in requirements and design. Throughout the bookwe present alternatives with their advantages and disadvantages. We encouragereaders to record the rationale for each choice.5. Object orientation. We cover all aspects of object-oriented development,including analysis, design, and programming. Ensuring that the reader seeshow to take projects all the way to implementation means that he or she getsmore than just an abstract view of the development process, and appreciatesthe reasons for many design principles.6. Quantitative and logical thinking. We cover the essentials of software metricsin several different chapters so that students can learn to think quantitatively.We also promote the judicious application of logic as embodied in OCL andassertions.7. Iterative and agile development. We strongly emphasize that readers shouldfollow an iterative approach to development. As project work, readers are askedto perform requirements analysis, design and implementation very near thebeginning of the book, and then again several times throughout the book. Toaccomplish this we introduce a complete project in Chapter 3. Initially, readersare asked to make only a small change to this project in order to begin tounderstand it. In Chapter 4, readers are then asked to write and reviewrequirements for new features to add to the system – again they design andimplement the features. Later, readers learn more details of topics such asdesign and quality assurance, and are asked to apply what they learn tosuccessively more advanced changes to their project. Concepts from the agilemovement are also emphasized: developing in very small increments, test-firstdevelopment, etc.8. Communicating effectively using documentation. We encourage readers topractice writing informative but concise documentation; we provide templatesand examples of each type of document.9. Risk management in all software engineering activities. Throughout thebook, we discuss many aspects of risk management, including evaluatingpotential costs and risks on a regular basis, balancing risks with benefits,avoiding doing work that is not worthwhile, and evolving plans as we learnmore information. We point out that the knowledge learned from the otherthemes above can be applied to reduce risk.xvii

Lethbridge.book Page xviii Tuesday, November 16, 2004 12:22 PMxviiiPrefaceChanges in the second editionIn the second edition, we have made a wide variety of small changes to keep upwith changes in the field. The following are some of the more significantchanges: Covers UML 2.0. Moves all discussion of use cases to Chapter 4. Introduces model-driven development. Discusses web-based software architectures and middleware. Integrates discussion of agile approaches, and techniques made popular bythose approaches including refactoring and test-driven development. Covers more of the essentials of measurement and metrics. Incorporates many new and changed exercises. All exercises have been given anew numbering scheme to prevent confusion with those in the first edition.Structure of the bookSize The book is small enough so that instructors can realistically require students toread it all during a 12-week course. We present a suggested schedule below.Depth Rather than covering all aspects of software engineering, we present inreasonable depth a cohesive collection of material that will give readers afoundation in topics central to the field. We focus on material that isimmediately applicable in industrial software projects.Examples and Readers can practice applying the concepts, since we provide an extensiveexercises set of examples and exercises. One set of project exercises is based on a fullyimplemented small system, which we provide. This means that, rather thanalways programming from scratch, readers are able to spend their timethinking about higher-level analysis and design issues, yet they can stillpractice implementation of their ideas. Readers also come to appreciatereuse, since the implemented system is based on a framework that isapplicable to a wide variety of client–server systems. The exercises varywidely in difficulty; some are easy and simply encourage the reader to thinkabout what they have read; others are intended to motivate advancedreaders. Many exercises have fully explained answers available in thestudent’s answer manual; other answers are available in a manual onlyavailable to instructors.Sequencing The sequence of material in the book is designed to allow students to rapidlystart work on real problems requiring analysis, design and implementation. Asreaders perform several iterations of project work, we introduce topics theywill need in each iteration. The early part of the book, for example, introducesthe knowledge about object orientation and architecture that they will need to

Lethbridge.book Page xix Tuesday, November 16, 2004 12:22 PMPrefaceunderstand the project work. Then we move on to requirements and objectoriented analysis, focusing initially on use cases and static modeling. Later, weintroduce dynamic modeling.Use of this book in a 12-week courseThe following is a suggested schedule for using this book in a second-yearuniversity course. For the main body of the book, Chapters 3 to 10, the allocatedtime corresponds roughly to the length of each chapter.The authors use this book in a 12-week course, where each week has threehours of lecture as well as three hours of lab and tutorial time. Students areexpected to read all the chapters, although the lectures focus most heavily on thecore material in Chapters 3 through 10, and particularly Chapters 3, 5, 8 and 9.We also anticipate that students work on a selection of exercises withdeliverables about four times during the course. We also expect them to deliverthree iterations of the project. We have provided suggested project activities atthe end of many chapters.Week 1 Chapters 1 and 2: Introduction and review (1 week).Weeks 2–3 Chapter 3: Reuse and the client–server framework (1.5 weeks).Project work: learning to use the client–server framework by making a minorchange to a system implemented using it.Weeks 3–4 Chapter 4: Domain analysis, use cases and requirements (1.5 weeks).Project work: adding features following requirements analysis.Weeks 4–5 Chapter 5: OO analysis and modeling (1.5 weeks).Project work: adding features that require considerable modeling.Week 6 Chapter 6: Design patterns (1 week).Week 7 Chapter 7: Use cases and user interfaces (0.5 weeks).Project work: adding a GUI.Weeks 8–9 Chapter 8: Dynamic modeling (1.5 weeks).Weeks 9–10 Chapter 9: Design principles and architecture (1.5 weeks).Project work: detailed design of some features.Week 11 Chapter 10: Testing (1 week).Project work: preparing a test plan.Week 12 Chapters 11 and 12: Introduction to project management and review (1 week).Other orderings are possible. In particular, the order in which Chapters 6through 11 can be covered is flexible. Also, parts of many chapters could beskipped in order to give greater emphasis to other material.xix

Lethbridge.book Page xx Tuesday, November 16, 2004 12:22 PMxxPrefaceAcknowledgementsWe would like to thank the following people who helped us improve this book: Those who have contributed insights or helped edit the book. There are toomany to mention them all, but we would especially like to thank Rohit Bahl,Bob Probert, K. Teresa Khidir, François Bélanger and Klaas van den Berg whomade particularly large contributions. Judy Kavanagh, who worked on the knowledge base of the accompanying website and helped refine the glossary. The University of Ottawa students in SEG2100 and SEG2500 with whom weused this book and its beta versions for several years. Many of the approachesto explaining things in the book arose from trying to answer tricky studentquestions. Students have also pointed out many improvements, which we haveincorporated.We would also like to thank our families who have had to put up with ridiculouswork schedules when deadline crunches approached.The publishers would also like to thank the following reviewers who providedhelpful feedback on the first edition of this textbook: Muthu Ramachandran,Leeds Metropolitan University, UK; Klaas van den Berg, Twente University, TheNetherlands; Renaat Verbruggen, Dublin City University, Republic of Ireland;Paul Krause, University of Surrey, UK; Filip Vanderstappen, Erasmus University,The Netherlands; Gero Wedemann, Fachhochschule Stralsund, Germany;Radmila Juric, University of Westminster, UK; Willem-Jan van den Heuvel,Universi

5.10 Implementing class diagrams in Java 216 5.11 Difficulties and risks when creating class diagrams 218 5.12 Summary 218 5.13 For more information 219 Lethbridge.