0% found this document useful (0 votes)
23 views43 pages

Se02-Oo Uml

Uploaded by

bharathvenna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
23 views43 pages

Se02-Oo Uml

Uploaded by

bharathvenna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

OO Paradigm and UML

Object Oriented Programming


https://softeng.polito.it/courses/09CBI

Version 2.4.2
© Maurizio Morisio, Marco Torchiano, 2020

Licensing Note
This work is licensed under the Creative Commons Attribution-
NonCommercial-NoDerivatives 4.0 International License.
To view a copy of this license, visit
http://creativecommons.org/licenses/by-nc-nd/4.0/.
You are free: to copy, distribute, display, and perform the work

Under the following conditions:


§ Attribution. You must attribute the work in the manner specified by
the author or licensor.

§ Non-commercial. You may not use this work for commercial


purposes.

§ No Derivative Works. You may not alter, transform, or build upon


this work.

§ For any reuse or distribution, you must make clear to others the
license terms of this work.
§ Any of these conditions can be waived if you get permission from the
copyright holder.

Your fair use and other rights are in no way affected by the above.
2

1
From procedural to object oriented programming paradigm

OBJECT ORIENTED PARADIGM

Programming paradigms
§ Procedural (Pascal, C,…)
§ Object-Oriented (C++, Java, C#,…)
§ Functional (LISP, Haskell, SQL,…)
§ Logic (Prolog)

2
Languages timeline

Global Structured prog Modules/ADT


variables Types Concurrency
Data Blocks Exceptions
structures
1st gen 2nd gen 3rd gen
Procedural HLL HLL HLL
FORTRAN ALGOL68 ADA
languages COBOL PASCAL MODULA2
ALGOL60 C

‘60 ‘70 ‘80 ‘90 ‘00


Object-oriented C++ Python
C#
SIMULA67 SMALLTALK EIFFEL JAVA
languages
ADA9X

Example - Receipt
§ Cash registers emit purchase receipts
§ A receipt is made up of items
§ Every item correspond to a product that
has a name and a price
§ Products’ info is stored in a price list
§ Any time a new product code is entered
the corresponding item is added to the
receipt
§ After the last item is entered, a list of the
items (with product name and price) are
printed together with the total sum.

3
Example: Shop Receipt
§ Input:
w 13
w 57
w 123
w 0 (end of receipt)
§ Output
Receipt:
ID13 : 16.62
ID57 : 9.73
ID123 : 0.06
------
Number of items: 3
Total: 26.41

Procedural (C)
float prices[MAX_LIST];
char* names[MAX_LIST];
int receipt[MAX_RCPT];
int n_items;
void add(int) {/* add item to receipt */ }
void print(){ /* print receipt */ }
void init() { /* initialize */ }
int read() { /* read item code */
int main(){
init();
int code;
while( (code = read()) ){ add(code); }
print();
}
8

4
Modules and relationships
Modules: Relationships
Data Call
Function (Procedure) Read/write

main()

read() add() print() init()

prices

names
receipt n_items

Problems
§ No syntactic relationship between:
w Arrays ( receipt, prices, names)
w Relative operations (add, print, init)
§ Lack of link between coupled arrays
(prices, names)
§ No control over size:
for (i=0; i<=20; i++){ prices[i]=0; }
§ No guarantee on initialization
w Actually performed?

10

10

5
Objects - Encapsulation
§ Bring together code and data
w E.g. add() + receipt + n_items

Interface
main()

Receipt
read() add() print() init()

prices

names
receipt n_items

11

11

Objects – Information Hiding


§ Hide object information from external
modules
w The only way to access data within an
object is through its interface

foo()
main()

Receipt

read() add() print() init()

prices

names
receipt n_items

12

12

6
Objects
§ Tie related data elements
w E.g. prices + names

Interface
main()

Receipt
read() add() print() init()

prices PriceList

names
receipt n_items

13

13

Objects
§ Represent semantically consistent
elements that map to problem-
domain concepts
w E.g., items and products

main()
Products
Receipt
read() add() print() init()

prices PriceList

Items names
receipt n_items

14

14

7
Classes
§ Represent high level concepts
w Often taken from problem domain
§ Are instantiated into Objects
w Define common features of Objects
§ Are related to each other
w Define links and communication patterns
among their instances
§ Can be defined by specialization
w Specific classes inherit from general ones

15

15

Classes

Is related to a
Receipt PriceList

Contains several Contains several

Item
Product
Refers to a

16

16

8
Object-Oriented approach
§ Defines a new component type
w Object (and class)
w Both data and functions accessing it are
within the same module
w Allows defining a more precise interface
§ Defines a new kind of relationship
w Message passing
w Read/write operations are limited to the
same object scope

17

17

Why OO?
§ Programs are getting too large to be fully
comprehensible by any person
§ There is a need for a way of managing
very-large projects
§ Object Oriented paradigm allows:
w programmers to (re)use large blocks of code
w without knowing all the picture
§ OO makes code reuse a real possibility
§ OO simplifies maintenance and evolution

18

18

9
An engineering approach
§ Given a system, with components and
relationships among them, we have to:
w Identify the components
w Define component interfaces
w Define how components interact with each
other through their interfaces
w Minimize relationships among components

20

20

Procedural vs. OO

Procedural
Subprogram
#1 Main Subprogram
Program #2

Data Subprogram
#3 Subprogram
#4

Subprogram
#5

Object #1

Object Oriented Data

Object #2
Main
Program
Data

Object #3

Data

21

21

10
Interface
§ Set of messages an object can receive
w Each message is mapped to an internal
“function” within the object
w The object is responsible for the
association (message à function)
w Any other message is illegal
§ The interface
w Encapsulates the internals
w Exposes a standard boundary

22

22

Interface
§ The interface of an object is simply the
subset of methods that other
“program parts” are allowed to call
w Stable
Interface
Object
method
Other
Rest of method
the method Fields of
parts
Program
method The Object
method
method method

23

23

11
Encapsulation
§ Simplified access
w To use an object, the user need only
comprehend the interface. No knowledge
of the internals are necessary
§ Self-contained.
w Once the interface is defined, the
programmer can implement the interface
(write the object) without interference of
others

24
24

Encapsulation
§ Ease of evolution
w Implementation can change at a later
time without rewriting any other part of
the program (as long as the interface
doesn't change)
§ Single point of change
w Any change in the data structure means
modifying the code in one location, rather
than code scattered around the program
(error prone)

25
25

12
Classification of OO languages
§ Object-Based (Ada)
w Specific constructs to manage objects
§ Class-Based (CLU)
w + each object belongs to a class
§ Object-Oriented (Simula, Python)
w + classes support inheritance
§ Strongly-Typed O-O (C++, Java)
w + the language is strongly typed

26

26

The Object-Oriented Paradigm

UML AND MODELING

27

27

13
UML
§ Unified Modeling Language
§ Standardized modeling and
specification language
§ Defined by the Object Management Group (OMG)
§ Graphical notation to specify, visualize,
construct and document an object-oriented
system
§ Integrates the concepts of Booch, OMT and
OOSE, and merges them into a single,
common and widely used modeling
language

28

28

UML
§ Several diagrams
w Class diagrams
w Activity diagrams
w Use Case diagrams
w Sequence diagrams
w Statecharts

29

29

14
UML Class Diagram
§ Captures
w Main (abstract) concepts
w Characteristics of the concepts
– Data associated to the concepts
w Relationships between concepts
w Behavior of classes

30

30

Abstraction levels
Concept
Entity
Abstract Class
Category
Type
Instance
Item
Concrete Object
Example
Occurrence
31

31

15
Class
§ Represents a set of objects
w Common properties
w Autonomous existence.
w E.g. facts, things, people
§ An instance of a class is an object of
the type that the class represents.
w In an application for a commercial
organization CITY, DEPARTMENT,
EMPLOYEE, PURCHASE and SALE are
typical classes.

32

32

Class - Examples
Class Diagram0
pkg

Employee City

Sale Department

33

16
Object
§ Model of a physical or logical item
w ex.: a student, an exam, a window
§ Characterized by
w identity
w attributes (or data or properties or status)
w operations it can perform (behavior)
w messages it can receive

34
Communication Diagram1 201
sd Communication Diagram1

Object

DAUIN : Department

John : Employee

35

17
Class and Object
§ Class (the description of object
structure, i.e. type):
w Data (ATTRIBUTES or FIELDS)
w Functions (METHODS or OPERATIONS)
w Creation methods (CONSTRUCTORS)
§ Object (class instance)
w State and identity

36

36

Class and object


§ A class is a type definition
w Typically no memory is allocated until an object
is created from the class
§ The creation of an object is called
instantiation. The created object is often
called an instance
§ There is no limit to the number of objects
that can be created from a class
§ Each object is independent. Interacting with
one object doesn't affect the others

37

37

18
Class Diagram0 2013/10/03 powered by Astah
pkg
Communication Diagram1
sd Communication Diagram1

Classes and objects


Employee City

Sale Department

DAUIN : Department

John : Employee

38

Attribute
§ Elementary property of classes
w Name
w Type
§ An attribute associates to each object
(occurrence of a class) a value of the
corresponding type
w Name: String
w ID: Numeric
w Salary: Currency

39

39

19
Attribute – Example
4a-Attributes

pkg
2017/03/09 powered by Astah

Course
- Code : String
- Year : int

Employee
- Salary : Currency City
- Name : String
- Inhabitants : int

40
40

Method
§ Describes an operation that can be
performed on an object
w Name
w Parameters
§ Similar to functions in procedural
languages
§ It represent the means to operate on
or access to the attributes

41

41

20
Method - Example
Class Diagram0
pkg

Employee
- ID : int
- name : String
- salary : double
+ printName() : void
+ getSalary() : double

42

Message passing
§ Objects communicate by message
passing
w Not by direct access to object’s local data
§ A message is a service request

Note: this is an abstract view that is


independent from specific
programming languages.

43

43

21
Messages
Communication Diagram0
sd Communication Diagram0
2014

1: printName()()

DAUIN : Department John : Employee

2: printName() Jane : Employee

44

Association
§ Represents a logical link between two
classes.
§ An occurrence of an association is a
pair made up of the occurrences of the
entities, one for each involved class
w Residence is an association between the
classes City and Employee;
w Exam is an association between the
classes Student and Course.

45

45

22
Associations
Class Association Class
Student between classes Course

Link
between objects

46

Association - Examples
2-Associations

Student Course
Attend

Works_in

Employee City
Residence

47

23
3.a-Recursive associations 2013/1

Recursive association-Samples
pkg

Friend

Student

Supervise

- manager

Employee
- employee

48

Link
§ Model of association between objects

49

24
Multiplicity
§ Describes the maximum and minimum
number of links in which a class
occurrence can participate
w Undefined maximum expressed as *
§ Should be specified for each class
participating in an association

50

Multiplicity - Example

0..4
Max
Min

A car can mount none,


up to four wheels

51

25
Multiplicity - Example

0..1

A wheel can be mounted


on none or at most one car

52

Multiplicity
§ Typically, only three values are used:
0, 1 and the symbol * (many)
§ Minimum: 0 or 1
w 0 means the participation is optional,
w 1 means the participation is mandatory;
§ Maximum: 1 or *
w 1: object is involved in at most one link
w *: each object is involved in many links

53

53

26
Multiplicity
3-Multiplicity

Order Invoice
Sale
1 0..1

Person City
Residence
0..* 1

Tourist Trip
Reservation
1..* 0..*

54

Operational interpretation
SID Name Surname Birthdate CID Title CFU
S2345 John Smith 1990-4-12 C001 Information Systems 8
S12344a-Association+Attributes
Jane Brown 1991-7-11 C002 Advanced Programming 10
2018/10/02 powered by Astah
S5678 pkg
Mario Rossi 1991-11-5 C003 Calculus 10

Student
Course
- SID : String
- CID : String
- Name : String
- Title : String
- Surname : String Attend 0..1
0..* - CFU : float
- Birthdate : Date

C001 C002 C003


Works_in
S2345 X
S1234
Employee X City

S5678
- Name : String X
Residence
- Name : String
- Salary : Currency - Inhabitants : int

55

27
Aggregation
§ B is-part-of A means that objects
described by class B can be attributes
of objects described by A

A B

56

Example
Car Engine
1
power

4 Tyre
1
CD player

57

28
Essential guidelines
§ If a concept has significant properties and/or
describes types of objects with an
autonomous existence, it can be represented
by a class.
§ If a concept has a simple structure, and has
no relevant properties associated with it, it is
likely an attribute of a class.
§ If a concept provides a logical link between
two (or more) entities, it is convenient to
represent it by means of an association.
§ Any operation that implies access to the
attributes of a class should be defined as a
method.

62

Example - Receipt
§ Cash registers emit purchase receipts
§ A receipt is made up of items
§ Every item correspond to a product that
has a name and a price
§ Products’ info is stored in a price list
§ Any time a new product code is entered
the corresponding item is added to the
receipt
§ After the last item is entered, a list of the
items (with product name and price) are
printed together with the total sum.

63

63

29
Class Diagram0 2020/03/08

pkg

Example - Classes

Receipt PriceList

Product
Item
- price : float
- name : string

64

64
Class Diagram0 2020/03/08

pkg

Example - Associations

Receipt PriceList
based on

contains contains

Product
Item
- price : float
refers to - name : string

65

65

30
1/1
Class Diagram0 2020/03/08

pkg

Example - Multiplicity

Receipt PriceList
based on
0..* 1
1 1

contains contains

0..*
0..*
Product
Item
- price : float
refers to - name : string
0..* 1

66

66
Class Diagram0 2020/03/08

pkg

Example - Methods
Receipt
PriceList
+ add(code : int) : void based on
0..* 1 + find(code : int) : Product
+ print() : void

1
1

contains contains

0..*
0..*
Product
Item
- price : float
- name : string
+ getPrice() : float refers to
+ print() : void 0..* 1 + getPrice() : float
+ print() : void

67

67

31
1/1
Example – Messages (Add)
Communication Diagram0 2020/03/08

sd Communication Diagram0

main 1: add(code:int) : void

2: find(code:int) : Product

receipt : Receipt price list : PriceList

3: create()

P1 : Product
P2 : Product
item1 : Item
P3 : Product

68

68
Communication Diagram1 2020/03/08
sd Communication Diagram1

Example – Messages (Print)


main 1: print() : void

receipt : Receipt price list : PriceList

2: print() : void
4: getPrice() : float

5: getPrice() : float P1 : Product


P2 : Product
item1 : Item
P3 : Product

3: print() : void

1/1
69

69

32
INHERITANCE

70

70

Inheritance
§ A class can be a sub-type of another class
§ The inheriting class contains all the
methods and fields of the class it inherited
from plus any methods and fields it defines
§ The inheriting class can override the
definition of existing methods by providing
its own implementation
§ The code of the inheriting class consists
only of the changes and additions to the
base class

71

71

33
Specialization / Generalization
§ B specializes A means that objects
described by B have the same
properties of objects described by A
§ Objects described by B may have
additional properties
§ B is a special case of A
§ A is a generalization of B (and possible
other classes)

72

72

Generalization

73

73

34
Set-Specialization
Inheritance 2015/07/22 powered by Astah
Person
- First : String
- Last : String
- SSN : String

Employee Student
- Salary : Currency - ID : int

Person
Employee
Student

74

Inheritance terminology
§ Class one above
w Parent class
§ Class one below
w Child class
§ Class one or more above
w Superclass, Ancestor class, Base class
§ Class one or more below
w Subclass, Descendent class, Derived class

75

75

35
Why inheritance
§ Frequently, a class is merely a modification
of another class. In this way, there is
minimal repetition of the same code
§ Localization of code
w Fixing a bug in the base class automatically
fixes it in the subclasses
w Adding functionality in the base class
automatically adds it in the subclasses
w Less chances of different (and inconsistent)
implementations of the same operation

76

76

Example of inheritance tree


High DIT makes Living species
code hard to
understand

Animal vegetal

Human being
DIT
Flower

salesman Customer

Flower seller

77

77

36
Twitter (simplified)
§ A registered user can
w Post a tweet
w Follow another user
w Reply to a tweet
w Add a like to a tweet

78

78

Example
Reply

Original

Citation

79

37
Class Diagram0 2019/10/02

pkg

Optional Recursive Associations


citation of

0..* - citator

0..1 Tweet
- original
- text : string
- cited - timestamp : int 0..1

- reply 0..*

reply to

80

Optional Recursive Associations

Tweet
reply
response to

original

citation of

citation

1/1
81

38
Optional Recursive Associations
The model allows this (wrong)
Tweetwhere a tweet is
configuration
at the same time both a
response and a citation reply
Response to
Citation of
original
other
Citation of

citation

82

Class Diagram1 2019/10/02

pkg tot_exc Specialization

Tweet
reply to citation of
- text : string
1 - timestamp : long 1

Total, exclusive

Reply Simple Citation


0..* 0..*

83

39
Specialization
Tweet Simple
Reply

reply Citation

original

citation

84

Class Diagram2
Partial Specialization
pkg par_exc

Tweet
1 1
- text : string
- timestamp : long

reply to citation of
partial, exclusive

Reply Citation
0..* 0..*

85

40
Partial Specialization
Tweet
Citation

reply

original

citation
Reply

86

Essential guidelines (II)


§ If one or more concepts are special
cases of another concept, it is
convenient to represent them by
means of a generalization.
§ When distinct classes may play the
same role w.r.t. an association to a
given class it is common to represent
this commonality by generalization
w Inheritance includes also associations

87

41
Modeling strategies
§ Top-down
w Start with abstract concepts and perform
successive refinements
§ Bottom-up
w Start with detailed concepts and proceed
with integrating different pieces together
§ Inside-out
w Like bottom-up but beginning with most
important concepts first
§ Hybrid

88

Model quality
§ Correctness
w No requirement is misrepresented
§ Completeness
w All requirements are represented
§ Readability
w It is easy to read and understand
§ Minimality
w There are no avoidable elements

89

89

42
References
§ Fowler, M. “UML Distilled: A Brief
Guide to the Standard Object Modeling
Language - 3rded.”, Addison-Wesley
Professional (2003)

90

90

43

You might also like