Lecture 3 Inheritance Polymorphism Idioms Mechanisms Frameworks Making

  • Slides: 36
Download presentation
Lecture 3 Inheritance & Polymorphism Idioms, Mechanisms, Frameworks “Making abstractions which are powerful and

Lecture 3 Inheritance & Polymorphism Idioms, Mechanisms, Frameworks “Making abstractions which are powerful and deep is an art. It requires tremendous ability to go to the heart of things, and get at the really deep abstraction. No one can tell you how to do it in science. No one can tell you how to do it in design. –Christopher Alexander

Patterns and Rules “A pattern language actually gives us the power to generate these

Patterns and Rules “A pattern language actually gives us the power to generate these coherent arrangements of space. Thus, as in the case of natural languages, the pattern language is generative. It not only teels us the rules of arrangement, but shows us how to construct arrangements—as many as we want—which satisfy the rules. . . When a person is faced with an act of design, what he does is governed entirely by the pattern language which he has in his mind at that moment. . . His act of design, whether humble, or gigantically complex, is governed entirely by the patterns he has in his mind at that moment, and his ability to combine these patterns to form a new design. ” – Christopher Alexander

“Every creative act relies on language. ” – Christopher Alexander “I understand the unease

“Every creative act relies on language. ” – Christopher Alexander “I understand the unease of all such people. They have probably found it difficult enough to recognize that their history, their economics, their social practices, the language that they speak, the mythology of their ancestors, even the stories that they were told in their childhood, are governed by rules that are not all given to their consciousness; they can hardly agree to being dispossessed in addition of that discourse in which they wish to be able to say immediately and directly what they think, believe, or imagine; they prefer to deny that discourse is a complex, differentiated practice, governed by analyzable rules and transformations, rather than be deprived of that tender, consoling certainty of being able to change, if not the world, if not life, at least their ‘meaning’, simply with a fresh word that can come only from themselves, and remain for ever close to the source. So many things have already eluded them in their language: they have no wish to see what they say now go the same way; at all costs, they must preserve that tiny smidgeon of discourse-whether written or spoken--whose fragile, uncertain existence must sustain their lives. They cannot bear ( and one cannot but sympathize) to hear someone saying: ‘Discourse is not life: its time is not your time; in it, you will not be reconciled to death; you may have killed God beneath the weight of all that you have said; but don’t imagine that, with all that you are saying, you will fabricate something that will live longer than he has. ” --Michel Foucault

Two Key Ideas • Sometimes, we want to talk about common things as a

Two Key Ideas • Sometimes, we want to talk about common things as a group, without having to worry about specifics. That is to say, sometimes we want to say something like: – All vehicles to the starting line • Without specifying all the different types of vehicles, Fords, Formula 1, Cart Cars, Trucks, etc. – All children inside • Without having to individually call Tommy, Bobby, Elizabeth, etc. • The way this is accomplished in OO is through the concepts of inheritance and polymorphism.

So What is Inheritance? • Inheritance implements an “is-a” or “is a type of”

So What is Inheritance? • Inheritance implements an “is-a” or “is a type of” relationship: – A man or woman is an animal – A bubble sort is a type of sorting algorithm – A driver’s license is a type of official documentation – A salaried employee is a type of Employee – A manager is a type of salaried employee • Inheritance is a way of reusing code and/or interfaces of a generic class • Inheritance can be either singular or multiple: – A professor is an employee, a student is a person, and a teaching assistant is a type of professor as well as a student. A teaching assistant is both a professor and a student at the same time. • Back to simulation and imitation: inheritance allows a design to mimic the real world, but: to what degree is the world really hierarchical?

Simple Inheritance • A Zoo has animals • Individual Animals know how to sleep

Simple Inheritance • A Zoo has animals • Individual Animals know how to sleep • Abstract sleep into base class, so you can command any Animal to sleep • Implement sleep() in concrete derivatives so each individual animal knows how to sleep

Inheritance continued • Inheritance is also often called a “Generalization/Specialization” relationship (Coad) • base

Inheritance continued • Inheritance is also often called a “Generalization/Specialization” relationship (Coad) • base class: generalization • derived class: specialization (it specializes or extends the base class) • Canine (generalization) – Collie (specialization) – Shetland Sheepdog (specialization) – Terrier (generalization and specialization) • Boston, Bull, Fox, Scottish, Clydesdale, Dandie Dinmont

Single vs. Multiple Inheritance • Single: Java, Smalltalk • Multiple: C++, Eiffel • Examples:

Single vs. Multiple Inheritance • Single: Java, Smalltalk • Multiple: C++, Eiffel • Examples: – – – Airplane + Corporate Asset Company_Plane Boat + Plane Hydroplane Car + Person Car_Owner Vehicle + House Mobile_Home Tax Exemption + Infant Well_Loved_Baby

Interface versus Implementation • Do you inherit just the interface or both the interface

Interface versus Implementation • Do you inherit just the interface or both the interface and the implementation? – C++: both (class and ABC) – Java: both (extends, implements interface) – Smalltalk, Eiffel: (implementation only)

Multiple Inheritance: Good or Evil? • The creators of the Java language felt multiple

Multiple Inheritance: Good or Evil? • The creators of the Java language felt multiple implementation inheritance to be so problematic they intentionally left it out of the language. • “We should not be afraid of the variety of ways in which we can use inheritance. Prohibiting multiple inheritance … achieves no other aim than to hurt ourselves. The mechanisms are there to help you: use them well, but use them. ” -- Bertrand Meyer • Multiple Inheritance is like a parachute. You don’t often need it, but when you do, you really need it. --Booch • The lack of multiple inheritance (as in Java or Smalltalk) often creates additional work (CORBA Event Channel)

Inheritance and Reuse • Inheritance is one key avenue to deliver on the OO

Inheritance and Reuse • Inheritance is one key avenue to deliver on the OO promise of reuse. • Inheritance reuses types. • But does inheritance break encapsulation? – The “rippling effect” of changing the base class implementation – Method overriding – Method hiding

Heuristics for Determining Legitimate Inheritance • Arthur Riel’s Two Questions Approach: – Q 1:

Heuristics for Determining Legitimate Inheritance • Arthur Riel’s Two Questions Approach: – Q 1: Is A a type of B? – Q 2: Is B a part of A? • If Yes/No: Legitimate Inheritance • If No/Yes: Illegitimate Inheritance – Example: Should Airplane derive from Wing, Fuselage, etc. ? – Example: Should a Collie derive from a Dog? • Only subclass for taxonomic reasons, never for reasons of simple utility – Real World: Example Visitor Pattern

Heuristics cont. • Peter Coad's Five Rules of Compliance: – Subtypes are "a special

Heuristics cont. • Peter Coad's Five Rules of Compliance: – Subtypes are "a special kind of", not "a role player". – Within a given Problem Domain, the subtype will never need to transmute into some other domain object. Eg. : Person ==> Teacher ==> TA Will a TA ever need to be a Student? ? – Subclass must extend rather than nullify the superclass (rules out Meyer's Uneffecting Inheritance) – Does not subclass for simple utility (must subclass for taxonomic reasons, not simply for convenience) – Within a single Problem Domain, the base class expresses a set of types of specializations… a role a person plays (clerk, head clerk, etc. ); a transaction type, specialized type of thing (passive/active radar sensor)

Bertrand Meyer’s 12 Categories • Object Oriented Software Construction tome – Model Inheritance •

Bertrand Meyer’s 12 Categories • Object Oriented Software Construction tome – Model Inheritance • Subtype: vertebrate <== mammal (most familiar form) • Restriction: rectangle <== square (constraint: 4 sides equal) • Extension: car <== Formula 1 Racer (extension (Java)) – Variation Inheritance (overloading/inherit to redefine) • functional: only method implementation modified • type: both implementation and signatures are modified • Uneffecting: inherit an overly-concrete class and generalize its interface (better done through facades) – Software Inheritance • Reification: Specialization of interface • Implementation: Specialization of implementation

Gang of Four Composition vs. Inheritance • Recommend Composition over Inheritance – Composition: strong

Gang of Four Composition vs. Inheritance • Recommend Composition over Inheritance – Composition: strong form of aggregation implying simultaneous lifetimes • Square and its four sides • Circle and its radius • hand its fingers (robotics) – Strong Composition implies: • a part cannot belong to more than one whole • concurrent instantiation and destruction with whole

Why use Composition over Inheritance • Composition trades in reuse (through inheritance) for delegation

Why use Composition over Inheritance • Composition trades in reuse (through inheritance) for delegation (via reference), which allows for dynamic runtime configuration • Inheritance generally ties you to a particular implementation • This is limiting because: – you can’t easily swap out that implementation for another at runtime – Inheritance can be seen to break encapsulation – Inheritance hinders your ability to “design for change” – Composition promotes delegation (distributed implementation)

Why Inheritance over Composition • Inheritance makes global changes easier to make (change the

Why Inheritance over Composition • Inheritance makes global changes easier to make (change the base class, and eureka). • Inheritance enforces type checking at compile time (in strongly typed languages) • Delegation can complicate the reading of source code, especially in non-strongly typed languages (Smalltalk)

Design Heuristics • Prefer composition over inheritance except when: – a clear hierarchy of

Design Heuristics • Prefer composition over inheritance except when: – a clear hierarchy of types exists within the Problem Domain itself, and this hierarchy is never expected to change – Defined roles exist that are never expected to change within a given Problem Domain

Taxonomic Complexity • Kingdom: Animalia – Phylum: Chordata (endoskeletal, closed circulation) • Class: Aves

Taxonomic Complexity • Kingdom: Animalia – Phylum: Chordata (endoskeletal, closed circulation) • Class: Aves (birds) – Hey, Harry, is a Struthioniformes (Ostrich) a bird? » Not if all birds can fly. • Problem Domain Abstraction and Reference – Such questions can only be answered in the context of a given Problem Domain – Model the ostrich flying problem through descendent hiding: fly() { null_op }

Mimetic Complexity • Suppose you are writing a matchmaking program for an online dating

Mimetic Complexity • Suppose you are writing a matchmaking program for an online dating service: – Does Jim need permission from Sue’s parents to treat her indifferently? – Does Linda send a single message to Bob when she wants to associate with his database? – Does Mary need to join a list before she can be analyzed and traversed by the boys? – Does Larry need a unique identifier before he can introduce himself to Helen? – These are stupid questions

Polymorphism • Polymorphism simply means that you can command an instance of a subtype

Polymorphism • Polymorphism simply means that you can command an instance of a subtype by issuing a command on the base class interface without having to know the specific subclass type • Examples of the concept: – Huckleberry Finn and the Grangerfords and Sheperdsons – Bluto (Belushi) and Otter in Animal House: Delta house versus Omega House: • Niedermeyer: dead man • Greg: dead man – A fire call to whoever is at the 911 departmental desk: Fire Chief, Lieutenant, Sergeant, Office, Maid, etc. – Polymorphism is highly non-politically-correct (it completely removes concern for individuality) • Private! Pick up that M 60 and head up that hill!

So what does this mean? • Every employee of the 911 Call Center knows

So what does this mean? • Every employee of the 911 Call Center knows how to handle a 911 call, regardless of “who they are” in the organization

Binding and Polymorphism • Example: A Kennel simulation, and dog. bark(); • Static (early)

Binding and Polymorphism • Example: A Kennel simulation, and dog. bark(); • Static (early) – C language • Dynamic (late, runtime) – True Polymorphism: Smalltalk – method name and class are concatenated together at runtime to find the method on the class and call it

Binding and Polymorphism • Hybrid (C++) – C++ with virtual function tables (each object

Binding and Polymorphism • Hybrid (C++) – C++ with virtual function tables (each object has a vptr in the class’s vtable) – C++ virtual function polymorphism works only with pointers and references, not objects. – Fast, no hashing is done, polymorphic behavior is determined by hash table lookup

Binding and Polymorphism • Pure Polymorphism (Java Interface, C++ ABC) – semantic vs. implementation

Binding and Polymorphism • Pure Polymorphism (Java Interface, C++ ABC) – semantic vs. implementation inheritance – a pure polymorphic method is one which does not have a base implementation – a pure virtual function (of an ABC in C++) provides a “placeholder” method name, but does not provide an implementation because the method is generically meaningless • a “taste” method on a fruit abstract class. . .

Why does this matter? • It matters because: – Some original OO languages tend

Why does this matter? • It matters because: – Some original OO languages tend to be strongly typed, and genericity was provided via polymorphism – Of the inherent topological character of Class inheritance.

Polymorphism Revisited • (Ax)(Bx > Fx) • All Birds Fly • An Osterich is

Polymorphism Revisited • (Ax)(Bx > Fx) • All Birds Fly • An Osterich is a Bird • An Osterich flies?

Essential Polymorphism • • A client has a reference to Base. A, could be

Essential Polymorphism • • A client has a reference to Base. A, could be Base. A, Impl. A, Derived. A, or Override. A A client has a reference to Impl. A, could be Impl. A, Derived. A, or Override. A A client has a reference to Derived. A, could be Derived. A, or Override. A A client has a reference to Override. A, could only be Override. A

Fast Poly, C++ style • • • Physicist p = new Physicist(“Feynman” ); Scientist

Fast Poly, C++ style • • • Physicist p = new Physicist(“Feynman” ); Scientist * s = &p; s->show_all(); s->show_name(); ((p)s)->show_field();

Hallmarks of Good OO Design • Short methods • obvious methods (self-evident naming) •

Hallmarks of Good OO Design • Short methods • obvious methods (self-evident naming) • no "God" objects (no one is omniscient) • no "Manager" objects (nobody is too busy) • trust your objects to "do the right thing" – handle errors through exception interface • good objects have clear responsibilities • TELL, don't ask.

Strategic Considerations • There are several strategic design tools that can be used to

Strategic Considerations • There are several strategic design tools that can be used to aid OOA/OOD. – Idioms – Mechanisms – Frameworks – Patterns

Idioms • Idioms are cultural language-specific and guidelines for implementation. • Idioms represent generally-accepted

Idioms • Idioms are cultural language-specific and guidelines for implementation. • Idioms represent generally-accepted practices in coding • Idioms represent styles of accepted Coding Good Behavior. – Examples: • use of exceptions in C++ and Java • long, descriptive naming convention in Smalltalk • Use of ALLCAPS #defines in C • small Initial + Upper Continued naming convention in Smalltalk and Java: an. Integer, do. It. Now() • Naming getters and setters in Smalltalk after instance vars. • Returning ^self to indicate expected use of return value in Smalltalk. – Ignoring an idiom will usually brand you as a a neophyte in within a particular development culture.

Mechanisms • Mechanisms are descriptions of a structure of co-operating and collaborating objects which

Mechanisms • Mechanisms are descriptions of a structure of co-operating and collaborating objects which together provide some behavior that can be seen as "greater than the sum of the parts". • Mechanisms are larger design units that are made up of cohesive classes that work together to solve a particular design problem. • Mechanisms are the verbal form of a pattern: they emphasise the pattern of interaction between the objects. • Classes are discovered from within the vocabulary of the Problem Domain, Mechanisms are invented to describe the collaborations between those classes.

Frameworks • Frameworks are large implementations of Patterns and Mechanisms that provide a reusable

Frameworks • Frameworks are large implementations of Patterns and Mechanisms that provide a reusable infrastructure in the form of a group of services. • Frameworks can be viewed as "mini-applications" that provide "prefab" collaborative classes that can be levereged by developers. • To use the Framework, the developer implements methods defined as abstract in the base classes of the Framework. Much of the Frameworks code is written as Template Methods which make “call backs” to user-defined hook methods. • A developer writes a control class that she "plugs in" to the existing framework, and can then use all of the services of the framework, as if she had written them herself. • A framework has hooks that allow functions within the control class to be called from the framework (via abstract methods). (The Hollywood Principle: Don't call us, we'll call you)

Framework Example

Framework Example

White and Black Box Frameworks • Inheritance-based Frameworks are White Box – Implementer derives

White and Black Box Frameworks • Inheritance-based Frameworks are White Box – Implementer derives an Application class from a Framework Base Class, which functions as a Template Method for further extension. – The Framework can be extended and modified by the derived class(es). – Limitations? • Composition-based Frameworks are Black Box – Implementer builds an application from parts (the parts represent the Framework). – The Framework does not often change. – Limitations? • Most Frameworks are implemented as White-Box Frameworks.