unified modeling language (uml) for oo domain analysis cse432 prof glenn blank

26
Unified Modeling Unified Modeling Language (UML) Language (UML) for OO domain for OO domain analysis analysis CSE432 CSE432 Prof Glenn Blank Prof Glenn Blank

Upload: nelson-shelton

Post on 24-Dec-2015

222 views

Category:

Documents


1 download

TRANSCRIPT

Page 1: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Unified Modeling Language Unified Modeling Language (UML)(UML)

for OO domain analysisfor OO domain analysis

CSE432CSE432Prof Glenn BlankProf Glenn Blank

Page 2: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Notation warsNotation warsEarly 90’s: 6-10 different notationsEarly 90’s: 6-10 different notations

Bertrand MeyerBertrand Meyer: circles and arrows: circles and arrows Distinguishes inheritance and client/supplier relationshipsDistinguishes inheritance and client/supplier relationships

Grady Grady BoochBooch: clouds, lines and decorations: clouds, lines and decorations GardeningPlan – Association- Environmental ControllerGardeningPlan – Association- Environmental Controller Heater and Cooler – Generalization/Specialization-> ActuatorHeater and Cooler – Generalization/Specialization-> Actuator Environmental Controller Environmental Controller ●●-“has a”- Heater (Cooler, Light)-“has a”- Heater (Cooler, Light) Actuator o– “using” – Temperature (client/supplier)Actuator o– “using” – Temperature (client/supplier) Actuator is an abstract class (‘A’ in a triangle)Actuator is an abstract class (‘A’ in a triangle)

Peter Peter CoadCoad, Ed Yourdon & Jill Nicola, Ed Yourdon & Jill Nicola: : Rounded boxes and annotated linesRounded boxes and annotated lines Line bisected by semi-circle represents generalization (inheritance)Line bisected by semi-circle represents generalization (inheritance) Line bisected by triangle represents whole/partLine bisected by triangle represents whole/part

So, what’s your reaction to all these (and more) notations?So, what’s your reaction to all these (and more) notations? “ “Can’t we all get along?” Hence three amigos create UML in mid-90’sCan’t we all get along?” Hence three amigos create UML in mid-90’s

Page 3: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Closer look at Coad & NicolaCloser look at Coad & Nicola

Two different boxes grouping classes:Two different boxes grouping classes: HIC (Human Interaction Component)HIC (Human Interaction Component) PDC (Problem Domain Components)PDC (Problem Domain Components) Why is “Separation of Concerns principle” a good idea?Why is “Separation of Concerns principle” a good idea?

First person scenariosFirst person scenarios Coad & Nicola call this the "Coad & Nicola call this the "I'm aliveI'm alive principle": principle":

Objects can be better understood by thinking about them and talking Objects can be better understood by thinking about them and talking about them in the first person:about them in the first person:"I know my own ____ and I can ___ myself.""I know my own ____ and I can ___ myself."

What goes in the blanks?What goes in the blanks?Attributes and behaviorsAttributes and behaviors

Why is putting these scenarios in the first person a good idea?Why is putting these scenarios in the first person a good idea?Promotes “object-think”: objects are autonomous, performing behaviorsPromotes “object-think”: objects are autonomous, performing behaviorsSimilarly, Kent Beck talks about the need for anthropomorphism in Similarly, Kent Beck talks about the need for anthropomorphism in responsibility-driven designresponsibility-driven design

Page 4: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Class diagrams in UMLClass diagrams in UML

Classes are boxes, lines are associationsClasses are boxes, lines are associations Add decorations to lines to refine themAdd decorations to lines to refine them But before we study the decorations….But before we study the decorations….

Page 5: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

A heuristic for class diagram designA heuristic for class diagram designDon't put any decorations on the associations at firstDon't put any decorations on the associations at first Semantics of relations tends to be Semantics of relations tends to be vaguevague

““Is a" relationship can mean SUBTYPE ("a square is a polygon")Is a" relationship can mean SUBTYPE ("a square is a polygon") or INSTANCE‑OF ("George is a square") or INSTANCE‑OF ("George is a square") or IDENTICAL‑TO ("The morning star is the evening star")or IDENTICAL‑TO ("The morning star is the evening star") or PROPERTY‑OF ("A circle is a round object") or PROPERTY‑OF ("A circle is a round object") or ROLE‑OF ("George is a President")or ROLE‑OF ("George is a President") or MADE‑OF ("My house is a brick one") or MADE‑OF ("My house is a brick one") or simply EXISTS (“To be or not to be…").or simply EXISTS (“To be or not to be…"). In many languages, there is no verb "is" at all, or it’s rarely used.In many languages, there is no verb "is" at all, or it’s rarely used.

Let the meaning of relations Let the meaning of relations emergeemerge from what they relate from what they relate Vagueness is natural: start off vague, get more specific graduallyVagueness is natural: start off vague, get more specific gradually

UML supports this heuristic by starting with simple UML supports this heuristic by starting with simple undirected lines (associations)undirected lines (associations)Later, add detail to your relationship structuresLater, add detail to your relationship structures

Page 6: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Two basic relationships of O-OTwo basic relationships of O-O

OOA typically distinguishes two relations: OOA typically distinguishes two relations: is‑ais‑a and and has‑ahas‑aWhy Why twotwo??That’s what O-O programming languages implement:That’s what O-O programming languages implement:

Smalltalk and Java: instance variables and inheritanceSmalltalk and Java: instance variables and inheritance C++: data members and class derivation C++: data members and class derivation

Meyer calls these Meyer calls these inheritanceinheritance and and client/supplierclient/supplierBooch: Booch: generalization/specializationgeneralization/specialization and and associationassociation or or aggregationaggregation or or compositioncompositionCoad and Yourdon: Coad and Yourdon: gen/specgen/spec and and whole/partwhole/partUML calls these UML calls these generalizationgeneralization and and associationassociation or or aggregationaggregation or or compositioncomposition

Page 7: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Generalizations Generalizations (inheritance)(inheritance)

Extract commonality among specializationsExtract commonality among specializations

UML uses arrowUML uses arrow

Generalizations form a hierarchyGeneralizations form a hierarchy

Multiple inheritance forms a latticeMultiple inheritance forms a lattice

Page 8: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

AssociationsAssociations

Client-supplier/association/whole‑partClient-supplier/association/whole‑part Typically parts or members of a classTypically parts or members of a class

MultiplicityMultiplicity: numbers at connection ends: numbers at connection ends Manager -1Manager -1――――* -> Employee* -> Employee Denotes 1 to many (*) relationships Denotes 1 to many (*) relationships 0 to many, 1 to 1 relationships also common 0 to many, 1 to 1 relationships also common From Extended Entity‑Relation models (EER)From Extended Entity‑Relation models (EER)

Role namesRole names at one connection end: at one connection end: Manager Manager ―――― sales rep -> Employee sales rep -> Employee Employee's role is sales repEmployee's role is sales rep

Page 9: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Five activities of OOAFive activities of OOA

Coad, Yourdon and Nicola:Coad, Yourdon and Nicola:1) Class‑&‑object: describe problem domain 1) Class‑&‑object: describe problem domain

in terms of classes of objectsin terms of classes of objects

2) Structure: describe relationships between classes 2) Structure: describe relationships between classes

3) Subject: organize classes into clusters or packages3) Subject: organize classes into clusters or packages

4) Attributes: describe data held by objects4) Attributes: describe data held by objects

5) Services: describe behaviors that objects can perform5) Services: describe behaviors that objects can perform

Which of these five activities are analysis Which of these five activities are analysis and which are design?and which are design?

Page 10: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Class & Object analysisClass & Object analysis

Another look at Another look at CoadCoad & Nicola notation & Nicola notation Why do all the classes except Count Why do all the classes except Count

have extra grey boxes?have extra grey boxes? An An abstractabstract class has one or more operations class has one or more operations

that must be implemented by that must be implemented by subclassessubclasses

UML represents an abstract class UML represents an abstract class by by italicizingitalicizing the class name the class name or adding the constraint label or adding the constraint label {abstract}{abstract}

Page 11: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Structure (association) analysisStructure (association) analysis

Lines connecting classesLines connecting classesIn UML, simple line is an In UML, simple line is an associationassociation

Decorations for multiplicity, role names, constraintsDecorations for multiplicity, role names, constraints

See example from See example from FowlerFowler What does {ordered} constraint mean?What does {ordered} constraint mean?

Aggregations and composition:Aggregations and composition: Arrow denotes navigabilityArrow denotes navigability e.g., Polygon and Circle refer to Point but not vice versae.g., Polygon and Circle refer to Point but not vice versa A A blackblack--filledfilled diamond denotes a diamond denotes a compositioncomposition

a part, a part, uniqueunique to this whole to this whole A A whitewhite--emptyempty diamond denotes an diamond denotes an aggregationaggregation

a part, but not unique to this wholea part, but not unique to this whole E.g., A Point may appear in only E.g., A Point may appear in only oneone Polygon or Circle Polygon or Circle

but a Style could appear in bothbut a Style could appear in both

An alternative notation for composition in boxesAn alternative notation for composition in boxes

Page 12: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Attributes and operationsAttributes and operations

A class box may have three partsA class box may have three parts Class name, attributes and operationsClass name, attributes and operations

Attributes in middle sectionAttributes in middle section Typically attributes are built-in types Typically attributes are built-in types UML lets you include information about default values UML lets you include information about default values

and visibility (+,-,#)and visibility (+,-,#)E.g., - name: String [1] = “Untitled” {readonly}E.g., - name: String [1] = “Untitled” {readonly}

private : type multiplicity default {property} (unmodifiable)private : type multiplicity default {property} (unmodifiable)I recommend you hold off on these details until designI recommend you hold off on these details until design

Operations in bottom section of class boxOperations in bottom section of class box Represent services, functions or methodsRepresent services, functions or methods Again, UML has a bit more notation, Again, UML has a bit more notation,

for information about parameters, default values and visibilityfor information about parameters, default values and visibilityE.g., + balanceOn(date:Date): MoneyE.g., + balanceOn(date:Date): MoneyAgain, I recommend you hold off on these details until designAgain, I recommend you hold off on these details until design

Page 13: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Your next assignmentsYour next assignments

http://www.cse.lehigh.edu/~glennb/oose/afruit.htmhttp://www.cse.lehigh.edu/~glennb/oose/afruit.htm

Note that there are two problems: fruit and undoNote that there are two problems: fruit and undo

Due Sunday, February 19Due Sunday, February 19

Project analysis due Monday, February 27Project analysis due Monday, February 27

Page 14: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Eclipse with plug-insEclipse with plug-ins

Open Source IDE for O-O and JavaOpen Source IDE for O-O and Java Plug-ins add more featuresPlug-ins add more features DrJava plug-in provides Java interpreterDrJava plug-in provides Java interpreter Omondo plug-in adds UML class diagramsOmondo plug-in adds UML class diagrams Available on campus by running “eclips”Available on campus by running “eclips” http://www.lehigh.edu/~sgh2/ (version 2.1)http://www.lehigh.edu/~sgh2/ (version 2.1)

or http://www.lehigh.edu/stem/teams/dieruff (3.0)or http://www.lehigh.edu/stem/teams/dieruff (3.0)

Page 15: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Dynamic behaviorsDynamic behaviors

Class diagrams represent Class diagrams represent staticstatic relationships. Why? relationships. Why?What about modeling What about modeling dynamicdynamic behavior? behavior?InteractionInteraction diagrams model how groups of object diagrams model how groups of object

collaborate to perform some behaviorcollaborate to perform some behavior Typically captures the behavior of a single use caseTypically captures the behavior of a single use case

Use Case: Order Entry Use Case: Order Entry 1) An Order Entry window sends a “prepare” message to an Order1) An Order Entry window sends a “prepare” message to an Order2) The Order sends “prepare” to each Order Line on the Order2) The Order sends “prepare” to each Order Line on the Order3) Each Order Line checks the given Stock Item3) Each Order Line checks the given Stock Item4) Remove appropriate quantity of Stock Item from stock 4) Remove appropriate quantity of Stock Item from stock 5) Create a deliver item5) Create a deliver item

Alternative: Insufficient StockAlternative: Insufficient Stock3a) if Stock Item falls below reorder level3a) if Stock Item falls below reorder level

then Stock Item requests reorderthen Stock Item requests reorder  

Page 16: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Sequence diagramSequence diagramVertical line is called an object’s Vertical line is called an object’s lifelinelifeline

Represents an object’s life during interactionRepresents an object’s life during interactionObject deletion denoted by X, ending a lifelineObject deletion denoted by X, ending a lifeline

Horizontal arrow is a message between two objectsHorizontal arrow is a message between two objectsOrder of messages sequences top to bottomOrder of messages sequences top to bottomMessages labeled with message name, Messages labeled with message name,

optionally arguments and control informationoptionally arguments and control informationControl information, in brackets, may express conditions, Control information, in brackets, may express conditions,

such as [hasStock], or iterationsuch as [hasStock], or iterationReturns (dashed lines) are optional; use them to add clarityReturns (dashed lines) are optional; use them to add clarity

Sequence diagrams can also represent concurrent processes: Sequence diagrams can also represent concurrent processes: UML 1 models UML 1 models asynchronousasynchronous messages as horizontal lines with messages as horizontal lines with halfhalf arrow heads arrow heads UML 2 makes this distinction by not filling an arrowhead UML 2 makes this distinction by not filling an arrowhead Fowler prefers older notation. Fowler prefers older notation. Why? Which do you prefer?Why? Which do you prefer?

After setting up Transaction Coordinator, After setting up Transaction Coordinator, invoke concurrent Transaction Checkersinvoke concurrent Transaction Checkers

If a check fails, kill all the Transaction Checker processesIf a check fails, kill all the Transaction Checker processesNote use of comments in margin Note use of comments in margin – When is this a good idea?– When is this a good idea?

Page 17: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Collaboration diagramsCollaboration diagrams

Objects are rectangular iconsObjects are rectangular icons e.g., Order Entry Window, Order, etc.e.g., Order Entry Window, Order, etc.

Messages are arrows between iconsMessages are arrows between icons e.g., prepare()e.g., prepare()

Numbers on messages indicate sequenceNumbers on messages indicate sequence Also spatial layout helps show flowAlso spatial layout helps show flow

Which do you prefer: sequence or collaboration diagrams?Which do you prefer: sequence or collaboration diagrams?Fowler now admits he doesn’t use collaboration diagramsFowler now admits he doesn’t use collaboration diagrams

Interaction diagrams show flow clearly, Interaction diagrams show flow clearly, but are awkward when modeling alternativesbut are awkward when modeling alternatives

UML notation for control logic has changed in UML 2 UML notation for control logic has changed in UML 2 but Fowler isn’t impressedbut Fowler isn’t impressed

Page 18: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

CRC cardsCRC cards(See multimedia from (See multimedia from The Universal MachineThe Universal Machine on CRC cards) on CRC cards)

Developed by Beck and Cunningham at TektronixDeveloped by Beck and Cunningham at Tektronix See http://c2.com/doc/oopsla89/paper.htmlSee http://c2.com/doc/oopsla89/paper.html This is the same Kent Beck that later wrote the book This is the same Kent Beck that later wrote the book

pioneering Extreme Programming. pioneering Extreme Programming.

CRC cards are now part of CRC cards are now part of XPXP. . Fowler introduces CRC and end of chapter 4Fowler introduces CRC and end of chapter 4

Page 19: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

ResponsibilitiesResponsibilities

Key idea: objects have Key idea: objects have responsibilitiesresponsibilities As if they were simple agents (or actors in scenarios)As if they were simple agents (or actors in scenarios)

AnthropomorphismAnthropomorphism of class responsibilities gets away of class responsibilities gets away from thinking about classes as just data holdersfrom thinking about classes as just data holders

““Object think” focuses on their active behaviorsObject think” focuses on their active behaviors

Each object is responsible for specific actionsEach object is responsible for specific actions Client can expect predictable behaviorsClient can expect predictable behaviors

Responsibility also implies independence: Responsibility also implies independence: To trust an object to behave as expected is to rely upon its To trust an object to behave as expected is to rely upon its

autonomy and modularityautonomy and modularity Harder to trust objects easily caught up in dependencies caused Harder to trust objects easily caught up in dependencies caused

by global variables and side effects.by global variables and side effects.

Page 20: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Low-techLow-tech

Ordinary index cardsOrdinary index cards Each card represents a Each card represents a classclass of objects. of objects. 3x5 is preferable to 4x6 at least early on – Why?3x5 is preferable to 4x6 at least early on – Why?

Each card has three componentsEach card has three components Name, Responsibilities, CollaboratorsName, Responsibilities, Collaborators

Page 21: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Class namesClass names

Class NameClass Name creates the vocabulary of our analysis creates the vocabulary of our analysis Use nouns as class names, think of them as simple agentsUse nouns as class names, think of them as simple agents Even classes that you think of verbs or actions can be made into nounsEven classes that you think of verbs or actions can be made into nouns E.g., “reading a card” becomes E.g., “reading a card” becomes CardReaderCardReader, a class of object (agent) , a class of object (agent)

that manages bank cardsthat manages bank cardsUse pronounceable names Use pronounceable names

If you cannot read aloud, it is not a good nameIf you cannot read aloud, it is not a good nameUse capitalization (or underscores) to initialize class names and to Use capitalization (or underscores) to initialize class names and to demarcate multi-word namesdemarcate multi-word names

such as CardReader rather than CARDREADER or card_reader. such as CardReader rather than CARDREADER or card_reader. Why do most OO developers prefer this convention?Why do most OO developers prefer this convention?

Avoid obscure, ambiguous abbreviationsAvoid obscure, ambiguous abbreviations E.g., is TermProcess something that terminates E.g., is TermProcess something that terminates

or something that runs on a terminal? or something that runs on a terminal? Try not to use digits within a name, such as CardReader2Try not to use digits within a name, such as CardReader2

Better for instances than classes of objectsBetter for instances than classes of objects

Page 22: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

ResponsibilitiesResponsibilities section section

Describes a class’s Describes a class’s behaviorsbehaviors Describe Describe whatwhat is to be done, not is to be done, not howhow! !

Use short verb phrasesUse short verb phrases E.g.: “reads card” or “look up words” E.g.: “reads card” or “look up words”

How do constraints of index cards guide class How do constraints of index cards guide class analysis?analysis? A good measure of appropriate complexityA good measure of appropriate complexity If you cannot fit enough tasks on a card, If you cannot fit enough tasks on a card,

maybe you need to divide tasks between classes, maybe you need to divide tasks between classes, on different cards?on different cards?

Page 23: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Collaborators Collaborators

Lists important Lists important supplierssuppliers and possibly clients of a class and possibly clients of a classWhy are classes that supply services more important Why are classes that supply services more important here?here?

Suppliers are necessary for the description of responsibilitiesSuppliers are necessary for the description of responsibilities

As you write down responsibilities for a class, add any As you write down responsibilities for a class, add any suppliers needed for themsuppliers needed for them

For example “read dictionary” obviously implies that a “dictionary” For example “read dictionary” obviously implies that a “dictionary” as a collaboratoras a collaborator

Developing CRC cards is first a process of discovering Developing CRC cards is first a process of discovering classes and their responsibilities classes and their responsibilities

People naturally cut up the world in terms of categories of objectsPeople naturally cut up the world in terms of categories of objects In object‑oriented analysis, one discovers new categories relevant In object‑oriented analysis, one discovers new categories relevant

to a problem domainto a problem domain

Page 24: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

CRC card simulationsCRC card simulationsDesigning for responsibility involves Designing for responsibility involves simulationsimulation

Objects model a world interacting behaviors Objects model a world interacting behaviors An analyst can prototype a system by running a simulation of objects An analyst can prototype a system by running a simulation of objects and their behaviors and their behaviors

Once you’ve developed a set of CRC cards, you're ready to run Once you’ve developed a set of CRC cards, you're ready to run simulationssimulations

or or structured walkthrough scenarios structured walkthrough scenarios -- -- Play “what if” to simulate scenarios that illustrate use of a system Play “what if” to simulate scenarios that illustrate use of a system Let each person be responsible for simulating one or more classesLet each person be responsible for simulating one or more classes

““Execute” a scenario by having each object, run at the right timeExecute” a scenario by having each object, run at the right time Start a simulation with the construction of an object of a class, Start a simulation with the construction of an object of a class, then run one of its behaviors (a responsibility of that class)then run one of its behaviors (a responsibility of that class) This behavior may pass control to some collaborator ‑‑ another classThis behavior may pass control to some collaborator ‑‑ another class Simulation becomes visible as an exchange of behavior and control from Simulation becomes visible as an exchange of behavior and control from

one card to anotherone card to another You may discover missing or incompletely described responsibilitiesYou may discover missing or incompletely described responsibilities

IMO, it really should be called responsibility-driven IMO, it really should be called responsibility-driven analysis, analysis, rather than rather than designdesign. .

Why? When is activity most useful?Why? When is activity most useful?

Page 25: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

From CRC cards From CRC cards to Interaction diagramsto Interaction diagrams

Fowler recommends first using CRC cards Fowler recommends first using CRC cards to begin modeling scenariosto begin modeling scenarios

Then document with UML sequence Then document with UML sequence (or collaboration) diagrams(or collaboration) diagrams

Why might this be a good approach?Why might this be a good approach?

Sequence diagrams show collaborations Sequence diagrams show collaborations among among manymany objects in a objects in a singlesingle use case use case StateState diagrams show the behavior of a diagrams show the behavior of a singlesingle object object

across across manymany use cases use cases We’ll examine state diagrams when we get to designWe’ll examine state diagrams when we get to design

Page 26: Unified Modeling Language (UML) for OO domain analysis CSE432 Prof Glenn Blank

Addendum for your Addendum for your team project assignmentteam project assignment

In addition to a class diagram In addition to a class diagram for your project’s problem domain,for your project’s problem domain,

Create one or more interaction (either sequence or Create one or more interaction (either sequence or collaboration) diagrams showing dynamic behavior collaboration) diagrams showing dynamic behavior of your classesof your classes

Use a UML tool such as Eclipse with Omondo Use a UML tool such as Eclipse with Omondo or Rational Rose or google for a free oneor Rational Rose or google for a free one

CRC cards are optional though recommendedCRC cards are optional though recommended

Project analysis due Monday, February 27Project analysis due Monday, February 27