Скачать презентацию OO domain modeling with UML class diagrams and Скачать презентацию OO domain modeling with UML class diagrams and

37cbb25cc5c1a5f17892f0094e2d1c8e.ppt

  • Количество слайдов: 34

OO domain modeling with UML class diagrams and CRC cards CSE 432 Prof Glenn OO domain modeling with UML class diagrams and CRC cards CSE 432 Prof Glenn Blank

What is a Domain Model? Illustrates meaningful conceptual classes in problem domain Represents real-world What is a Domain Model? Illustrates meaningful conceptual classes in problem domain Represents real-world concepts, not software components Software-oriented class diagrams will be developed later, during design

A Domain Model is Conceptual, not a Software Artifact Conceptual Class: Software Artifacts: Sales. A Domain Model is Conceptual, not a Software Artifact Conceptual Class: Software Artifacts: Sales. Database amt item vs. What’s the difference? Sale Double amt; Item item; void print()

Domain Model Relationships Conceptual Class Diagram Classes, attributes, associations Use Case Model Domain objects Domain Model Relationships Conceptual Class Diagram Classes, attributes, associations Use Case Model Domain objects Define terms Glossary Functional Requirements Dynamic Behavior Interaction Diagrams What do you learn about when and how to create these models?

Identify conceptual classes from noun phrases Vision and Scope, Glossary and Use Cases are Identify conceptual classes from noun phrases Vision and Scope, Glossary and Use Cases are good for this type of linguistic analysis However: Words may be ambiguous or synonymous Noun phrases may also be attributes or parameters rather than classes: n n If it stores state information or it has multiple behaviors, then it’s a class If it’s just a number or a string, then it’s probably an attribute

From NPs to classes or attributes Consider the following problem description, analyzed for Subjects, From NPs to classes or attributes Consider the following problem description, analyzed for Subjects, Verbs, Objects: The ATM verifies whether the customer's card number and PIN are correct. SC V OA O RO A If it is, then the customer can check the account balance, deposit cash, and withdraw cash. SR V OA V O A Checking the balance simply displays the account balance. SM OA V OA Depositing asks the customer to enter the amount, then updates the account balance. SM V OR V OA Withdraw cash asks the customer for the amount to withdraw; if the account has enough cash, SM OA V OR OA V SC V O A the account balance is updated. The ATM prints the customer’s account balance on a receipt. OA V S OA O C V 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

Steps to create a Domain Model Identify candidate conceptual classes Draw them in a Steps to create a Domain Model Identify candidate conceptual classes Draw them in a UML domain model Add associations necessary to record the relationships that must be retained Add attributes necessary for information to be preserved Use existing names for things, the vocabulary of the domain

Monopoly Game domain model (first identify concepts as classes) Monopoly Game Die Board Player Monopoly Game domain model (first identify concepts as classes) Monopoly Game Die Board Player Piece Square 8

Monopoly Game domain model Larman, Figure 9. 28 Monopoly Game domain model Larman, Figure 9. 28

Discovering the Domain Model with CRC cards (See multimedia from The Universal Machine on Discovering the Domain Model with CRC cards (See multimedia from The Universal Machine on CRC cards: umwords) Developed by Beck and Cunningham at Tektronix n n See http: //c 2. com/doc/oopsla 89/paper. html This is the same Kent Beck that later wrote the book pioneering Extreme Programming (XP) CRC cards are now part of XP

Low-tech Ordinary index cards n n Each card represents a class of objects. 3 Low-tech Ordinary index cards n n Each card represents a class of objects. 3 x 5 is preferable to 4 x 6 at least early on – Why? Each card has three components n Name, Responsibilities, Collaborators

Responsibilities Key idea: objects have responsibilities n As if they were simple agents (or Responsibilities Key idea: objects have responsibilities n As if they were simple agents (or actors in scenarios) Anthropomorphism of class responsibilities gets away from thinking about classes as just data holders n “Object think” focuses on their active behaviors Each object is responsible for specific actions n Client can expect predictable behaviors Responsibility also implies independence: n n To trust an object to behave as expected is to rely upon its autonomy and modularity Harder to trust objects easily caught up in dependencies caused by global variables and side effects.

Class names Class Name creates the vocabulary of our analysis n Use nouns as Class names Class Name creates the vocabulary of our analysis n Use nouns as class names, think of them as simple agents n Verbs can also be made into nouns, if they are maintain state n E. g. , “reads card” suggests Card. Reader, managing bank cards Use pronounceable names: n If you cannot read aloud, it is not a good name Use capitalization to initialize Class names and demarcate multi-word names n E. g. , Card. Reader rather than CARDREADER or card_reader n Why do most OO developers prefer this convention? Avoid obscure, ambiguous abbreviations n E. g. , is Term. Process something that terminates or something that runs on a terminal? Try not to use digits within a name, such as Card. Reader 2 n Better for instances than classes of objects

Responsibilities section Describes a class’s behaviors n Describe what is to be done, not Responsibilities section Describes a class’s behaviors n Describe what is to be done, not how! Use short verb phrases n E. g. : “reads card” or “look up words” How do constraints of index cards guide class analysis? n n A good measure of appropriate complexity If you cannot fit enough tasks on a card, maybe you need to divide tasks between classes, on different cards?

Collaborators Lists important suppliers and possibly clients of a class Why are classes that Collaborators Lists important suppliers and possibly clients of a class Why are classes that supply services more important here? n Suppliers are necessary for the description of responsibilities As you write down responsibilities for a class, add any suppliers needed for them n For example “read dictionary” obviously implies that a “dictionary” as a collaborator Developing CRC cards is first a process of discovering classes and their responsibilities n n People naturally perceive the world as categories of objects In object-oriented analysis, one discovers new categories relevant to a problem domain

CRC card simulations Designing for responsibility involves simulation Objects model a world interacting behaviors CRC card simulations Designing for responsibility involves simulation Objects model a world interacting behaviors After developing a set of CRC cards, run simulations n AKA structured walkthrough scenarios -n Play “what if” to simulate scenarios that illustrate use of a system n Let each person be responsible for simulating one or more classes n n “Execute” a scenario of classes performing responsibilities: n Start a simulation with the construction of an object of a class, then perform one of its responsibilities (a behavior) n A responsibility may pass control to a collaborator ‑‑ another class n Simulation becomes visible as a sharing of responsibilities n You may discover missing or incompletely described responsibilities n See football example in multimedia IMO, it really should be called responsibility-driven analysis, rather than responsibility-driven design. n Why? When is responsibility driven activity most useful?

Class Diagram Notation Wars Early 90’s: 6 -10 different notations n n Bertrand Meyer: Class Diagram Notation Wars Early 90’s: 6 -10 different notations n n Bertrand Meyer: circles and arrows Distinguishes inheritance and client/supplier relationships Grady Booch: clouds, lines and decorations Gardening. Plan – Association- Environmental Controller Heater and Cooler – Generalization/Specialization-> Actuator Environmental Controller ●-“has a”- Heater (Cooler, Light) Actuator o– “using” – Temperature (client/supplier) Actuator is an abstract class (‘A’ in a triangle) Peter Coad, Ed Yourdon & Jill Nicola: Rounded boxes and annotated lines Line bisected by semi-circle represents generalization Line bisected by triangle represents whole/part 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’s

Closer look at Coad & Nicola Two different boxes grouping classes: n n n Closer look at Coad & Nicola Two different boxes grouping classes: n n n HIC (Human Interaction Component) PDC (Problem Domain Components) Why is “Separation of Concerns” principle a good idea? First person scenarios: n n n Coad & Nicola call this the "I'm alive principle": Objects can be better understood by thinking about them and talking about them in the first person: "I know my own ____ and I can ___ myself. " What goes in the blanks? Attributes and behaviors Why is putting these scenarios in the first person a good idea? “Object-think”: objects are autonomous, perform behaviors Similarly, Kent Beck talks about the need for anthropomorphism in responsibility-driven design

Class diagrams in UML Classes are boxes, lines are associations n n Add decorations Class diagrams in UML Classes are boxes, lines are associations n n Add decorations to lines to refine them But before we study the decorations….

A heuristic for class diagram design Don't put any decorations on the associations at A heuristic for class diagram design Don't put any decorations on the associations at first Semantics of relations tends to be vague n n n n “Is a" relationship can mean SUBTYPE ("a square is a polygon") or INSTANCE‑OF ("George is a square") or IDENTICAL‑TO ("The morning star is the evening star") or PROPERTY‑OF ("A circle is a round object") or ROLE‑OF ("George is a President") or MADE‑OF ("My house is a brick one") or simply EXISTS (“To be or not to be…"). In many languages, there is no verb "is" at all, or it’s rarely used. Let the meaning of relations emerge from what they relate n Vagueness is natural: start off vague, get more specific gradually UML supports this heuristic by starting with simple undirected lines (associations) Later, add detail to your relationship structures

Two basic relationships of O-O OOA typically distinguishes two relations: is‑a and has‑a Why Two basic relationships of O-O OOA typically distinguishes two relations: is‑a and has‑a Why two? That’s what O-O programming languages implement: n n Smalltalk and Java: instance variables and inheritance C++: data members and class derivation Meyer calls these inheritance and client/supplier Booch: generalization/specialization and association or aggregation or composition Coad and Yourdon: gen/spec and whole/part UML calls these generalization and association or aggregation or composition

Associations A link between two classes (“has a”) n Typically modeled as a member Associations A link between two classes (“has a”) n Typically modeled as a member reference n Notation from Extended Entity Relation (EER) models A Person works for a Company Role Person employee 0. . * employer works for 1 Company Association Name Role names and multiplicity at association ends Direction arrow to aid reading of association name

Generalization / Specialization Classes may be subclasses of other classes n n “a kind Generalization / Specialization Classes may be subclasses of other classes n n “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: n n What do cars have in common with vehicles? Same properties and behaviors UML: generalization/specialization relationship n Drawn as a line with an arrow head on one end Inheritance in OO programming languages

Generalization Example Generalization Example

Advantages of Inheritance? Advantages of Inheritance?

OOP = Data abstraction + inheritance + dynamic binding (polymorphism) Polymorphism: a function can OOP = Data abstraction + inheritance + dynamic binding (polymorphism) Polymorphism: a function can do different behaviors at runtime Dynamic binding: delay function binding to a subtype until runtime Suppose we want to draw a heterogeneous collection of shapes? class Point {. . . }; //a Point has x and y coordinates class Shape { //Why do we say Shape is an abstract class? protected: //accessible to subclasses but otherwise private Point center; //all Shapes have a center Point public: Point where() { return center; } //early binding by default virtual void move(Point to) //can override virtual function { center = to; draw(); } // by derived classes virtual void draw()=0; //=0 is a "pure" virtual function //draw() must be implemented by derived classes //. . .

Subclasses override virtual functions class Triangle: public Shape { Point sw, se, top; //Three 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 shapes Shape a. Shape; //illegal--why? Circle c(Point(20, Calling a virtual function { //Construct some shapes Shape a. Shape; //illegal--why? Circle c(Point(20, 30), 7); //legal--what does it do? //Create an array of various shapes Shape* shapes[10]; //Why is this legal? shapes[0] = new Circle(Point(20, 30), 7); //assign a Circle shapes[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++) shapes[i]->draw(); //draw all the shapes //each shape draws itself! } Why do we say that elements of shapes array are polymorphic? Polymorphic design supports B. Meyer’s Open-Closed principle: n n 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 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() n //. . . } Why is the dynamic binding version better for big, growing programs? Many design patterns build on polymorphism

Five activities of OOA Coad, Yourdon and Nicola: 1) Class‑&‑object: describe problem domain in Five activities of OOA Coad, Yourdon and Nicola: 1) Class‑&‑object: describe problem domain in terms of classes of objects 2) Structure: describe relationships between classes 3) Subject: organize classes into clusters or packages 4) Attributes: describe data held by objects 5) Services: describe behaviors that objects can perform Which of these five activities are analysis and which are design?

Concrete and abstract classes Identifying classes is 1 st activity of domain analysis Remember Concrete and abstract classes Identifying classes is 1 st activity of domain analysis Remember the linguistic analysis technique Can ignore inheritance and polymorphism for first draft, then factor out commonality as superclasses An abstract class has one or more operations that must be implemented by subclasses UML represents an abstract class by italicizing the class name or adding the constraint label {abstract}

Structure (association) analysis Lines connecting classes In UML, simple line is an association n Structure (association) analysis Lines connecting classes In UML, simple line is an association n Decorations for multiplicity, role names, constraints See example from Fowler n What does {ordered} constraint mean? Aggregations and composition: n n n Arrow denotes navigability e. g. , Polygon and Circle refer to Point but not vice versa A black-filled diamond denotes a composition a part, unique to this whole n A white-empty diamond denotes an aggregation a part, but not unique to this whole n E. g. , A Point may appear in only one Polygon or Circle but a Style could appear in both An alternative notation for composition in boxes

Attributes and operations A class box may have three parts n Class name, attributes Attributes and operations A class box may have three parts n Class name, attributes and operations Attributes in middle section n n Typically attributes are built-in types UML lets you include information about default values and visibility (+, -, #) E. g. , - name: String [1] = “Untitled” {readonly} private : type multiplicity default {property} (unmodifiable) I recommend you hold off on these details until design Operations in bottom section of class box n n Represent services, functions or methods Again, UML has a bit more notation, for information about parameters, default values and visibility E. g. , + balance. On(date: Date): Money Again, I recommend you hold off on these details until design

Eclipse with plug-ins Open Source IDE for O-O and Java n n n Plug-ins Eclipse with plug-ins Open Source IDE for O-O and Java n n n Plug-ins add more features Dr. Java plug-in provides Java interpreter Plug-in adds UML class diagrams Available on campus by running “eclips” Also available for download: http: //www. lehigh. edu/stem/teams/dieruff (3. 0)