1 ָ נן oop Dynamic Binding uBinding uBinding time uMotivation uDynamic Binding uHigh Level Methods
2 ָ נן oop Binding Time uBinding: linking between messages and methods uThe same entity may refer to objects of different classes, each of which has a different implementation of the same method More generally, binding time is the time when an attribute of some portion of a program, or the meaning of a particular construct is determined Compile Time Link Time Execution Time: Program Init Procedure/function begin Statement Execution uStatic Binding (AKA Early Binding): the compiler uses the type of variables to do the binding at a compile (link) time uDynamic Binding (AKA Late Binding): the decision is made at run time based on the type of the actual values Inclusion Polymorphism + Overriding = Binding Question
3 ָ נן oop Main Binding Techniques Early (static) binding, is the binding of functions in a program at compile time. The programmer knows the type of data for each function called. For example: AddRealNums(x, y) x, y - of type real. Late (dynamic) binding of the message selector to the appropriate method at run time. The programmer doesn't know the specific method that will be used. For example: AddNumbers(x, y) x, y - are number objects.
4 ָ נן oop Static vs. Dynamic Types uConsider the call: Manager M; M.raise_salary(10); uWhat is the type of this in the called method? lStatic Type: Employee * What can be determined in compile time lDynamic Type: Manager * Actual type, as determined in run time No simple way for the programmer to examine the dynamic type uSuppose that raise_salary calls print, then, which version of print will be called? lBased on the static type? or, lBased on the dynamic type? Employee raise_salary print + Employee raise_salary print + Manager print ++ Manager print ++
5 ָ נן oop Static vs. Dynamic Binding uStatic Binding: binding based on static type. lMore efficient lLess flexible lStatic type checking leads to safer programs uDynamic Binding: binding based on dynamic type. lLess efficient lMore flexible lMay need dynamic type checking! uAs it turns out, dynamic binding is the only reasonable choice: lWhy? lIf static typing is so good, why “spoil” it with dynamic binding?
6 ָ נן oop Motivation I: Containers #define SIZEOF(a) (sizeof(a)/sizeof(*a))... Manager Alice, Bob; Engineer Chuck, Dan, Eve; SalesPerson Faith, Gil, Hugh; Employee Ira, Jim, Kelly;.... Employee *delegation[] = { &Bob, &Dan, &Faith, &Kelly};... for (int i = 0; i < SIZEOF(delegation); i++) delegation[i]->print(cout); Employee print + SalesPerson print ++ Manager print ++ Engineer print ++ Which print should be called here?
7 ָ נן oop Another Container Example uA display list in a graphic application. uList elements: lObjects of subclasses of class Shape: Points, lines, triangles, rectangles, circles, etc. uWe want the list to contain elements of type Shape, but each should be capable of preserving its own special properties. uIf we loop over the list and send each element in it a draw message, the element should respond according to its “dynamic type”.
8 ָ נן oop class Shape { Point location; public:... void move(Point delta) { hide(); location += delta; draw(); }... }; class Rectangle: public Shape { public: void hide(void) const {... } void draw(void) const {... } }; class Shape { Point location; public:... void move(Point delta) { hide(); location += delta; draw(); }... }; class Rectangle: public Shape { public: void hide(void) const {... } void draw(void) const {... } }; Which hide should be called here? Which draw should be called here? Motivation II: High Level Methods Shape location draw* hide* move + (delta) Some Shape draw + hide + uHigh Level Methods: methods which are coded using only the public interface of a class. uFacilitate code reuse in inheritance.
9 ָ נן oop Motivation III: External Functions void duplicate(const Shape *base) { enum {Dx = 12, Dy = 30}; Shape *clone = base->clone(); clone->move(Dx,Dy); clone->draw(); } void duplicate(const Shape *base) { enum {Dx = 12, Dy = 30}; Shape *clone = base->clone(); clone->move(Dx,Dy); clone->draw(); } Shape clone+, draw+ Star clone++, draw++ Which version of draw() and clone() should be called here?
10 ָ נן oop Dynamic Binding is the Answer! uThe rule: A called method should be selected based on the actual type of the object it is sent to. lMeaningful only for reference semantics. Value semantics: dynamic type == static type. lThis is why this is a pointer to the object, rather than the object itself. In a “better C++” this would be a reference to an object. Archaic C++ code used the idiom this = 0. uAll methods in Smalltalk, Eiffel and all other “decent” object-oriented programming languages are dynamically bound.
11 ָ נן oop Dynamic Binding in C? struct Shape { int x, y;... /* Other common fields */ Shape_type type; union { struct Rectangle {... } r; struct Circle {... } c; struct Line {... } l;.../* Other shape kinds */ } data; }; struct Shape { int x, y;... /* Other common fields */ Shape_type type; union { struct Rectangle {... } r; struct Circle {... } c; struct Line {... } l;.../* Other shape kinds */ } data; }; enum Shape_type { rectangle, circle, line,... }; void rotate(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void rotate(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void draw(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } void draw(Shape *p) { switch (p->type) { case rectangle:... case circle:... case line: } } Strong Coupling pointers to functions can be used instead.
12 ָ נן oop Disadvantages of the C Solutions uImplicit assumption: consistency between value of the type tag and usage of the union field data. lProgrammer’s responsibility: no compiler aid or checking uDispersed coding: the code for different operations on the same shape is spread all over the program. lDifficult to understand uInsusceptibility to change: whenever a new kind of shape is introduced, the following must be changed: lDefinition of Shape_type lDefinition of Shape lFunction rotate lFunction draw lAll other functions Some OO programming languages do not include a switch like statement, just because of the above bad usage of switch !
13 ָ נן oop class Circle: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; The Shapes Example in C++ class Shape { public: virtual void draw(void); virtual void hide(void); virtual void rotate(int deg);... protected: int x, y;... /* Other common fields */ }; class Shape { public: virtual void draw(void); virtual void hide(void); virtual void rotate(int deg);... protected: int x, y;... /* Other common fields */ }; class Line: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; class Rectangle: public Shape { public: virtual void draw(void) {... } virtual void hide(void) {... } //... }; The specialized code is associated with the type, not with each function. OOP promotes the shift of focus from operations to operands The type tag is hidden, and maintained by the compiler
14 ָ נן oop Downcasting vs. Dynamic Binding void draw(Shape *p) { if (Circle *q = dynamic_cast p) { // Draw circle... } else if (Line *q = dynamic_cast p) { // Draw line... } else if (Rectangle *q = dynamic_cast p) { // Draw rectangle... }... } void draw(Shape *p) { if (Circle *q = dynamic_cast p) { // Draw circle... } else if (Line *q = dynamic_cast p) { // Draw line... } else if (Rectangle *q = dynamic_cast p) { // Draw rectangle... }... } RTTI considered harmful: lOrder of classes in the if chains is significant lModule must change whenever new class is added to the hierarchy
15 ָ נן oop Dynamic Binding and the Container Problem uGiven is a set of employees as in Employee *department[100]; uThen, how can we determine if a department[3] is a manager or not? uDynamic Binding Answer: lThe question is wrong!!! lThere is never a need to determine the dynamic type of an object. lDifferences between objects: Different state lDifferences between classes: Different implementation uUsage of RTTI in all but very special cases indicates a misunderstanding of the power of dynamic binding.
16 ָ נן oop High Level Methods Dynamic binding makes methods truly polymorphic. The same code will do different things for different objects: void Shape::move(Point delta) { hide(); location += delta; draw(); } void Shape::move(Point delta) { hide(); location += delta; draw(); } Internal (in-class) dynamic binding uLow level methods: implemented only using data members u code not affected by overriding uHigh level methods: may use also other methods u partially polymorphic code uOuter level methods: methods implemented solely with (externally accessible) methods u fully polymorphic code
17 ָ נן oop Dynamic Binding and Static Typing uStatic typing: guarantee that a method exists lA variable of type T can contain only objects of type T, or of type T', where T' is derived from T. lA message to an object is legal only if its static type recognizes it. uDynamic binding: make sure that the right method is selected. lThe method invoked for an object depends on its dynamic type. uStatic typing + Dynamic binding: the right combination of safety and power lExamples: Eiffel, C++, Java, Object-Pascal, Turbo-Pascal, etc.
18 ָ נן oop C++ Example struct Base { virtual void f(void) {... } void g(void) {...} }; struct Derived: public Base { virtual void f(void) {...} // Override f() of Base void g(void) {...} // Override g() of Base void h(void) {...} } y; Base *px = &y; px->f(); // The right method px->g(); // The wrong method px->h(); // Compile time error! No guarantee that the method exists struct Base { virtual void f(void) {... } void g(void) {...} }; struct Derived: public Base { virtual void f(void) {...} // Override f() of Base void g(void) {...} // Override g() of Base void h(void) {...} } y; Base *px = &y; px->f(); // The right method px->g(); // The wrong method px->h(); // Compile time error! No guarantee that the method exists
19 ָ נן oop Comparison of Binding Techniques uDynamic binding is more flexible. Static is more efficient. lStatic types are more efficient. lCalling static methods is more efficient. uStatic method binding may give better error detection, just as static typing gives better error detection. uUsage: lStatic binding: homogenous set of objects that are similar to an existing class; inheritance simply makes the new set of objects easier to implement. lDynamic binding: heterogeneous mix of objects that share operations that are conceptually the same, but may have different implementations.