ObjectOriented Analysis Design Using UML Dr Tim Menzies
Object-Oriented Analysis & Design Using UML Dr. Tim Menzies School of Computer Science & Engineering, UNSW tim@menzies. com Wednesday, May 13, 1998 1
Dear Kaz, Julian, Bhuvan u u One course. 2. 5 days of materials and labs. Please take to it with much red pen. This course structure is motivated by a remark by Craig Mann: l u can’t draw sequence diagrams till we have the column names; don’t have column names till we have objects; can’t work out objects till we understand classes Also: l I wanted to leave time for students to u u Go home early work on some problem they invent Is there any good material we can steal from the CRC/requirements eng. courses and add in here? I’m assuming that you’ll treat this as a working document, not to be used commercially until we fix a price (if ever). 2
Dear Kaz, Julian, Bhuvan (II) u u u Also, do we have any notation summaries we can drop in? Also, do we have any other material we want to drop in? e. g. are we still selling persistence? if yes, then I have some oodbms stuff to add. What else: e. g. language overviews? l l l Java C++ We could ask some language gurus to code up some e. g. s of common UML constructs (association, inheritance, constructors, class variables…) 3
Dear Kaz, Julian, Bhuvan (III) u Lastly: should it have “UML” in the title? is “UML” a selling point? or is ooa-d the real issue here? 4
Contents p. 4: An introduction to OO p. 15: Objects and classes p. 30: CRC cards p. 39: Noun analysis p. 51: Uses cases… sequence diagrams p. 74: Class diagrams p. 104: Evolutionary, iterative development p. 124: OO Metrics } The royal road p. 153: State Transition Diagrams p. XXX: References p. end: Case study: costing the supermarket 5
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 6
An Introduction to Object-Oriented 7
Why OO? u The use of object-oriented technology is becoming widespread in industry, l u The wallpaper of the software world we live in Genuine productivity and reliability gains can be experienced if object-oriented techniques are understood and systematically applied. l Next generation in commercially viable modeling tools 8
The Language Dial Both: OO you are here, probably What you do: procedural thinking, structure charts, functions, C, Pascal, Cobol, FORTRAN, Lisp What you do it to: declarative thinking, E-R modelling, logic programming, SQL, Prolog 9
OO: The Past least • • Physical level dependency M: N hard No ad-hoc queries Navigation pre-defined, hard to change Relational • • Ad-hoc queries Weak semantics Entity Relationship • • Easier to understand More semantics • • More semantics More operations defined on complex data types Automatic support for inheritance Hierarchical CODASYL (network) Semantics in Data Model Semantic most Object Oriented Extended Relational • 10
What’s wrong with relational? C 1 C 2 Gate Instance C 3 2 AND 4 AND P Gate Type u u GT GT 2 AND flattening and 4 AND scattering: unnatural Wire Instance traversal: expensive ops on composite parts: awkward Same problems with multi-media, GIS, CAD, . . . GI C 1 C 2 C 3 P Pin Type Parent PT I/O 2 AND 4 AND 4 AND A B C D E I I 0 I I O WI GT 1 GI 1 . . . W 1 W 2 W 3 W 4 W 5 W 6 W 7 4 AND 2 AND P P C 1 C 2 C 3 A B C D C C C Description C=A&B E=A&B&C&D GT 4 AND … 11
OO: Simplifies Development? classes initial thinking working system classes u u OO analysis constructs: classes OO coding constructs: classes SDLC analysis constructs: DFS, E-R SDLC coding constructs: Tables, Cobol (e. g. ) l u Lost access to the final DFDs OO better for metrics l l Uniform conceptual model throughout the lifecycle Better for metrics, prototyping (RAD) 12
An OO Project Lifecycle on tion laborati p e c E In tion truc Cons it Trans ion Requirements Analysis Design Code Test Time Iterations 1 2 3 4 5 6 7 8 9 10 13
Another Surprise u Object-oriented is not just a programming language technique l u Can “do OO” without writing one line of C++, Delphi, Smalltalk, Eiffel, Java, Power. Builder, Vbasic, …. It’s a method of structuring a discussion about a domain l Good for groups u u l Combine data and functions in one blob Hides tedious detail Good for modeling at many levels u u u Business process re-engineering Meta-principles of design Particular problems 14
History of the UML Nov ‘ 97 UML approved by the OMG 15
What is the UML? u u UML stands for Unified Modeling Language The UML combines the best of the best from l l u u Data Modeling concepts (Entity Relationship Diagrams) Business Modeling (work flow) Object Modeling Component Modeling The UML is the standard language for visualizing, specifying, constructing, and documenting the artifacts of a softwareintensive system It can be used with all processes, throughout the development life cycle, and across different implementation technologies 16
What UML is Not u u UML is not a methodology What is a methodology? l Method for co-ordinating and predicting team work u UML is not a case tool u What is a case tool? l l l l Mechanism for sharing design documents between teams Support for specification to code or code to specification Scheduler Report generator from specifications or code Time or defect tracking tool Version control; intelligent version control (Design rationale) Requirements engineering: negotiating the resolution of conflicts between different people’s specifications 17
Objects & Classes 18
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 19
Buzzwords: Classes and Objects u Classes make objects l l u Objects have l l l u Attributes (state, date) Operations (behaviour, function, code) Identity (uniqueness, memory location) Objects can use l l u Design time: classes Runtime: objects Inheritance (ask your father) Classification (factory, stencil) Encapsulation (border gaurds) Polymorphism (polly wanna cracker and don’t care how you do it) By the way, classes are objects too! 20
Classes & Objects Man Tim Don 21
Objects = Operations, Attributes, Associations Attributes Age Spouse Address Associations my. Left. Arm my. Left. Leg my. Right. Arm. . head arm body leg arm leg Operations Jump. . Talk. . . Dance Ask Friend Jump Walk Jump Shake my. Head Shake my. Body A working OO system: a conversation between networks of objects 22
Inheritance and Polymorphism u u Polymorphism: of many forms Inheritance: ask your father can move the same way Shape bitmap move internally, all “shapes” are bitmaps. Circle Triangle Square draw themselves differently if shapes need to move, they get the “move” from their parent 23
Notation Class 1 attributes operations isa Class 2 gets all the attributes, operations, and relationships of Class 1, and some. . . 24
Isa and Identity u ER needed generalisation links Employee num, name, dob Pilot num, name, dob, flt_hours u Generalisation needs program support l l l Auto copy of super attributes to sub Auto join over the generalisation link Identity support Employee name, dob Pilot flt_hours 25
Using Inheritance To Improve Data Models u Data models ignore distinctions based on behaviour Data-only models only see this { Person DOB Walk } shared attribute shared behaviour Old. Male Female Dance Jump OO models see all specialised behaviours 26
Inheritance: Normalising Behaviour u Old men jump the same way as young men l But, when they dance, they jump less Person DOB Walk abstract class Male Female Jump Dance Jump Old. Male Young. Male Dance 27
More to OO than Inheritance: Associations Ground. Vechile 1. . 10 registration wheels owner doors Car Truck 1 1. . 3 Perso n name pay. Ta x 1 Trailer wheels unhitch. Trailer driver. Tired 28
Notation min 2. . max 2 Class 1 min 1. . max 1 relationship At runtime, Class 2 can access between min 1 to max 2 objects of type Class 1 Class 2 If an attribute is of a type that we are building, replace it with a relationship 29
Person name dob address Address street# streetname postcode Person name dob Address street# streetname post. Code address Person and Address Class } Note, nested instances shown as relationships: shrinks the design document Design issues l l If Person goes, should we delete its address Where is suburb and age u “encapsulation” 30
Encapsulation u Encapsulation permits the large scale reorganisation of a system Can change the internals as required l Class interface is “age ==> number” l u Q: How do we compute “age” from person? Store dob and work it out as requested? l Store current age and update each year? l u A: We don’t care u. As long as we maintain the interface Person name dob age address Address street# streetname post. Code suburb } Q: when should we cache rather than compute on demand? 31
Polymorphism Customer interest? balance? interest? Investment. Account Cheque. Account Savings. Account If new account added l As long as it responds to “interest? ”, we don’t need to change existing code 32
CRC Cards 33
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 34
u Tactile Modelling: Brainstorming with CRC Cards Discovery technique: anthropomorphic thinking u CRC = “Class” Responsibility Collaboration Cards l l “Class” = class/module Responsibility u l 1 or more methods/functions in this module Collaboration for each responsibility u Calls to other modules/classes Module/Class name: Role (mission statement): superclasses: Responsibilities Collaborators 35
The CRC Process u u 5 x 3” cards, pencils, erasers One module / card l u Walk through known scenarios l u “Own the card” Accept reasonable behaviours l l u Each card has a “mission statement” And work out the collaborations required for each such behaviour Reject operations that don’t fit the mission statement Walk, talk, hold, argue, rubout, tear up. 36
Example CRC Card name: Logon Validation Service Superclasses: Service Role: Handles validation of user logons Responsibilities: 1. Accesses records to see if a user’s name and password are valid. 2. Check if user’s password has expired. Collaboration: 1, 2. User Record 37
Example CRC Card name: Audit Log Role: Maintains a log of audit events. Responsibilities: 1. Maintains a list of retained audit events in chronological order. 2. Removes audit events that have exceeded their retention period. 3. Allow new audit events to be logged. Collaboration: 1, 2, 3. Audit Event 38
Example CRC Cards Card Name: Warehouse Role: Representation of a warehouse Responsibilities: m 1. Knows its address, floor space m 2. Allocates floor space into different sized regions m 3. Allocates floor space for items Collaborations: 2, 3. Floor. Plan, 3. Item Card Name: Item Role: Representation of a physical item which can be stored Responsibilities: m 1. Knows its description, dimensions, weight, storage conditions m 2. Knows its barcode, storage status m 3. Knows if storage state is consistent Collaborations: None 39
CRC Sessions: Products u Candidate classes/ objects l u Stories l u Prone to change Cards l u Prone to change A talking team l Hopefully, not prone to change 40
Hints for Using CRC cards u Team: 2 too little; 10 too much l u Well before brainstorming: l u l l All ideas are good ideas, think fast and furious (ponder later), Give every voice a turn (round robin with “pass”) A little laughter can be a powerful force Just before brainstorming: l u Prepare (assign known documentation, users, current systems, software…) Rules while brainstorming: l u Include users (!!), analysts (who can make connections), designers (seen but not often heard), facilitator (quality focused) Review rules, state session objectives Just after: l Find the definite “yes” and “no” before noting the “maybes” 41
Noun Analysis 42
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 43
Deleting and Adding Nouns u u The programmer giveth, and the programmer taketh away. Not all nouns in the CRC stories are useful. l u Some we throw away (synonyms, homonyms, too boring). Not all useful nouns are in the CRC stories l Some we add via experience nouns “natural” in the domain useful “natural” nouns special “secret” nouns known to developers useful secrets 44
Deleting Nouns #1: Not Class if Wrong Size u Class, not subsystem l l u GUI is too big to be a class Person is about the right size Not attributes l “Top right corner” best as an attribute 45
Deleting Nouns #2: Not Class if Something Else u Class, not operation l “Open” is not a class u l Classic novice mistake: u u u Operation within a class Class with verb name and only one operation Re-inventing sub-routines Class, not relationship Manager E. g. “job description” hire, fire l job description * friends Person * 1 * 0. . 1 spouse * Task Cashier receive. Dollars 46
Deleting Nouns #3: Not Class if No Structure u Object has state, behaviour, identity l u u I. e. some internal data or some special behaviour, and something that is separate to other objects Classes are needed for sets of objects Is the phone number +61 -2 -9385 -4034 a class or an Person object? phone. Number: String u Is not worth modeling, its only a string Person u It is worth modeling, has a rich structure Phone. Number label: String country. Code area. Code digits connect 47
Adding Nouns Using Patterns u Patterns: l l u Abstracted portions of previous class models Useful in new situations Advanced concept 48
Adding Nouns With Patterns: Example #1 1 Place Participant * 1 Actor Item 1 u 1 * * * Transaction 1 1 1. . * 1 Transaction * Line Item * 1 1 Specified * Item 1 Subsequent * Transaction 1. . * 1 Subsequent Transaction * Line Item Line 330 of specification: “… so after customers pays, then…” l l Patterns-literate designer: “pays? pays! a transaction! 9 classes I’ve already built! Reuse!” Now, go back to the user; check you have actors, items, places, any subsequent transactions, …. 49
Adding Nouns With Patterns: Example #2 Ground. Vechile 1. . 3 1. . 10 owner Car u u Truck 1 Person 1 Trailer 12 classes are missing from this diagram. Can you see them? l l Yes: if you know the OO patterns of financial applications No: otherwise 50
Adding Nouns With Patterns: Example #2 (cont. ) u Over 90% of all MIS applications are 3 -tiered l u Size estimation: l l u Databases layer, business model layer, dialgoue layer (screens) Business Model = 1 class , Dialogue = 1 class, Data =1 class, Helper = 0. 5 class Total = 3. 5* Model classes Cost estimation (very approximate) l Assumes we know classes/month for developers u u l e. g. from previous application Typical industry values: 2 -20; average (4 -8) (3. 5*Model class)/(Class/month) 51
Adding Nouns With Patterns: Example #3 u Line 1024 of the spec says: “the id is checked amongst known customers then. . . ” l Patterns-literate designer: Customers? Plural? Ah ha: need: u u u u Customer A Customer. DM (data manager) class to store the list of known Customers Maybe a Customer. DBHook class to write Customers to and from the Database A Customer. Editor screen class A Customer. Enquiry search screen class A Customer. Proxy (can stand in for a Customer in “dangerous” situations; e. g. half way through an edit sequence). Customer. Error to handle exception cases about Customers Seven nouns from one! If Xs, then l X, XDM, XDBHook, Xed, Xenquire, Xproxy, XError 52
Noun Analysis: Summary u u Working system contains only some domain terms as data structures. Working system can contain more than those domain terms. Noun review rules for culling noun. Patterns for adding nouns. 53
Use Case Diagrams, Use Case Text, Scenario Text. Sequence Diagrams 54
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 55
Use Cases u u u CRCs= elicitation Use cases = representation Informal technique for requirements capture l u Adopted, in various forms, by all the major methodologies Use cases and software modules: complementary view of an application l Use case = end-user’s view; good for application requirements u l Users can read, understand, and critique business-level use cases/scenarios OO model = developer’s view; good for structure and interaction of application parts 56
Use Case Structure u Dozen’s l u Contains: l l l u Not hundreds Brief goal statement 1 sunny day event (main course, primary scenario) N rainy day(s) (alternate courses, secondary scenarios) Full business process: l Installing the database u l From “installation starts” to “database working” Printing a report on Employee performance u From “selecting a DB table” to “collect from printer” to “discussing it with CEO” to “sending out evaluation letters” 57
Use Cases have “Actors” u An actor is someone or some thing that must interact with the system under development Registrar Professor Student Billing System 58
Use Cases u A use case is a pattern of behavior the system exhibits l u Each use case is a sequence of related transactions performed by an actor and the system in a dialogue Actors are examined to determine their needs l l Chancellor -- balances budget Lecturer -- request roster Student -- maintain subject selection Enrollment records -- receive billing information from registration Maintain Curriculum Request Course Roster Maintain Schedule 59
Documenting Use Cases u A flow of events document is created for each use cases l u u Written from an actor point of view Details what the system must provide to the actor when the use cases is executed Typical contents l l How the use case starts and ends Normal flow of events Alternate flow of events Exceptional flow of events 60
Maintain Curriculum Flow of Events u u u This use case begins when the Registrar logs onto the Registration System and enters his/her password. The system verifies that the password is valid (E-1) and prompts the Registrar to select the current semester or a future semester (E 2). The Registrar enters the desired semester. The system prompts the professor to select the desired activity: ADD, DELETE, REVIEW, or QUIT. If the activity selected is ADD, the S-1: Add a Course subflow is performed. If the activity selected is DELETE, the S-2: Delete a Course subflow is performed. If the activity selected is REVIEW, the S-3: Review Curriculum subflow is performed. If the activity selected is QUIT, the use case ends. 61
Use Case Diagram u Use case diagrams are created to visualize the relationships between actors and use cases Student Role Lecturer Student Choose Subject Make budget Enrollment records Chancellor 62
Uses and Extends Use Case Relationships u As the use cases are documented, other use case relationships may be discovered l l u A uses relationship shows behavior that is common to one or more use cases An extends relationship shows optional behavior Over-use of extends = functional decomposition uses Assign Seat extends Book flight Upgrade seat 63
Using & Extending a Use-Case u Use l u Extend l u Contains another complete use-case Extends another use-case Beware: l Rumbaugh says Use = aggregation and Extend = inheritance 64
Use Cases: Example Chemist Sell new drugs Customer Service old drugs Identify extends Counter transaction Propose Therapy Accountant Drug Company Chemist Handle Finance 65
Scenarios u Use case: general l u Traveller offers flight data, system checks availability and asks for payment, user confirms flight details and pays, transactions stops. Scenario: specific l Tim says he wants to fly to Perth on Tuesday, travel agent uses Win. Term to check the flight details, highlights screen, copies text, pastes into Microsoft Word, prints, shows Tim oks it, and offers Visa Card. Agent swipes card and when screen says “approved”, makes the booking. 66
Sequence Diagrams u u Used to trace the execution of a scenario in the same context as the object diagram Describes a single execution without conditionally They illustrate interactions that are inherent in their isolated behaviour but whose overall form isn’t apparent in their isolated behaviour Easier to read than object diagram l u esp. the passing of control/messages Good for capturing semantics of scenarios in the early phases 67
Sequence Diagram: Notation Thing 1: Class Thing 2 : Class 3 Thing 4 event 1 time event 2(Arg 1, Arg 2) event 3: return. Type event 4 68
Sequence Diagram: Example Caller Phone Line Callee caller lifts receiver time dial tone begins dial(9) dial tone ends dial(1) ringing tone phone rings tone stops answer phone ringing stops 69
Sequence Diagram u A sequence diagram displays object interactions arranged in a time sequence : Student registration form registration manager math 101 section 1 1: fill in info 2: submit 3: add course(joe, math 01) 4: are you open? 5: are you open? 6: add (joe) 70
Collaboration Diagram u A collaboration diagram displays object interactions organized around objects and their links to one course form : 1: set course info another Course. Form 2: process 3: add course : Registrar the. Manager : Curriculum. Manager a. Course : Course 4: new course 71
Problems with Uses Cases u How big? l l The grain-size problem Domain-specific u u u How big is a piece of string? Too many Too user-focused l Classes that do not appear in a use case u u Are ok (Rumbaugh) Should not exist (Jacobson) 72
Use Cases & Objects u u u Not one-to-one Use cases suggest lots of objects Need to resolve inconsistencies & overlaps l l l Synonyms (same object, different name) Homonyms (different object, same name) True overlaps u u Pointer to more abstract objects As new objects created, keep tractability to use cases 73
Use Cases & Software Life Cycle u Analysis l u Design l l u End-users can understand a use case Audit the design with use cases Find missing modules/objects Coding l What % of the use cases can we cover this week? 74
on tion laborati p e c E In An OO Project Lifecycle tion n uc tr Cons itio Trans Requirements Analysis Design Code Test Iterations (deliver use cases) 1 Time 2 3 4 5 6 7 8 9 10 75
Use Cases & Evolutionary Programming u u Iterations operationalise use cases Graph of % use-case coverage vs time l l Tests for run-away specification Assesses % completion % coverage time u Aim for some use cases running early l Initial thin path through the design; widened as application development progresses. 76
Class Diagrams. 77
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 78
Notation u Cardinality: How many things are associated to another thing? 1 to 1 * 0. . M 0. . 1 1+ * 3 -5 * {ordered} u Aggregation (hasa, part-of, assembly) aggregation (1 to 1) 1 to many (maybe 0) * 0. . M aggregation (1 to M) 1 to 0 or 1 u 1 to 1 or more (not 0) N-M multiplicity Inheritance (isa) Y X Y isa X 1 to many (sequence) * 79
Multiplicities Student * * Body University Heart 2 -3 Bicycle * 1+ Account * 1+ * Wheel Owner 80
A Sample Business Model Home Loan Collateral secures uses has Customer * works with for a makes* Payment * handles Service Agent * * Loan * responsible for works for Car Loan Business Loan has a Loan History makes Institution 81
Aggregation u u Lifetime of the container = lifetime of the contents If container goes, and there are contents, what should we do? l l l u u If container created, do we create contents? Processing to container typically passes to contents l u u Block? Ask? Remove? e. g. Person. walk ==> legs. walk + arms. swing + heart. speed. Up Best viewed as physical containment (I. e. not a Java, Smalltalk concept) Use rarely in high-level design (says Timm) 82
Q: Associate or “has-a”? u What do you think: l l l u Club has members Airplane has wings, engine, seats Company has divisions When in doubt: l associate 83
What Should Subclasses Do? u u u Valid sub-class actions l Defining specific behaviour for that class l Changing defaults l Extending inherited behaviour Example: l Applications print their files in different ways l But all files still respond to “print”. Subclasses should extend, not amputate 84
Q: Isa Car Yard? u If A isa subclass of B l Then we should be able to say that A is-a B Sales. Yard Car. Yard u So, is this design ok? l l Discuss If not, then fix it! 85
A: Isa Car Yard? u A car is-not a yard full of cars Sales. Yard contains Car. Yard contains * Vehicle * Car Note: is this second link needed? 86
Poor Uses of Inheritance Number Integer Fraction 2 Fraction * 1 contains Comment: confuses inheritance with association Comment: better 87
everyone moves the same way odd: empty class odd: pen class? Figure colour , centre position pen thickness, pen type move!, select!, rotate!, display! 1 Dimensional orientation scale! can’t scale 0 -D things 0 Dimensional Point display! Line endpoints display! Arc radius, startangle arc. Angle display! only 2 -D things can be filled 2 Dimensional orientation, fill type scale!, fill! Spline control pts display! Polygon num of sides vertices display! everyone gets their own display Circle diameter display! rotate! simpler rotate 88
Q: Design a Graphics System u u A “graph-file” stores “sheets” (pages) containing lots of “things”. “Things” can be “text”, “lines”, “circles”, “squares”, “rectangles”, or “groups” of things (and “groups” can be grouped). Design this system using the Unified Notation ignoring windowing details (e. g. scroll bars, mouse, windows. . . ) 89
A: Design a Graphics System Document * Sheet * Drawing. Object Text common recursive modelling technique 2. . * Group Geometry 1 Ellipse Rectangle Circle Square Line To come: “Q: Isa Square a Rectangle? ” 90
Q: Isa Square a Rectangle? u If the attributes of an instance changes at runtime l u The class of that instance should not So, is a square a rectangle? Rectangle width, height Square 91
A: Isa Square a Rectangle u At runtime, if width=height, then our “rectangles” become “squares”. Rectangle width, height is. Square square u And is a circle an ellipse? 92
Q: Car Loans u u Persons have up to 4 employees. Owners can own several cars. Cars can be financed by several loans. Banks loan to persons, companies, and other banks Fix the supplied design: l Hints: replace pointers with associations; get multiplicities right; eliminate IDs; ? ? add classes. Person name age employer 1 ID employer 2 ID employer 3 ID person ID address Car owner ID vehicle ID owner type model year Car loan vehicle ID customer type customer ID account number band ID interest rate current balance Company name company ID Bank name bank ID 93
A: Car Loans * owns Owner name Person age address u u Company * * employment borrows Car model year * Bank * lends Loan account# interest rate current balance lein * Persons have < 4 employees: ignored (? artificial). Account number left in: why? Any extra sub-classing we can do? Are any relationships redundant? 94
Is Multiple Inheritance Essential? Employee Hourly Salaried Exempt Employee Vested Employee Unvested Employee Vested Hourly Employee u Grady Booch: l u MI is like a parachute: used rarely, but then you really need it Do we really need MI here? l What if an employee’s “role” changes; e. g. to salaried? 95
Removing Multiple Inheritance (I) u When all subclasses are equal, replace inheritance with association Employee Payroll Employee Hourly Salaried Exempt Employee u Employee Pension Vested Employee Unvested Employee Disadvantage: l Need “re-route” code at Employee which resends some Employee messages to Pensions or Payrolls 96
Removing Multiple Inheritance (II) u When 1 superclass dominates, use inheritance and association. Employee Pension Employee Hourly Salaried Exempt Employee u Vested Employee Unvested Employee Disadvantage: if design changes: l “dominance” might change as well 97
Removing Multiple Inheritance(III) Employee Hourly Vested Un. Vested Employee u u Salaried Employee Salaried Unvested Employee Exempt Employee Salaried Vested Employee Exempt Un. Vested Employee Nested generalisation. One leaf for each combination of superclasses: can get very big!!! 98
u Qualifiers are keys on a “many” join. l l u Aid navigation ? ? should not live in high-level design Qualifiers shown on the 1 side l u Qualified associations Are always an attribute on the many side Reduce the size of the many set l but may not restrict to 1: 1 (e. g. Marina) Directory name * File Marina * Boat Marina propulsion * Boat 99
u Attributed associations Used when: l l The link “attribute” also has operations. The link “attribute” has class associations User uses * * Workstation Session logoff 100
Attributed Associations can be Rich Structures uses Workstation User * Session. Eve nt time * Help. Reque st request 1 Help. Reply ss. Name 1 Session start. Time stop. Time logoff 1 0 Logon. Screen prompt password. File check. Password start. Session display 0 101
Attributed Associations can be Rich Structures some concepts are relationships, not classes, attributes, or operations Manager hire, fire job description Person * * Task Cashier only managers can hire and fire (built into our design) receive. Dollars 1 Job History assessment 1 stop start 0. . 1 Time. Stamp date 1 time 102
Using Attributed Associations Attributed associations good for properties that can only exist when a relationship exists Shipment * * Stored. Item quantity sold Item * Warehouse holds * sent Shipped. Item quantity * u Order * Ordered. Item quantity 103
Implementing Attributed Associations 2 -5 Subject 1) Top Level 20 -100 * Student * Enrolment grade 1 2) Coad’s view Enrolment Subject 20 - grade 2(doing the 100 5 multiplicity dance) 1 Student 3) The full wiring Subject 1 1 1 List 20 -100 1 Enrolment grade 1 2 -5 1 List 1 1 Student 1 1 104
Simplifying Attributed Associations Subject 1 1 1 List 20 -100 1 Enrolment grade 1 2 -5 1 List 1 1 Student 1 1 4) Assume only joining subject to student Subject 1 1 List 20 -100 1 Enrolment grade Student 1 1 5) Fold grade into student Subject 1 1 List 20 -100 1 Student grade 105
Assessing the Options 3) The full-wiring: complicated to build (first time. . ) but most general Subject 1 1 1 List 20 -100 1 Enrolment grade 1 2 -5 1 List 1 1 Student 1 1 4) Assuming joins: simpler, could add back-pointers later, but losses the student subject constraint 2 -5 Subject 1 1 List 20 -100 1 Enrolment grade Student 1 1 5) Makes future change very hard! Subject 1 1 List 20 -100 1 Student grade 106
Evolutionary, iterative development 107
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 108
OO: Implies Interation classes initial thinking working system classes u u OO analysis constructs: classes OO coding constructs: classes Change is faster Iteration must be managed 109
What the Iterative Life Cycle Is Not u u u It is not hacking It is not a playpen for developers It is not unpredictable It is not redesigning the same thing over and over until it is perfect It is not an excuse for not planning and managing a project It is not something that affects only the developers on a project 110
What the Iterative Life Cycle Is u u u It is planned and managed It is predictable It accommodates changes to requirements with less disruption It is based on evolving executable prototypes, not documentation It involves the user/customer throughout the process It is risk driven 111
Iterations Retire Risks Initial Project Scope Define scenarios to address highest risks Plan Iteration N • Cost • Schedule Iteration N Develop Iteration N • Collect cost and quality metrics Assess Iteration N Revise Overall Project Plan • Cost • Schedule • Scope/Content Revise Project Risks • Reprioritize Risks Eliminated 112
OO life cycle: some surprises u u u Traditional (waterfall) Paper or deadline driven Activities: 1) 2) 3) 4) 5) 6) u Requirements Analysis Design Code (starts here) Test Maintain u u u OO Risk-driven Iteration-based Light-weight processes Waterfall activities become sub-routines within an iteration Little support for iteration l Activity I+1 can revise I (but not earlier) 113
An OO Project Lifecycle te t, tas Firs e n, bit The ew h h c , Now ard allow w s , y Lastl Requirements Analysis Design Code Test Time Iterations 1 2 3 4 5 6 7 8 9 10 114
Risk Profile of an Iterative Development Taste Waterfall Bite Risk Chew hard Swallow Preliminary Iteration Architect. Iteration Devel. Iteration Transition Iteration Postdeployment Time 115
Three Important Features of the Iterative Approach u Continuous integration l u Frequent, executable releases l l l u Not done in one lump near the delivery date Some internal; some delivered Microsoft: the daily build Brookes: grow, not build Attack risks through demonstrable progress l Progress measured in products, not documentation or engineering estimates 116
Selecting Iterations u How many iterations do I need? l u On projects taking 18 months or less, 3 to 6 iterations are typical Are all iterations on a project the same length? l l Usually Iteration length may vary by phase. For example, initial elaboration iterations may be shorter than later-stage construction iterations 117
New Features 118
OO Project Management u u u Booch: Object Solutions, 1996 Following assumes a 12 month project Five stages: l l l Conceptualisation (now called “inception”) Analysis (now, with design, called “elaboration”) Design Evolve (now called “construction”) Maintain (now called “transistion”) u Adds user-community focus 119
Conceptualisation u u 1 month (ish) Core team = l u u Architect, SAP 1, SAP 2 Usually deadline driven Products l l l Risk list #1 Prototype: broad, shallow, ? only throw-able thing “Vision statement” 120
The Risk List u Top 10 things that could send the project off the rails l u u Assessed: active or passive Each item has an action plan l u Ranked in “Oh no!” order Managed risk reduces stress Risk list is stuck on everyone’s desk l Risk is everyone’s business 121
Analysis u u 1 -2 months Analysis team = l u Core + QA 1 + User 2 Products l l l Risk list #2 CRC Scenarios: stop when 80% done “Context statement” : what is out of scope Domain model: first cut at obvious classes in business model 122
Design u u 1 -2 months Design team = l u Core + QA 1 + AP 2 +. . . + APx + writer + systems Products l l Risk list #3 Architecture u u l Release plan u u u l Description: categories (teams), clusters (people), patterns Executable skeleton: production quality code Releases contain scenarios Small projects: every 2 -3 months Large projects: every 6 -9 months Test criteria 123
Evolve u u u 7 -9 months Design team Products: l l Releases QA results Documentation Behavioral prototypes u u u 1 category change = ignorable 2 category change = inform architect 3 category change = tiger team(s) of SAPs to rapidly explore a technical option v ? ? change direction of project 124
Maintain u Products l Hit list 125
On to Mentor u Could do a nice throw to Mentor just here. Could say “Booch has spoken: this is _THE_ way to build OO systems. How silly: there are many ways to build an OO system. Everyone has a local process. What is needed is not a process, but a tool for supporting local customisations. All the methodologies use the same set of core techniques. Why not document those techniques, and rules for combining them, then use that as a customisation tool. Hey presto: MENTOR. ” 126
OO Metrics 127
Use Case 1 Brainstorming Class 4 3 7 General 2 5 Scenario u 1: Objects & Classes u 2: CRC cards u 3: Noun analysis Use cases diagrams Design Specific u u u 5: Use case text, scenario text 6: Sequence diagrams 7: Class diagrams l u u 8 9 and repeat Object 6 l. Patterns u 4: The Royal Road Patterns 8. Evolutionary, iterative development 9. OO Metrics 128
References u Ballpark Estimating of OO Software Projects u u Philip Haynes , Object Oriented Pty Ltd. , p. haynes@oopl. com. au Submitted to OOPSLA ‘ 98: Software engineering practices and OO metrics. Bringing OO Projects under Quantitative Control: An Output, Cash and Time Driven Approach u Philip Haynes and Brian Henderson-Sellers u American Programmer The Economics of Object-Oriented Software. u C. Jones, u American Programmer, 129
The Bad News u Industry is not very good at estimation: l Usually done u u u With very imperfect information In a short time frame. Consequently: l l l Only 9% of projects in large companies are brought in on time and on budget On average, projects are over budget by 189% 30% of large projects fail to deliver at all 130
The Good News u u OO systems very regular Experience with one development can be mapped into other developments l u Systematic rules of thumb can be applied to create very good ballpark estimates. This lecture: l l Regularities in OO systems Specific estimation model used successfully at OO Pty u Fixed price estimates for > 100 projects (5 -15% error) v e. g. 500 person-months work; time estimates accurate. 85% 131
When is a Smalltalk method too big? 132
When is a C++ method too big? 133
When is a Java method too big? 134
Review Outliers Metric (averages) Suspect point Max Instance variables 8 Methods per class 40 Arguments per function 4 Local vars per function 5 12 60 6 5 Expected Average 1. 8 24 1. 1 0. 1 Also: • In terms of reuse / usage, classes used more than 6 times should be subject to higher quality standards than less frequently used classes. • Big classes (#methods, #variables) usually mean that “ 1” class is really > 1 • Big argument lists: no data inversion 135
Time in Project Phase u If you blow these percentages, review! Phase min% System definition 7 Component development 30 Testing: sys+acceptance 15 Project management 15 QA 4 Additional doco 4 max% normal% 25 50 50 30 4 4 15 42 20 15 4 4 136
Phase Definitions u u u System definition: requirements definition, use case model, UI Layout design, report design, non-function requirements specification, architectural specification. Component development: high level design, detailed design, design documentation, component review, code inspection, unit test, integration, defect correction. System and acceptance test: test case design, test case preparation, test execution, test management. 137
More Phase Definitions u u u Project management: project planning, estimation, project tracking, staff management, configuration management. QA: quality assurance: audits, process improvement Additional doco: additional documentation such as user manuals etc. l Other phases include documentation overhead that is usually approximately 10%. 138
Sample Applications Project Size Category Success Factors Project (Classes) Major Project Observations Tiny < 50 25 Personal capability Small 50 -125 14 Removal of project road blocks. Medium of strong 125 -1000 39 Large 1000 -10, 000 2 Huge > 10, 000 0 Execution processes. Reduction of the effects of project scale. 139 Luck? ?
Estimates and Project Categories u Big projects l l u Communication costs slow class production Too slow (< 1 class/month) = cancellation Small projects l Very effected by (e. g. ) u u u start-up costs; e. g. learning new language Losing key personnel Medium-sized projects l Ideal candidate for estimation 140
Class: the unit of OO estimation u Directly observable in implementation l u Can be tracked over whole life cycle Median class size: 55 -65 LOC l l In C++, Java, Eiffel, Smalltalk, … (LOC measured using an industry standard) 141
The OO Estimation Recipe u Find “X”: the number of classes l l u Infer from business model? use cases? screens? function points? from component counting? from legacy system? Business model is best! Find “Y”: the classes/month for your developers l How? u u u Historical records Industry averages: 5 classes/month Estimate = X/Y (in months) 142
Classes per 160 hour Month u u u u u < 1: Project with a strong risk of cancellation or of a highly mission critical nature. 1: Typical large project performance. l Communication effort slows down clas production 2. 5: Medium project performance, average team. 3. 5: Good team doing a difficult project. 5: Realistic productivity for a highly competent team in a reasonable environment 7: Good team, small to medium sized project, soft environment. 10: Expert development team in favourable environment. 28 -40 : World-class performance in a small project in an excellent environment. > 40: Never seen by Haynes. 143
Classes from Use Cases? No! u Use cases/ sequence diagrams l l u Use cases describe “what” l u Not “why” Use case size not uniform l u Great requirements engineering technique Rotten estimation technique. Grain size varies across applications Experimentally: l No correlation use cases and size 144
Classes from Business Model? Yes! System size (classes) business classes A B C D E Ratio of the total number of classes to 330 505 622 316 2. 56 2. 46 2. 60 2. 03 154 Average u 2. 66 2. 5 0. 3 Conclusion: from this, and other data, we say that total classes is business model classes times 3. 6 145
Why a Factor of 3? u Most modern software systems have similar layered architectures, ie GUI Business Model Database • For each Business class (in the Business Model) there exists 1 GUI class, 1 database class + 0. 6 helper classes. Total Classes = 3. 6 x Business classes 146
Architectures u Usually, more complex however 147
Classes from Components? Maybe. u Software architectures tend to remain relatively constant l u u u Know your architectural patterns Large parts of most applications are devoted to technology, typically 65 -75% Separate technology components from business components Identify major subsystems and then create an estimate of number of components 148
Classes from Screens? Maybe. u u Could reverse engineer size of system from screens. Total classes = 3. 6 * screens. l l u But: l l u Reduces to 2. 6 if working OODBMS link Economic justification for OODBMS Beware small screens (table maintenance, sub Uis) They can distort estimate Business model is more reliable. 149
Classes from Function Points? No! u Older-style estimation technique. l u Assuming OO FP = 21 LOC/FP l l l u How do you track the FP's then? FP's are a derived measure. l u Median class size: 55 -65 LOC 1 class = 2. 6 - 3. 1 FP per class So a class implements about 3 business ideas. FP's are not countable in the actual implementation. l u Function point counts can be extracted from text specification. Classes are a direct measure. FP's talk a long time to count l Making their utilisation practically difficult. 150
Classes From Legacy Systems? Maybe. u Convert legacy LOC to “logical LOC” l Strip multiple blank lines, comment only lines u l u Strip automatically, or hand-count a sample of the code Usually a reduction to 33 -45% real to logical LOC. Method: l l Convert logical LOC to function points Convert function points to classes 151
Example u Porting 1, 000 lines of Cobol to Java: l u u how long? 1 M lines = about 333, 333 logical LOC Method: l l COBOL: 107 LOC/ FP; i. e. 3115 function points Java: 2. 6 - 3. 1 FP/class; i. e. 1004 to 1198 classes u u Low-end of a large project; l l u Assume 1198 Therefore 2. 5 classes per month Therefore 479 person months If we need “it” in 2 years l Then we need 20 people for that project. 152
Secrets#1 : The Inflation Factor u u Expect the unexpected. Internally, inflate your estimates by 15 -30% l Requirements creep: 2% per month. u 12 month project 25% increase in scope Other factors: v l u u Staff turn-over, poor quality But don’t mention this in the initial estimate: l “Agh, so you wanted white tiles not black. This will cost you. …” 153
Secrets#2 : C++ = Java = Smalltalk =. . . u An end to the language wars l l u If mature tools and developers who know those tools Cost estimation independent of OO language choice Let us no longer debate C++ vs Java vs … l Lets get on with the job: u Supporting business 154
State Transition Diagrams 155
156
Need more on STDs u ? ? grab stuff from previous OO PL course? 157
References 158
Good Books u u u Very good UML introduction book: UML Distilled: Martin Fowler Very good OO introduction book: The CRC book: David Bellin & Susan Suchman Simone Best analysis text (with examples!!) in non-standard notation: P. Coad (et al), Object Models: Strategies, Patterns, and Applications, 2 nd ed. (2 nd Edition) Prentice Hall Best OO management text: G. Booch , Object Solutions: Managing the Object-Oriented Project , Addison-Wesley 1996 Best patterns text: F. Buschmann and R. Meunier and H. Rohnert and P. Sommerlad and M. Stal , A System of Patterns: Pattern-Oriented Software Architecture , John Wiley & Sons 1996 Good OO modelling intro text: J. Rumbaugh and M. Blaha and W. Premerlani and F. Eddy and W. Lorenson, , Object-Oriented Modeling and Design, 1991 Prentice-Hall l Chapters 2, 3, 4, 8. 1, 8. 2, 8. 3, 8. 4 159
More Good Stuff u u u Good strategies text: A. J. Riel Object-Oriented Design Heuristics Addison-Wesley 1996 Latest on the Booch/Rumbaugh/jacobson gang of 3: http: //www. rational. com (unified method) Classic patterns text: Gamma E. et al , Design Patterns: Elements of Reusable Object-Oriented Software , Addison-Wesley, 1995 Analysis patterns text: M. Fowler , Analysis Patterns: Reusable Object Models , Addison Wesley 1997 Classic Use Case text: I. Jacobson and M. Christerson and P. Jonsson and G. Overgaard, Object-Oriented Software Engineering: A Use Case Driven Approach, Addison-Wesley. 1992 My pointers: http: //www. cse. unsw. EDU. AU/~timm/links/Themes. html#Objectoriented 160
Case Study 161
Costing the Supermarket u u Goal: prepare a cost estimate for a cashier support system for a busy suburban supermarket. Method: design the business model, final size is 3. 5 times the objects in the business model. Prepare estimate assuming 5 classes per month per developer. 162
Steps u u u Conduct a CRC session to collect stories. One story must be “customer buys something”. Perform noun analysis Pick two stories and write out in detail (1 pages text each max). Repeat noun analysis Write two sequence diagrams Draw one class diagram (hint: it fits on 1 page of A 4). 163
Supermarket: The Details u u Customers can pay with a combination of credit cards, cash, checks. Also, trustworthy customers can be given credit (if they are not over their limit). Cashier details are stored (name, shifts, sales in a shift). Cashiers count out their float into a cash drawer before the shift, and count it back at the end (this must tally with initial float + sales). On the weekend, cashiers also handle the occasional delivery to the store (the manager does this on weekdays). Cashiers also handle customers when they return bad items. 164
Supermarket: More Details u u u Our store and the store items are in special tax categories. Sale price is marked price plus taxes for the store and that item. Sometimes, when an item is not moving well, it is given a special mark down price for a short period “on sale now for a limited time!”. Assume: l l l A store class that has DMs holding the cashiers, sales, etc. We know nothing about customers except the small number that we give credit to. A bar-code reader that is attached to the register. 165
Solution u Solution comes from Coad, chapter 1. We can l l u Photocopy the whole chapter and give to instructors as there cheat sheet. Port Coad’s sequence diagrams and class diagrams to UML and attach here. I envision 4 -6 labs taking 30 -60 minutes each (see the “Steps” slide 3 pages back). 166
- Slides: 166