CSC/ECE 517 Fall 2012/ch1a 1w23 as

From Expertiza_Wiki
Jump to navigation Jump to search
The printable version is no longer supported and may have rendering errors. Please update your browser bookmarks and please use the default browser print function instead.

1w23: Multiple Inheritance and Mixins

Introduction

The purpose of this article is to give a brief introduction about multiple inheritance, consider some of its issues and discuss techniques employed by different programming languages to handle such issues. In this relation, the article also compares solutions provided by different programming languages, especially against Ruby mixins, by listing their advantages and disadvantages.

Multiple Inheritance

Multiple Inheritance is a technique of establishing hierarchical relationships within a set of classes, such that a single class can inherit  behaviors from multiple parent classes. Although it might seem useful to include methods from multiple classes, the major issue with multiple inheritance is the ambiguity in referencing the parent class methods,  when more than one parent classes share a method with the same name.This ambiguity is predominant in cases where the inheritance hierarchy is more than one level deep, where the class in the lowermost level inherits from two classes, that have overridden the same method from their parent in different ways.<ref>http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem</ref>

A Real World Example

A known example of multiple inheritance to represent winged animals and mammals, using classes and objects is cited here <ref> http://stackoverflow.com/questions/9359948/multiple-inheritance-whats-a-good-example</ref>. A Winged animal and a mammal inherit primitive attributes of an animal. While a winged animal can fly; a mammal can breathe and reproduce; they both eat, move and share features generic to animals. A bat being a winged mammal possesses features common to both winged animal and mammal. It follows that class Bat inherits from classes WingedAnimal and Mammal and in turn classes WingedAnimal and Mammal inherit from class Animal. In reference to this context, let us write our own implementation and explore the issues of multiple inheritance.

Class Diagram for the example.

Issues of Multiple Inheritance

  • Due to inheritance, the parent class’s objects get duplicated to child class. As a result, Class Bat duplicates Animal objects through each of WingedAnimal and Mammal classes. When Bat accesses any of the Animal's attributes, the compiler would be ambiguous about determining the correct path to use since two paths are available from Animal to Bat. This problem of multiple inheritance is called diamond problem <ref>http://www.artima.com/weblogs/viewpost.jsp?thread=246488</ref>. Compiler takes arbitrary decisions during such situations.
  • Objects of parent classes can be separately managed by using virtual tablesas in C++. By explicitly specifying the virtual table pointer, the Bat class can access WingedAnimal and Mammal classes unambiguously. However virtual tables occupy significant portion of memory thereby limiting their extensive usage.
  • The order by which a child class inherits parent classes also matters. If Bat inherits WingedAnimal prior to Mammal, then WingedAnimal precedes Mammal and common methods are accessed in this order of precedence. Hence if the Programmer is not aware of such precedence, debugging would be difficult.

Solutions

Programming languages provide different solutions to handle the issues of multiple inheritance. Here we consider the techniques offered by C++, Java, Ruby, Scala and Python.

Multiple Inheritance in C++

C++ supports multiple inheritance with the notion of virtual classes and virtual functions. In the example, the Animal class defines virtual function canEat() with WingedAnimal and Mammal classes virtually inheriting the features of Animal. The Bat class can now unambiguously access canEat() method of Animal class, using virtual table pointers of WingedAnimal and Mammal. The example written using C++ virtual functions is shown below.

class Animal
{
 public:
 void virtual canEat() {
 }
};
class WingedAnimal :virtual public Animal
{
 public:
 void canFly() {
 }
 void canEat() {
 }
};
class Mammal :virtual public Animal
{
 public:
 void canGiveBirth() {
 }
 void canEat() {
 }
};
class Bat :public WingedAnimal, public Mammal
{
 public:
 void canFly() {
 }
 void canGiveBirth() {
 }  
};
int main()
{
 int i = 0;
 Animal *instances[3];
 WingedAnimal w;
 Mammal m;
 Bat b;
 instances[0] = &w;
 instances[1] = &m;
 instances[2] = &b;
 while(i<3)
   instances[i++]->canEat();
 return 0;
}

Multiple Inheritance in Java

Java doesn’t support multiple inheritance but provides a feature called interfaces to simulate inheritance from multiple classes. Interface is an abstract class which provides a generic template by just declaring variables and methods without implementing them. Concrete classes that inherit interfaces are supposed to implement its methods. The example written using Java interfaces is shown below.

interface Animal
{
  void canEat();  
}
interface WingedAnimal extends Animal
{
  void canEat();  
  void canFly();  
}
class ImplementWingedAnimal implements WingedAnimal  
{
   public void canEat() {    
   }
   public void canFly() {    
   }
}
interface Mammal extends Animal
{
  void canEat();
  void canGiveBirth();
}
class ImplementMammal implements Mammal
{
   public void canEat() {    
   }
   public void canGiveBirth() {    
   }    
}
interface Bat extends WingedAnimal, Mammal
{
   void canEat();    
}
class ImplementBat implements Bat
{  
   ImplementWingedAnimal w = new ImplementWingedAnimal();
   ImplementMammal m = new ImplementMammal();     
   public void canEat() {            
     m.canEat();  
     w.canEat();      
   }
   public void canFly() {
   }
   public void canGiveBirth() {
   }    
}
public class MultipleInheritance
{
  public static void main(String args[])
  {
    ImplementBat b = new ImplementBat ();
    b.canEat();       
  } 
}

Multiple Inheritance in Ruby

Ruby doesn't support multiple inheritance but provides a similar feature using modules and mixins.

Modules

A Module is an encapsulation of methods and variables, although similar in function to a Class, differs from a class in the sense that it cannot be instantiated. Modules are more dynamic and allow us to organize the code in a more granular way.Each module can add something to the existing class. A module can be thought of an encapsulation of a subset of the full capabilities of an object. An example found in the book ,The Well-Grounded Rubyist <ref>http://www.manning.com/black2/SampleChapter4.pdf [Pg.92] </ref>, is the stack-like module. The module encapsulates the characteristics of being like a stack,implements the operations that can be performed by a stack but is not the actual Stack class. This allows us to use this module to mix-in stack-like behaviour into other classes that require them.

Mixins

A Mixin is a concept that allows inclusion of special characteristics into existing classes, so that common features that need to be reused in several classes can be selectively included, thus avoiding implementation of unnecessary functions like in the case of interfaces. Mixins allow us to dynamically bind special features defined in modules, into core classes without really making any changes to the objects. This improves flexibility when we want to add plugins and extensions to the existing framework.<ref>http://www.innovationontherun.com/why-rubys-mixins-gives-rails-an-advantage-over-java-frameworks/</ref>.The source code for the same example implemented using ruby mixins is shown below.

module Animal
  def canEat     
  end  
end
module WingedAnimal
  include Animal    
  def canEat
  end      
  def canFly
  end      
end
module Mammal
  include Animal
  def canEat
  end
  def canGiveBirth
  end  
end
class Bat
  include WingedAnimal
  include Mammal
  include Animal  
end
  
Bat.new().canEat()

Multiple inheritance in other languages

Scala offers traits that are similar to Java interfaces to support multiple inheritance. Traits define a template with methods and variables which any class can make use of. The difference between interfaces and traits is that traits can implement methods. A Scala class can inherit from any number of traits together with a class in a way to support multiple inheritance. Traits can be mixed in to a class even without inheriting it but just by including it at the time of creating instances similar to extend feature in ruby. <ref>http://joelabrahamsson.com/entry/learning-scala-traits</ref>. Trait can also extend a class and methods to be overridden are usually prefixed by the keyword override. The language enforces method names to be different across inherited traits to avoid the issues of multiple inheritance. Python supports a limited version of multiple inheritance by extending multiple classes in depth-first left-right order <ref>http://docs.python.org/tutorial/classes.html</ref>. If a python class D inherits classes A, B, C and if an instance variable or method is not available in the current class, it checks in A and its base classes, then moves to B and its base classes and eventually to C thus moving from left to right. In this way, python avoids the diamond problem by making the search order linear, by which the derived class accesses attributes of its parent classes. In addition python also defines mixins to access reusable features within a class.

Advantages of mixins

  • Firstly, when a module gets mixed into different classes, each class acquires the same reference to the module and hence even dynamic changes to the module gets reflected in the behavior of the classes <ref>http://www.linuxtopia.org/online_books/programming_books/ruby_tutorial/Ruby_Modules_Mixins.html</ref>. In this way, the module’s code is not just copied to individual classes as in static languages instead its reference is provided.
  • Secondly, the mixed in state and behavior can be accessed by the instance of target class just like accessing its own features.
  • Thirdly, a class can include any number of modules in a way it can simulate multiple inheritance without having the related issues.

Questions to Ponder

Do mixins solve all of the problems of multiple inheritance?

Undoubtedly mixins solve some of the problems of multiple inheritance. There is no ambiguity in resolving the request to a common method implemented by multiple modules. In that case, the lastly included module is responsible for handling accesses to common methods. Though the order of precedence of included modules matters, it looks clearer than C++. However languages like Scala and Eiffel implement multiple inheritance far more safely by explicitly forcing the user to have different method names across inherited classes.

Are mixins a clear advantage over interfaces?

Mixins are more advantageous than interfaces because of their features. Interfaces have some limitations. As seen from the example, the derived class Bat uses the instances of WingedAnimal and Mammal classes (has-a relationship) to access respective attributes. Interface is nice in the sense it provides a generic template that could be implemented differently by different classes. However the target class has to necessarily implement every method of the interface. This would pose problems to a Class which is interested in implementing specific features of the interface. On the contrary, Mixins eliminate this inconvenience by mixing in the state and behavior of the modules in the target class and allows it to use them as it needs. Hence the target class can just use module’s features selectively or completely instead of implementing by itself. The size of multiple inheritance code using mixins is smaller than interfaces and C++ variants and this is obvious from the example.

Do mixins have any disadvantages not shared by multiple inheritance or interfaces?

Inspite of making the lives of programmers better with effective code reuse and avoiding unnecessary implementation of methods that cause clutter in the code, the concept of Mixins can easily be abused resulting in namespace pollution. This is caused when a class includes multiple modules each of which contains several hundred method implementations. Having hundreds of methods mixed into a single class, makes it difficult to identify the source modules of the methods, thereby causing confusion while implementing these methods, whereas in the case of multiple inheritance we can easily identify the class to which the method belongs. Another disadvantage that follows from the namespace collision is the case where we have multiple methods with the same name in different modules.In such a case whenever a call to that method is made, the method which belongs to the module that was included last will be called. In the above example, the method call canEat() invokes Animal's canEat() method since Animal was the last included module. The problem with this is that, this takes place silently without any warning. This may result in accidentally inheriting wrong methods.

Conclusion

In this article, we have discussed about multiple inheritance and means by which it is implemented in different languages. Though multiple inheritance is a useful feature, many languages do not support them due to its associated issues. Given its advantages, mixin in ruby seems to be a viable option to achieve multiple inheritance. However mixins too have limitations which should be taken care of during implementation.

References

<references/>

See Also

1. Dominic Duggan and Ching Ching Techaubol- OOPSLA '01 Proceedings of the 16th ACM SIGPLAN conference on Object-oriented programming, systems, languages, and applications, :Modular Mixin-Based Inheritance for Application Frameworks

2. Lucas Carlson and Leonard Richardson. 2006. Ruby Cookbook (Cookbooks (O'Reilly)). O'Reilly Media, Inc..

3. Herbert Schildt. 2000. Java 2: The Complete Reference (4th ed.). McGraw-Hill Professional.

4. http://en.wikipedia.org/wiki/Mixin