CSC/ECE 517 Fall 2012/ch1b 1w37 ss

From PG_Wiki
Jump to: navigation, search

Modules and Mixins


Contents

Regular Expressions

Definition


Regexp objects

r = /my regular expression/


Replace

"faculty".sub(/c/, "") >> "faulty"


Search

string1="I will drill for a well for you"
=> "I will drill for a well for you"
r=Regexp.new(/w.ll/)
=> /w.ll/
r.match(string1)
=> #<MatchData "will">

Suppose you want to retrieve the first digit in a string.Here's an example:

e4=Regexp.new('\d')
=> /\d/
string="hello12 123"
=> "hello12 123"
e4.match(string)
=> #<MatchData "1">
	

The above example since \d matches only digits it selects the 1 from Hello12.In order to retrieve the digits"12" from "hello12" we need to use \w which recognizes all word character[0-9A-Z a-z_] .Here's an example showing it.

e4=Regexp.new('\d\w*')
=> /\d\w*/
e4.match(string)
=> #<MatchData "12">

List of commonly used Regular expressions

The table below represents some special characters and their meaning in the patterns.

Regex- Character	Meaning
(...)	Capture everything enclosed
(a|b)	a or b
a?	Zero or one of a
a*	Zero or more of a
a+	One or more of a
a{3}	Exactly 3 of a
a{3,}	3 or more of a
a{3,6}	Between 3 and 6 of a
.	Any single character
\s	Any whitespace character
\S	Any non-whitespace character
\d	Any digit
\D	Any non-digit
\w	Any word character (letter, number, underscore)
\W	Any non-word character
\b	Any word boundary
[abc]	A single character of: a, b or c
[^abc]	Any single character except: a, b, or c
[a-z]	Any single character in the range a-z
[a-zA-Z]	Any single character in the range a-z or A-Z
^	Start of line
$	End of line
\A	Start of string
\z	End of string
options: i case insensitive m make dot match newlines x ignore whitespace in regex 
o perform #{...} substitutions only once

More Examples

Example Description

/([Rr])uby&\1ails/	Match ruby&rails or Ruby&Rails
/(['"])(?:(?!\1).)*\1/	Single or double-quoted string. \1 matches whatever the 1st group matched . \2 matches whatever the 2nd group matched, etc.

Example Description

/^Ruby/	Match "Ruby" at the start of a string or internal line
/Ruby$/	Match "Ruby" at the end of a string or line
/\ARuby/	Match "Ruby" at the start of a string
/Ruby\Z/	Match "Ruby" at the end of a string
/\bRuby\b/	Match "Ruby" at a word boundary
/\brub\B/	\B is nonword boundary: match "rub" in "rube" and "ruby" but not alone
/Ruby(?=!)/	Match "Ruby", if followed by an exclamation point
/Ruby(?!!)/	Match "Ruby", if not followed by an exclamation point

Example

line1 = "Cats are smarter than dogs";
line2 = "Dogs also like meat";
if ( line1 =~ /Cats(.*)/ )
  puts "Line1 starts with Cats"
end
if ( line2 =~ /Cats(.*)/ )
  puts "Line2 starts with Dogs"
end

This will produce following result:
Line1 starts with Cats

Example

text = "rails are rails, really good Ruby on Rails"
# Change "rails" to "Rails" throughout
text.gsub!("rails", "Rails")
# Capitalize the word "Rails" throughout
text.gsub!(/\brails\b/, "Rails")
puts "#{text}"
This will produce following result:
Rails are Rails, really good Ruby on Rails
	

Modules and Mixins

Modules

Definition

How Modules differ from classes?

Unlike classes, objects cannot be created based on modules nor can it be sub classed.However, it can be specified that the functionality of one module should be added to another class, or a specific object.

Uses of modules

Modules serve two purpose: 1.They act as namespace in C++, letting definition of methods whose names will not clash with those defined elsewhere. 2.Modules allow to share functionality between classes.


Example

module Window 
def Window.top 
# .. 
end 
def Window.bottom 
# .. 
end 
end 

module Border 
def Border.top 
# ... 
end 
def Border.width 
# .. 
end
end

When a program needs to use these modules, it can simply load the two files using the Ruby [http://ruby.about.com/od/rubyfeatures/a/require.htm require] statement, and reference the qualified names.

 
require 'window' 
require 'border' 
trueTop = Window.top + Border.Top.

Mixins

Definition

How mixinsis different from #include and multiple inheritance?


Example

Consider the following example taken from class notes [http://courses.ncsu.edu/csc517//common/lectures/notes/lec6.pdf Class notes of CSC517, NCSU] to illustrate mixins.

 
module Introspect 
  def kind 
    puts "#{self.class.name}" 
  end 
end 

class Animal 
  include Introspect 
  def initialize(name) 
     @name = name 
  end 
end 

class Car 
  include Introspect 
  def initialize(model) 
    @model = model 
  end 
end 
d = Animal.new("Cat") 
c = Car.new("Ferrari") 
d.kind # kind method is available through … 
c.kind # .. the mixin Introspect 
>>Animal 
>>Car 

Consider another example to understand mixins better.


module Persistence
  def load sFileName
   puts "load code to read #{sFileName} contents into my_data"
  end
 def save sFileName
  puts "Uber code to persist #{@my_data} to #{sFileName}"
 end
 def kind
  puts "#{self.class.name}"
 end
end

class BrandNewClass
    include Persistence
    attr :my_data

        def data=(someData)
        @my_data = someData
    end
end
b = BrandNewClass.new
b.data = "My pwd"
b.save "MyFile.secret"
Uber code to persist My pwd to MyFile.secret
b.kind
>>BrandNewClass

Similar functionality in other OO languages

Namespace in C++ (similar to modules)

Definition


Steps involved

To use C++ namespaces, there are two steps involved:


Example

namespace  NewOne
{
      int p;
      long q
}
*	p and q are normal variables but integrated within the NewOne [http://en.wikipedia.org/wiki/Namespace namespace].  
*	In order to access this variables from the outside the [http://en.wikipedia.org/wiki/Namespace namespace], we have to use the scope operator ::. 
*	From previous example:

NewOne::p;
NewOne::q;

A namespace definition can be nested within another [http://en.wikipedia.org/wiki/Namespace namespace]definition.  Every namespace definition must appear either at file scope or immediately within another namespace definition.  For example:

// a namespace with using directive
#include <iostream>
using namespace std;
namespace SampleOne
{
       float p = 10.34;
}
 
namespace SampleTwo
{
       using namespace SampleOne;
       float q = 77.12;
       namespace InSampleTwo
       {
              float r = 34.725;
       }
}
 
int main()
{
       // this directive gives you everything declared in SampleTwo
       using namespace SampleTwo;
       // this directive gives you only InSampleTwo
       using namespace SampleTwo::InSampleTwo;
       // local declaration, take precedence
       float p = 23.11;
 
       cout<<"p = "<<p<<endl;
       cout<<"q = "<<q<<endl;
       cout<<"r = "<<r<<endl;
       return 0;
}

Multiple inheritance (C++ only) (similar to mixins)

Definition

You can derive a class from any number of base classes. Deriving a class from more than one direct base class is called multiple inheritance.


Example
 
In the following example, classes A, B, and C are direct base classes for the derived class X:
class A { /* ... */ };
class B { /* ... */ };
class C { /* ... */ };
class X : public A, private B, public C { /* ... */ };
The following inheritance graph describes the inheritance relationships of the above example. An arrow points to the direct base class of the class at the tail of the arrow:
 
 

The order of derivation is relevant only to determine the order of default [http://en.wikipedia.org/wiki/Initialization_(programming) initialization] by [http://en.wikipedia.org/wiki/Constructor constructors] and cleanup by [http://en.wikipedia.org/wiki/Destructor_(computer_programming) destructors].
A direct base class cannot appear in the base list of a derived class more than once:
class B1 { /* ... */ };                   // direct base class
class D : public B1, private B1 { /* ... */ }; // error
However, a derived class can inherit an indirect base class more than once, as shown in the following example:
 
class L { /* ... */ };                  // indirect base class
class B2 : public L { /* ... */ };
class B3 : public L { /* ... */ };
class D : public B2, public B3 { /* ... */ }; // valid
*	In the above example, class D inherits the indirect base class L once through class B2 and once through class B3.
*	However, this may lead to ambiguities because two subobjects of class L exist, and both are accessible through class D. 
*	You can avoid this ambiguity by referring to class L using a qualified class name. For example:
B2::L
or
B3::L.
You can also avoid this ambiguity by using the base specifier virtual to declare a base class, as described in Derivation (C++ only).

Interface (Java) (similar to mixins)

Definition
Properties of Interface:
Example
*	When a class implements an [http://en.wikipedia.org/wiki/Interface_(Java) interface], you can think of the class as signing a contract, agreeing to perform the specific behaviors of the interface. 
*	If a class does not perform all the behaviors of the [http://en.wikipedia.org/wiki/Interface_(Java) interface], the class must declare itself as abstract.
/* File name : Animal.java */
interface Animal {

	public void eat();
	public void travel();
}

*	A class uses the [http://www.roseindia.net/help/java/i/implement-keyword.shtml implements] keyword to implement an [http://en.wikipedia.org/wiki/Interface_(Java) interface]. The implements keyword appears in the class declaration following the extends portion of the declaration.
/* File name : MammalInt.java */
public class MammalInt implements Animal{

   public void eat(){
      System.out.println("Mammal eats");
   }

   public void travel(){
      System.out.println("Mammal travels");
   } 

   public int noOfLegs(){
      return 0;
   }

   public static void main(String args[]){
      MammalInt m = new MammalInt();
      m.eat();
      m.travel();
   }
} 
This would produce following result:
Mammal eats
Mammal travels

Comparable

Definition


Example

Here is an example taken from class notes [http://courses.ncsu.edu/csc517//common/lectures/notes/lec6.pdf Class notes of CSC517, NCSU] to illustrate [http://www.ruby-doc.org/core-1.9.3/Comparable.html comparable]mixin.

class Line 
  def initialize(x1, y1, x2, y2) 
    @x1, @y1, @x2, @y2 = x1, y1, x2, y2 
  end   
end 

We compare two lines on the basis of their lengths. We add the Comparable mixin as follows:

class Line  
  include Comparable  
  def length_squared 
    (@x2-@x1) * (@x2-@x1) + (@y2-@y1) * (@y2-@y1)
end
def <=>(other) 
    self.length_squared <=> other.length_squared 
  end 
end 

Spaceship operator

 
l1 = Line.new(1, 0, 4, 3) 
l2 = Line.new(0, 0, 10, 10) 
puts l1.length_squared 
if l1 < l2 
  puts "Line 1 is shorter than Line 2" 
else if l1 > l2 
  puts "Line 1 is longer than Line 2" 
else 
  puts "Line 1 is just as long as Line 2" 
 end 
end 
>>Line 1 is shorter than Line 2

Enumerable

Definition

Enumerable is a standard mixin which can be used to put into other classes.It has a method called inject that can be applied to adjacent elements of a set.


Example

Consider the following example.

[1, 2, 3, 4, 5 ,6].inject {|v, n| v+n }
>>21

class VowelFinder 
  include Enumerable 
  def initialize(string) 
    @string = string 
  end 
  def each 
    @string.scan(/[aeiou]/) do |vowel| 
      yield vowel 
    end 
  end 
end  


VowelFinder.new("abacadabra").inject {|v, n| v+n} 
>>aaaaa

Simulating Multiple Inheritance


Example


 require 'set'      # A collection of unordered values with no duplicates
 
 module Taggable
   attr_accessor :tags
   
   def taggable_setup
     @tags = Set.new
   end
   
   def add_tag(tag)
     @tags << tag
   end
   
   def remove_tag(tag)
     @tags.delete(tag)
   end
 end
 
 class TaggableString < String
   include Taggable
   def initialize(*args)
     super
     taggable_setup
   end
 end
 
 s = TaggableString.new('It is a bright, it is a sunny day')
 s.add_tag 'sentence'
 s.add_tag 'quotation'
 s.tags                          # =>    #<Set: {"sentence", "quotation"}>

Given below is another simple example of how modules and mixins can be used to simulate multiple inheritance in Ruby.

 module A
   def a1
     puts "Inside a1"
   end
   def a2
     puts "Inside a2"
   end
 end
 
 module B
    def b1
      puts "Inside b1"
    end
    def b2
      puts "Inside b2"
    end
 end
 
 class Sample
   include A
   include B
   def s1
     puts "Inside s1"
   end
 end
 
 obj = Sample.new
 obj.a1             # => Inside a1
 obj.a2             # => Inside a2
 obj.b1             # => Inside b1
 obj.b2             # => Inside b2
 obj.s1             # => Inside s1

Advantages of Multiple Inheritance

Although multiple inheritance has its disadvantages, there are a couple of good reasons for using multiple inheritance. Generally, multiple inheritance is used in one of the following ways:

1. Multiple Independant Protocols

Example: Our classification of objects in everyday life is naturally hierarchical. We know that all cats are mammals, and all mammals are animals. Smaller classes inherit characteristics from the larger classes to which they belong. If all mammals breathe, then all cats breathe.

class Mammal
def breathe
puts "inhale and exhale"
end
end

class Cat<Mammal
def speak
puts "Meow"
end
end

tama = Cat.new

tama.breathe
>> inhale and exhale

tama.speak
>> Meow

2. Mix and Match

Example

module A
  def a1
    puts "Module A method a1"
  end
  def a2
    puts "Module A method a2"
  end
end
module B
  def b1
    puts "Module B method b1"
  end
  def b2
    puts "Module B method b2"
  end
end

class Sample
  include A
  include B
  def s1
    puts "Class method s1"
  end
end

samp=Sample.new
samp.a1
samp.a2
samp.b1
samp.b2
samp.s1
>> Module A method a1
Module A method a2
Module B method b1
Module B method b2
Class method s1

3. Submodularity

Example

 
class Calc
  def initialize x,y
    @x=x
    @y=y
  end

  def result
puts "product #{Product.result(@x,@y)}"
puts "Sum #{Sum.result(@x,@y)}"
  end
end
class Product
  def Product.result x,y
    x*y
  end
end
class Sum

  def Sum.result x,y
    x+y
  end
end
a= Calc.new 3,4
a.result
>> product 12
Sum 7

4. Separation of interface and implementation

Example:

class Shape
  def draw
    raise NotImplementedError.new(
              "Method not implemented")
  end
end
class Square < Shape
  def draw
    puts "abstract method"
  end
end

s = Square.new.draw
>> abstract method

Disadvantages of Multiple Inheritance

1. Name collision

 // This is our top most abstract class.
 class AbstractSuperClass{
   abstract void method();
 }
 
 // These are the two concrete sub classes which extend the above super class
 class ConcreteSubOne extends AbstractSuperClass{
   void method(){
     System.out.println("I am going to test multiple Inheritance");
   }
 }
 
 class ConcreteSubTwo extends AbstractSuperClass{
   void method(){
     System.out.println("I will cause the Deadly Diamond of Death");
   }
 }

 // This is our last class which extends both of the above concrete classes
 class DeadlyDiamondEffect extends ConcreteSubOne, ConcreteSubTwo{
   //Some methods of this class
   //This inherits a do() method from ConcreteSubOne and another do() from ConcreteSubTwo. When this is called there is an ambiguity.
 }

2. Repeated inheritance

Example

module A
  def a1
    puts "Module A method a1"
  end
  def a2
    puts "Module A method a2"
  end
end

class A1
  include A
  def a1
    puts "Module A1 method a1"
  end
  def a2
    puts "Module A1 method a2"
  end
end

class Sample < A1
  include A
  def s1
    puts "Class method s1"
  end
end

Here Sample class uses / mixes unnecessarily repeatedly methods of module A

3. Method combination

Example Consider the example TeachingAssistant example of multiple inheritance discussed in csc517 class. Even though the program works fine, consider the situation when, user wants to access to_s method of person / student fter declaring to_s in teaching_assistant class?!

module Person
  attr_accessor :name
  attr_accessor :height
  attr_accessor :weight
  def to_s
    "Person[" + @name + ", height = " + @height + ", weight =" + weight + "]"
  end
end

module Student
  include Person
  attr_accessor :major
  attr_accessor :hometown
  def to_s
    "Student[" + @name + ", height = " + @height + 
    ", weight = " + weight + ", major = " + major + 
    ", hometown = " + hometown + "]"
    end
end

module Employee
  attr_accessor :title
  attr_accessor :wage
  include Person
  def to_s
    "Employee[" + @name + ", height = " + @height + 
    ", weight = " + weight + ", title = " + title + 
    ", wage = " + wage+ "]"
   end
end

class TeachingAssistant
include Student
include Employee
  def to_s
    "TeachingAssistant[" + @name + ", height = " + @height + 
    ", weight = " + weight + ", \n   major = " + major + 
    ", hometown = " + hometown + ", title = " + title + 
    ", wage = " + wage + "]"
   end
end

john = TeachingAssistant.new();
john.name = "John"
john.height = "6 ft. 2 in."
john.weight = "180 lbs."
john.major = "CS"
john.hometown = "Springfield"
john.title = "busboy"
john.wage = "$7.25/hr."
john.to_s


4. Implementation difficulties


Consider the below situation where class E inherits A through B C D, if E wishes to access methods of A, which route will class E follow to inherit the methods of A?



5. Misuse



Resolution of Name conflicts or Collisions

Multiple inheritance may cause name conflicts when a sub-class inherits different super-classes that contain the methods or variables with the same name. This can be resolved in many ways.


Compound selectors in Ruby

Suppose a class Sub inherits two different methods for MethodOne from two different super-classes, SuperClassOne and SuperClassTwo. In Ruby, we can use Compound Selectors to refer to the method as shown below:

SuperClassOne.MethodOne      #Uses the MethodOne method inherited from SuperClassOne
SuperClassTwo.MethodOne      #Uses the MethodOne method inherited from SuperClassTwo


Renaming in Eiffel

In Eiffel language, naming conflicts are overcome in inherited features by renaming. It contains a rename clause to remove name conflicts. This is illustrated below:

Class Sub inherit
  SuperClassOne rename x as x1, y as y1;
  SuperClassTwo rename x as x2, y as y2;
  feature....

Here, the inherit clause would be illegal without the rename clause. This ensures that name conflicts are resolved. This also allows the programmer to give meaningful and appropriate names to the inherited features.

Specifying Objects

The Object-Oriented programming paradigm has two ways for specifying objects.

Set based language - object specification Protocol based language - object specification


Comparison between Set based language and Protocol based language

Let us compare and contrast between Set based language - object specification and Protocol based language - object specification

Set based language - object specification Protocol based language - object specification
First, a class is described which abstracts the features or properties of the object we want to specify. First, an object that is a concrete representation of the object we are trying to specify is created. This is the prototype.
After describing the template or class, instances or objects for that class are created to perform the actual work. Classes can be described by Meta-classes. Multiple instances of that object are obtained by copying or cloning.
Every object instance for a class is unique and holds its internal values for all the features defined for that class. Each and every instance has those properties and internal values that are specific and unique to itself and a reference to its prototype, called an extension. Essentially, there is no distinction between an instance and a prototype. Any instance can be copied or cloned to become the prototypical object for its duplicates.


Inheritance in Set based language - object specification


Example:

represents all cars and contains features that all cars should have.



Inheritance in Protocol based language - object specification


Example:


Extending specific objects

Ruby as a set-based language


Ruby as a prototype-based language


Extending Objects


 class Person
   attr_reader :name, :age, :occupation
   
   def initialize(name, age, occupation)
     @name, @age, @occupation = name, age, occupation
   end
   
   def mild_mannered?
     true
   end
 end
 
 Amy = Person.new('Amy Wilson', 23, 'student')
 John = Person.new('John Mason', 40, 'professor')
 Amy.mild_mannered?                                  # => true 
 John.mild_mannered?                                 # => true

The above class describes all the people who are mild-mannered. What if there are some other people who are not as mild-mannered as they appear. That is they have some super-powers as well.

 module SuperPowers
   def fly
     'Flying!'
   end
   
   def leap(what)
     "Leaping #{what} in a single bound!"
   end
   
   def mild_mannered?
     false
   end
   
   def superhero_name
     'Superman'
   end
 end

Here, we have two situations. Some objects of the person class are mild-mannered, while some other objects of the same person class have super powers with them. Extending Objects - example

The only way to achieve this is to extend only those objects that have super powers instead of extending the entire class itself.

 Amy.extend(SuperPowers)
 puts Amy.superhero_name          # => Superman
 puts Amy.fly                     # => Flying!
 puts Amy.leap(rocks)             # => Leaping #{what} in a single bound!   
 puts Amy.mild_mannered?          # => false             
 puts John.mild_mannered?         # => true

Given below is another example that illustrates extending specific objects.

 module CarAction
   def goLeft(steps)
     Movement.new(self, steps)
   end
 end  
 
 
 #The Actions module can be included to allow a class to generate movements.
 class BigCar
   include CarAction
   def carMethod
     puts "This is a method inside BigCar class"
   end
 end
 
 #After CarActions is included goLeft can be executed by any instance of BigCar.
 car1 = BigCar.new
 car1.carMethod
 movement1 = car1.goLeft
 
 
 #The CarActions module is not included in the SmallCar class.
 class SmallCar
   def carMethod
     puts "This is a method inside SmallCar class"
   end
 end
 
 #Extend adds the methods to one instance, not to all instances.
 car2 = SmallCar.new
 car2.extend CarActions
 movement2 = car.goLeft
 
 car3 = SmallCar.new
 movement3 = car.goLeft      #Error: car3 does not extend CarActions, hence cannot call the goLeft method.

References

Class notes of CSC517, NCSU [1] [2] [3] [4] [5] Multiple Inheritance [6] [7] http://www.informatics.susx.ac.uk/research/groups/nlp/datr/datrnode33.html http://csis.pace.edu/~bergin/patterns/multipleinheritance.html Subclasses and Superclasses Mixins http://en.wikipedia.org/wiki/Interface_%28Java%29 Object Composition Is-a relatioship http://en.wikipedia.org/wiki/Eiffel_%28programming_language%29#Renaming http://ruby-doc.org/docs/ProgrammingRuby/html/ext_ruby.html http://rubular.com/ http://www.tutorialspoint.com/ruby/ruby_regular_expressions.htm http://www.tenouk.com/Module23.html http://en.wikipedia.org/wiki/Interface_(Java) http://www.tutorialspoint.com/java/java_interfaces.htm http://publib.boulder.ibm.com/infocenter/comphelp/v8v101/index.jsp?topic=%2Fcom.ibm.xlcpp8a.doc%2Flanguage%2Fref%2Fcplr134.htm


External Links

Compile time Run time http://wiki.answers.com/Q/What_are_the_advantages_of_single_inheritance_over_multiple_inheritance http://archive.eiffel.com/doc/manuals/technology/bmarticles/joop/multiple.html Ruby extend and Include Ruby Multiple Inheritance with modules and mixins http://download.oracle.com/javase/tutorial/java/IandI/abstract.html http://download.oracle.com/javase/tutorial/java/IandI/usinginterface.html Abstract types http://en.wikipedia.org/wiki/Reusability

See Also

http://www.ruby-lang.org/en/ http://www.ruby-lang.org/en/downloads/ http://en.wikipedia.org/wiki/Ruby_%28programming_language%29 http://rubyonrails.org/ Object oriented Programming Learn Ruby Functional programming Imperative Programming Interpreted language Reflection Dynamic language Python Perl Ruby on Rails Model View Controller - MVC Metaprogramming Ruby: Program Like the Ruby Pros Design Patterns in Ruby Garbage Collection in Ruby Threads in Ruby

Personal tools
Namespaces
Variants
Actions
Navigation
Toolbox