CSC/ECE 517 Fall 2007/wiki2 10 ab

From Expertiza_Wiki
Jump to navigation Jump to search

Problem Statement

Inheritance vs. delegation. Follow the debate on inheritance vs. delegation. Construct (or, better, cite) examples that show cases where inheritance is better, and cases where delegation is better. Attempt to characterize the situations in which you should employ one or the other.

What is Inheritance

Inheritance in the concept of Object Oriented Programming is the process by which one object can inherit or acquire the properties of other objects. With the use of inheritance each object which are instances of derived classes can only define the properties which are unique to itself and derive qualities or common attributes from other objects which are instances of base classes .The obvious advantages of inheritance is reusability which greatly reduces code repetition. Inheritance is directly supported by object oriented languages and it gives way to the concept of polymorphism. The inheritance relationship between the base and derived classes is illustrated at compile time which means that a class cannot change its parent class dynamically at run-time .

What is Delegation

Delegation, in the concept of object oriented programming refers to the ability of an object in assigning or delegating the implementation of certain functions to other objects. This concept is also referred to as dynamic inheritance. As compared to inheritance delegation is not directly supported by object oriented languages but on the other hand unlike inheritance , the class to which the function is delegated can be changed at runtime.

Inheritance or Delegation

The following contents refers to the debates on in which conditions inheritance would be a better approach and in which delegation would be better. As given in http://www.perlmonks.org/index.pl?node_id=278375[1], it mentions that the choice between inheritance and delegation would depend on the linguistic interpretation of the application. As given in the site a class car can inherit from vehicles and hence it would inherit all functionality that a vehicle has. But a car class would not inherit from a wheel class since a car is not a wheel, rather it is composed of wheels and hence it can delegate the functionality of the wheel operations to the wheel class. As a general rule it can be said that for a Is-A relationship between the derived and base class it would be safe to use inheritance , while delegation would be suitable for implementing a Has-A relationship. A more clear representation of the Is-A and a Has-A relationship with examples is given in this page http://c2.com/cgi/wiki?CompositionInsteadOfInheritance[2]. The following C++ code taken from [2] has been used .

 Below is a mouth class which has a eat function
 class Mouth {
 public:
 void eat(Food bite);
 };
 To illustrate inheritance the person class extends the functionality of the mouth class and hence it has the eat function too. 
 class Person: public Mouth {
 };
 With the idea of delegation the Person class would delegate the eat function to the Mouth class as is illustrated here.  
 class Person {
 public:
 void eat(Food bite) {
 itsMouth.eat(bite);
 }
 private:
 Mouth itsMouth;
 };

If we consider the question if a Person is a Mouth and if a Person has a Mouth , it can be seen which principle should be implemented

The reference in http://faqs.javabeat.net/design-patterns/java-design-patterns-interview-questions-faqs-1.php[3] specifies that the choice between inheritance and delegation may sometime depend on factors such as programming language support for eg multiple inheritance. So if there is a constraint on a class which already needs to inherit from a certain class it can delegate other functionality to another class since it cannot inherit from another class due to the programming language constraint. This page http://gdp.globus.org/gt3-tutorial/multiplehtml/ch04s01.html[4] refers to another example which explains how the constraint in inheriting from multiple classes makes it convenient to use delegation. This has been explained with the help of UML class diagrams and clearly states that due to the use of delegation , the complexity of the code may be slightly increased. This site gives an example of a MathImpl class which inherits from GridServiceImpl class . The MathImpl class provides implementation of all mathematical opertaions like add, subtract, multiply, divide, sine , cosine, tangent, matrixAdd, matrixInverse etc. In the event that this class would want to inherit from some other class this would not be possible since it already does inherit from one class. With the delegation approach, the implementation of the mathematical operators could be separated into three different clases ArithmeticProvider, TrignometricProvider and MatrixProvider to which the different operations could be delegated respectively and the respective Provider clases could then inherit separately from some other class. A few other pages which comapare inheritance vs delegation are given below http://www.stepwise.com/Articles/Technical/2000-03-03.01.html[5] http://www.softwarefederation.com/csci4448/courseNotes/05_ObjectOrientedDesign.pdf [6]

Examples in which Inheritance may be better

As referred in http://defprog.com/html/inheritance.html[7], inheritance should be utilized carefully and should be used when overall classes have the same behavior and overall differ by limited number of methods and plus they should satisfy the Is-A relationship. For example consider a base class Student which contains methods that implement the functionality of a student eg name, Student Id, Age, Major etc. Complementary to this there can be derived classes like UnderGraduate Student , Graduate student or Doctoral Student in which the only extra functionality that these derived classes would have would be the classification of degree and the no of credit hours required to complete the required degree. Hence following the principle given in [7], inheritance would make more sense here since all the type of Students would have to have all of the features of students and also include very limited number of extra features. Delegation of all basic functionality of student methods to the Student Class would simply extend the complexity of a simple code. Hence in this case inheritance would definitely be a better choice.

Examples in which Delegation may be better

Again referring to [7], a very good example may be provided of a case where the concept of inheritance has not been utilized well. This page claims that the java.util.Stack class could have been better implemented via delegation rather than inheriting from the Vector class. Since it inherits from the Vector class it is possible to change the size of the Stack which should not be the case. Instead a better design implementation would be to make the Stack Class delegate the functionality required to the Vector Class and keep only the methods pop(), push() , peek() and empty() as accessible to the outside world. The code snippet taken from this source as to how this could have been done via delegation has been shown below.

public class SafeStack {
private final Vector stack;
public SafeStack() {
stack = new Vector();
}
 public synchronized Object push(Object item) {
         stack.addElement(item);
       return item;
 }
 public synchronized Object peek() {
         int len = size();
       if (len == 0) {
           throw new EmptyStackException();
       }
         return stack.elementAt(len - 1);
 }
 public synchronized Object pop() {
         Object obj;
       int len = stack.size();
       obj = peek();
       stack.removeElementAt(len - 1); // gc!
       return obj;
 }
 public boolean empty() {
         return stack.size() == 0;
 }
}

The reference in http://www.builderau.com.au/program/java/soa/Dynamic-Classification-with-Interfaces-and-Delegation/0,339024620,320269511,00.htm [8]provides another example where it would be more suitable to use delegation rather than inheritance. This example clearly illustrates how java's constraint on inability to inherit from multiple classes has to depend on delegation to reduce a lot of implementation complexity

Summarizing with pros and cons of Inheritance and Delegation

To conclude the advantages of Inheritance lies in the fact that it is directly supported by object oriented languages and incorporates the features of code reuse which can remove redundancy and reduce lines of code. On the other hand inheritance may not be a very good choice when many features of the superclass is not really needed by the subclass. In this case, inheritance would merely cause many unnecessary features to be incoporated in a class simply because it needed some features of the superclass. This would lead to inefficient solutions of problems. The disadvantage of delegation is that it is not directly supported by all object oriented languages and hence may lead to more complex implementations. On the other hand the main advantage of delegation lies in run-time flexibility which means that the delegated class can be changed at run-time.

External Links

[1] http://www.perlmonks.org/index.pl?node_id=278375

[2] http://c2.com/cgi/wiki?CompositionInsteadOfInheritance

[3] http://faqs.javabeat.net/design-patterns/java-design-patterns-interview-questions-faqs-1.php

[4] http://gdp.globus.org/gt3-tutorial/multiplehtml/ch04s01.html

[5] http://www.stepwise.com/Articles/Technical/2000-03-03.01.html

[6] http://www.softwarefederation.com/csci4448/courseNotes/05_ObjectOrientedDesign.pdf

[7] http://defprog.com/html/inheritance.html

[8] http://www.builderau.com.au/program/java/soa/Dynamic-Classification-with-Interfaces-and-Delegation/0,339024620,320269511,00.htm