CSC/ECE 517 Fall 2011/ch2 2c ds: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
Line 36: Line 36:
Mixin example:
Mixin example:


Module A consists of the methods method_A1 and method_A2.
Module ParkingSlot consists of the methods park and unpark
   <span style="color:#4682B4">
   <span style="color:#4682B4">
   module Test1
   module ParkingSlot
    def method_A1
def park
    # … Some code … 
#code to park the car
    end
end
    def method_A2
def unpark
    # … Some code…
#code to unpark the car
    end
end
   end
   end
  </span>
  </span>


Module B consists of the methods method_B1 and method_B2.
Module ParkingMeter consists of the methods calculate and printreceipt
  <span style="color:#F4A460">
  <span style="color:#F4A460">
   module Test2
   module ParkingMeter
    def method_B1
def calculate
    # … Some code … 
#code to calculate the fee
    end
end
    def method_B2
def printreceipt
    # … Some code…
#code to print the receipt
    end
end
   end
   end
  </span>
  </span>
Line 63: Line 64:


  <span style="color:#6B8E23">
  <span style="color:#6B8E23">
   class Sample 
   class Parking
  include Test1
#include ParkingSlot
  include Test2
#include ParkingMeter
    def class_method
def printCarDetails
    puts “Calling from class”
#code to print the details and type of car
    end
end
  end
  end
  </span>
  </span>


The modules A and B are “included” in the Sample class. All the variables and the instance methods of the modules A and B are now said to be “mixed in” into the class.
The modules ParkingSlot and ParkingMeter are “included” in the Sample class. All the variables and the instance methods of the modules ParkingSlot and ParkingMeter are now said to be “mixed in” into the class.
It is now possible for class instances to use these methods defined in the modules as and when required.
It is now possible for class instances to use these methods defined in the modules as and when required.


   samp=Sample.new   
   p=Parking.new   
   samp.method_A1    # -> Method A1 from module Test1
   p.park            # -> Method park from module ParkingSlot
   samp.method_A2    # -> Method A2 from module Test1
   p.unpark          # -> Method unpark from module ParkingSlot
   samp.method_B1    # -> Method B1 from module Test2
   p.calculate      # -> Method calculate from module ParkingMeter
   samp.method_B2   # -> Method B2 from module Test2
   p.printreceipt   # -> Method printreceipt from module ParkingMeter
   samp.class_method # -> Calling from class
   p.printCarDetails # -> Calls printCarDetails from class


The class Sample inherits from both the modules and the methods of the module defined in the modules are now available as instance methods in Sample. Hence, it is now possible to use the methods with an instance of the Sample class ''samp''.
The class Sample inherits from both the modules and the methods of the module defined in the modules are now available as instance methods in Sample. Hence, it is now possible to use the methods with an instance of the Sample class ''samp''.

Revision as of 14:06, 21 September 2011

Mixins v/s Interfaces

Introduction

Interfaces

In the Java programming language, an interface is a reference type, similar to a class that can contain only constants, method signatures, and nested types. There are no method bodies. Interfaces cannot be instantiated—they can only be implemented by classes or extended by other interfaces.

Example:

 public interface ParkingLot {
       boolean add(Car car, int slot);
       boolean remove(Car car);
       boolean findCar(Int number);
       int freeSlotsCount();
       int occupiedSlots();
       int parkingType();
       int calculateParkingFee(int hours, int charge, int duration);
       int findParkingSlot();
 }


Interfaces have another very important role in the Java programming language. Interfaces are not part of the class hierarchy, although they work in combination with classes. The Java programming language does not permit multiple inheritance (inheritance is discussed later in this lesson), but interfaces provide an alternative.

In Java, a class can inherit from only one class but it can implement more than one interface. Therefore, objects can have multiple types: the type of their own class and the types of all the interfaces that they implement. This means that if a variable is declared to be the type of an interface, its value can reference any object that is instantiated from any class that implements the interface.

Mixins

Modules provide a structure to collect classes, methods, and constants into a single, separately defined unit. They provide the simplest and an elegant way to adhere to the Don't repeat yourself principle.

A Mixin is a class that is mixed with a module or a set of modules i.e. the implementation of the modules and the class are intertwined and combined together <ref>Mixins </ref> . This gives us a neat and controlled way of adding new functionality to classes. Modules are similar to classes in that they hold a collection of methods, variables constants and other modules and class definitions.

The real usage of a Mixin is exploited when the code in the Mixin starts to interact with code in the class that uses it. Modules provide a structure to collect Ruby classes, methods, and constants into a single, separately named and defined unit thereby. This is useful so that you can avoid clashes with existing classes, methods, and constants.

Modules are defined in Ruby using the module keyword.

Mixin example:

Module ParkingSlot consists of the methods park and unpark

 
 module ParkingSlot

def park #code to park the car end def unpark #code to unpark the car end

 end

Module ParkingMeter consists of the methods calculate and printreceipt


 module ParkingMeter

def calculate #code to calculate the fee end def printreceipt #code to print the receipt end

 end

When a class includes a module via include Module Name, all the methods on that module become instance methods on the class.


 class Parking

#include ParkingSlot #include ParkingMeter def printCarDetails #code to print the details and type of car end

  end

The modules ParkingSlot and ParkingMeter are “included” in the Sample class. All the variables and the instance methods of the modules ParkingSlot and ParkingMeter are now said to be “mixed in” into the class. It is now possible for class instances to use these methods defined in the modules as and when required.

 p=Parking.new   
 p.park            # -> Method park from module ParkingSlot
 p.unpark          # -> Method unpark from module ParkingSlot
 p.calculate       # -> Method calculate from module ParkingMeter
 p.printreceipt    # -> Method printreceipt from module ParkingMeter
 p.printCarDetails # -> Calls printCarDetails from class

The class Sample inherits from both the modules and the methods of the module defined in the modules are now available as instance methods in Sample. Hence, it is now possible to use the methods with an instance of the Sample class samp.

Hence, Mixins can be thought of taking different methods and variables defined in different modules making them available as instance methods in the class as well, thereby extending the class’ functionality. Effectively mixed in modules behave as superclass.

Supported Languages

The following table shows support for Mixins and Interfaces by most commonly used languages.

Languages Mixins Interfaces
Ruby Yes No
Java No Yes
Python Yes No
Smalltalk Yes No
Perl Yes No
C# No Yes

Multiple Inheritance

Multiple Inheritance refers to a feature in some object oriented programming languages in which a class can inherit behaviors and behaviors from more than one superclass. This contrasts with single inheritance in which a class can inherit behavior from at most one superclass. Though Multiple Inheritance provides its own advantages of improved modularity and ease of reuse of code in certain applications, it has its own set of disadvantages which sometimes outweigh the possible advantages.


Diamond Problem

This section describes the well know “Diamond Problem” associated with multiple Inheritance and the succeeding sections describe how Mixins and interfaces can be used to overcome this problem. The diamond problem is the ambiguity that can occur when a class inherits from two different classes that both descend from a common superclass. For example, consider a scenario where one decides to combine the Frog and Dinosaur species which both are inherited from the animal class. The talk() method in the Animal class is abstract and both Frog and Dinosaur needs to implement this method.

Lets say both Frog and Dinosaur implement the talk method like this:

   public class Frog extends Animal {
         void talk() {
              System.out.println(“I am Frog, I can croak “);
         } 
  }

and,

   public class Dinosaur extends Animal {
         void talk() {
              System.out.println(“I am Dinosaur, I can roar “);
         } 
  }

When the Frogsaur is created, it inherits from both Frog and Dinosaur.


   public class Frogsaur extends Frog, Dinosaur {
      // Note below syntax is used just for demonstration
   }

The problem happens when someone tries to invoke talk() method on a Frogsaur object from the Animal reference.

   Animal animal = new Frogsaur();
   animal.talk(); // which method to invoke ???


Due to this ambiguity caused by the diamond problem, it isn’t clear whether the runtime system should invoke Frog’s talk() method or Dinosaur talk() method.

Approaches

Different programming languages have addressed the diamond problem in different ways

In Java, interfaces solve all these ambiguities caused by the diamond problem. Through interfaces, Java allows multiple inheritance of interface but not of implementation. Implementation, which includes instance variables and method implementations, is always singly inherited. As a result, confusion will never arise in Java over which inherited instance variable or method implementation to use.

Ruby does not support multiple inheritance. Mixin provide a way which eliminates the need for multiple inheritance. Ruby has modules which are just like abstract classes in Java. Modules can have different methods implemented in them. They cannot be instantiated like abstract classes. They cannot inherit from other modules or classes. Ruby classes can inherit from only one superclass but can have unlimited number of modules in them to exploit the usage of predefined implementations in these modules. This provides functionality similar to multiple inheritance avoiding any ambiguities.

The below code demonstrates two modules Frog and Dinosaur, each of which contain the talk method defined in them. The Frogsaur class includes these two methods and defines its own talk method. This example was chosen to exhibit on how Ruby resolves method calls at run time.


 module Frog
     def talk
         puts "I can croak"
     end
 end
 module Dinosaur
     def talk
         puts "I can roar"
     end
 end
 class Frogsaur
     include Frog 
     include Dinosaur
        def talk
            puts "I can roar like a dinosaur and croak like a frog"
        end
 end
 fs = Frogsaur.new
 fs.talk         # -> I can roar like a dinosaur and croak like a frog

When the method talk is called on the Frogsaur object, Ruby makes sure that the latest method defined in the hierarchy is chosen. Here in this example, the talk method in the Frogsaur class is defined the latest and hence “I can roar like a dinosaur and croak like a frog” is printed. If there was no method defined in the class, method from the Dinosaur is printed since it is next in the hierarchy specified by the include statements.

Comparison between Mixins and Interfaces

This is a general comparision:

Mixins Interfaces
In Ruby, modules have the implementation of the methods. So all the classes which include the modules gets the same Implementation because classes create a reference to these modules. In Java, all classes which implement the interfaces should provide implementation for each of the methods declared in the interface. This might duplicate the code if the 2 or more classes have similar functionality.
Relatively smaller because the classes automatically get access to methods defined in the modules. Modules server as a central repository Relatively larger because a class implementing more than one interfaces has to provide implementation.
Having more modules in the classes can make code less readable. Ideally mixins are suitable for small teams having few modules. The code is more readable here as the implementation is provided to each method and can be found in place
In Ruby, a method inside a module can have Module name as qualifier. Hence it’s possible for a class to have inherit two or more modules which have same names. In Java, the class itself has to provide the implementation of the methods. Inheriting methods of same names from different interfaces will signal an error message.
Modules cannot be inherited and cannot form is-a hierarchy Interfaces can extend another interface and hence can form is-a hierarchy

Drawbacks of Mixins and Interfaces

The drawbacks of the technique of Mixins are very much debated. Though Mixins provide us with an easy way to write flexible and decoupled code and also help us solve the diamond problem, they pose their own problems. In large programs there could be large number of modules and each module could have loads of methods each performing a certain task, to trace the origin of the methods and to keep in mind the hierarchy is practically impossible. Another issue associated with Mixins pose is silent method overriding. Although Java provides polymorphic behavior with the use of interfaces, they sometimes tend to be very slow. The implementation of interfaces are also limited to public methods and constants with no implementation.

Conclusion

Although mixins have certain advantages over interfaces, they possess their own share of disadvantages. Mixins are generally used in small frameworks and interfaces , more than solving the problem of multiple inheritance provide polymorphism feature which makes object-oriented code more flexible and easy to modify and maintain.

References

<references/>

See Also