Eiffel: Analysis, Design and Programming Bertrand Meyer. Chair of Software Engineering. - 6 - Genericity. What’s wrong with this code?. class LIST_OF_CARS feature extend (v: CAR ) is … remove (v: CAR ) is … item: CAR is … end. class LIST_OF_CITIES feature
Chair ofSoftware Engineering
extend (v: CITY) is …
remove (v: CITY) is …
item: CITYis …
DRY Principle: Don’t Repeat Yourself
classLIST[G ]featureextend (x : G )... last : G ... end
To use the class: obtain a generic derivation, e.g.
cities: LIST[CITY ]
Formal generic parameter
Actual generic parameter
How can we define consistent “container” data structures, e.g. list of accounts, list of points?
Dubious use of a container data structure:
c : CITY ; p : PERSONcities : LIST ...
people : LIST ...
cities.extend ( )
c := cities.last
What if wrong?
cities : LIST [CITY]
people: LIST [PERSON]
c : CITY
c := cities.last
Type-safe call (during execution):
A feature call x.fsuch that the object attached to x has a feature corresponding to f.
[Generalizes to calls with arguments, x.f(a, b) ]
Static type checker:
A program-processing tool (such as a compiler) that guarantees, for any program it accepts, that any call in any execution will be type-safe.
Statically typed language:
A programming language for which it is possible to write a static type checker.
LIST [CITY ]
LIST [LIST [CITY ]]
A type is no longer exactly the same thing as a class!
(But every type remains based on a class.)
bound by the program text:
Dynamic types from i_th_power :
There is at least one feature f applicable to x
If more than one possible feature,execution will select the right feature
When compiling, type checker checks if there is at least one feature named talk in type ANIMAL, which is the declared type of a.
At run-time, execution will select the right feature to invoke, which will be talk fromCAT here.
e.g.LIST [INTEGER], LIST [PERSON]
HASH_TABLE[G, H―> HASHABLE]
VECTOR [G―> NUMERIC]
+Adding two vectors
... The rest as before ...
Expression to be tested
SCOPEof the Object-Test Local
[G -> FIGURE]
What will happen?
p := r