CSC/ECE 517 Fall 2010/ch3 3b sv

From Expertiza_Wiki
Revision as of 20:49, 6 October 2010 by Vsubram3 (talk | contribs)
Jump to navigation Jump to search

Multiple Inheritance and Mixins

Inheritance is a concept of Object Oriented Programming (OOP) that facilitates reuse and compartmentalization of code by creating objects ( which are collections of attributes and behaviors ) which can be derived from existing objects. The deriving object(class) is termed as the child class/sub-class/derived class , and, the object(class) whose methods are being used is called the parent class/super-class/base class. This relationship between the super and sub-classes arising due to inheritance creates a hierarchy amongst the classes. Inheritance is termed as Single Inheritance if there is only one base class. Languages like C++,Java,Ruby,Python and SmallTalk support inheritance.

Definitions

Multiple Inheritance

If a child class inherits behaviors and attributes from two or more parent classes, it is termed as Multiple Inheritance. Languages supporting this feature include C++,Perl and Python. The main advantage of Multiple Inheritance is that it enables an user to combine independent(and not so independent) concepts(classes) into a composite concept called the derived class. For instance,given a set of interaction base classes and a set of base classes defining display options, the user can create a new window by selecting a style of window interaction and appearance from the given base classes.

Suppose there are N concepts, each of which can be combined with one of M other concepts, N+M classes are required to represent all the combined concepts. The situation with N = M = 1 is Single Inheritance. Examples with N>=2 and M>=2 are common and Multiple Inheritance plays an important role in such situations by avoiding replication.

Interfaces

Java designers cut the features of multiple inheritance and operator overloading from C++ to keep the language simple,object oriented and familiar. Interfaces were introduced in Java to simulate multiple inheritance. Interfaces (defined using the keyword interface) are abstract type containing only the method signatures and constant declarations. A class which implements an interface does so by implementing all its methods. Thus, interfaces act as templates.

Modules

A module is defined as a component which regroups similar things. Modules differ from classes as modules are just names to regroup things which we think are similar, whereas, classes consist of variables and methods describing the state and the behavior of an entity [1]. A module "protects" the names it contains. The primary benefits of using modules are:

  • The code is more organized.
  • The risk of name clashes is eliminated as modules provide namespace facility.
  • Mixins can be implemented using modules.

Unlike classes, objects can neither be created nor sub-classed based on modules. Instead, the functionality of a particular module can be specifies to be added to a particular class or object.


Mixin

Mixins are one of the defining features of Ruby that is closely related to Duck typing. Duck typing is a technique that allows usage of objects to respond to a certain set of method calls interchangeably. Mixins are a group of methods that are not yet attached to any class. They exist in a module, and are useful only when they are included in a class. Mixin thus behaves as an interface with implemented methods.

Mixins cannot be instantiated, but, provide functionality to be inherited by a subclass. Ruby supports only single inheritance. So, mixins prove to be of great importance in Ruby as they simulate multiple inheritance capability in Ruby which allows classes to inherit functionalities from two or more mixins [2],[3],[4].

An Enumeration is a type of mixin module which can be used by all the classes. Its does not depend on the language syntax. It is defined as “ an operation that is performed on elements of a set”. example of enumeration is: [34, 56, 76, 96].each {|a| puts a}



Traits

A trait can be considered as a collection of methods which serves as a simple model for structured object oriented programs [5]. The main difference between mixins and traits lies in the way both are composed. Mixins are composed using only the inheritance operation, but, traits can include symmetric sum, aliasing and method exclusion. Traits is not an abstract type and implements methods.

With Traits, classes are organized in a single inheritance hierarchy. Traits are basically used to specify incremental differences in the behavior of sub- and super-classes. Traits are supported in programming languages like Fortress,Perl,SmallTalk and Joose framework for JavaScript.

Diamond Problem : Loophole in Multiple Inheritance

With single inheritance, classes cannot be classified into the branches of the hierarchy and hence, is limiting. Multiple inheritance overcomes this and supports complex relationship models.

But multiple inheritance has the following problems:

  • It is possible that a class inherits multiple features with the same name.
  • There can be more than one path to a given ancestor from a class ( known as the diamond problem or fork-join inheritance )
  • Encapsulation of inheritance: Is it allowed for a client or inheritor of a class to depend on the inheritance structure of that class?
  • Common ancestor duplication problem: Must the common ancestor be duplicated or not?
  • Duplicate parent operation invocation problem: Multiple inheriting from two classes that both invoke the same parent operation on a common ancestor can cause duplicate invocation of this parent operation. How is this problem dealt with?


The conflicting-features problem can be resolved by permitting renaming or by having a linear class hierarchy. The diamond problem is an ambiguity arising when two classes B and C inherit from class A, and both B and C are inherited by class D. If both classes B and C override the definition of a method inherited from A, then, when class D inherits this same method, conflict arises if D should use the method from B or C.

Figure 1. The diamond problem hierarchy

In C++, Virtual inheritance was proposed as one solution for class D to inherit only one copy of A's methods. But object initialization is a problem when we have only one copy. Another consequence of diamond problem is that multiple inheritance interacts poorly with modular typechecking of multiple dispatch.

Java makes use of the concept of interfaces to simulate Multiple Inheritance and the responsibility of implementing the functions defined in the interfaces lies with the classes making use of the interface. Similarly Ruby uses the concept of mixins and SmallTalk and Perl use Traits. But each solution has its own pros and cons.

Comparison

Mixins and Interfaces

FEATURE MIXINS JAVA INTERFACES
Maintainability In Ruby, modules have the implementation of the methods. So all the classes who “include” the module get the same method and its functionality. The definition of the method can change at run time. Java forces the classes using the interfaces to implement the methods defined in the interface. This might lead to code duplication if two classes have similar functionality. Secondly, changes have to be made at both places if the method changes in future.
Size of the Code The class/objects automatically get access to the methods of the included module(s). If a class inherits multiple interfaces, it is forced to implement unnecessary, and sometimes, duplicate code which makes the code grow in size.
Readability The module and the class using the module can be in different files. Hence, the code is less readable. So mixins are beneficial for individual or small teams. For bigger teams, documentation becomes an important criterion. The code is more readable and explicit as the implementation of a method can be found at a place.
Naming Conflicts Modules provide the facility of namespace. So it is possible for a class to inherit two or more methods of same name from different modules. Since the class itself has to provide the implementation of the methods, inheriting methods of same names from different interfaces will signal an error message.


Mixins and C++ Multiple Inheritance

ADVANTAGES DISADVANTAGES
MIXINS 1. Avoids complex features like virtual base classes.
2. Code is less verbose.
3. Modules can be made aware of who included them.
1. In case of naming conflicts while mixing multiple modules, notification of the error may be incorrect.
2. Ruby is used for implementation inheritance and finds very less use in inheritance implementation.
3. Since it supports non-virtual classes, getting two copies of the base class requires odd code.
C++ MULTIPLE INHERITANCE 1. Naming conflicts point to the proper error normally.
2. Can be used for both interface and implementation inheritance.
3. Supports virtual base classes.
1. C++ classes do not have any knowledge of who inherited them.
2. Poses diamond problem



In the classic scenario of diamond problem [ Figure 1 ], Ruby simplifies the inheritance to look like D<C<B<A. In C++ Multiple Inheritance, C::foo cannot call B::foo, but with Ruby mix-ins,this is possible.

Conclusion

Each of the above approaches- Multiple Inheritance, Interfaces, Mixins and Traits - have their own pros and cons. Each one tries to solve the deadly Diamond problem in a different way, but, no one solves it completely. Traits have the disadvantage that they don not allow states. The programmer has to make the choice of which mechanism fits the best depending upon the task under consideration.


References

[1] http://ruby-doc.org/docs/ProgrammingRuby/html/tut_modules.html

[2] http://juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/

[3] http://ruby.about.com/od/beginningruby/a/mixin.htm

[4] http://stackoverflow.com/questions/533631/what-is-a-mixin-and-why-are-they-useful

[5] http://en.wikipedia.org/wiki/Trait_%28computer_science%29

[6] http://www.amazon.com/Programming-Ruby-Pragmatic-Programmers-Second/dp/0974514055 Programming Ruby: The programmatic programmer’s guide


See Also

[1] http://www.oreillynet.com/ruby/blog/2007/01/digging_deep_mixing_it_up_or_i_1.html Article from O'Reilly's website which discusses mixins at depth

[2] http://www.sapphiresteel.com/The-Little-Book-Of-Ruby

[3] http://www.parashift.com/c++-faq-lite/multiple-inheritance.html#faq-25.8

[4] http://www.juixe.com/techknow/index.php/2006/06/15/mixins-in-ruby/