CSC 517 Fall 2010/ch3 n S30: Difference between revisions
No edit summary |
No edit summary |
||
Line 60: | Line 60: | ||
As the word suggest, delegation means assign the task to some other entity. In object oriented programming terminology it an be explained as, process of implementation of one method to other method in different class. Delegation is also called as dynamic inheritance. It is an alternative to some inheritance and | As the word suggest, delegation means assign the task to some other entity. In object oriented programming terminology it an be explained as, process of implementation of one method to other method in different class. Delegation is also called as dynamic inheritance. It is an alternative to some inheritance and | ||
When two objects are not of the same type, let’s say there are two objects A and B, A has some method and attributes, which B is interested in using. Then, using delegation technique, | When two objects are not of the same type, let’s say there are two objects A and B, A has some method and attributes, which B is interested in using. Then, using delegation technique, | ||
This mechanism can be suitable where we have to decide at run time based on the user input, which functionality needs to be executed. | This mechanism can be suitable where we have to decide at run time based on the user input, which functionality needs to be executed. |
Revision as of 14:48, 6 October 2010
Introduction
When we think of object oriented programming, the Inheritance feature attracts our attention. However, there are many other alternatives to the traditional inheritance such as Delegation, Message Forwarding and decomposition. In this article, we will explore more about these three alternatives and compare with classic inheritance concept.
Inheritance
Inheritance is a powerful concept in object oriented programming which allows code reusability. In this the functionality of the base class can be inherited by its subclasses. At the same time subclass can have its own functionality.
There two type inheritance
Single Inheritance
This property restricts that a class can only inherit from one class. Java and Ruby are examples of object-oriented languages that have single inheritance.
Multiple Inheritance
This property allows a single class to inherit functionality from multiple classes. C++ allows Multiple Inheritance, however, the major drawback of this property is that it leads to the classical Diamond Multiple Inheritance Problem.
The concept of Inheritance can be better explained with a code in Ruby. In ruby we have single Inheritance.
Example in Ruby
class Animal def sleep puts " I want to sleep " end end class Herbivorous < Animal def eat puts " I want to eat plants " end end
Code execution
MyAnimal = Herbivorous.new MyAnimal.sleep #I want to sleep MyAnimal.eat #I want to eat plants
Here the class Herbivorous inherits the class Animal. So when we create an object of the Herbivorous class we are able to inherit methods from the Animal class.
When to use inheritance
- Inheritance is used when there is an IS-A relationship between two classes. For example, Herbivorous is-an Animal.
- When code re-usability is desired.
- Inheritance is used when sub categories can be created from complex class.
Delegation
As the word suggest, delegation means assign the task to some other entity. In object oriented programming terminology it an be explained as, process of implementation of one method to other method in different class. Delegation is also called as dynamic inheritance. It is an alternative to some inheritance and
When two objects are not of the same type, let’s say there are two objects A and B, A has some method and attributes, which B is interested in using. Then, using delegation technique, This mechanism can be suitable where we have to decide at run time based on the user input, which functionality needs to be executed.
Code example in Ruby
module Airplane def motion raise NotImplementedError.new end end class Wheel include Airplane def motion puts " Performs circular motion." end end class Wing include Airplane def motion puts "Performs Vertical motion" end end class AirplaneActivity include Airplane def initialize @var = Wing.new end def motion @var.motion end def setWing @var = Wing.new end def setWheel @var = Wheel.new end end
Call
obj = AirplaneActivity.new obj.motion # output => "Performs Vertical motion" obj.setWheel # create new object of Herbivorous class obj.motion # output => "Performs Circular motion"
Delegation Vs Inheritance
As there different classes, the functionality of one can be changed without affecting functionality of other classes.
Use the delegation pattern when:
- Delegation is used when there is HAS-A relationship between two object. For example, Airplane has engine and wings. Relationship between all these three classes depict the HAS-A relationship. Based on which activity to be monitored, corresponding motion() method is invoked. This is not the case with the inheritance, to get the silghtly different functionality, we have to over write the existing method.
- Delegation should be used when there the two objects are of the different type but has some what similar functionality.
- Delegation can be used where components that behave identically, but this situation may change over the time.
- delegation leverage loose coupling in the components and hence the alteration of one component does not affect the system much. In the inheritance, on the other hand, there is a tight coupling between parent class and its children hence modification in parents functionality may lead logical error in all its children.
- Delegation is sometimes called as dynamic inheritance as the binding happens at run time. In the above example, based on the object, corresponding methods are invoke. This not the case with inheritance as its is determined at the compile time.
Disadvantages of delegation
One of the of delegation is, it increases the code size as compared to inheritance. In above code also we have written one interface and three classes to make delegation work.
Message Forwarding
In object oriented programming, message forwarding is one of the most powerful techniques. In this, when a message is sent to an object and if that object does not process that particular method, then instead of displaying error, receiving object gets a second chance to process a message.
SmallTalk and Objective-C supports this mechanism.
Let’s look at the simple example for message forwarding. Lets say we have two classes ‘Nurse’ and ‘Doctor’.
In the above example, when the message for ‘operate’ comes to the Nurse, it does not handle that messages as ‘Nurse don’t do operations alone and has to be done by doctor.’ Hence instead of giving a error, it forwards that message along with input parameters to the ‘Doctor’ object. Doctor object handles the operate method and return the response to the Nurse object. From the abstract view, it appears that Nurse object is only handling the message but in real, Doctor’s object working on it. Message forwarding simulates multiple inheritances in object oriented programming as object that forwards message can inherits method from its super class and the class where it is forwarding the method. In other words, Nurse inherits functionality from its super class and Doctor class.
For selection of different objects to forward the message, observer design pattern is follow. Languages like objective-C have extensive support for message forwarding. To implement this, observer design pattern is used. There are four parts to a message: a receiver object, a method name, optional method arguments, and an optional return value.
Code example – objective -C
id newObject; // could be any object; newObject = [[NewObject alloc] init]; // create and initialize the object [newObject doSomethingWith: anotherObject]; // send it a message. - (void) forwardInvocation: (NSInvocation*)anInvocation { if ([anObject respondsToSelector: [anInvocation selector]]) return [anInvocation invokeWithTarget: anObject]; else return [self doesNotRecognizeSelector: [anInvocation selector]]; }
Message forwarding Vs. Inheritance
- Message forwarding is leverage the functionality of reusing the code of some other class. This functionality cannot be implemented using inheritance as code reuse is done only in the inheritance hierarchy and not beyond that.
- Compared to inheritance, message forwarding provides privilege of loosely coupled design as the different objects can communicate via exchange of massages. In inheritance, there is always a tight coupling .
- This helps data to be sent to objects of different classes in a very efficient manner. Languages like objective –C or SmallTalk have specific methods to implement this. Also message forwarding can be simulated with other object oriented languages like Java , Ruby and many more.
- The change of a state in one object must be reflected in another object without keeping the objects tight coupled.
- In inheritance, if we want custom implementation, then we have to override the method to provide new functionality. In this we cannot change the method prototype. If user wants to change prototype of the method, then all the overridden methods have to change the prototypes. In contrast to that, with the help of message forwarding, we can avoid this situation as the messages are getting passed to other object, hence no dependencies.
Disadvantages of Message forwarding
- In message forwarding, each argument have to allocate extra memory, however in inheritance, as derived class object at call of it parent object only reference to the arguments are passed. As an example, if a big string (around 2000 characters) to be passed as an argument, that much memory has to be allocated. However, in inheritance as all the objects are tightly coupled, sending the object reference is enough.
Message forwarding can also be simulated from other objected oriented languages.
Example using Java
Class A { Public String a() { return a1();} Protected String a1 {return “A”;} } Interface IB{ Public String b(); } Class B implements IB{ Public String b() {return b1();} Protected String b1() {return “B”;} } Class C extends A implements IB { B b; //aggregation Public String b(){ b.b();} //Forwarding Protected String b1() {return “C”;} Protected String a1() {return “C”;} }
C c = new C(); c.b(); // output => B c.b1(); // output =>
In the above code, when
Decomposition
Decomposition follows the divide and conquer strategy which help to solve any complex problem. It is method of breaking down bigger problem or system into smaller ones for clear understanding of its functionality. The different part after decomposition of the systems interacts with each other through well defined interfaces.
Lets say, we decompose our system by writing functions. Here, we do not have objects and the functions are dependent on each other. So, if the implementation of one of the function changes, all the other functions which are dependent on this function also need to changed.
To avoid this problem, Decomposition in object-oriented OOP design is preferred. In this, we create well defined objects. These objects interact with each other through well defined interfaces. So if the implementation in one of the object changes then, only two objects between which the interaction takes place need to change their implementation. This has the advantage that, due to changes in one of the objects we do not affect a larger portion of the system.
In object oriented programming multiple inheritances plays an important role. Languages like C++ allowed multiple inheritances. The well known problem for multiple inheritances is diamond problem and due to the complex hierarchy programmer’s finds less visibility of the functionality in inheritance tree. Hence decomposition is considered as a solution to these problems.
Consider the above airplane system. The airplane consists of wheel, wings, propellers, cockpit, etc.
In Object Oriented Decomposition we create objects of these classes. Also we create an object Controller which interacts with all these objects and is responsible for the overall functioning the system.
Suppose if there is a problem with the wheel, this does not affect the functionality of other objects. Only the central controller and the wheel need to implement the necessary changes. This does not affect the functionality of other objects.
Inheritance vs Decomposition
- In Inheritance we need to define methods in the Super class which can be used by the objects in sub class. This can be achieved by using the extends functionality in Java.
- Where as in the case of Decomposition, the objects define their own methods. So there is minimal dependency between the interacting objects.
- When the system is huge and the depth hierarchy tree is large, decomposition should be used.
- When we want the components of the system to be loosely coupled.
References
Delegation (programming) - http://en.wikipedia.org/wiki/Delegation_%28programming%29
API documentation for Objective-C - http://www.gnustep.org/resources/documentation/Developer/Base/Reference/NSObject.html
objective-C - http://en.wikipedia.org/wiki/Objective-C
Decomposition - http://www.ibm.com/developerworks/webservices/library/ar-soastyle/