OO domain modeling with UML class diagrams and CRC cards CSE432 Prof Glenn Blank.
-
Upload
patrick-caldwell -
Category
Documents
-
view
235 -
download
1
Transcript of OO domain modeling with UML class diagrams and CRC cards CSE432 Prof Glenn Blank.
OO domain modelingOO domain modelingwith UML class diagramswith UML class diagrams
and CRC cardsand CRC cards
CSE432CSE432Prof Glenn BlankProf Glenn Blank
What is a Domain Model?What is a Domain Model?
Illustrates meaningful conceptual classes Illustrates meaningful conceptual classes in problem domainin problem domain
Represents real-world concepts, Represents real-world concepts, not software componentsnot software components
Software-oriented class diagrams will Software-oriented class diagrams will be developed later, during designbe developed later, during design
A Domain Model is Conceptual,A Domain Model is Conceptual,not a Software Artifactnot a Software Artifact
SaleSale
amtamt
itemitem
SalesDatabaseSalesDatabase
SaleSale
Double amt;Double amt;
Item item;Item item;
void print()void print()
Conceptual Class:Conceptual Class: Software Artifacts:
vs.
What’s theWhat’s the
difference?difference?
Domain Model RelationshipsDomain Model Relationships
Domain Model
Use Case Model
Interaction Diagrams
Glossary
Dynamic Behavior
Functional Requirements
Conceptual Class DiagramClasses, attributes, associations
Domainobjects
Define terms
What do you learn about when and how to create these models?
Identify conceptual classesIdentify conceptual classesfrom noun phrasesfrom noun phrases
Vision and Scope, Glossary and Use Cases Vision and Scope, Glossary and Use Cases are good for this type of linguistic analysisare good for this type of linguistic analysis
However:However:Words may be ambiguous or synonymousWords may be ambiguous or synonymousNoun phrases may also be attributes or Noun phrases may also be attributes or parameters rather than classes:parameters rather than classes: If it stores state information or it has multiple If it stores state information or it has multiple
behaviors, then it’s a classbehaviors, then it’s a class If it’s just a number or a string, then it’s probably If it’s just a number or a string, then it’s probably
an attributean attribute
From NPs to classes or attributesFrom NPs to classes or attributes
The ATM verifies whether the customer's card number and PIN are correct. S V O O OIf it is, then the customer can check the account balance, deposit cash, and withdraw cash. S V O V O V O Checking the balance simply displays the account balance. S O V ODepositing asks the customer to enter the amount, then updates the account balance. S V O V O V O Withdraw cash asks the customer for the amount to withdraw; if the account has enough cash, S O V O O V S V Othe account balance is updated. The ATM prints the customer’s account balance on a receipt. O V S V O O
Analyze each subject and object as follows:Does it represent a person performing an action? Then it’s an actor, ‘R’.Is it also a verb (such as ‘deposit’)? Then it may be a method, ‘M’.Is it a simple value, such as ‘color’ (string) or ‘money’ (number)?Then it is probably an attribute, ‘A’.Which NPs are unmarked? Make it ‘C’ for class.
Verbs can also be classes, for example:Deposit is a class if it retains state information
R
R
M
M
A A
A
A
A A
A
A A
A A
A A
A
C
C
R
M
R
Consider the following problem description, analyzed for Subjects, Verbs, Objects:
C
Steps to create a Steps to create a Domain ModelDomain Model
Identify candidate conceptual classesIdentify candidate conceptual classes
Draw them in a UML domain modelDraw them in a UML domain model
Add associations necessary to record Add associations necessary to record the relationships that must be retainedthe relationships that must be retained
Add attributes necessary for information Add attributes necessary for information to be preservedto be preserved
Use existing names for things, Use existing names for things, the vocabulary of the domainthe vocabulary of the domain
88
Monopoly Game domain modelMonopoly Game domain model(first identify concepts as classes)(first identify concepts as classes)
Monopoly Game
Player Piece
Die Board
Square
Monopoly Game domain modelMonopoly Game domain modelLarman, Figure 9.28Larman, Figure 9.28
Discovering the Domain Model with CRC cardsDiscovering the Domain Model with CRC cards(See multimedia from (See multimedia from The Universal Machine The Universal Machine on CRC cards: on CRC cards:
umwordsumwords))
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 (XP) pioneering Extreme Programming (XP)
CRC cards are now part of CRC cards are now part of XPXP
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
ResponsibilitiesResponsibilitiesKey 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 of class responsibilities gets away from thinking about classes as just data away from thinking about classes as just data holdersholders ““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 To trust an object to behave as expected is to rely upon
its autonomy and modularityits autonomy and modularity Harder to trust objects easily caught up in dependencies Harder to trust objects easily caught up in dependencies
caused by global variables and side effects.caused by global variables and side effects.
Class namesClass namesClass 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 Verbs can also be made into nouns, if they are maintain stateVerbs can also be made into nouns, if they are maintain state E.g., “reads card” suggests E.g., “reads card” suggests CardReaderCardReader, managing bank cards, managing bank cards
Use 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 name
Use capitalization to initialize Class names and Use capitalization to initialize Class names and demarcate multi-word namesdemarcate multi-word names E.g., CardReader rather than CARDREADER or card_reader E.g., 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 terminatesE.g., is TermProcess something that terminates
or something that runs on a terminal? or something that runs on a terminal? Try Try notnot to use digits within a name, such as CardReader2 to use digits within a name, such as CardReader2 Better for instances than classes of objectsBetter for instances than classes of objects
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?
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 here?Why are classes that supply services more important 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 For example “read dictionary” obviously implies that
a “dictionary” as a collaboratora “dictionary” as 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 perceive the world as categories of objectsPeople naturally perceive the world as categories of objects In object-oriented analysis, one discovers new categories In object-oriented analysis, one discovers new categories
relevant to a problem domainrelevant to a problem domain
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 After developing a set of CRC cards, run After developing a set of CRC cards, run simulationssimulations AKAAKA structured walkthrough scenariosstructured 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 of classes performing responsibilities:Execute” a scenario of classes performing responsibilities: 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 perform one of its responsibilities (a behavior)then perform one of its responsibilities (a behavior) A responsibility may pass control to a collaborator ‑‑ another classA responsibility may pass control to a collaborator ‑‑ another class Simulation becomes visible as a sharing of responsibilities Simulation becomes visible as a sharing of responsibilities You may discover missing or incompletely described responsibilitiesYou may discover missing or incompletely described responsibilities See football example in multimediaSee football example in multimedia
IMO, it really should be called responsibility-driven IMO, it really should be called responsibility-driven analysis, analysis, rather than responsibility-driven rather than responsibility-driven designdesign. . Why? When is responsibility driven activity most useful?Why? When is responsibility driven activity most useful?
Class Diagram Notation WarsClass Diagram Notation WarsEarly 90’s: 6-10 different notationsEarly 90’s: 6-10 different notations
Bertrand Meyer: circles and arrowsBertrand Meyer: circles and arrows Distinguishes inheritance and client/supplier relationshipsDistinguishes inheritance and client/supplier relationships
Grady Booch: clouds, lines and decorationsGrady Booch: 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 Coad, Ed Yourdon & Jill Nicola: Peter Coad, Ed Yourdon & Jill Nicola: Rounded boxes and annotated linesRounded boxes and annotated lines Line bisected by semi-circle represents generalizationLine bisected by semi-circle represents generalization 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?” Can’t we all get along?” Hence three amigos create UML in mid-90’sHence three amigos create UML in mid-90’s
Closer look at Coad & NicolaCloser look at Coad & NicolaTwo 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 scenarios:First 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 Objects can be better understood by thinking about them and
talking about them in the first person:talking 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?
““Object-think”: objects are autonomous, perform behaviorsObject-think”: objects are autonomous, perform behaviorsSimilarly, Kent Beck talks about the need for Similarly, Kent Beck talks about the need for anthropomorphism in responsibility-driven designanthropomorphism in responsibility-driven design
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….
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
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
Associations A link between two classes (“has a”)
Typically modeled as a member referenceTypically modeled as a member reference Notation from Extended Entity Relation (EER) modelsNotation from Extended Entity Relation (EER) models
A Person works for a Company
Role names and multiplicity at association endsDirection arrow to aid reading of association name
Person Companyemployee employ
erworks for
Association Name
Role
0..* 1
Generalization / SpecializationClasses may be subclasses of other classes
“a kind of” or “is a” Cars are a kind of vehicle (Or a car is a vehicle) Chairs are a kind of furniture People are a kind of mammal
Generalization captures commonality: What do cars have in common with vehicles? Same properties and behaviors
UML: generalization/specialization relationship Drawn as a line with an arrow head on one end
Inheritance in OO programming languages
Generalization Example
Mammal
PumaTiger
Feline
Quadruped
Lion
Lizard
Advantages of Inheritance?GrainStore
grainType : StringgrainGrade : Stringcapacity : intquantity : int
add( amount : int, type : String, grade : String )remove( amount : int )getType() : StringgetGrade() : StringgetCapacity() : intgetQuantity() : int
RailCar Silo Truck
OOP = Data abstraction + inheritance
+ dynamic binding (polymorphism)Polymorphism: a function can do different behaviors at runtimeDynamic binding: delay function binding to a subtype until runtimeSuppose we want to draw a heterogeneous collection of shapes?
class Point { ... }; //a Point has x and y coordinatesclass Shape { protected: //accessible to subclasses but otherwise private
Point center; //all Shapes have a center Point public:
Point where() { return center; } //early binding by defaultvirtual void move(Point to) //can override virtual function { center = to; draw(); } // by derived classesvirtual void draw()=0; //=0 is a "pure" virtual function
//draw() must be implemented by derived classes//...
};
//Why do we say Shape is an abstract class?
Subclasses override virtual functions
class Triangle: public Shape {Point sw, se, top; //Three points define triangle
public:Triangle(Point a, Point b, Point c) : sw(a), se(b), top(c) {}draw() //implementing pure virtual function
{ put_line(sw,top); //draw line from sw to top put_line(top,se); //draw line from top to se put_line(se,sw); //draw line from se to sw }};class Circle : public Shape {
int radius; public:
Circle(Point a, int r) : center(a), radius(r) {}draw(); //draw a circle using center and radius
};
Calling a virtual function
{ //Construct some shapesShape aShape; //illegal--why?Circle c(Point(20,30),7); //legal--what does it do?
//Create an array of various shapesShape* shapes[10]; //Why is this legal?shapes[0] = new Circle(Point(20,30),7); //assign a Circleshapes[1] = new Triangle(Point(50,50),Point(30,30),Point(40,40));//... maybe assign other shapes, Rectangles, Squares, etc.
for (int i=0; i < 10; i++) //draw all the shapes shapes[i]->draw(); //each shape draws itself!
}Why do we say that elements of shapes array are polymorphic?Polymorphic design supports B. Meyer’s Open-Closed principle:
A module should be open to extension but closed to modification So important that it’s built into most OO programming languages
Why dynamic binding?What kind of code does dynamic binding avoid?
Avoids lots of switch statements, e.g.:switch (shapes[i]->isa) //each Shape derived class has an isa data member{ case(triangle) Triangle::draw(); //test enumeration
case(circle) Circle::draw(); //run specific draw()// ...
}Why is the dynamic binding version better for big, growing programs?
Many design patterns build on polymorphism
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?
Concrete and abstract classesConcrete and abstract classes
Identifying classes is 1st activity of domain analysis Identifying classes is 1st activity of domain analysis
Remember the linguistic analysis techniqueRemember the linguistic analysis technique
Can ignore inheritance and polymorphism for first Can ignore inheritance and polymorphism for first draft, then factor out commonality as superclassesdraft, then factor out commonality as superclasses
An An abstractabstract class has one or more operations class has one or more operations that that mustmust be implemented by subclasses be implemented by subclasses
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}
Structure (association) analysisStructure (association) analysisLines 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 FowlerSee example from Fowler 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 bothAn alternative notation for composition in boxesAn alternative notation for composition in boxes
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} private : type multiplicity default {property} (unmodifiable)(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
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 Plug-in adds UML class diagramsPlug-in adds UML class diagrams Available on campus by running “eclips”Available on campus by running “eclips” Also available for download:Also available for download:
http://www.lehigh.edu/stem/teams/dieruff (3.0)http://www.lehigh.edu/stem/teams/dieruff (3.0)