CSC/ECE 517 Fall 2011/ch2 2c ds

From Expertiza_Wiki
Revision as of 05:44, 20 September 2011 by Dnyayac (talk | contribs) (→‎Approaches)
Jump to navigation Jump to search

Introduction

Interfaces

Mixins

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. 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. They help the programmer adhere to the DRY (Don’t Repeat Yourself) principle and allows them to add the functionality of modules into your classes.

Modules are defined in Ruby using the module keyword.

Supported Languages

Multiple Inheritance

Diamond Problem

Approaches

Different programming languages have addressed this 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.

Comparison between Mixins and Interfaces

Advantages and Disadvantages

Conclusion

References

Useful links