eif f el analysis design and programming
play

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


  1. A de A defe ferred fe rred feature ature I n e.g. LI ST : f or t h require not af t er def erred ensure index = old index + 1 end 32

  2. Mixing Mixing deferre deferred and effectiv d and effective featur e features es I n t he same class Ef f ect ive! search ( x : G ) -- Move t o f ir st posit ion af t er current -- where x appears, or af t er if none. do f rom until af t er or else it em = x loop f or t h end end Def er r ed! “Programs with holes” 33

  3. “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 34

  4. Defe Deferr rred clas d classe ses in Eiff s in Eiffel elBa Base se * CONTAI NER * * * BOX COLLECTI ON TRAVERSABLE * * * * * * I NFI NI TE BAG SET HI ERARCHI CAL LI NEAR FI NI TE * * * * * * * I NTEGER_ BOUNDED UNBOUNDED COUNTABLE TABLE ACTI VE BI LI NEAR I NTERVAL … … * * * * * RESI ZABLE CURSOR_ I NDEXABLE DI SPENSER SEQUENCE STRUCTURE * * ARRAY STRI NG HASH_TABLE STACK QUEUE * def erred 35

  5. Deferr Defe rred cla d classes es for an for anal alys ysis is def erred class VAT inherit TANK f eature in_valve , out _valve : VALVE f ill is -- Fill t he vat . require in_valve.open out _valve.closed def erred ensure in_valve.closed out _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 36

  6. Polymor Polymorph phic data structures ic data structures f l class LI ST [ G ] f eature ... last : G is ... ext end ( x : G ) is ... (SQUARE) end f l : LI ST [ FI GURE ] r : RECTANGLE (TRI ANGLE) s : SQUARE (RECTANGLE) (POLYGON) 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 37

  7. Figure hierar Figure hierarchy (remin chy (reminder) der) display* cent er * * FI GURE r ot at e* move* * * per imet er* OPEN_FI GURE CLOSED_FI GURE display + r ot at e + per imet er + per imet er + move + SEGMENT POLYLI NE + + ELLI P SE POLYGON . . . per imet er ++ side1 . . . RECTANGLE TRI ANGLE per imet er ++ side2 CI RCLE diagonal display ++ r ot at e ++ * def erred display + per imet er ++ move ++ r ot at e + + ef f ect ive SQUARE move + ++ redef ine d 38

  8. Enforcing a Enforcing a type: th type: the pro e problem blem f l . st or e ("FI LE_NAME") ... -- Two year s lat er: f l := ret rieved ("FI LE_NAME“) x := f l . last -- [1] print ( x . diagonal ) -- [2] 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. 39

  9. Enforcing g a a type: : the e Object t Test Opt ional (if omit t ed Expr ession t o be Obj ect -Test Local j ust t est s f or void) t est ed 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 SCOPE of t he Obj ect -Test Local 40

  10. 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 41

  11. 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. 42

  12. 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 43

  13. Top Topic ics for t s for today oday � 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 44

  14. 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 ] 45

  15. Constraine Constrained genericity d genericity class VECTOR [ G ] f eature plus alias "+" ( ot her : VECTOR [ G ]): VECTOR [ G ] -- Sum of cur rent vect or and ot her . 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 46

  16. Adding two vectors Adding two vectors u + v = w 2 = = i i c c a a b b + + 1 47

  17. 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 -- Requires “+” operat ion on G! Result . put ( c , i ) i := i + 1 end 48

  18. The s The solut olutio 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. 49

  19. 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 ]]] 50

  20. 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 ] 51

  21. Combining abstracti Combining abstractions ons Given t he classes � TRAI N_CAR, RESTAURANT how would you implement a DI NER? 52

  22. 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 53

  23. Composite fig Com posite figures ures 54

  24. Multiple in Multiple inherit heritance ance: Co : Compos mposite figures ite figures Simple figures A composite figure 55

  25. De Definin fining the n g the notion of otion of co compos mposite figure ite figure cent er LI ST display FI GURE count [ FI GURE ] hide put r ot at e r emove move … … COMPOSI TE_ FI GURE 56

  26. In the In the ove overall structure rall structure LI ST FI GURE [ FI GURE ] OPEN_ CLOSED_ FI GURE FI GURE per imet er * COMPOSI TE_ SEGMENT POLYLI NE P OLYGON FI GURE ELLI PSE per imet er + per imet er + diagonal RECTANGLE CI RCLE per imet er ++ per imet er ++ TRI ANGLE SQUARE per imet er ++ 57

  27. A comp A composit ite e figu figure re as a list as a list bef or e af t er it em f or t h Cur sor 58

  28. Com Composite fig posite figures ures class COMPOSI TE_FI GURE inherit FI GURE LI ST [ FI GURE ] f eature display -- Display each const it uent f igure in t urn. do f rom st ar t until af t er loop it em . display f or t h Requir es dynamic end binding end ... Similarly f or move , rot at e et c. ... end 59

  29. Goin Going g one lev one level el of abstr of abstrac acti tion hig n highe her A simpler f orm of procedures display , move et c. can be obt ained t hr ough t he use of it er at ors Use agent s f or t hat pur pose 60

  30. Multiple inheritance Multipl e inheritance: Combining : Combining abstraction abstractions +, –, < , < =, � , / NUMERI C COMPARABLE > , > =, … … (commut at ive (t ot al or der r ing) r elat ion) I NTEGER REAL COMPLEX STRI NG 61

  31. 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 62

  32. Multiple inheritance Multipl e inheritance: Combining : Combining abstraction abstractions +, –, < , < =, � , / NUMERI C COMPARABLE > , > =, … … (commut at ive (t ot al or der r ing) r elat ion) I NTEGER REAL COMPLEX STRI NG 63

  33. How How do we writ do we write e CO COMPARABLE MPARABLE ? def erred class COMPARABLE [ G ] f eature 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 end 64

  34. Less Lesson ons fr s from t om this exa 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 65

  35. Mu Multip ltiple i le inheri heritance: N tance: Name c me clashes shes f B f A ? C 66

  36. Re Resolving nam solving name cl e clashes ashes f B f A rename f as A_f A_f , f C 67

  37. Conseque Consequences nces of of renaming renaming a1 : A f f A B b1 : B c1 : C ... c1 . f rename f as A_f c1 . A_f C A_f , f a1 . f b1 . f I nvalid: � a1 . A_f � b1 . A_f 68

  38. 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) 69

  39. Featur Feature me e mergin rging f + A f * B C f * D � Def erred + Ef f ect ive 70

  40. Featur Feature me e mergin rging: with dif g: with differe ferent names nt names class D h + g * f * A B C inherit A rename g as f end B g f h C f rename D h as f � Def erred end + Ef f ect ive f eature ... Renaming end 71

  41. Featur Feature merging: e merging: effective feature effective features f + f + f + A B C f -- f -- D � Def erred + Ef f ect ive -- Undef ine 72

  42. Un Undefin definition ition def erred class T inherit S undef ine v end f eature ... end 73

  43. Mer Merging ging thro through ugh un undefinit definition ion f + f + f + A B C class D f -- inherit A f -- undef ine f end D B � Def erred C undef ine f end + Ef f ect ive f eature -- Undef ine ... end 74

  44. Merging effective feature Merging effective features with di s with different fferent na names mes f + h + g + C B A class D inherit g A f undef ine f end f -- B rename f -- g as f h f undef ine f end D C rename h as f end f eature ... end 75

  45. 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 76

  46. Featur Feature merging: e merging: effective feature effective features g + A f + B h + C g f h f D f - f - a1 : A b1 : B c1 : C d1 : D a1 . g b1 . f c1 . h d1 . f 77

  47. A A spe special case of cial case of mu multiple ltiple in inherita heritance nce UNI VERSI TY id _MEMBER TEACHER STUDENT ?? ?? ASSI STANT ???? This is a case of repeat ed inher it ance 78

  48. Indirec Indirect and di t and direct repeat rect repeated inherit ed inheritanc ance A A C B D D 79

  49. Multiple is Multiple is al also rep so repeate eated inheritanc d inheritance copy A t ypical case: ANY is_equal copy ++ C LI ST is_equal ++ copy C_copy D is_equal C_is_equal ?? 80

  50. Sha Sharing ring an and re d replicatio plication f A g g g_c g g_b C B D 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. 81

  51. 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: copy ANY is_equal a1 : ANY d1 : D C LI ST … copy ++ is_equal ++ a1 := d1 copy C_copy a . copy ( … ) is_equal C_is_equal D 82

  52. 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 83

  53. 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. 84

  54. 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 ) 85

  55. Multiple In Multiple Inherit heritan ance and C ce and Class T lass Tables ables Why does t his not work wit h mult iple subt yping ? Can we st ill do O(1) lookup ? 86

  56. The dy The dynam namic ic bind bindin ing fun g funct ctio ion Name × St at icType × DynamicType � Code 87

  57. The dy The dynam namic ic bind bindin ing fun g funct ctio ion (Name × St at icType) � DynamicType � Code 88

  58. The dy The dynam namic ic bind bindin ing fun g funct ctio ion (Name × St at icType) � DynamicType � Code St at ic Dynamic 89

  59. Feature Tables Featu re Tables Dynamic Type A B C St at ic Type f of A Code Point er Code Point er Code Point er g of A Code Point er Code Point er Code Point er h of B Code Point er g of C Code Point er 90

  60. 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 LI ST end ARRAY class ARRAYED_LI ST [ G ] inherit LI ST [ G ] ARRAY [ G ] ARRAYED_LI ST ... invariant st ar t s_f r om_1 : lower = 1 end a : ARRAY [ I NTEGER ]; l : ARRAYED_LI ST [ I NTEGER ] ... Class invar iant a := l violat ion a.r esize (-10, 10) 91

  61. 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! 92

  62. Non-confor Non-conformi ming inheritanc ng inheritance class ARRAYED_LI ST [ G ] inherit LI ST [ G ] Non-conf or ming inherit { NONE } inher it ance LI ST ARRAY ARRAY [ G ] ... invariant st ar t s_f r om_1: lower = 1 end ARRAYED_LI ST a : ARRAY [ I NTEGER ]; l : ARRAYED_LI ST [ I NTEGER ] ... Not allowed a := l a.r esize (-10, 10) 93

  63. No n No need for eed for select select Pot ent ial ambiguit y is r esolved is f avor of conf orming parent : count FI NI TE f : FI NI TE [ ... ] al : ARRAYED_LI ST [...] … ARRAY LI ST f := al print ( f . count ) count capacit y ARRAYED_LI ST Ver sion f r om LI ST 94

  64. Covarian Covariance ce class LI ST [ G ] f eature LI ST CURSOR cur sor : CURSOR go_t o ( c: CURSOR ) is do …end … end LI NKED_LI ST LI NKED_CURSOR 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 95

  65. Anchore Ancho 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 -- No need t o redef ine ` go_t o’ … end 96

  66. 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 ot her t ype, y will be t r eat ed as it if also had t hat t ype. 97

  67. 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 98

  68. Th The p e pro roblem w blem with th cova variance riance class LI ST f eature list : LI ST [...] cursor: CURSOR go_t o ( c: like cursor ) is do … linked_list : LI NKED_LI ST [...] end … end c : CURSOR class LI NKED_LI ST inherit LI ST … redef ine cursor, ... end f eature list := linked_list cursor: LI NKED_CURSOR list .go_t o (c) -- No need t o redef ine ` go_t o’ … end Cat call! 99

  69. 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 or ar gument t ype 100

Download Presentation
Download Policy: The content available on the website is offered to you 'AS IS' for your personal information and use only. It cannot be commercialized, licensed, or distributed on other websites without prior consent from the author. To download a presentation, simply click this link. If you encounter any difficulties during the download process, it's possible that the publisher has removed the file from their server.

Recommend


More recommend