300144 300888 Object Oriented Analysis
Dr Mahsa Razavi
Lecture 6
Classes & Class Diagrams
References
Textbook Chapter 8
Bhuvan’s book Chapter 6 Booch’s book Chapter 3, 5 (5.7), 9
2
Things in Last Lecture
• UseCaseDiagrams
• Relationships in use case diagram • Activity Diagrams
• UML’s Extensibility Mechanisms
3
Main Topics of Lecture
• Revisiting Class and Object
• Representing a class with UML Class Notation
and documentation
• Translating a Class Diagram to code
• Identify classes from use cases
• Relationships in Class Diagram: – Inheritance, Association & Aggregation
• Multiplicities in Class Diagram
4
Revisiting Classes and Objects
▪ An object is an entity encapsulated with a set of attributes (data members) and behaviors (function members)
▪ A Class is a definition or a template for a set of Objects with the same structure of data and operations
▪ NOTE:
▪ A Class is not an individual object
▪ A Class is not simply a collection of objects
▪ but the representation of the whole set of objects.
5
The Star of OO Fundamentals
CLASSIFICATION
Fundamentals of Object-Orientation: THE OBJECT
6
Class Notation in UML
• Documentaclass
• Represent a class in UML
• Translate a class diagram to code • Identifyclasses
Object Oriented Analysis – 300144 7
<
A one word name for the class prefixed with the optional stereotype
Description
Briefly explain what the class is representing
Relationship
List other related classes
Attributes
List of attributes describing the class
Responsibility
Responsibility eventually translated into combination of attributes and behaviour
Business Rules
Special business rules and constraints
Complexity
A metric about the class’s complexity
Object Oriented Analysis – 300144 8
Class Documentation Template
Represent a class in UML
• Classes in UML appear as rectangles with multiple sections
• The first section contains its name (defines a type)
• The second section contains the class’s attributes
• The third section contains the class’s methods Object Oriented Analysis – 300144 9
UML Notation: class diagram
Stereotype:
Type of the Class. Entity for Analysis.
<
Patient
-name : String -dateOfBirth: Date
+register ()
Name of the Class
Attributes of the Class
Operations of the Class
Accessibility: + for public, – for private and # for protected
10
Data Type
UML Notation: Class Diagram (Cont.)
<
Consultation
– date: Date
– time: Time
– booked: boolean – diagnosis: String
+ bookConsultation()
+ maintainConsultation()
This diagram says that there is a class called
Consultation with four private attributes: date, time,
booked and diagnosis, and two public methods:
bookConsultation() and maintainConsultation().
11
Major Ingredients in a Class Diagram
Patient
Doctor
–
–
:
DoctorID Qual [0..N]
+ getDoctorDtls ()
Class: With 3 Compartments
Inheritance
Association
Aggregation
Class Description Contains: Attributes & Operations
Multiplicity
1..N
0N
At each end Of Association
Notes
12
Translation to Code
• A fully dressed class diagram can be translated into codes straightforwardly
– Define the class with the specified name
– Define the attributes with specified accessibility (and data
types)
– Define the method skeletons with specified accessibility (and argument data types and return data type)
• Note that a class diagram may not have sufficient information to define a complete class
– Types are optional in class diagrams but mandatory in class definition
– Method definition is not included in class diagrams.
13
Class in Programming Language
class Patient { private:
string name;
Date dateOfBirth; public:
bool register(); };
C++
class Patient {
private String name; private Date dateOfBirth; public boolean register(); }
Java
Patient
– name: String
– dateOfBirth: Date
+ register(): bool
14
How to Identify Classes?
• Noun analysis of the text within Use Cases reveals first cut of a list of classes
• Otherdocuments,problemstatementsetc.canbe inspected for nouns as well
• These nouns represent entities in problem space, which are potential classes
• Attributes and responsibilities (methods) are added to these classes but at analysis level they might be incomplete and inaccurate.
15
Noun Analysis – An Example
Use Case Thumbnail: UC10-RegistersPatient Actors: A10-Patient, A80-Administrator, A90-
GovernmentHealthRegulatorySystem, A95-PrivateInsuranceProvider
Use Case Description: this use case deals with registration of new patients in the hospital management system. These registration details include name, address, date of birth and related details of the patient, including Medicare card and status (private or public patient). A10-Patient provides all the details and A80-Administrator enters them into the system. A90- GovermentHealthRegulatorySystem is an interface to an external system, which is provided by the State department of health, to verify the Medicare card details of public patients. A95-PrivateInsuranceProvider is an interface to an external system for individual private health insurance companies, to verify the insurance details of private patients.
Stereotype and Package: <
Pre-Conditions: Patient must have not been already registered with the hospital Post-Conditions: Patient is registered in the hospital system
Use Case Relationships: Associates with actors: A10-Patient, A80-Administrator
16
Noun Analysis – An Example (Cont.)
Basic Flow:
1. A patient arrives at the hospital for some medical treatment
2. The administrator asks the patient if they have been previously treated at this hospital
3. Patient provides the answer (A1)
4. Administrator asks patient for his/her personal details such as Name, Address, Telephone, DOB, Emergency Contact
5. Patient Provides details as requested
6. Administrator enters details into system
7. System verifies details (A2)
8. Administrator asks patient whether he is a public or private patient
9. Patient provides the answer
[Public]
1. Administrator ask public patient for Medicare number
2. Patient provides Medicare number
3. Administrator enters Medicare number into system
4. System verifies patient identify with Government Health Regulatory System (A3)
17
Noun Analysis – An Example(Cont.)
Basic Flow:
[Private]
1. Administrator ask private patient for insurance details
2. Patient provides insurance details
3. Administrator enters insurance details (e.g. company & policy number) into system
4. System verifies patient identity with Private Health Insurance Company System (A4)
10.
11.
System saves patient details
System confirms patient registration
Alternative Flow:
A1 – if the patient has visited the hospital previously, he/she will have been registered in the hospital’s system. The administrator informs the patient of existing registration.
A2 – If insufficient or incorrect details have been provided, the patient is requested to provide the details again
A3- The patient cannot be verified with the government health regulatory system, so the administrator asks the patient for the Medicare card detail again. If no verification is possible, the patient is conditionally registered as either a full fee paying patient, or one who will provide Medicare details later
A4- The Patient cannot be verified with the private health insurance company’s system, so the administrator asks the patient for the private health insurance details again. If no verification is possible, the patient is conditionally registered as either a full fee paying patient and his details with the health insurance company are to be verified later
18
Class-Responsibility-Collaborator (CRC) Cards to Identify Classes
A CRC card representing the Patient class
Patient
Responsibility
Collaborators
Briefly specify the illness/problem
Administrator
Allocate type of doctor
Administrator
Check doctor’s availability for day/time
Consultation, Doctor
Select appointment day/time
Consultation
A CRC card representing the Consultation class
Consultation
Responsibility
Collaborators
Check doctor’s availability for day/time
Patient, Doctor
Select appointment day/time
Patient
19
Class Relationships in UML • Inheritance
• Association • Aggregation • ……
Object Oriented Analysis – 300144 20
Relationship between Classes
• Classes can be related in a variety of ways – Inheritance: is-a relationship
– Association: is associated/is related relationship – Aggregation: has a / whole-part relationship
– Composition, Dependency …
21
Relationships in a Class Diagram
AGGREGATION “HAS_A”
ASSOCIATION “IS ASSOCIATED TO”
1..* 1..4 1..*
Department
Doctor
1
INHERITANCE “IS_A”
0..1 1..2
Operating Theatre
Hospital
Dentistry
Surgery
Medicine
22
The Inheritance Relationship
Department
INHERITANCE “IS_A”
Dentistry
Surgery
Medicine
Inheritance lets you build classes based on other classes and avoid duplicating code
23
Association Relationship on Class Diagram
ASSOCIATION “IS ASSOCIATED TO”
Department
1..4 1..*
Doctor is associated with Department; Department also is associated with Doctor; The Relationship is loose.
Doctor
24
Role Name in Association Relationship
“Professor Wrote Book”
Professor
1..*
A role name (Wrote) explains how an object (Professor) participates in the relationship (Professor – Book)
0..*
Wrote
Book
25
Aggregation Relationship on Class Diagram
AGGREGATION “HAS_A”
Hospital
1..*
Hospital has Department; Closer/Tighter Relationship
Department
26
Aggregation vs Composition
27
Multiplicity
• Provides Business Rules;
• Invaluable in DB Design.
28
Multiplicities on Class Diagrams
• Associations can indicate the number of instances involved in the relationship
– this is known as multiplicity
– An association with no markings is “one to one”
• An association can also indicate directionality
• If so, it indicates that the “knowledge” of the relationship is
not bidirectional
• The arrows describe the ways you can navigate
• All associations are assumed to be bi-directional by default
• Some associations may be designated as unidirectional if necessary
29
Multiplicities on Class Diagrams (Cont.)
• Multiplicities encompass Business Rules – They are for Objects belonging to Classes
– They are useful for database design
• Multiplicity states:
– For two classes in an association (or aggregation) relationship
– “An object of one class deals with how many objects of another Class”
• A Car object associates with Four Wheels
– Then multiplicity will be 1 for Car and 4 for Wheel
– If using aggregation relationship (appropriate in this case), the Car as the aggregator, the multiplicity will always be one.
• Note: Multiplicities are meaningless for Inheritance relationship
30
Multiplicities on Class Diagrams (Cont.)
Hospital
Multiplicity:
An Object of one Class Relates to How Many Objects of the Other Class
Department
1
1..*
1..4
1..*
Operating Theatre
Dentistry
Surgery
Medicine
0..1 1..2
Object Oriented Analysis – 300144
31
Doctor
Class diagrams for hospital management system
32
“Patient Details” Class Diagram
1..*
0..*
Person
-FirstName -LastName -DateOfBirth
Patient
-PatientID -MedicareCard -EmergancyContact
Address
+createPerson() +changePeson () +calculateAge () +getPerson ()
-StrNo -StrName -City -PostCode -Country
+createAddress () +maintainPhone () +getPhone ()
Phone
+getPatientDetails ()
-STDCode -PhoneNumber -PhoneType
PublicPatient
+submitMedicareClaim ()
+createPhone () +maintainPhone () +getPhone ()
PrivatePatient
-InsuranceCompany -DateStarted -DateOfExpiry -LevelOfCover
+submitInsuranceClaim ()
Public Patients have medicare card details
33
“Staff Details” Class Diagram
-Qualification -Specialization -Registration
Doctor
Staff
-EmpID -DateJoined -TaxNumber -Level
Nurse
Administrator
+getStaffDetails () +createStaff () +maintainStaff ()
+maintainAdmin ()
+checkAvailablity () +checkSpecialization () +getDoctor ()
-Type
Physician
+getPhysician ()
+getNurse () +getNurseType ()
Nurse types are: General Midwife, Surgical
Surgeon
-OperatingSpeciality
+getSurgeon () +getSpeciality ()
34
“Consultation Details” Class Diagram
Physician
1
1..* 0..*
Attribute types are suggestions only
1
Consultation
-Date : Date
-Time: Time -Booked: Boolean -Diagnosis:String
Patient
+bookConsultation () +maintainConsultation ()
Calendar
-Date -TimeStatus
Prescription
maintainCalendar ()
-PrescriptionNumber -PrescriptionDate -PrescriptionEndDate
+createPrescription ()
1
0..*
35
“Accounting” Class Diagram
-BillNumber -Amount -Status
Bill
Payment
Cash PAyments
are directly handdled in the Payment class
-Type -Amount -ReceiptID -DatePaid
1 1..*
+getBillStatus () +updateBill () +getBillAmount () +createAmount ()
BPay
-ReferenceNumber -BillerCode
Cheque
CreditCard
+maintainPayment () +displayPayment () +acceptPayment ()
-CardNumber -ExpiryDate -CardHolder
-ChequeNumber -BankNumber -BankBranch
36
SWOT of Class Diagrams
Strengths
1. Structural representation 2.Classes, relations 3.Encapsulation and Reuse 4.Multiplicities
Weaknesses
1.Inability to show any dynamics
2.Relationships: confusion between Association and Aggregation
Objectives
1.MOPS, MOSS
2.Capture Business Entities, Rules, DB design
3.Technical Programming Classes
Traps
1.Inappropriate level of use
2.Code generation
3.Lack of Granularity considerations
37
Workbook Exercises
For The Class Room!!
38
Workbook Exercises
1. Identify two business classes in the OO Trust System. Write at least 5 attributes and 5 operations for each of these two classes. Add an appropriate stereotype for the two classes.
2. Draw a class diagram with at least 5 classes. Incorporate all three relationships (association, inheritance, aggregation). Add multiplicities to the association relationship. Be sure to add explanatory notes where needed.
39
Discussion on OO Trust System
1. Business Banking deals with business customers who are small to medium size companies. The provided services include business accounts, business transactions (e.g. withdrawal and deposit money), and business loans. This is a strict onsite service at the bank via a business-customer operator and/or a bank manager. The department is also linking with other larger banks or financial firms so that a joint lending can be made if the bank financial support is limited.
2. Personal Banking deals with general private customers. There are a number of available services including personal accounts, personal transactions (deposit and withdrawal via an ATM or a bank teller at the counter ), home loans, personal loans and insurances. These services can be done at the bank or using the internet. Staff who is responsible for personal banking is the bank tellers, personal-customers operator and/or a bank managers.
40
Discussion on OO Trust System
3. Risk Analysis is responsible for analysing and reporting any potential threads from business accounts and/or personal accounts. The risk analysis must be carried out prior to the approval of a new (business and private) account and/or a loan. This analysis can be also carried out at any stage for an account in case of a suspicion. The department is also responsible for profit and loss analysis on an ongoing basis. Risk analysis department can link with associated organisations, such as other banks and government agencies so that the credit histories and/or criminal records can be checked.
4. Human Resource (HR) Management is responsible for maintaining employee’s personal records (e.g. information, salary, degree, skills, etc), work schedule of employees, leave and leave balances. The HR department is also responsible for recording of cash flow, e.g. Income and expense for a daily period basic. All information can be accessible from anywhere by managers and/or authorised accountants via the secured internet or the internal LAN.
41
Possible Classes From Problem Statement
• Business Banking
• Business Customer
• Company
• Business account
• Business Transaction
• Withdrawal (business)
• Deposit (business)
• Money
• Business loan
• Service
• Bank
• Business-Customer Operator
• Bank Manager
• Department
• Other Bank
• Financial Firm
• Lending
▪ Personal Banking
▪ Private Customer
▪ Service
▪ Personal Account
▪ Personal Transaction ▪ Deposit (personal)
▪ Withdrawal (personal) ▪ ATM
▪ Bank Teller
▪ Home Loan
▪ Personal Loan ▪ Insurance
▪ Service
▪ Staff
▪ Personal Customer Operator ▪ And more …
42
Use Case for Withdrawal
Use Case Thumbnail: UC10-Withdrawal
Actors: A20-PrivateCustomer, A130-PersonalCustOp, A110-Teller
Use Case Description: this use case deals with withdrawal of a private customer from the personal loan via a personal- customer operator and a bank teller. A20-PrivateCustomer provides all the bank details, identification and the amount of withdrawn money. A130-PersonalCustOp enter the information and validate if the transaction is satisfied before handing the case to a bank teller. The teller will carry out withdrawal transaction. The cash and the receipt will be given to the customer.
Pre-Conditions: Customer is already registered in the system. Post-Conditions: Customer is given the cash and the receipt.
43
Use Case for Withdrawal (cont)
Basic Flow:
1. PrivateCustomer (customer) requests a withdrawal with a PersonalCustOp (operator).
2. The operator requests the bank detail and Identification of the customer.
3. The customer presents the bank card and his/her ID card to the operator.
4. The operator enters the detail (via the card reader) into system (A1).
5. The operator asks for the amount of withdrawal.
6. The customer gives the amount.
7. The operator validates if the withdrawal can be made (A2).
8. The operator hand the customer to a BankTeller (teller).
9. The teller processes the transaction.
10. The system updates the records of the personal loan
11. The teller gives the cash and the receipt to the customer.
Alternative Flow:
A1 – The customer detail is invalid and/or the card is invalid. The customer will be asked to give further details to verify
A2 – The withdrawal amount is over the limit. The customer will be asked to reduce the amount.
44
Two Business Classes
<
– customerID: int
– name: String
– address: Address[]
– dateOfBirth: Date
– Status: String
Attributes?
+ getName(): String
+ getID(): int
+ updateContactDetails(): void
Operations?
+ makeAppointment(): boolean + updateStatus: void
<
– loanID: int – date: Date
– type: int
– amount: float
– customer: PersonalCustomer
Attributes?
+ getCustomer(): PersonalCustomer + getLoandAmount(): float
+ getLoanType(): int
+ makeNewOLpoaenr(a):tvioidns?
+ updateLoan(loanID int): void
Note: the attributes and operations for two classes might not be completed
45
Two Business Classes
<
– customerID: int
– name: String
– address: Address[]
– dateOfBirth: Date
– Status: String
+ getName(): String
+ getID(): int
+ updateContactDetails(): void + makeAppointment(): boolean + updateStatus: void
<
– loanID: int
– date: Date
– type: int
– amount: float
– customer: PersonalCustomer
+ getCustomer(): PersonalCustomer + getLoandAmount(): float
+ getLoanType(): int
+ makeNewLoan(): void
+ updateLoan(loanID int): void
Note: the attributes and operations for two classes might not be completed
46
*
A Sample of A Class Diagram
*
47
A Sample Class Diagram —— Property For Sale
48
“Property For Sale” Class Diagram
• Property and Owner: aggregation relationship
• Property associated with (we may use aggregator relationship) Advertisement, OpenHouse, Sale or Auction, Inspection (either Owner, Buyer, or both can require for an inspection but may not be included here)
• Sale or Auction associated with Contract that in turn linked with Payment and Bill
• Agent associates with OpenHouse, Consultant associated with Sale (Auctioneer with Auction)
• Consultant and Solicitor associated with Contract
• Buyer associated with Advertisement, OpenHouse, Sale or Auction,
Contract, Agent, Solicitor, and Bill and Payment.
• Inspection and classes related to home loan application could be put in a separate diagram (Pre-sale processes).
• Insurance may be only needed for property rental.
• Multiplicities: Owner may have more properties; Property has one Advertisement and one Sale (Auction) but more OpenHouse; One Sale with one Contract; Agent and Solicitor can be linked with more than one OpenHouse, Sales, Contract, Buyer needs to pay one Bill for one or more Payments etc.
49
PersonalCustomer
Conclusions
• Business Class Diagrams shows
✓ Classes
✓Attributes of Classes ✓Operations of Classes ✓Relationships among the Classes.
• Multiplicities are Important, as they show Business Rules
• StereotypesandNotesaddvaluetotheDiagrams 50
Project Work : (During Practical in the Lab);
Carry Out the Project Work
Discuss Project Work with Team Members and Tutor
51
RUP Case Study – Train Traffic Management System (TTMS)
Elaboration-1
Object Oriented Analysis – 300144 52
Analysing System Functionality
• Attention now turns to developing the overall architecture framework for the TTMS
• Requiredsystemfunctionalityleadingtothe definition of the TTMS architecture
• Transitionfromsystemsengineeringtothe disciplines of hardware and software engineering
• Howthesystem’saggregatepartsprovidethe required functionality
• Use activity diagrams to analyse various use case scenarios to develop this further level of detail.
Object Oriented Analysis – 300144 53
Route Train
• Primary scenario of the Route Train use case. – interactionoftheDispatcheractorandthe
RailOperationsControlSystem
– designatedastheprimarycommandandcontrolcentrefortheTTMS
• Twocompetingtechnicalconcerns: – thedesiretoencapsulateabstractions
– theneedtomakecertainabstractionsvisibletootherelements
• Solution: define modularity as the property of a system that has been decomposed into a set of cohesive and loosely coupled elements
Object Oriented Analysis – 300144 54
Object Oriented Analysis – 300144 55
The Route Train Primary Scenario
Monitor Train Systems
• TrainEngineer chooses to perform a detailed monitoring of the LocomotiveAnalysisandReporting system
– has a yellow condition
– the constituent elements providing this capability: OnboardDisplay system,
LocomotiveAnalysisandReporting system, EnergyManagement system, DataManagement unit.
• OnboardDisplay system as the interface between TrainEngineer and TTMS
– receives TrainEngineer’s request to monitor the train systems
– requests the appropriate data from other three systems.
– overview level of status information is provided to TrainEngineer for review.
• TrainEngineer could remain at the overview level and end the primary scenario.
• Alternate scenario: TrainEngineer requests a more detailed review from LocomotiveAnalysisandReporting system
– has presented a yellow condition indicating some type of problem requiring attention.
– OnboardDisplay system retrieves detailed data from system for presentation.
• After reviewing information, TrainEngineer returns to monitoring the
overview level of system status information.
Object Oriented Analysis – 300144 56
Object Oriented Analysis – 300144 57
A Monitor Train Systems Alternate Scenario
Monitor Train Systems (Cont.)
• The second alternate scenario Predicting Failure use case could be appended to the activity diagram provide a more complete picture of system capability
– TrainEngineer requests a failure prediction analysis – condition: {request Predict Failure}
• Another way to depict the Monitor Train Systems use case—with its primary and alternate scenarios—is by using an interaction overview diagram
Object Oriented Analysis – 300144 58
Object Oriented Analysis – 300144 59
An Interaction Overview Diagram for Monitor Train Systems