Eif f el: Analysis, Design and Programming
Bertrand Meyer (Nadia Polikarpova)
Chair of Softw are Engineering
Eif f el: Analysis, Design and Programming Bertrand Meyer (Nadia - - PowerPoint PPT Presentation
Eif f el: Analysis, Design and Programming Bertrand Meyer (Nadia Polikarpova) Chair of Softw are Engineering - 8 - I nherit ance 2 Ove verview rview Basics Redef init ion Polymor phism and dynamic binding I nherit ance
Chair of Softw are Engineering
2
3
Ove verview rview
Basics Redef init ion Polymor phism and dynamic binding I nherit ance and cont ract s Def erred classes Polymorphic cont ainers I nher it ance and genericit y: const rained gener icit y Mult iple inherit ance Non-conf or ming inher it ance Covar iance and anchor ed t ypes
4
Ext Exten endi ding ng the bas the basic ic noti notion
LIST_OF_ CARS BAG_OF_ CARS
LINKED_LIST_ OF_CARS LIST_OF_ CITIES
LIST_OF_ PERSONS
Abst ract ion Specializat ion Type paramet er izat ion Type paramet er izat ion
Genericity I nheritance
5
Inher nherita itance ba nce basi sics cs
Principle: Describe a new class as ext ension or specializat ion of an exist ing class (or sever al wit h multiple inherit ance) I f B inherit s f rom A : As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) As t ypes: whenever an inst ance of A is r equired, an inst ance of B will be accept able (“is-a” relat ionship)
6
Te Termin rminology
I f B inherit s f rom A (by list ing A in it s inherit clause): B is an heir of A A is a parent of B For a class A: The descendants of A ar e A it self and (recursively) t he descendant s of A ’s heir s Proper descendants exclude A it self Rever se not ions: Ancestor Proper ancestor Mor e pr ecise not ion of inst ance: Direct instances of A I nstances of A : t he dir ect inst ances
(Ot her t er minology: subclass, superclass, base class)
B A C D E
7
Wha What t you can you can do to inhe do to inheri rite ted d feat featur ures
Ef f ect (implicit ) Redef ine Undef ine Rename Change expor t st at us Select
8
Example Example hierarch hierarchy
cent er* per imet er* per imet er +
. . . . . .
* def erred + ef f ect ive ++ redef ined display* r ot at e* move*
* FI GURE * OPEN_FI GURE * CLOSED_FI GURE SEGMENT POLYLI NE + ELLI P SE CI RCLE + POLYGON TRI ANGLE SQUARE RECTANGLE
per imet er + display + r ot at e + move + per imet er ++ side1 side2 diagonal per imet er ++ display + r ot at e + move + per imet er ++ display ++ r ot at e ++ move ++
9
Re Redefin definition ition
Class may redef ine (“override”) inherit ed f eat ures Redef init ion is explicit I n line wit h Unif or m Access principle, may redef ine inher it ed f unct ion int o at t ribut e Not t he ot her way around!
10
Re Redefin definition ition 1: 1: pol polygon ygons
class POLYGON inherit CLOSED_FI GURE create make f eature ver t ex : ARRAY [POI NT] vert ex_count : I NTEGER per imet er : REAL is
er imet er lengt h do f rom ... until ... loop Result := Result + ver t ex [i ] . dist ance (ver t ex [i + 1]) ... end end invariant vert ex_count > = 3 vert ex_count = ver t ex.count end
ver t ex [i ] ver t ex [i + 1]
11
Re Redefin definition ition 2: 2: rec rectang tangles les
class RECTANGLE inherit POLYGON redef ine per imet er end create make f eature diagonal, side1, side2 : REAL per imet er : REAL is
er imet er lengt h do Result := 2 (side1 + side2) end invariant vert ex_count = 4 end side1 side2 diagonal
12
(POLYGON) (RECTANGLE)
p r
p : POLYGON ; r : RECTANGLE ; t : TRI ANGLE x : REAL Permit t ed: x := p.perimet er x := r.perimet er x := r.diagonal p := r NOT permit t ed: x := p.diagonal
r := p
13
Dynamic bin Dynamic binding ding
What is t he ef f ect of t he f ollowing (if some_t est is t rue)?
if some_t est then
p := r
else
p := t
end
x := p.perimet er Redef init ion: A class may change an inherit ed f eat ure, as wit h POLYGON redef ining perimet er . Polymorphism: p may have dif f er ent f orms at run-t ime. Dynamic binding: Ef f ect of p.perimet er depends on run- t ime f orm of p.
14
Wit Witho hout dy t dynam namic bi c bindi nding? g? display (f : FI GURE)
do if “f is a CI RCLE” then
...
elseif “f is a POLYGON” then
...
end end
and similarly f or all ot her rout ines! Tedious; must be changed whenever t here’s a new f igure t ype
15
With in With inherit heritanc ance an e and associated techniq d associated technique ues
Wit h: I nit ialize: and: Then j ust use: f : FI GURE c : CI RCLE p : POLYGON
create c.make (...) create p.make (...) if ... then
f := c
else
f := p
end
f.move (...) f.rot at e (...) f.display (...)
16
Binding Binding
Binding is t he process in which A rout ine invocat ion f (a), x.f (a) is connect ed t o code t hat is execut ed Accessing or writ ing t o a variable a a := E is connect ed a memor y locat ion.
17
Stat Static v c vs. dynam
ic bind bindin ing
I f binding is done at compile t ime, t his is called “St at ic Binding” using “St at ic Linking”. I f binding is done at progr am load t ime, t his is called “St at ic Binding” using “Dynamic Linking”. I f binding is done at runt ime t his is called “Dynamic Binding”.
18
Stat Static Bind c Bindin ing g in C in C
I n t he .h header f ile:
extern int f oo (ar g c); ext ern f loat my_variable;
I n t he .c f ile:
int f oo (ar g c); f loat my_variable;
19
Execution n of f a a call l in n C
On t he caller side: Push t he argument s on t he st ack Push t he current PC + 1 on t he st ack (ret urn address) J ump t o t he code t o execut e This is “f illed out ” dur ing linking/ binding Clean t he st ack
20
Exec Executio ution of a n of a ca call in C ll in C (cont.) (cont.)
On t he callee side: Add some ext r a memory on t he st ack f or t he local var iables I nit ialize t he local variables (if necessary) Execut e t he implement at ion of t he r out ine Read t he r et urn address f rom t he st ack J ump t o t he ret urn address
21
Dyna Dynamic Bind c Bindin ing g in non-O in non-OO
Dynamic binding is not exclusive f or obj ect -or ient at ion: Lisp (1958) For t h (1970) - a mixt ure called “Threaded Code” C (1970) - Why ?
22
Dyna Dynamic Bind c Bindin ing g in C in C
# include < st dio.h> void hello () { print f ("Hello\ n"); } void wor ld () { print f ("World\ n"); } int main (int argc, char **argv) { void (*f unc)(void); if (argc > 1) f unc = hello; else f unc = wor ld; f unc (); / * Dynamic Binding */ }
23
Dyna Dynamic Bind c Bindin ing g and OO and OO
We need dynamic binding in obj ect -orient at ion I dent if iers used in progr am t ext are r elat ive t o t he curr ent
At t r ibut es are r elat ive t o Current Rout ines may be redef ined in subclasses
24
Using c Using cla lass tables ss tables
Class Table Point er I nt eger Field I nt eger Field I nt eger Field Class A Point er t o f eat ure f Point er t o f eat ur e g
class t able
class A f eature
a,b,c : I NTEGER f is
do
c := a + b g
end
g is ...
end
25
Wi With inheritanc th inheritance
Class Table Point er I nt eger Field I nt eger Field I nt eger Field Class B Point er t o f eat ure f Point er t o f eat ure g Boolean Field Point er t o f eat ure h A B
class B inherit A redef ine f f eature
d: BOOLEAN f is ... h is ...
end
26
Contracts and in Contracts and inherita heritance nce
I ssue: what happens, under inherit ance, t o
Class invariant s? Rout ine precondit ions and post condit ions?
27
Inva nvariants riants
I nvar iant I nherit ance rule:
The invariant of a class aut omat ically includes t he
invariant clauses f r om all it s parent s, “and”-ed. Accumulat ed result visible in f lat and int erf ace f or ms.
28
Contracts and in Contracts and inherita heritance nce
r require
require
a1.r (… ) …
Cor rect call in C:
if a1. t hen
a1.r (...)
end
r ++
C A D B
client of inherit s f rom ++ redef init ion
29
Assertion redeclar Assertion redeclaratio ation rule n rule
When redeclar ing a r out ine, we may only:
Keep or weaken t he precondit ion Keep or st r engt hen t he post condit ion
30
A simple language rule does t he t rick! Redef ined ver sion may have not hing (assert ions kept by def ault ), or require else new_pr e ensure then new_post Result ing assert ions are:
Assertion Assertion redeclarat redeclaration rule in ion rule in Eif Eiffel fel
31
The ro The role of le of deferred classes deferred classes
Express abst ract concept s independent ly of implement at ion Express common element s of various implement at ions Terminology: Ef f ective = non-def erred (i.e. f ully implement ed)
32
I n e.g. LI ST: f or t h
def erred end
A A de defe ferred fe rred feature ature
ensure
index = old index + 1
require not af t er
33
Def er r ed!
I n t he same class search (x : G)
do f rom until af t er or else it em = x loop
f or t h
end end “Programs with holes”
Mixing Mixing deferre deferred and effectiv d and effective featur e features es
Ef f ect ive!
34
“Do “Don’ n’t call t call us, we’l us, we’ll l call you! call you!”
A powerf ul f orm of reuse:
The reusable element def ines a general scheme Specif ic cases f ill in t he holes in t hat scheme
Combine r euse wit h adapt at ion
35
Defe Deferr rred clas d classe ses in Eiff s in Eiffel elBa Base se
CONTAI NER
*
BOX
*
COLLECTI ON
*
TRAVERSABLE
*
FI NI TE
*
I NFI NI TE
*
BOUNDED
*
UNBOUNDED
*
COUNTABLE
*
RESI ZABLE
*
BAG
*
SET
*
HI ERARCHI CAL
*
LI NEAR
*
TABLE
*
ACTI VE
*
I NTEGER_ I NTERVAL
*
BI LI NEAR
*
I NDEXABLE
*
CURSOR_ STRUCTURE
*
DI SPENSER
*
SEQUENCE
*
ARRAY STRI NG HASH_TABLE STACK
*
QUEUE
*
… …
* def erred
36
def erred class VAT inherit TANK f eature in_valve, out _valve: VALVE f ill is
require in_valve.open
def erred ensure in_valve.closed
is_f ull end empt y, is_f ull, is_empt y, gauge, maximum, ... [Ot her f eat ures] ... invariant is_f ull = (gauge > = 0.97 * maximum) and (gauge < = 1.03 * maximum) end
Defe Deferr rred cla d classes es for an for anal alys ysis is
37
Polymor Polymorph phic data structures ic data structures
class LI ST [G] f eature ... last : G is ... ext end (x: G) is ... end f l: LI ST [FI GURE] r : RECTANGLE s: SQUARE t : TRI ANGLE p: POLYGON ... f l.ext end (p); f l.ext end (t ); f l.ext end (s); f l.ext end (r ) f rom f l.st ar t until f l.af t er loop f l.it em.display; f l.f ort h end
(SQUARE) (RECTANGLE) (TRI ANGLE) (POLYGON)
f l
38
Figure hierar Figure hierarchy (remin chy (reminder) der)
cent er* per imet er* per imet er +
. . . . . .
* def erred + ef f ect ive ++ redef ined display* r ot at e* move*
* FI GURE * OPEN_FI GURE * CLOSED_FI GURE SEGMENT POLYLI NE + ELLI P SE CI RCLE + POLYGON TRI ANGLE SQUARE RECTANGLE
per imet er + display + r ot at e + move + per imet er ++ side1 side2 diagonal per imet er ++ display + r ot at e + move + per imet er ++ display ++ r ot at e ++ move ++
39
Enforcing Enforcing a a type: th type: the pro e problem blem
f l.st or e ("FI LE_NAME") ...
f l := ret rieved ("FI LE_NAME“) x := f l.last
print (x.diagonal )
What ’s wr ong wit h t his?
I f x is declared of t ype RECTANGLE, [1] is invalid. I f x is declared of t ype FI GURE, [2] is invalid.
40
Obj ect -Test Local
Enforcing g a a type: : the e Object t Test
if attached {RECTANGLE } f l.last as r then
print (r.diagonal ) … Do anyt hing else wit h r , guarant eed t o be non-void … and of dynamic t ype (descendant of ) RECTANGLE
else
print ("Too bad.")
end
Expr ession t o be t est ed SCOPE of t he Obj ect -Test Local Opt ional (if omit t ed j ust t est s f or void)
41
Earlier mechan Earlier mechanism ism: assignmen : assignment attempt t attempt
f : FI GURE r : RECTANGLE ... f l.r et r ieve ("FI LE_NAME") f := f l.last r ?= f
if r / = Void t hen
print (r.diagonal )
else
print ("Too bad.")
end
42
As Assi signment a gnment att ttempt empt
x ?= y wit h x : A Semant ics:
I f y is at t ached t o an obj ect whose t ype conf or ms t o
A, perf or m normal r ef erence assignment .
Ot herwise, make x void.
43
What we h What we have seen ave seen
Basics Redef init ion Polymor phism and dynamic binding I nherit ance and cont ract s Def erred classes Polymorphic cont ainers
44
Top Topic ics for t s for today
I nher it ance and genericit y: const rained gener icit y Mult iple inherit ance Non-conf or ming inher it ance Covar iance and anchor ed t ypes
45
Inherit Inheritanc ance + Ge + Generi nericity city
Unconst rained genericit y LI ST [G] e.g. LI ST [I NTEGER], LI ST [PERSON] Const r ained gener icit y HASH_TABLE [G, H > HASHABLE ] VECTOR [G > NUMERI C ]
46
Constraine Constrained genericity d genericity
class VECTOR [G ] f eature plus alias "+" (ot her : VECTOR [G]): VECTOR [G]
require lower = ot her.lower upper = ot her.upper local a, b, c: G do ... See next ... end ... Ot her f eat ur es ... end
47
Adding two vectors Adding two vectors i a b c = + i a b c = + + = u v w
1 2
48
Constraine Constrained genericity d genericity
Body of plus alias "+":
create Result.make (lower, upper ) f rom
i := lower
until
i > upper
loop
a := it em (i ) b := ot her.it em (i ) c := a + b
Result.put (c, i )
i := i + 1
end
49
The s The solut
ion
Declare class VECTOR as
class VECTOR [G –> NUMERI C] f eature
... The rest as bef ore ...
end
Class NUMERI C (f rom t he Kernel Library) provides f eat ures plus alias "+", minus alias "-"and so on.
50
Im Impro proving the solution ving the solution
Make VECTOR it self a descendant of NUMERI C, ef f ect ing t he corr esponding f eat ures:
class VECTOR [G –>
NUMERI C] inherit NUMERI C
f eature
... Rest as bef ore, including inf ix "+"...
end
Then it is possible t o def ine v : VECTOR [I NTEGER ] vv : VECTOR [VECTOR [I NTEGER ]] vvv : VECTOR [VECTOR [VECTOR [I NTEGER]]]
51
In the end In the end.. ...
Genericit y is always const rained because LI ST [G] is j ust an abbr eviat ion of LI ST [G -> ANY]
52
Combining abstracti Combining abstractions
Given t he classes
TRAI N_CAR, RESTAURANT
how would you implement a DI NER?
53
Examples of m Examples of multipl ultiple inheritan e inheritance ce
Combining separat e abst ract ions:
Rest aurant , t r ain car Calculat or , wat ch Plane, asset Home, vehicle Tram, bus
54
Com Composite fig posite figures ures
55
Multiple in Multiple inherit heritance ance: Co : Compos mposite figures ite figures
A composite figure Simple figures
56
De Definin fining the n g the notion of
compos mposite figure ite figure
COMPOSI TE_ FI GURE
cent er display hide r ot at e move … count put r emove …
FI GURE LI ST [FI GURE]
57
In In the the ove
rall structure
COMPOSI TE_ FI GURE FI GURE LI ST [FI GURE]
OPEN_ FI GURE CLOSED_ FI GURE SEGMENT POLYLI NE P OLYGON ELLI PSE RECTANGLE SQUARE CI RCLE TRI ANGLE per imet er + per imet er* per imet er ++ diagonal per imet er ++ per imet er ++ per imet er +
58
A comp A composit ite e figu figure re as a list as a list
Cur sor it em f or t h af t er bef or e
59
Com Composite fig posite figures ures
class COMPOSI TE_FI GURE inherit
FI GURE LI ST [FI GURE]
f eature
display
do f rom st ar t until af t er loop
it em.display f or t h
end end
... Similarly f or move, rot at e et c. ...
end
Requir es dynamic binding
60
Goin Going g one lev
el of abstr
acti tion hig n highe her
A simpler f orm of procedures display, move et c. can be
Use agent s f or t hat pur pose
61
Multipl Multiple inheritance e inheritance: Combining : Combining abstraction abstractions
COMPARABLE NUMERI C STRI NG COMPLEX I NTEGER REAL
< , < =, > , > =, … +, –, , / …
(t ot al or der r elat ion) (commut at ive r ing)
62
The Jav The Java- a-C# solu # soluti tion
No mult iple inher it ance f or classes “I nt er f aces”: specif icat ion only (but no cont r act s)
Similar t o complet ely def erred classes (wit h no
ef f ect ive f eat ure) A class may inherit f rom:
At most one class Any number of int erf aces
63
Multipl Multiple inheritance e inheritance: Combining : Combining abstraction abstractions
COMPARABLE NUMERI C STRI NG COMPLEX I NTEGER REAL
< , < =, > , > =, … +, –, , / …
(t ot al or der r elat ion) (commut at ive r ing)
64
How How do we writ do we write e CO COMPARABLE MPARABLE?
def erred class COMPARABLE [G] f eature end
less alias "< " (x : COMPARABLE [G]): BOOLEAN
def erred end
less_equal alias "< =" (x : COMPARABLE [G]): BOOLEAN
do Result := Current <
x or Current ~ x
end
great er alias "> " (x : COMPARABLE [G]): BOOLEAN
do Result := x <
Current end
great er _equal alias "> =" (x : COMPARABLE [G ]): BOOLEAN
do Result := x <
= Current end
65
Less Lesson
s from t
his exampl ple
Typical example of progr am wit h holes We need t he f ull spect rum f r om f ully abst r act (f ully def err ed) t o f ully implement ed classes Mult iple inher it ance is t here t o help us combine abst r act ions
66
Mu Multip ltiple i le inheri heritance: N tance: Name c me clashes shes f C f
A B
67
Re Resolving nam solving name cl e clashes ashes f
rename f as A_f
C f
A B
A_f , f
68
Conseque Consequences nces of
renaming a1: A b1: B c1: C ... c1.f c1.A_f a1.f b1.f
rename f as A_f C f A B A_f , f f
I nvalid:
a1.A_f b1.A_f
69
Are Are all name all name clas clashe hes bad s bad?
A name clash must be r emoved unless it is:
Under repeat ed inherit ance (i.e. not a real clash) Bet ween f eat ures of which at most one is ef f ect ive
(i.e. ot hers are def er red)
70
Featur Feature me e mergin rging A B C D f +
f * f * Def erred + Ef f ect ive
71
Featur Feature me e mergin rging: with dif g: with differe ferent names nt names A B C D h +
g * f * Def erred + Ef f ect ive Renaming g f h f
class D inherit A rename g as f end B C rename h as f end f eature ... end
72
Featur Feature merging: e merging: effective feature effective features A B C D f + f + f +
Def erred + Ef f ect ive
f -- f --
73
Un Undefin definition ition
def erred class
T
inherit
S
undef ine v end f eature
...
end
74
Mer Merging ging thro through ugh un undefinit definition ion
class D inherit A undef ine f end B C undef ine f end f eature ... end
A B C D f + f + f + f -- f --
Def erred + Ef f ect ive
75
Merging effective feature Merging effective features with di s with different fferent na names mes A B C D h + f + g + f -- f --
class D inherit A undef ine f end B rename g as f undef ine f end C rename h as f end f eature ... end
h f g f
76
Accepta Acceptable ble na name clashes me clashes
I f inherit ed f eat ures have all t he same names, t here is no harmf ul name clash if : They all have compat ible signat ur es At most one of t hem is ef f ect ive Semant ics of such a case: Merge all f eat ures int o one I f t here is an ef f ect ive f eat ure, it imposes it s implement at ion
77
Featur Feature merging: e merging: effective feature effective features
a1: A b1: B c1: C d1: D a1.g b1.f c1.h d1.f
A B C D g+ f + h+ g f h f f - f -
78
A A spe special case of cial case of mu multiple ltiple in inherita heritance nce
TEACHER STUDENT ASSI STANT UNI VERSI TY _MEMBER
id This is a case of repeat ed inher it ance
?? ?? ????
79
Indirec Indirect and di t and direct repeat rect repeated inherit ed inheritanc ance
A D B C A D
80
Multiple is Multiple is al also rep so repeate eated inheritanc d inheritance
A t ypical case: copy ++ is_equal ++
copy is_equal
?? copy C_copy is_equal C_is_equal C LI ST D ANY
81
Sha Sharing ring an and re d replicatio plication
Feat ures such as f , not renamed along any of t he inherit ance pat hs, will be shared. Feat ures such as g, inher it ed under dif f erent names, will be replicat ed.
A B C D f g g g_b g g_c
82
The nee The need d for s for selec elect
A pot ent ial ambiguit y ar ises because of polymor phism and dynamic binding: a1: ANY d1: D … a1 := d1 a.copy (… )
copy ++ is_equal ++ copy C_copy is_equal C_is_equal
C LI ST D
copy is_equal
ANY
83
Removing th Removing the a e ambiguity mbiguity
class
D
inherit
LI ST [T ]
select
copy, is_equal
end
C
rename
copy as C_copy, is_equal as C_is_equal, ...
end
84
Whe When n is a name is a name clas clash h acce accept ptabl ble?
(Bet ween n f eat ures of a class, all wit h t he same name, immediat e or inherit ed.)
They must all have compat ible signat ures. I f more t han one is ef f ect ive, t hey must all come
f rom a common ancest or f eat ure under repeat ed inher it ance.
85
Another Another app applicatio lication of r n of renaming enaming
Provide locally bet t er adapt ed t erminology. Example: child (TREE ); subwindow (WI NDOW)
86
Multiple In Multiple Inherit heritan ance and C ce and Class T lass Tables ables
87
The dy The dynam namic ic bind bindin ing fun g funct ctio ion
88
The dy The dynam namic ic bind bindin ing fun g funct ctio ion
89
The dy The dynam namic ic bind bindin ing fun g funct ctio ion
90
Featu Feature Tables re Tables
f of A g of A h of B g of C A B C Dynamic Type St at ic Type Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er Code Point er
91
Non-confor Non-conformi ming inheritanc ng inheritance
class ARRAY [G] f eature ... lower , upper : I NTEGER r esize (l, u: I NTEGER) ensure lower = l; upper = u end class ARRAYED_LI ST [G] inherit LI ST [G] ARRAY [G] ... invariant st ar t s_f r om_1: lower = 1 end a: ARRAY [I NTEGER]; l: ARRAYED_LI ST [I NTEGER] ... a := l a.r esize (-10, 10)
ARRAYED_LI ST LI ST ARRAY
Class invar iant violat ion
92
Inher nherita itance ba nce basi sics: e cs: exte xtended nded
I f B inherit s f rom A : As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) As t ypes: whenever an inst ance of A is r equired, an inst ance of B will be accept able (“is-a” relat ionship) I f B inherit s f rom A in a non-conf orming way: As modules: all t he services of A are available in B (possibly wit h a dif f er ent implement at ion) No relat ionship bet ween t ypes!
93
Non-confor Non-conformi ming inheritanc ng inheritance
class ARRAYED_LI ST [G] inherit LI ST [G] inherit {NONE} ARRAY [G] ... invariant st ar t s_f r om_1: lower = 1 end a: ARRAY [I NTEGER]; l: ARRAYED_LI ST [I NTEGER] ... a := l a.r esize (-10, 10)
ARRAYED_LI ST LI ST ARRAY
Non-conf or ming inher it ance Not allowed
94
No n No need for eed for select select
count count capacit y
ARRAY LI ST ARRAYED_LI ST FI NI TE Pot ent ial ambiguit y is r esolved is f avor of conf orming parent : f : FI NI TE [...] al: ARRAYED_LI ST [...] … f := al print (f .count )
Ver sion f r om LI ST
95
Covarian Covariance ce
class LI ST [G] f eature cur sor : CURSOR go_t o (c: CURSOR) is do …end … end class LI NKED_LI ST [G] inherit LI ST [G] redef ine cursor , go_t o, ... end f eature cur sor : LI NKED_CURSOR go_t o (c: LI NKED_CURSOR) is do …end … end
LI NKED_LI ST LI ST LI NKED_CURSOR CURSOR
96
Ancho Anchore red types d types
class LI ST [G] f eature cur sor : CURSOR go_t o (c: like cur sor ) is do …end … end class LI NKED_LI ST [G] inherit LI ST [G] redef ine cur sor , ... end f eature cur sor : LI NKED_CURSOR
… end
97
Sema Semantic ics of an s of anch chore red d ty types pes
I n class C : x: SOME_TYPE y: like x I n class C, y is t reat ed exact ly as wit h y: SOME_TYPE I n a descendant D of C, if x has been redeclared t o some
98
Type re Type redefin definitio ition rule n rule
Eif f el: covar iant redef init ion of result (may change t ype t o a descendant of t he or iginal t ype) covar iant redef init ion of ar gument s Tradit ional not ion of subt yping : covar iant redef init ion of result cont r avar iant redef init ion of argument s (may change t ype t o an ancest or of t he or iginal t ype) Cont ravariant redef init ion: saf e but useless
99
Th The p e pro roblem w blem with th cova variance riance
list : LI ST [...] linked_list : LI NKED_LI ST [...] c: CURSOR … list := linked_list list .go_t o (c)
class LI ST f eature cursor: CURSOR go_t o (c: like cursor ) is do … end … end class LI NKED_LI ST inherit LI ST redef ine cursor, ... end f eature cursor: LI NKED_CURSOR
… end
Cat call!
100
CAT CAT call calls
CAT st ands f or Changing Availabilit y or Type A rout ine is a CAT if some redef init ion changes it s expor t st at us or t he t ype of any of it s ar gument s A call is a cat call if some redef init ion of t he rout ine would make it invalid because of a change of export st at us
101
Cat Catcall ll cas cases es
Covar iant redef init ion of argument s
Descendant hiding (in earlier versions of Eif f el)
102
Covarian Covariant redefinit t redefinition ion: non-gen : non-generi eric ca c case se
class ANI MAL f eature
eat (a_f ood: FOOD)
def erred end end class WOLF inherit ANI MAL redef ine eat end f eature
eat (a_meat : MEAT)
do … end end
WOLF ANI MAL FOOD MEAT GRASS
103
animal: ANI MAL wolf : WOLF f ood: FOOD grass: GRASS
create wolf create grass
animal := wolf f ood := grass animal.eat (grass)
Covarian Covariant redefinit t redefinition ion: non-gen : non-generi eric ca c case se
WOLF ANI MAL FOOD MEAT GRASS
104
animal_list : LI NKED_LI ST [ANI MAL] sheep_list : LI NKED_LI ST [SHEEP] sheep: SHEEP wolf : WOLF sheep_list .ext end (sheep) animal_list := sheep_list animal_list .ext end (wolf )
Cov Covar arian ant t rede redefi finit itio ion: gen : gener eric cas c case
WOLF ANI MAL SHEEP
105
class LI NKED_LI ST [ANY] f eature ext end (v: ANY) do …end end class LI NKED_LI ST [SHEEP] f eature ext end (v: SHEEP) do …end end class LI NKED_LI ST [WOLF] f eature ext end (v: WOLF) do …end end
Cov Covar arian ant t rede redefi finit itio ion: gen : gener eric cas c case
106
class RECTANGLE inherit POLYGON export {NONE}
add_vert ex
end
…
invariant
ver t ex_count = 4
end
r : RECTANGLE; p: POLYGON ... p := r p.add_ver t ex (...)
Descend scendant h ant hidi ding ng
RECTANGLE POLYGON
Ear lier : cat call! Now: not allowed
107
class RECTANGLE inherit {NONE} POLYGON export {NONE}
add_vert ex
end
…
invariant
ver t ex_count = 4
end
r : RECTANGLE; p: POLYGON ... p := r p.add_ver t ex (...)
Descend scendant h ant hidi ding: s ng: solutio ution 1 n 1
RECTANGLE POLYGON
Not allowed Nonconf or ming inher it ance
108
class POLYGON f eature ... var iable_ver t ex_count : BOOLEAN do Result := True end add_ver t ex (...) require var iable_ver t ex_count do ... end end class RECTANGLE inherit POLYGON redef ine var iable_ver t ex_count end f eature ... var iable_ver t ex_count : BOOLEAN = False end p: POLYGON ... if p.var iable_ver t ex_count then p.add_ver t ex (...) end
Descend scendant h ant hidi ding: s ng: solutio ution 2 n 2
RECTANGLE POLYGON
109
Inher nherita itance: s nce: summ mmary ( ary (1)
Type mechanism: let s you or ganize our dat a abst r act ions
int o t axonomies
Module mechanism: let s you build new classes as
ext ensions of exist ing ones
Polymorphism: f lexibilit y wit h t ype saf et y Dynamic binding: aut omat ic adapt at ion of oper at ion t o
t arget , f or mor e modular sof t ware archit ect ures
Cont r act s inherit ance: ensures proper t ies t o client s in
presence of polymorphism
Def erred classes: a mechanism t o express propert ies of
abst r act concept s
110
Inher nherita itance: s nce: summ mmary ( ary (2)
Polymorphic cont ainer s + obj ect t est : f lexible and t ype-
saf e
Const r ained gener icit y: allows calling specif ic f eat ur es
Mult iple inherit ance: power f ul way of combining
abst r act ions
Non-conf or ming inherit ance: a way t o express code
reuse wit hout subt yping
Cat calls: result f rom covariant r edef init ion of argument
t ypes (even mor e t ricky wit h genericit y!)