SEN2022 · Week 8 · Structural Modeling

Structural modeling: CRC cards, class and object diagrams

Extracting classes from text, CRC cards, and attributes, operations, associations, multiplicity, aggregation, composition, generalization and object diagrams in a class diagram. The highest-scoring drawing question on the midterm.

structural modelclassobjectattributeoperationvisibilityderived attributeCRC cardresponsibilitycollaborationassociationmultiplicityassociation classaggregationcompositiongeneralizationabstract classobject diagramtextual analysis

The structural model shows what data the system holds and how that data is connected. The use case answers “what is being done”, the structural model answers “what is it done with”. The exam question of this week is almost always the same: a scenario is given and you are asked to draw a class diagram with the classes, attributes, relationships and multiplicities. Marks are lost by writing the multiplicity at the wrong end and by confusing aggregation with composition.

Golden rules:

  1. Noun → class or attribute, verb → operation or relationship.
  2. Multiplicity is read from the opposite end. The answer to “how many B does one A have?” is written at the B end.
  3. The diamond is on the whole side. Hollow: the part is independent (aggregation). Filled: the part dies with the whole (composition).
  4. The triangle is at the superclass. The arrow leaves the subclass.

Elements of the structural model

ElementMeaningExample
ClassA template for objects of the same kindStudent, Book
ObjectAn instance of a classayse : Student
AttributeData the class holdsstudentNo, title
OperationWork the class doesreserve(), calculateFine()
AssociationA relationship between classesStudent “makes” Reservation
MultiplicityHow many1, 0.., 1..

At the analysis stage the model describes the business world (the problem domain): there is no database table, Java type or getter/setter detail yet.

Finding classes

Textual analysis

Look at the words in the use case descriptions:

Kind of wordWhat it becomesExample
Common nounClassstudent, book, reservation
Proper nounObject“Central Branch”
Adjective, valueAttributetitle, due date, amount
Doing verbOperationreserves, calculates
“Has”, “contains”Relationship (aggregation/composition)an order consists of lines
“Is a kind of”Generalizationa student is a person

Other ways: brainstorming (the team lists candidate classes), common object lists (physical things, events, roles, places), patterns (ready-made forms like order-order line, reservation).

CRC cards

A CRC (Class-Responsibility-Collaboration) card shows, on one card per class, the responsibilities and the classes it collaborates with.

+---------------------------------------+
| Class: Reservation       ID: 4        |
| Type: Concrete, domain                |
+---------------------------------------+
| Responsibilities   | Collaborators    |
|--------------------+------------------|
| Knowing:           |                  |
|  code, date,       |                  |
|  end time          |                  |
| Doing:             |                  |
|  check if expired  |                  |
|  set aside copy    | Copy             |
|  notify student    | Student          |
+---------------------------------------+
Back: attributes (code, createdAt,
expiresAt), relationships (Student, Copy)

Responsibilities are of two kinds: knowing (the data it knows) and doing (the work it does). A class that cannot do a responsibility on its own writes the class it collaborates with on the right side. Role-playing: team members take the cards in their hands and act out a use case step by step; a missing responsibility or class shows up immediately.

Class diagram

The class box

+---------------------------+
|         Student           |
+---------------------------+
| -studentNo : String       |
| -name : String            |
| -birthDate : Date         |
| -/age : int               |
+---------------------------+
| +reserve(c : Copy) : Bool |
| +getActiveCount() : int   |
+---------------------------+
PartSyntaxExample
Attributevisibility name : type-name : String
Derived attributewith /-/age : int
Operationvisibility name(parameter : type) : return+reserve(c : Copy) : Bool
Visibility+ public, - private, # protected, ~ package

Kinds of operation: constructor (creates an object), query (returns information without changing state, e.g. getActiveCount), update (changes state, e.g. reserve).

Association and multiplicity

An association is a solid line between two classes. A name (makes, contains) and a reading direction can be written on it. At each end is written how many objects from the class at that end are possible.

NotationMeaning
1Exactly one
0..1Zero or one
0..* or *Zero or more
1..*At least one
2..5Between 2 and 5
3Exactly three

How to read: “How many Reservations does a Student have?” → 0..3 → written at the Reservation end. “How many Students does a Reservation have?” → 1 → written at the Student end.

+---------+ 1    makes >   0..3 +-------------+
| Student |---------------------| Reservation |
+---------+                     +-------------+

PITFALL · writing the multiplicity at its own end. The 3 in the sentence “a student has at most 3 reservations” is written next to Reservation, not next to Student. Each time, ask “how many Y does one X have?” and write the answer next to Y.

Association class

It is used when the relationship itself has data. Student and course are in a many-to-many relationship; the grade belongs neither to the student nor to the course.

+---------+ *          * +--------+
| Student |--------------| Course |
+---------+      :       +--------+
                 :
          +------------+
          | Enrollment |
          +------------+
          | grade      |
          | semester   |
          +------------+

Aggregation and composition

Both are whole-part (part-of) relationships.

AggregationComposition
SymbolHollow diamond, on the whole sideFilled diamond, on the whole side
Does the part live independentlyYesNo, it disappears with the whole
Can the part belong to several wholesIt canNo, a single whole
ExampleTeam <>- Player, Branch <>- CopyOrder <#>- OrderLine, Building <#>- Room
+-------+ 1        1..* +-----------+
| Order |<#>------------| OrderLine |
+-------+               +-----------+
(<#> = filled diamond, if the Order is deleted the lines go too)

+--------+ 1       0..* +--------+
| Branch |<>------------|  Copy  |
+--------+              +--------+
(<> = hollow diamond, if the branch closes the copy moves to another branch)

Generalization

An “is-a-kind-of” relationship. The subclass inherits the attributes and operations of the superclass and adds its own.

          +----------+
          | Person   |  (abstract, italic)
          +----------+
          | -name    |
          | -email   |
          +----------+
              /_\
               |
       +-------+-------+
       |               |
+-----------+   +-------------+
| Student   |   | Librarian   |
+-----------+   +-------------+
| -studentNo|   | -staffNo    |
+-----------+   +-------------+

An abstract class is a class with no direct objects (nobody is just a “Person”). A concrete class is a class that has objects.

PITFALL · confusing generalization with aggregation. “A student is a person” → generalization. “A branch has copies” → aggregation. Ask: “is it ‘is a kind of’ or ‘has a / is part of’?”

Worked example: the campus library class diagram

Scenario: “The library has several branches. Each book has one or more physical copies, and each copy is kept at one branch. Students borrow copies; a loan record is for a single student and a single copy. A student can make at most 3 reservations at the same time; a reservation holds a single copy. Students and librarians are persons; the name and e-mail of both are kept.”

Step 1: Classes. Branch, Book, Copy, Student, Librarian, Person, Loan, Reservation.

Step 2: Attributes and operations.

ClassAttributeOperation
Person (abstract)name, email
StudentstudentNo+reserve(c : Copy)
LibrarianstaffNo+confirmReturn(l : Loan)
Bookisbn, title, author+availableCopies() : int
Copybarcode, status+setStatus(s : String)
Branchname, address
LoanloanDate, dueDate, returnDate, /fine+calculateFine() : Money
Reservationcode, createdAt, expiresAt+isExpired() : Bool

Step 3: Relationships and multiplicity.

RelationshipTypeEnd 1End 2
Book - CopyAssociationBook 1Copy 1..*
Branch - CopyAggregation (Branch is the whole)Branch 1Copy 0..*
Student - LoanAssociationStudent 1Loan 0..*
Copy - LoanAssociationCopy 1Loan 0..*
Student - ReservationAssociationStudent 1Reservation 0..3
Reservation - CopyAssociationReservation 0..1Copy 1
Student, Librarian - PersonGeneralization

Read the Reservation - Copy row: a Reservation holds exactly one Copy (1 at the Copy end). A Copy can be in at most one reservation at a time (0..1 at the Reservation end).

Step 4: The drawing (summary).

Student     1 -------- 0..3 Reservation
Reservation 0..1 ----- 1    Copy
Student     1 -------- 0..* Loan
Copy        1 -------- 0..* Loan
Book        1 -------- 1..* Copy
Branch      1 <>------ 0..* Copy
Student   ---|> Person {abstract}
Librarian ---|> Person {abstract}

Each line is a relationship: the number on the left is written at the end of the class on the left, the number on the right at the end of the class on the right. On the exam you draw this with boxes; what matters is that the multiplicity at each end is on the right side.

Object diagram

An object diagram shows the objects in the system at a particular moment and the links between them. It is a “photograph” of the class diagram. The object name is written in the form name : Class, underlined; attributes are shown with their actual values. Multiplicity is not written.

+------------------+     +------------------+
| ayse : Student   |-----| r1 : Reservation |
| studentNo="2041" |     | code="R-118"     |
+------------------+     +------------------+
        |                         |
        |                +------------------+
        |                | c7 : Copy        |
        |                | status="On Hold" |
        |                +------------------+
+------------------+     +------------------+
| r2 : Reservation |-----| c9 : Copy        |
| code="R-131"     |     | status="On Hold" |
+------------------+     +------------------+

Here there are 5 objects (ayse, r1, r2, c7, c9) and 4 links: ayse-r1, ayse-r2, r1-c7, r2-c9. An object diagram is a good way to test multiplicities: if you try to add a fourth reservation for Ayse, you violate the 0..3 rule in the class diagram.

Common mistakes

Wrong ideaThe truth
Multiplicity is written at its own endIt is read from the opposite end: “how many B does an A have” → at the B end
The diamond is on the part sideThe diamond is on the whole side
In composition the part can move to another wholeIt cannot, it disappears with the whole
The generalization arrow from top to bottomFrom bottom to top, the triangle at the superclass
Every noun is a classSome are attributes (date, amount) or unnecessary (system, screen)
Putting data belonging to the relationship at one endUse an association class
Writing multiplicity in an object diagramLinks are single, there is no multiplicity
Writing getters/setters in analysisThey are not written in analysis; they are a design detail

Test yourself

Exam-style questions. Solve them on paper first, then reveal the answer.

Question 1easy

Read the association: Customer 1 ---- 0..* Order. How many orders can one customer have, and how many customers does one order have?

Show answer
A customer has zero or more orders; an order belongs to exactly one customer.

Multiplicity is read from the opposite end. The 0..* on the Order side: "one Customer has 0 or more Orders." The 1 on the Customer side: "one Order belongs to exactly one Customer."

Question 2medium

Give the multiplicity: 'A gym class session has one trainer; a trainer leads between 0 and 10 sessions per week.' (Trainer end, Session end)

Show answer
Trainer end: 1, Session end: 0..10

How many Trainers does a Session have? 1, and this number is written at the Trainer end. How many Sessions does a Trainer lead? 0..10, and this is written at the Session end.

Question 3easy

An Order is made of OrderLines; an OrderLine cannot exist without its Order and is deleted with it. Which relationship?

  1. Association
  2. Aggregation
  3. Composition
  4. Generalization
Show answer
C) Composition

Composition is a strong whole-part relationship: the part belongs to a single whole and disappears with the whole. The filled (black) diamond is drawn on the whole side, at Order.

Question 4medium

A Team has Players, but a player can leave and join another team and still exists. Which relationship and which symbol?

Show answer
Aggregation, a hollow (white) diamond at the Team end

Aggregation is a weak whole-part relationship: the part can live independently of the whole. The hollow diamond is drawn on the whole side. If it were composition, the players would disappear when the team broke up.

Question 5easy

What do the visibility symbols +, -, # mean?

Show answer
+ public, - private, # protected

+ is accessible from everywhere (public), - only from inside the class (private), # the class and its subclasses (protected). ~ is package visibility. In analysis, attributes are usually written as private and operations as public.

Question 6medium

In a class, the attribute /age : int appears next to birthDate : Date. What does the slash mean?

Show answer
age is a derived attribute, calculated from birthDate.

/ marks a derived attribute: it is not stored, it is calculated from other attributes. The /total of an Order is calculated from the sum of the lines.

Question 7hard

'Students take Courses. For each student-course pair we must store the grade and the semester.' Where do grade and semester go?

Show answer
In an association class (e.g., Enrollment) attached to the Student-Course association.

The grade belongs neither to the Student nor to the Course; it belongs to the relationship between the two. An association class is a class attached to the association line with a dashed line: Enrollment (grade, semester). It is often seen in many-to-many relationships.

Question 8medium

From the text 'A courier delivers an order to a customer's address and records the delivery time', identify candidate classes using textual analysis.

Show answer
Courier, Order, Customer, Address (and possibly Delivery); delivery time is an attribute.

Nouns are class candidates: courier, order, customer, address. Verbs (delivers, records) are operation or relationship candidates. "Delivery time" is a value, so it becomes an attribute (in the Delivery or Order class). If Address is kept simple, it can also be an attribute of Customer.

Question 9easy

On a CRC card, what goes on the right side?

  1. Attributes
  2. Collaborators
  3. Responsibilities
  4. Superclasses
Show answer
B) Collaborators

CRC = Class, Responsibilities, Collaborators. The left side of the card holds the responsibilities (knowing and doing), the right side the classes it collaborates with. Attributes and relationships can be written on the back.

Question 10medium

In the object diagram on this page, how many objects and how many links are shown?

Show answer
5 objects, 4 links

Objects: ayse:Student, r1:Reservation, r2:Reservation, c7:Copy, c9:Copy. Links: ayse-r1, ayse-r2, r1-c7, r2-c9. Total 5 objects, 4 links. In an object diagram multiplicity is not written, and the names are shown underlined.

Question 11medium

Which statement about generalization is TRUE?

  1. The arrow goes from superclass to subclass
  2. A subclass inherits attributes and operations of its superclass
  3. Composition is a kind of generalization
  4. An abstract class must have instances
Show answer
B) A subclass inherits attributes and operations of its superclass

Generalization is an "is-a-kind-of" relationship; the arrow goes from the subclass to the superclass, with the hollow triangle at the superclass. The subclass inherits everything from the superclass and adds its own. An abstract class has no direct objects (its name is written in italics).

Question 12easy

A Copy belongs to exactly one Book; a Book has at least one Copy. Write the multiplicity at each end.

Show answer
Book end: 1, Copy end: 1..*

How many Books does a Copy have? 1 → at the Book end. How many Copies does a Book have? At least 1 → 1..* at the Copy end.

Verification: Multiplicity, relationship type and counting questions were checked one by one against the UML 2 class diagram rules (multiplicity is read from the opposite end; in composition the part disappears with the whole; generalization is a hollow triangle from the subclass to the superclass). The numbers of objects and links in the object diagram were counted by hand on the drawing on the page and compared twice.

Review card

Class box: name / attributes / operations Visibility: + public - private # protected ~ package attribute: -name : String operation: +reserve(b : Book) : Boolean /attr = derived (calculated, not stored) Multiplicity: 1, 0..1, 0..*, 1..*, 2..5 → read from the OPPOSITE end Association: solid line, name + reading direction (▸) Association class: data belonging to the relationship (Enrollment: grade) Aggregation: hollow diamond on the WHOLE side, the part lives independently Composition: filled diamond on the WHOLE side, the part dies with the whole Generalization: hollow triangle at the SUPERCLASS, "is-a-kind-of" Abstract class: italic name, no objects CRC: Class | Responsibilities (left) | Collaborators (right) Textual analysis: noun → class/attribute, verb → operation/relationship Object diagram: object:Class (underlined), values, link (no multiplicity)