Post on 01-Jun-2020
transcript
1
Introduction to Programming – Lecture 12
1
Chair of Software Engineering
Introduction to Programming
Bertrand Meyer
Last revised 24 November 2004
Introduction to Programming – Lecture 12
2
Chair of Software Engineering
Lecture 12:The dynamic model
Introduction to Programming – Lecture 12
3
Chair of Software Engineering
Changing values: assignment
target := source
source is an expression:
Call to a query:positionupper_left.position
Arithmetic or boolean expression:a + (b * c)(a < b) and (c = d)
target may be: An attributeResult in a functionA “local variable” of a routine (not yet seen)
2
Introduction to Programming – Lecture 12
4
Chair of Software Engineering
Assignment
Replaces a value by another
x
y
2
0p.set (2, 1)
0
1
p
Introduction to Programming – Lecture 12
5
Chair of Software Engineering
Setting fields (in routines of the class)
classPOSITION
feature – Access
x: REAL-- Horizontal position
y: REAL-- Vertical position
feature – Element change
set (xval, yval: REAL) is-- Set coordinates to (`xval', `yval').
requirex_positive: xval >= 0y_positive: yval >= 0
do
x := xvaly := yval
ensurex_set: x = xvaly_set: y = yval
endend
Introduction to Programming – Lecture 12
6
Chair of Software Engineering
Do not confuse assignment with equality
x := y
if x = y then...
3
Introduction to Programming – Lecture 12
7
Chair of Software Engineering
Effect of an assignment
Reference types: reference assignmentExpanded types: value copy
3class TWO_VALUES feature
item: INTEGERright: TWO_VALUESset (n: INTEGER; r: TWO_VALUES) is
-- Reset both fieldsdo
item := nright := r
endend
t: TWO_VALUES
...
create t
...
t.set (25, Void)
item := nright := r
Introduction to Programming – Lecture 12
8
Chair of Software Engineering
Assignment
class METRO_STATION featurelocation: POSITIONname: STRINGlength: REAL
set_all (p: POSITION; l: REAL; n: STRING) isdo
location := plength := lname := n
endend
Introduction to Programming – Lecture 12
9
Chair of Software Engineering
A linked list of strings
Haldenegg
item right
Central
item right
Haupt-bahnhof
item right
(LINKABLE) (LINKABLE) (LINKABLE)
first_element
last_element
active
count 3
Parade-platz
item right
: inserting at the end
(LINKABLE)
4
Introduction to Programming – Lecture 12
10
Chair of Software Engineering
Inserting an item at the end
extend (v: STRING) is-- Add v to end.-- Do not move cursor.
localp: LINKABLE [STRING]
dop := new_cell (v)if is_empty then
first_element := pactive := p
elselast_element.put_right (p)if after then active := p end
endcount := count + 1
end
Introduction to Programming – Lecture 12
11
Chair of Software Engineering
LINKABLE cells
class LINKABLE featureitem: STRING
-- Value in this cell
right: LINKABLE-- Cell, if any, to which this one is chained
put_right (other: like Current) is-- Put other to the right of current cell.
doright := other
ensurechained: right = other
endend
Haldenegg
item right
Introduction to Programming – Lecture 12
12
Chair of Software Engineering
A linked list of strings
Haldenegg
item right
Central
item right
Haupt-bahnhof
item right
(LINKABLE) (LINKABLE) (LINKABLE)
first_element
last_element
active
count 3
Parade-platz
item right
: inserting at the end
(LINKABLE)
5
Introduction to Programming – Lecture 12
13
Chair of Software Engineering
Local variables (in routines)
A form of entity (they are also called “local entities”)
Just declare them on entry to a routine:
r (...) is-- Header comment
require...
localx: REALm: METRO_STATION
do... Can use x and m here ...
ensure...
end
Local variables include Result for a function
Introduction to Programming – Lecture 12
14
Chair of Software Engineering
Our “maximum” computation
highest_name: STRING is-- Alphabetically greatest station name of line
dofrom
fancy_line.start ; Result := ""until
fancy_line.afterloop
Result := greater (Result, fancy_line.item.name)
fancy_line.forthend
end
Introduction to Programming – Lecture 12
15
Chair of Software Engineering
Initialization
Automatic initialization rules:0 for numbers (integers, reals)“Null” character for charactersFalse for booleans
Void for references
These rules apply to:Fields (from class attributes), on object creationLocal variables, on start of routine execution
(includes Result)
6
Introduction to Programming – Lecture 12
16
Chair of Software Engineering
Is this OK?
In class METRO_STATION:
is_greater (m: METRO_STATION): BOOLEAN is-- Does current station -- have a higher name than m?
doif name > m.name then
Result := Trueend
end
Introduction to Programming – Lecture 12
17
Chair of Software Engineering
The trouble with reference assignment
A comfortable mode of reasoning:
-- Here SOME_PROPERTY holds of a
“Apply SOME_OPERATION to b”
-- Here SOME_PROPERTY still holds of a
This applies to “expanded” values, e.g. integers
-- Here P (a) holds
OP (b)
-- Here P (a) still holds of a
Introduction to Programming – Lecture 12
18
Chair of Software Engineering
Dynamic aliasing
a, b: LINKABLE [STRING]
create a....
b := a
a.put ("Haldenegg")
-- Here a.item has value "Haldenegg"
b.put ("Paradeplatz")
-- Here a.item has value ?????
Haldenegg
item right
a b
7
Introduction to Programming – Lecture 12
19
Chair of Software Engineering
On the other hand...
-- I heard that the boss’s cousin earns less-- than 50,000 francs a year
“Raise Caroline’s salary by 1 franc”
-- ?????
Metaphors:“The beautiful daughter of Leda”“Menelas’s spouse”“Paris’s lover”
= Helen of Troy
Introduction to Programming – Lecture 12
20
Chair of Software Engineering
Practical advice
Reference assignment is useful
It’s also potentially tricky
As much as possible, leave it to specialized libraries of general data structures
Introduction to Programming – Lecture 12
21
Chair of Software Engineering
Variants of assignment and copy
Reference assignment (a and b of reference types):
b := a
Object duplication (shallow): c := clone (a)
Object duplication (deep): d := deep_clone (a)
Also: shallow field-by-field copy (no new object is created):
e.copy (a)
8
Introduction to Programming – Lecture 12
22
Chair of Software Engineering
Shallow and deep cloningInitial situation:
Result of:
b := a
c := clone (a)
d := deep_clone (a)
“Almaviva”namelandlord
loved_one
O1
“Figaro”O2 “Susanna”O3
b
“Almaviva”O4
c
“Almaviva”O5
“Figaro”O6 “Susanna”O7
d
a
Introduction to Programming – Lecture 12
23
Chair of Software Engineering
Where do these mechanisms come from?
Class ANY in the Eiffel “Kernel Library”
Every class that doesn’t explicitly inherit from another is considered to inherit from ANY
As a result, every class is a descendant of ANY.
Introduction to Programming – Lecture 12
24
Chair of Software Engineering
Completing the inheritance structure
A B
D E
C
ANY
NONE
Inheritsfrom
9
Introduction to Programming – Lecture 12
25
Chair of Software Engineering
A related mechanism: Persistence
a.store (file)....b ?= retrieved (file)
Storage is automatic. Persistent objects identified individually by keys.
These features come from the library class STORABLE.
Introduction to Programming – Lecture 12
26
Chair of Software Engineering
Setter procedures
set_attribute procedure, e.g.
set_temperature (u: REAL) is-- Set temperature value to u.
dotemperature := u
ensuretemperature_set: temperature = u
end
Client will use e.g. x.set_temperature (21.5).
Client cannot directly assign to attribute
Introduction to Programming – Lecture 12
27
Chair of Software Engineering
Other uses of a setter procedure
set_temperature (u: REAL) is-- Set temperature value to u.
requirenot_under_minimum: u >= -273not_above_maximum: u <= 2000
dotemperature := uupdate_database
ensuretemperature_set: temperature = u
end
10
Introduction to Programming – Lecture 12
28
Chair of Software Engineering
Information hiding
class A
feature
f ...g ...
feature {NONE}
h ...
feature {B, C}
j ...
feature {A, B, C}
k
end
In clients, with the declaration a1: A, we have:
a1.f, a1.g: valid in any client
a1.h: invalid anywhere (including in A’s own text).
a1.j: valid only in B, C and their descendants(not valid in A!)
a1.k: valid in B, C and their descendants, as well as in A and its descendants
Introduction to Programming – Lecture 12
29
Chair of Software Engineering
An example of selective export
LINKABLE exports its features to LINKED_LISTDoes not export them to the rest of the worldClients of LINKED_LIST don’t need to know about LINKABLE cells.
Haldenegg
item right
Central
item right
Haupt-bahnhof
item right
first_element
active
count 3
Introduction to Programming – Lecture 12
30
Chair of Software Engineering
Exporting selectively
classLINKABLE [G]
feature {LINKED_LIST}
put_right (...) is do ... end
right: G is do ... end
...end
11
Introduction to Programming – Lecture 12
31
Chair of Software Engineering
Objects and references
States of a reference:
Operations on references: create pp := qp := Voidif p = Void then ...
VOID ATTACHED
create p
p := q (where q is attached)
p := Void
p := q (where q is void)
p ATTACHED
p VOID
Introduction to Programming – Lecture 12
32
Chair of Software Engineering
What to do with unreachable objects
Reference assignmentsmay make some objects useless.
Two possible approaches:Manual “free” (C++).Automatic garbage collection (Eiffel, Oberon, Java, .NET)
“Almaviva”namelandlord
loved_one
aO1
“Figaro”O2
“Susanna”O3
Introduction to Programming – Lecture 12
33
Chair of Software Engineering
The C programmer’s view
Newsgroup posting by Ian Stephenson, 1993 (as cited in Object-Oriented Software Construction, 2nd
edition):
I say a big NO! Leaving an unreferenced object around is BAD PROGRAMMING. Object pointers ARE like ordinary pointers — if you allocate an object you should be responsible for it, and free it when its finished with. (Didn't your mother always tell you to put your toys away when you'd finished with them?)
12
Introduction to Programming – Lecture 12
34
Chair of Software Engineering
Arguments for automatic collection
Manual reclamation is dangerous for reliability.
Wrong “frees” are among the most difficult bugs to detect and correct.
Manual reclamation is tedious.
Modern garbage collectors have acceptable performance overhead.
GC is tunable: disabling, activation, parameterization....
Introduction to Programming – Lecture 12
35
Chair of Software Engineering
Properties of a garbage collector (GC)
Consistency (never reclaim a reachable object). Completeness (reclaim every unreachable object –eventually).
Consistency (also called safety) is an absolute requirement. Better no GC than an unsafe GC.
But: safe automatic garbage collection is hard in C-based languages.
Introduction to Programming – Lecture 12
36
Chair of Software Engineering
Two kinds of type
Reference types; value of an entity is a reference. Example:b: POINT
Expanded types; value of an entity is an object. Example:d: expanded POINT
b
(POINT)
d
(POINT)
13
Introduction to Programming – Lecture 12
37
Chair of Software Engineering
Expanded classes
A class may also be declared as expanded class C
... The rest as usual ...
Then you can declare:a: C
with the same effect asb: expanded C
in the earlier syntax (still permitted, with same meaning).
Introduction to Programming – Lecture 12
38
Chair of Software Engineering
Basic types as expanded classes
expanded class INTEGER ... expanded class BOOLEAN ... expanded class CHARACTER ... expanded class REAL ... expanded class DOUBLE ...
n: INTEGER
Introduction to Programming – Lecture 12
39
Chair of Software Engineering
The object-oriented form of call
some_target.some_feature (some_arguments)
For example:
Paris.displayLine6.extend (Station_Parade_Platz)
x := a.plus (b) ???????
14
Introduction to Programming – Lecture 12
40
Chair of Software Engineering
Infix and prefix operators
In
a − bthe − operator is “infix”
(written between operands)
In
− bthe − operator is “prefix”
(written before the operand)
Introduction to Programming – Lecture 12
41
Chair of Software Engineering
Infix and prefix operators
expanded classINTEGER
feature
infix "+" (other: INTEGER): INTEGER is-- Sum with other
do...
end
infix "*" (other: INTEGER): INTEGER is -- Product by other
do...
end
prefix "–": INTEGER is-- Unary minus
do...
end
...end
Calls are then of the form i + j rather than i.plus (j).
Introduction to Programming – Lecture 12
42
Chair of Software Engineering
End of lecture 12