<?xml version="1.0"?>
<feed xmlns="http://www.w3.org/2005/Atom" xml:lang="en">
	<id>https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Csgodbol</id>
	<title>Expertiza_Wiki - User contributions [en]</title>
	<link rel="self" type="application/atom+xml" href="https://wiki.expertiza.ncsu.edu/api.php?action=feedcontributions&amp;feedformat=atom&amp;user=Csgodbol"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Csgodbol"/>
	<updated>2026-10-04T07:48:43Z</updated>
	<subtitle>User contributions</subtitle>
	<generator>MediaWiki 1.41.0</generator>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42581</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42581"/>
		<updated>2010-11-25T00:20:07Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hence delegation means simply passing off a task to someone else so as to complete it on its behalf.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42580</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42580"/>
		<updated>2010-11-25T00:19:26Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
Hence delegation means passing off a task to someone else so as to complete it on its behalf.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42579</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42579"/>
		<updated>2010-11-25T00:19:16Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
Hence delegation means passing off a task to someone else so as to complete it on its behalf.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42578</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42578"/>
		<updated>2010-11-25T00:19:09Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
Hence delegation means passing off a task to someone else so as to complete it on its behalf.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42577</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42577"/>
		<updated>2010-11-25T00:18:55Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
Hence delegation means passing off a task to someone else so as to complete it on its behalf.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42576</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42576"/>
		<updated>2010-11-25T00:12:21Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. The term Delegation was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. &lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42575</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42575"/>
		<updated>2010-11-25T00:11:41Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means &amp;quot;passing a duty off to someone or something else&amp;quot;. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. &lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42574</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42574"/>
		<updated>2010-11-25T00:09:12Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate. &lt;br /&gt;
Thus it refers to one object relying upon another to provide a specified set of functionalities.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42573</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42573"/>
		<updated>2010-11-25T00:08:01Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. It provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42572</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42572"/>
		<updated>2010-11-25T00:01:29Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].&lt;br /&gt;
&lt;br /&gt;
Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42571</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42571"/>
		<updated>2010-11-24T23:56:32Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate.&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42570</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42570"/>
		<updated>2010-11-24T23:52:59Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
&lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate.&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42569</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42569"/>
		<updated>2010-11-24T23:52:38Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities. In simple words, it means passing a duty off to someone or something else. &lt;br /&gt;
In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
Delegation is a simple yet, powerful concept of handing a task over to another part of the program. In object-oriented programming it is used to describe the situation wherein one object defers a task to another object, known as the delegate.&lt;br /&gt;
Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibility for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [19]]&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation[http://www.khelll.com/blog/ruby/delegation-in-ruby/ [20]]:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7] ]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object[http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html[10]]&lt;br /&gt;
| use delegation [http://dev.perl.org/perl6/rfc/193.html [14]]&lt;br /&gt;
&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.[http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ [13]]&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method [http://wiki.tcl.tk/11033 [12]]&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.[[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html [11]]&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as shown in the table above. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[19] [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[20] [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[21] [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[http://api.jquery.com/delegate/ Delegation in Jquery]&lt;br /&gt;
*[http://www.programmingvideotutorials.com/csharp/csharp-delegates C# delegates]&lt;br /&gt;
*[http://media.pragprog.com/titles/dscpq/delegates.pdf Cocoa programming]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42047</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42047"/>
		<updated>2010-11-18T20:49:08Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html]&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
&lt;br /&gt;
[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42046</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42046"/>
		<updated>2010-11-18T20:46:30Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References and Notes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html]&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42045</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42045"/>
		<updated>2010-11-18T20:32:19Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation as a Language Feature */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports [http://en.wikipedia.org/wiki/Prototype-based_programming  prototype-based programming]. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time # will give output as Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new #Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 &lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html]&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42043</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42043"/>
		<updated>2010-11-18T20:27:56Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Table of Comparison */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html]&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42042</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42042"/>
		<updated>2010-11-18T20:27:29Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning [7]]:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''[ http://en.wikipedia.org/wiki/C%2B%2B C++]'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Perl_6 Perl 6]'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html]&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Python_(programming_language) Python]'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Php PHP]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Tcl Tcl]'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Java_(programming_language) Java]'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Objective_c Objective-C]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/Ruby_(programming_language) Ruby]'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''[http://en.wikipedia.org/wiki/C_Sharp_(programming_language) C#]'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10] [http://www.mail-archive.com/perl6-language-objects@perl.org/msg00512.html Delegation in Perl]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[18] [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42031</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42031"/>
		<updated>2010-11-18T20:10:59Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation vs Inheritance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance] is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 2 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
SingleForwardable module:Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
2)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''C#'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42029</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42029"/>
		<updated>2010-11-18T20:10:42Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation vs Inheritance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance :&lt;br /&gt;
* [http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
* Forwardable&lt;br /&gt;
* SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''C#'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42027</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42027"/>
		<updated>2010-11-18T20:09:45Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation vs Inheritance */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming) Inheritance]:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning]:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation. It has two modules &lt;br /&gt;
a)Forwardable&lt;br /&gt;
b)SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module:-&lt;br /&gt;
&lt;br /&gt;
Using the methods def_delegator and def_delegators the Forwardable module provides delegation of specified methods to a designated object.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' Using the methods def_delegators, the [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object. This module is similar to Forwardable, but instead of their defining classes, it works on objects themselves.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby.&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''C#'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
*[17] [http://www.scribd.com/doc/27239260/Rails-Magazine-Issue-1-The-Beginning Rails Magazine]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42023</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42023"/>
		<updated>2010-11-18T19:54:25Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Example of delegation in Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
#using forwardable module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using data module&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Preparing object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt;&lt;br /&gt;
 # Adding delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
#using delegate module&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
#using date module&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''Syntax for implementing Delegation'''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Class Delegator &lt;br /&gt;
 {&lt;br /&gt;
  function __construct() {$this-&amp;gt;delegate = NULL ; }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class Delegate {function thing() {return 'Delegate Implementation' ;}}&lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''C#'''&lt;br /&gt;
| Yes.Delegate keyword is used to create a delegate and the type of a delegate is defined by the name of the delegate.&lt;br /&gt;
| //declaring a delegate named 'Del' that can encapsulate a method that takes a string as an argument and returns void&lt;br /&gt;
public delegate void Del(string message);&lt;br /&gt;
// Creating a method for a delegate.&lt;br /&gt;
public static void DelegateMethod(string message)&lt;br /&gt;
{&lt;br /&gt;
   System.Console.WriteLine(message);&lt;br /&gt;
}&lt;br /&gt;
// Instantiating the delegate.&lt;br /&gt;
Del handler = DelegateMethod;&lt;br /&gt;
// Calling the delegate.&lt;br /&gt;
handler(&amp;quot;Hello World&amp;quot;);&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42018</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42018"/>
		<updated>2010-11-18T19:26:56Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References and Notes */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''Support for Delegation'''&lt;br /&gt;
! '''              Syntax for implementing Delegation              '''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc.&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  &lt;br /&gt;
def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| lass Delegator {&lt;br /&gt;
  function __construct() {&lt;br /&gt;
    $this-&amp;gt;delegate = NULL ;&lt;br /&gt;
  }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
class Delegate {&lt;br /&gt;
  function thing() {&lt;br /&gt;
    return 'Delegate Implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
 &lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
 &lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''C#'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] [http://msdn.microsoft.com/en-us/library/ms173172.aspx C# delegation]&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42012</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42012"/>
		<updated>2010-11-18T19:20:48Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Simple Java Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
//class A does the task of class C&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // class C delegates the method to class A&lt;br /&gt;
   A a = new A();&lt;br /&gt;
//delegated methods&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''          Support for Delegation          '''&lt;br /&gt;
! '''          Syntax for implementing Delegation          '''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc.&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| Yes. Using Automatic Delegation (via __getattr__ and __setattr__) it can provide delegation with uses similar to inheritance without any limits and better control.&lt;br /&gt;
| def __getattr__(self, attr): return getattr(self.file, attr)&lt;br /&gt;
  &lt;br /&gt;
def __setattr__(self, attr, value): return setattr(self.file, attr, value) &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| Yes&lt;br /&gt;
| lass Delegator {&lt;br /&gt;
  function __construct() {&lt;br /&gt;
    $this-&amp;gt;delegate = NULL ;&lt;br /&gt;
  }&lt;br /&gt;
  function operation() {&lt;br /&gt;
    if(method_exists($this-&amp;gt;delegate, &amp;quot;thing&amp;quot;))&lt;br /&gt;
      return $this-&amp;gt;delegate-&amp;gt;thing() ;&lt;br /&gt;
    return 'default implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
class Delegate {&lt;br /&gt;
  function thing() {&lt;br /&gt;
    return 'Delegate Implementation' ;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
 &lt;br /&gt;
$a = new Delegator() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
 &lt;br /&gt;
$a-&amp;gt;delegate = 'A delegate may be any object' ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
 &lt;br /&gt;
$a-&amp;gt;delegate = new Delegate() ;&lt;br /&gt;
print &amp;quot;{$a-&amp;gt;operation()}\n&amp;quot; ;&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| Yes.Delegation-based model for Tk widgets.Included in Tcllib&lt;br /&gt;
| //defining a delegate method&lt;br /&gt;
Object instproc delegate {method obj} {&lt;br /&gt;
   my set delegate($method) $obj&lt;br /&gt;
 }&lt;br /&gt;
 Object instproc unknown {m args} {&lt;br /&gt;
   if {[my exists delegate($m)]} {&lt;br /&gt;
     eval [my set delegate($m)] $m $args&lt;br /&gt;
   } elseif {[my exists delegate(*)]} {&lt;br /&gt;
     eval [my set delegate(*)] $m $args&lt;br /&gt;
   }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| Yes. Two ways.&lt;br /&gt;
| 1st way: Using an interface called Thingable to specify the type of delegates that respond to thing()&lt;br /&gt;
  2nd way: Use of traditional wrapper methods.&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Delegating class has an outlet or property, usually one that is named delegate; if it is an outlet, it includes methods for setting and accessing the value of the outlet&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| Yes&lt;br /&gt;
| Wrapper method, delegate lib, forwardable module.&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] []&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42010</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42010"/>
		<updated>2010-11-18T19:18:54Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''Programming language'''&lt;br /&gt;
! '''          Support for Delegation          '''&lt;br /&gt;
! '''          Syntax for implementing Delegation          '''&lt;br /&gt;
|-&lt;br /&gt;
! '''C++'''&lt;br /&gt;
| No in built support.Delegation has to be done manually.Time consuming&lt;br /&gt;
| Create a delegation link in delegator.&lt;br /&gt;
  class MyClass &lt;br /&gt;
  {&lt;br /&gt;
    FuBar fb; //delegation link&lt;br /&gt;
    void Fu() { fb.Fu(); } //&lt;br /&gt;
    void Bar() { bar.Bar(); }&lt;br /&gt;
  }&lt;br /&gt;
  &lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Perl 6'''&lt;br /&gt;
| Yes via a pragma for delegating method calls to attributes of an object&lt;br /&gt;
| &lt;br /&gt;
  use delegation&lt;br /&gt;
                attr1 =&amp;gt; [qw( method1 method2 method3 )],&lt;br /&gt;
                attr2 =&amp;gt; [qw( method4 method5 )],&lt;br /&gt;
                attr3 =&amp;gt; __ALL__,&lt;br /&gt;
                attr4 =&amp;gt; __ALL__,&lt;br /&gt;
                # etc.&lt;br /&gt;
                ;&lt;br /&gt;
calls like:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;method5(@other_args);&lt;br /&gt;
would act as if they were:&lt;br /&gt;
&lt;br /&gt;
        $obj-&amp;gt;{attr1}-&amp;gt;method3(@args);&lt;br /&gt;
        $obj-&amp;gt;{attr2}-&amp;gt;method5(@other_args);&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Python'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''QtRuby'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''PHP'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Tcl'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Java'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Objective-C'''&lt;br /&gt;
| No&lt;br /&gt;
| No&lt;br /&gt;
&lt;br /&gt;
|-&lt;br /&gt;
! '''Ruby'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
&lt;br /&gt;
Thus delegation is a powerful design/reuse technique, and can be viewed as a relationship between objects where one object forwards certain method calls to another object, called its delegate. Delegation is simply passing a duty off to someone/something else. &lt;br /&gt;
&lt;br /&gt;
Delegation pattern is better than inheritance in some ways and it is supported by many languages in various ways as in the given table. Delegation is useful to express relationship among classes, reducing coupling between classes, run-time flexibility – the delegate can be changed at run-time. &lt;br /&gt;
It has certain disadvantages too, such as, it is not directly supported by most popular object-oriented languages, also it doesn’t facilitate dynamic polymorphism. &lt;br /&gt;
&lt;br /&gt;
Hence the choice of using delegation depends on various factors such as programming language-support for multiple inheritance or design constraints requiring polymorphism.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] []&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42004</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=42004"/>
		<updated>2010-11-18T19:02:41Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison  =&lt;br /&gt;
==Cross platform comparison==&lt;br /&gt;
{| class=&amp;quot;wikitable sortable&amp;quot;  border=&amp;quot;1&amp;quot; style=&amp;quot;font-size: 100%; text-align: center; width: auto;&amp;quot;&lt;br /&gt;
|-&lt;br /&gt;
! '''GUI Toolkit'''&lt;br /&gt;
! '''Microsoft Windows|Windows'''&lt;br /&gt;
! '''Linux'''&lt;br /&gt;
! '''Mac OS X'''&lt;br /&gt;
|-&lt;br /&gt;
! '''Tk'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''FxRuby'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''WxRuby'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''QtRuby'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''Shoes'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''Swing'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''Monkeybars'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''Cocoa'''&lt;br /&gt;
| No&lt;br /&gt;
| No&lt;br /&gt;
| yes&lt;br /&gt;
|-&lt;br /&gt;
! '''GTK'''&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
| yes&lt;br /&gt;
|}&lt;br /&gt;
&lt;br /&gt;
&amp;lt;br /&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else.&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
*[12] [http://wiki.tcl.tk/11033 Tcl example]&lt;br /&gt;
*[13] [http://code.activestate.com/recipes/52295-automatic-delegation-as-an-alternative-to-inherita/ Python delegation example]&lt;br /&gt;
*[14] [http://dev.perl.org/perl6/rfc/193.html Perl delegation]&lt;br /&gt;
*[15] [http://rosettacode.org/wiki/Delegate PHP delegation]&lt;br /&gt;
*[16] []&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41998</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41998"/>
		<updated>2010-11-18T14:08:47Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Complex Java Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ class-C need not refer to class-A or class-B, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41988</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41988"/>
		<updated>2010-11-18T06:10:42Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Feature Matrix */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41960</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41960"/>
		<updated>2010-11-18T05:17:37Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
== Delegation as a Language Feature ==&lt;br /&gt;
&lt;br /&gt;
Prototype-based programming is a classless type of Object oriented programming technique which performs the work of inheritance in class-based languages.  Delegation is the language feature that supports prototype-based programming. It is the mechanism by which code is selected for execution in a dynamic way. Delegation is the process by which a function or method, referred to in the context of one object, is found in another object. When a method is referred to by code defined for an object but is not itself found to be defined in the object the language runtime searches other objects, called delegates. Depending on the object model of the individual language the delegates may defined when the object is created or may be specified by the method-call syntax. The analogous process in a class-based language is dispatching to an inherited method, and an object's delegates perform the role of superclasses in a class-based language.[http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation]&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://en.wikipedia.org/wiki/Prototype-based_programming#Delegation Delegation as a Language Feature]&lt;br /&gt;
*[8]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[9]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[10]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[11] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41958</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41958"/>
		<updated>2010-11-18T04:58:20Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html Examples of delegation in Java]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41905</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41905"/>
		<updated>2010-11-18T03:50:22Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Examples of delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41895</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41895"/>
		<updated>2010-11-18T03:43:27Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Examples of delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41894</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41894"/>
		<updated>2010-11-18T03:43:12Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls. Thus delegation is like inheritance done manually through object composition.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Examples of delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41849</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41849"/>
		<updated>2010-11-18T03:15:05Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Delegation in Java */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways:&lt;br /&gt;
&lt;br /&gt;
*By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Examples of delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41848</id>
		<title>CSC/ECE 517 Fall 2010/ch6 6a PC</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch6_6a_PC&amp;diff=41848"/>
		<updated>2010-11-18T03:13:55Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Delegation-based programming languages'''&lt;br /&gt;
&lt;br /&gt;
''&amp;quot; I do not care how it is done, or who is it assigned to. If something is understood to be placed in the hands of another party, it is delegation &amp;quot; - 'Anonymous'&lt;br /&gt;
&lt;br /&gt;
__TOC__&lt;br /&gt;
&lt;br /&gt;
= Introduction =&lt;br /&gt;
&lt;br /&gt;
Dictionary defines delegation as the assignment of authority and responsibility to another person to carry out specific activities.In programming context it is nothing different. It is basically entrusting an action to another agent. This term was initially introduced by Henry Lieberman in his 1986 paper &amp;quot;Using Prototypical Objects to Implement Shared Behavior in Object-Oriented Systems&amp;quot;.  [http://portal.acm.org/citation.cfm?id=28718] He defines delegation in object oriented languages as a programming language feature making use of the method lookup rules for dispatching so-called self-calls.&lt;br /&gt;
&lt;br /&gt;
[[Image:Delegation_self.jpg]]&lt;br /&gt;
&lt;br /&gt;
The above diagram depicts that a message receiver is asking another object (message holder) to do something on its behalf which may delegate it to someone and so on and so forth&lt;br /&gt;
&lt;br /&gt;
== Delegation ==&lt;br /&gt;
&lt;br /&gt;
[http://en.wikipedia.org/wiki/Delegation_(programming) Delegation], is also referred to as [http://en.wikipedia.org/wiki/Object_composition#Aggregation aggregation],consultation, or forwarding. In delegation one class may contain an instance of another class, and &amp;lt;i&amp;gt;delegate&amp;lt;/i&amp;gt; some responsibility to that class. This is also referred to as the [http://en.wikipedia.org/wiki/Has-a has-a] relationship. Aggregation should not be confused with [http://en.wikipedia.org/wiki/Object_composition composition]. Both aggregation and composition are used to describe one object containing another object, but composition implies ownership [http://en.wikipedia.org/wiki/Object_composition#Aggregation]. Aggregation is more general and doesn't imply any responsibilities for memory management. A class which contains other classes is called a &amp;lt;i&amp;gt;composite&amp;lt;/i&amp;gt; class, while a class being contained is called a &amp;lt;i&amp;gt;composited&amp;lt;/i&amp;gt; or &amp;lt;i&amp;gt;composed&amp;lt;/i&amp;gt; class [http://en.wikipedia.org/wiki/Object_composition].Delegation is a very powerful reuse technique. The provides run time flexibility. It is also called dynamic inheritance.[http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html]  &lt;br /&gt;
&lt;br /&gt;
Delegation can be implemented in many programming languages like Ada, Aikido, C, C#, C++, Common Lisp, D, E, Go, J, Java, JavaScript, Logtalk, Objective-C,Oz, Perl,Perl 6, PHP, PicoLisp, Pop11, Python, Ruby, TCL, Vorpal [http://rosettacode.org/wiki/Delegate]&lt;br /&gt;
&lt;br /&gt;
Example in a Java like language:&lt;br /&gt;
&lt;br /&gt;
 class Delegate&lt;br /&gt;
 {&lt;br /&gt;
     void doSomething()&lt;br /&gt;
     {&lt;br /&gt;
         // &amp;quot;this&amp;quot; is also known as &amp;quot;current&amp;quot;, &amp;quot;me&amp;quot; and &amp;quot;self&amp;quot; in other languages&lt;br /&gt;
         this.callMe()&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() &lt;br /&gt;
     {&lt;br /&gt;
         print(&amp;quot;I am Delegate&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class Delegator&lt;br /&gt;
 {&lt;br /&gt;
     private Delegate d;  // delegationlink&lt;br /&gt;
     public Delegator(Delegate d)&lt;br /&gt;
     {&lt;br /&gt;
         this.d = d;&lt;br /&gt;
     }&lt;br /&gt;
     void doSomething() {&lt;br /&gt;
         d.doSomething() // call doSomething() on the Delegate instance&lt;br /&gt;
     }&lt;br /&gt;
     void callMe() {&lt;br /&gt;
         print(&amp;quot;I am Delegator&amp;quot;)&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 d = new Delegate()&lt;br /&gt;
 b = new Delegator(d) // establish delegation between two objects&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Here calling b.doSomething() will result in ''&amp;quot;I am Delegate&amp;quot;'' being printed, since class Delegator &amp;quot;delegates&amp;quot; the method callMe() to a given object of class Delegate.&lt;br /&gt;
&lt;br /&gt;
== Delegation vs Inheritance ==&lt;br /&gt;
&lt;br /&gt;
Inheritance:&lt;br /&gt;
* Inheritance is restricted to compile time&lt;br /&gt;
* Since it targets type rather than instances, it cannot be removed/changed at runtime&lt;br /&gt;
* Inheritance can be statically type-checked&lt;br /&gt;
&lt;br /&gt;
Delegation:&lt;br /&gt;
* Delegation takes place at run-time&lt;br /&gt;
* Since it takes place at run-time, it can even be removed at run-time&lt;br /&gt;
* Cannot guarantee static type-safety (By using interfaces, delegation can be made more flexible and typesafe)&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Hints to use Inheritance&lt;br /&gt;
* Inheritance is used to create sub-categories of objects&lt;br /&gt;
* Mostly identified in 'is-a' relationships between objects&lt;br /&gt;
* Inheritance is used when two objects are of the same type but one of the objects may need to have its own customized functionality. The child object just inherits from the parent and writes its own implementation of the feature it needs extra.&lt;br /&gt;
* Inheritance can be implemented on objects of the same type only.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Inheritance_db_newtable.gif ]]&lt;br /&gt;
  &lt;br /&gt;
Here we have an abstract base class. We extend this to to provide something that we can represent any product by. We then provide a few specialisations for typical products like book,cd.This is a usual case when inheritance is used.&lt;br /&gt;
&lt;br /&gt;
Hints to use Delegation&lt;br /&gt;
* Delegation is used when two objects aren't of the same type but one has methods and attributes that the other wants to use internally instead of writing its own implementation&lt;br /&gt;
* Identified as 'as-a' relationships where the type of included object may change during runtime.&lt;br /&gt;
* Delegation is used when methods implementation needs to be handled by some other class within the parent tree. The class that will handle the method isn't known at compile time.&lt;br /&gt;
* Code execution within objects needs to be determined dynamically.&lt;br /&gt;
&lt;br /&gt;
[[ Image:Delegation.jpg ]]&lt;br /&gt;
&lt;br /&gt;
In the above diagram, class C inherits from A. Also, class C has a method called as Call which simple calls the method Call from class B. Hence, class C is delegating its functionality to be implemented by Class B. For this, class C has an object reference to class B.&lt;br /&gt;
&lt;br /&gt;
= Situations where you can use delegation =&lt;br /&gt;
&lt;br /&gt;
Consider following situation:&lt;br /&gt;
&lt;br /&gt;
* Objective: We want a robot to have a heat sensor capability. &lt;br /&gt;
* Initial design: So we initially decide to build a Robot class like the one shown below:&lt;br /&gt;
&lt;br /&gt;
[[ Image:robotclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
* Problem with the design: Now all Robots should have a heat sensor. What if some robot did not have a heat sensor capability?&lt;br /&gt;
* Solution: So we make a Robot base class and a VolcanoRobot class which inherits from Robot and performs the heat-sensor operations&lt;br /&gt;
&lt;br /&gt;
[[ Image:volcanoclass.jpg]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
* Problem: But with this design whenever we want to modify anything related to the heat sensor, we will have to change the robot class. Also, with our design we have exposed heat sensor methods to Robot class.&lt;br /&gt;
* Solution: Hence, in such situations delegation is best. &lt;br /&gt;
&lt;br /&gt;
[[ Image:Ruby_delegation.jpg]]&lt;br /&gt;
&lt;br /&gt;
* New design: Delegate the heat sensor functionality to Heat Sensor class. VolcanoRobot still has the 3 methods that are related to the sensor, but those are wrapper methods, they do nothing but to call the sensor corresponding ones, and that’s exactly what delegation is, just delegate functionality to the contained parts(delegates).&lt;br /&gt;
&lt;br /&gt;
Delegation and composition go hand in hand to provide a flexible neat solution and also it serves the principle “separate changeable code from static one” .  The price that one needs to pay for this is that we need wrapper methods, and extra time needed in processing because of the call of these wrapper methods.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Delegation Design Pattern ==&lt;br /&gt;
&lt;br /&gt;
It is a design pattern in object oriented languages where an object expresses certain behavior to the outside but in reality delegates responsibility for implementing that behaviour to an associated object.&lt;br /&gt;
&lt;br /&gt;
Consider the following examples in java:&lt;br /&gt;
&lt;br /&gt;
 class Subordinate  // the &amp;quot;delegate&amp;quot;&lt;br /&gt;
 {  &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       System.out.print(&amp;quot;Subordinate is performing&amp;quot;); &lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
 class Manager // the &amp;quot;delegator&amp;quot;&lt;br /&gt;
 { &lt;br /&gt;
     Subordinate slave = new Subordinate();  // create the delegate &lt;br /&gt;
     void performTask() &lt;br /&gt;
     { &lt;br /&gt;
       slave.performTask(); // delegation&lt;br /&gt;
     } &lt;br /&gt;
 }&lt;br /&gt;
 public class Main {&lt;br /&gt;
     // to the outside world it looks like Manager is actually doing work.&lt;br /&gt;
     public static void main(String[] args) {&lt;br /&gt;
         Manager boss = new Manager();&lt;br /&gt;
         boss.performTask();&lt;br /&gt;
     }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
have to write more stuff here. Examples from various programming lang.&lt;br /&gt;
&lt;br /&gt;
= Delegation in Ruby =&lt;br /&gt;
&lt;br /&gt;
Delegation pattern in Ruby is implemented in 3 ways:&lt;br /&gt;
&lt;br /&gt;
1)'''Forwardable lib:'''[http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/index.html Forwardable lib] is a library that supports delegation, it has 2 modules Forwardable and SingleForwardable:&lt;br /&gt;
&lt;br /&gt;
Forwardable module&lt;br /&gt;
&lt;br /&gt;
The Forwardable module provides delegation of specified methods to a designated object, using the methods def_delegator and def_delegators.&lt;br /&gt;
&lt;br /&gt;
* def_delegator(obj, method, alias = method) : Defines a method method which delegates to obj. If alias is provided, it is used as the name for the delegate method.&lt;br /&gt;
&lt;br /&gt;
* def_delegators(obj, *methods): Shortcut for defining multiple delegator methods, but with no provision for using a different name.&lt;br /&gt;
&lt;br /&gt;
2)'''SingleForwardable module:''' The [http://www.ruby-doc.org/stdlib/libdoc/forwardable/rdoc/classes/SingleForwardable.html SingleForwardable] module provides delegation of specified methods to a designated object, using the methods def_delegators. This module is similar to Forwardable, but it works on objects themselves, instead of their defining classes.&lt;br /&gt;
&lt;br /&gt;
3)'''Delegate lib:'''[http://www.ruby-doc.org/stdlib/libdoc/delegate/rdoc/index.html Delegate Lib] is another lib that provides delegation in Ruby&lt;br /&gt;
&lt;br /&gt;
== Example of delegation in Ruby ==&lt;br /&gt;
Using Forwardable module provided in Ruby, this is how we would implement Robot example seen above:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require 'forwardable'&lt;br /&gt;
class Robot&lt;br /&gt;
  # Extending provides class methods&lt;br /&gt;
  extend Forwardable&lt;br /&gt;
  # Use of  def_delegators&lt;br /&gt;
  def_delegators :@arm,:package,:stack&lt;br /&gt;
  # Use of  def_delegator&lt;br /&gt;
  def_delegator :@heat_sensor, :measure ,:measure_heat&lt;br /&gt;
  def initialize&lt;br /&gt;
    @heat_sensor = HeatSensor.new&lt;br /&gt;
    @arm = RobotArm.new&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class HeatSensor&lt;br /&gt;
  #Celsius or Fahrenheit scale&lt;br /&gt;
  def measure(scale=&amp;quot;c&amp;quot;)&lt;br /&gt;
    t = rand(100)&lt;br /&gt;
    t = scale==&amp;quot;c&amp;quot; ? t : t * (9/5)&lt;br /&gt;
    puts &amp;quot;Heat is #{t}° #{scale.upcase}&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
class RobotArm&lt;br /&gt;
  def stack(boxes_number=1)&lt;br /&gt;
    puts &amp;quot;Stacking #{boxes_number} box(es)&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
  def package&lt;br /&gt;
    puts &amp;quot;Packaging&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using Single Forwardable module:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;forwardable&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
Date = Date.today # output will be &amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Prepare object for delegation&lt;br /&gt;
date.extend SingleForwardable #=&amp;gt; #&amp;lt;Date: 4909665/2,0,2299161&amp;gt; # Add delegation for Time.now&lt;br /&gt;
date.def_delegator :Time, &amp;quot;now&amp;quot;,&amp;quot;with_time&amp;quot;&lt;br /&gt;
puts date.with_time #=&amp;gt;Thu Jan 01 23:03:04 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Using delegate lib:&lt;br /&gt;
&lt;br /&gt;
require &amp;quot;delegate&amp;quot;&lt;br /&gt;
require &amp;quot;date&amp;quot;&lt;br /&gt;
# Notice the class definition&lt;br /&gt;
class CurrentDate &amp;lt; DelegateClass(Date)&lt;br /&gt;
  def initialize&lt;br /&gt;
    @date = Date.today&lt;br /&gt;
    # Pass the object to be delegated to the superclass. &lt;br /&gt;
    super(@date)&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def to_s&lt;br /&gt;
    @date.strftime &amp;quot;%Y/%m/%d&amp;quot;&lt;br /&gt;
  end&lt;br /&gt;
 &lt;br /&gt;
  def with_time&lt;br /&gt;
    Time.now&lt;br /&gt;
  end&lt;br /&gt;
end&lt;br /&gt;
 &lt;br /&gt;
cdate = CurrentDate.new ## Notice how delegation works. Instead of doing cdate.date.day and defining attr_accessor for the date just do c.day&lt;br /&gt;
puts cdate.day #=&amp;gt;1&lt;br /&gt;
puts cdate.month #=&amp;gt;1&lt;br /&gt;
puts cdate.year #=&amp;gt;2009 # Testing added methods like to_s&lt;br /&gt;
puts cdate #=&amp;gt; 2009/01/01&lt;br /&gt;
puts cdate.with_time #=&amp;gt; Thu Jan 01 23:22:20 +0200 2009&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= Delegation in Java =&lt;br /&gt;
Java supports delegation in the same way as other languages do. By using an instance of the class we would have otherwise inherited, and then forwarding messages to the instance we can do delegation in Java.[http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html] e.g. We can associate a class with a thread in two ways: *By inheriting directly from class Thread.&lt;br /&gt;
*By implementing the Runnable interface and delegating to a Thread object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Examples of Delegation in Java ===&lt;br /&gt;
Given below are the two examples of delegation, first being a simple one while the second being a complex example.&lt;br /&gt;
&lt;br /&gt;
==== Simple Java Example ====&lt;br /&gt;
&lt;br /&gt;
In this example, the class C has method which does not perform itself and rather delegates to class A, the methods f() and g(). It seems that Class C is doing the work but in reality class A is doing it.[http://en.wikipedia.org/wiki/Delegation_pattern]&lt;br /&gt;
&lt;br /&gt;
 class A {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C {&lt;br /&gt;
   // delegation&lt;br /&gt;
   A a = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { a.f(); }&lt;br /&gt;
   void g() { a.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   X x = new X();&lt;br /&gt;
   void y() { /* do stuff */ }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Complex Java Example ====&lt;br /&gt;
&lt;br /&gt;
By using interfaces, delegation can be made more flexible[ C need not refer to classA or classB, delegation is abstracted] and typesafe. Here, class C can delegate to either class A or class B. The implements clauses, improves type safety, since this ensures that each of the class must implements the methods in the interface. The main tradeoff being more code.&lt;br /&gt;
 interface I {&lt;br /&gt;
   void f();&lt;br /&gt;
   void g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class A implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;A: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;A: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class B implements I {&lt;br /&gt;
   void f() { system.out.println(&amp;quot;B: doing f()&amp;quot;); }&lt;br /&gt;
   void g() { system.out.println(&amp;quot;B: doing g()&amp;quot;); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 class C implements I {&lt;br /&gt;
   // delegation&lt;br /&gt;
   I i = new A();&lt;br /&gt;
&lt;br /&gt;
   void f() { i.f(); }&lt;br /&gt;
   void g() { i.g(); }&lt;br /&gt;
&lt;br /&gt;
   // normal attributes&lt;br /&gt;
   void toA() { i = new A(); }&lt;br /&gt;
   void toB() { i = new B(); }&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
 void main() {&lt;br /&gt;
   C c = new C();&lt;br /&gt;
&lt;br /&gt;
   c.f();&lt;br /&gt;
   c.g();&lt;br /&gt;
 }&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Table of Comparison =&lt;br /&gt;
fjskdjfldsjl&lt;br /&gt;
&lt;br /&gt;
= Feature Matrix =&lt;br /&gt;
kflksjfklsjd&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Conclusion =&lt;br /&gt;
Delegation is simply passing a duty off to someone/something else&lt;br /&gt;
&lt;br /&gt;
= References and Notes =&lt;br /&gt;
&lt;br /&gt;
*[1]  [http://portal.acm.org/citation.cfm?id=28718 Using prototypical objects to implement shared behavior in object-oriented systems]&lt;br /&gt;
*[2]  [http://en.wikipedia.org/wiki/Object_composition#Aggregation Aggregation]&lt;br /&gt;
*[3]  [http://en.wikipedia.org/wiki/Object_composition Object Composition]&lt;br /&gt;
*[4]  [http://www.ccs.neu.edu/research/demeter/papers/context-journal/node3.html Issues Involved in Supporting Behavioral Evolution ]&lt;br /&gt;
*[5]  [http://rosettacode.org/wiki/Delegate Delegates]&lt;br /&gt;
*[6]  [http://javalab.cs.uni-bonn.de/research/darwin/delegation.html Darwin Project]&lt;br /&gt;
*[7]  [http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;br /&gt;
*[8]  [http://best-practice-software-engineering.ifs.tuwien.ac.at/patterns/delegation.html Delegation Design Pattern]&lt;br /&gt;
*[9]  [http://en.wikipedia.org/wiki/Delegation_pattern Examples of delegation in Java]&lt;br /&gt;
*[10] [http://www.techartifact.com/blogs/2009/05/delegation-versus-inheritance-in-java.html]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= Further Reading =&lt;br /&gt;
&lt;br /&gt;
*[http://en.wikipedia.org/wiki/Delegation_pattern Delegation Pattern in detail]&lt;br /&gt;
*[http://www.khelll.com/blog/ruby/delegation-in-ruby/ Delegation in Ruby]&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38392</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38392"/>
		<updated>2010-10-16T01:11:29Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38391</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38391"/>
		<updated>2010-10-16T01:11:13Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Sequel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38390</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38390"/>
		<updated>2010-10-16T01:10:56Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Sequel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38389</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38389"/>
		<updated>2010-10-16T01:10:36Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Sequel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38388</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38388"/>
		<updated>2010-10-16T01:10:14Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Merb */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38387</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38387"/>
		<updated>2010-10-16T01:09:50Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Merb */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Features&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38386</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38386"/>
		<updated>2010-10-16T01:09:33Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Merb */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
Features&lt;br /&gt;
Merb has set of following features:&amp;lt;sup&amp;gt;[14]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Plugins ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Plugins in Merb are implemented as simple gems. Plugins can either be installed to the system’s repository or bundled into the gems directory in an application’s distribution; Merb applications simply add the /gems folder as an alternate repository.&lt;br /&gt;
&lt;br /&gt;
Plugins for Merb include support for ActiveRecord, DataMapper, and Sequel, with support for SQL sessions, model generation, and database.yml baked in to all three. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Controllers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s controllers are made up of two components. First, an AbstractController, which handles layout- and template-finding, instance variable assignment, and before/after filters. Second, a Merb::Controller, which handles request/response semantics.&lt;br /&gt;
Controllers also support excellent content-type negotiation.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Mailers ====&lt;br /&gt;
&lt;br /&gt;
Merb’s Mailers are implemented on top of AbstractController, so you get all the default controller behavior (including templates, assigns, and before/after filters) for free in the Mailer. But instead of calling render, you call render_mail, which takes options like: render_mail :html =&amp;gt; :foo, :text =&amp;gt; :bar.&lt;br /&gt;
Mailers have their own root directory, which contains controller classes inside it, as well as a views directory, and an optional helpers directory. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Parts ====&lt;br /&gt;
&lt;br /&gt;
Parts have a directory structure that’s identical to the Mailer structure, and you can use them to separate out logic about partials that are used throughout the application. Parts take advantage of the flexibility of the AbstractController to allow simple Controller/View delegation. &lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Exceptions ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb handles exceptions also. Instead of exception raising throwing an error in your application, Merb catches certain types of exceptions and allows you to handle them in a controller/view fashion. For instance, raising NotFound will call the Exception#not_found action, which you can customizeas appropriate. Raising an error in this way will also send the appropriate error-code back to the browser.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Tests and Specs ====&lt;br /&gt;
&lt;br /&gt;
Merb is testing-framework-agnostic i.e it can be used as Test::Unit, Rspec, or test/spec. All three testing frameworks have built-in support for mock objects that allows to micro-target tests exactly as desired. Merb is modular, hence it’s easy to test the controller without a request object.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Generators ====&lt;br /&gt;
&lt;br /&gt;
Merb has a series of generators that allow you get up and running quickly. The Merb application generator is started via merb-gen app application-name. It’ll build a skeleton app that includes folders for controllers, parts, and Mailers.&lt;br /&gt;
Merb has controller generators, which create an empty controller file, a view directory with an empty index.html.erb, an empty helper file, and a test file in the chosen spec framework. Merb also has model generators, which are implemented by the ORM plugins, and support a special syntax: merb-gen Product name:string price_in_cents:integer which will generate a new model that implements those attributes using its own syntax. For instance, ActiveRecord would generate a migration, while DataMapper would generate new model using its property syntax.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38376</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38376"/>
		<updated>2010-10-16T00:55:49Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;br /&gt;
*[14]http://www.merbivore.com&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38375</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38375"/>
		<updated>2010-10-16T00:53:12Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38374</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38374"/>
		<updated>2010-10-16T00:51:30Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Sequel */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38373</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38373"/>
		<updated>2010-10-16T00:49:52Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Merb */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38370</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38370"/>
		<updated>2010-10-16T00:34:42Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* iBATIS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
iBATIS comes with the following design philosophies:&amp;lt;sup&amp;gt;[13]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Simplicity: iBATIS is widely regarded as being one of the simplest persistence frameworks available today.&lt;br /&gt;
Fast Development: iBATIS's philosophy is to do all it can to facilitate hyper-fast development.&lt;br /&gt;
Portability: iBATIS can be implemented for nearly any language or platform like Java, Ruby, and C# for Microsoft .NET.&lt;br /&gt;
Independent Interfaces: iBATIS provides database-independent interfaces and APIs that help the rest of the application remain independent of any persistence-related resources,&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Advantages of IBATIS ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Suppports Stored procedures: iBATIS encapsulates SQL in the form of stored procedures so that business logic is kept out of the database, and the application is easier to deploy and test, and is more portable.&lt;br /&gt;
&lt;br /&gt;
Supports Inline SQL: No precompiler is needed, and you have full access to all of the features of SQL.&lt;br /&gt;
&lt;br /&gt;
Supports Dynamic SQL: iBATIS provides features for dynamically building SQL queries based on parameters.&lt;br /&gt;
&lt;br /&gt;
Supports O/RM: iBATIS supports many of the same features as an O/RM tool, such as lazy loading, join fetching, caching, runtime code generation, and inheritance&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38368</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38368"/>
		<updated>2010-10-16T00:31:13Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* References */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;br /&gt;
*[13]http://www.tutorialspoint.com/ibatis/ibatis_quick_guide.htm&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38365</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38365"/>
		<updated>2010-10-16T00:28:32Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* iBATIS */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38364</id>
		<title>CSC/ECE 517 Fall 2010/ch3 3f ac</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2010/ch3_3f_ac&amp;diff=38364"/>
		<updated>2010-10-16T00:28:07Z</updated>

		<summary type="html">&lt;p&gt;Csgodbol: /* Datamapper */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
= ORM for Ruby =&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Introduction ==&lt;br /&gt;
Object-relational mapping in computer software is a programming technique for converting data between incompatible type systems in object-oriented programming languages. This creates, in effect, a &amp;quot;virtual object database&amp;quot; that can be used from within the programming language. There are both free and commercial packages available that perform object-relational mapping, although some programmers opt to create their own ORM tools. &amp;lt;sup&amp;gt;[4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
[[Image:ORM.png|660x660px|&amp;lt;span title=&amp;quot;ORM&amp;quot;&amp;gt;&amp;lt;/span&amp;gt;]]&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Advantages of ORM&amp;lt;sup&amp;gt;[2][4]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt; ==&lt;br /&gt;
*ORM reduces the amount of code needed to be written.&lt;br /&gt;
*Facilitates implementing the Domain Model pattern.&lt;br /&gt;
*Changes to the object model are made in one place.&lt;br /&gt;
*Rich query capability. ORM tools provide an object oriented query language. &lt;br /&gt;
*Navigation. You can navigate object relationships transparently. Related objects are automatically loaded as needed.&lt;br /&gt;
*Data loads are completely configurable allowing you to load the data appropriate for each scenario.&lt;br /&gt;
*Concurrency support. Support for multiple users updating the same data simultaneously.&lt;br /&gt;
*Cache managment. Entities are cached in memory thereby reducing load on the database.&lt;br /&gt;
*Transaction management and Isolation.&lt;br /&gt;
*Key Management. Identifiers and keys are automatically propogated and managed.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== Disdvantages ==&lt;br /&gt;
*Most O/R mapping tools do not perform well during bulk deletions of data and particularly complex or even simple joins.&lt;br /&gt;
*Stored procedures may have better performance, but are not portable.&lt;br /&gt;
*In addition, heavy reliance on ORM software has been pointed to as a major factor in producing poorly designed databases.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
== List of ORM software for Ruby ==&lt;br /&gt;
*ActiveRecord, part of Ruby on Rails &amp;amp; Open Source&lt;br /&gt;
*Datamapper, MIT license&lt;br /&gt;
*iBATIS, free open source&lt;br /&gt;
*Sequel, free open source&lt;br /&gt;
*Merb&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== ActiveRecord ===&lt;br /&gt;
&lt;br /&gt;
Active Record connects business objects and database tables to create a persistable domain model where logic and data are presented in one wrapping. An object that wraps a row in a database table or view, encapsulates the database access, and adds domain logic on that data.&amp;lt;sup&amp;gt;[5][11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Active Record‘s main contribution to the pattern is to relieve the original of two stunting problems: lack of associations and inheritance. By adding a simple domain language-like set of macros to describe the former and integrating the Single Table Inheritance pattern for the latter, Active Record narrows the gap of functionality between the data mapper and active record approach. A Ruby library is available which implements the object-relational mapping (ORM) design pattern. It creates a persistable domain model from business objects and database tables, where logic and data are presented as a unified package. ActiveRecord adds inheritance and associations to the pattern above, solving two substantial limitations of that pattern. A set of macros acts as a domain language for the latter, and the Single Table Inheritance pattern is integrated for the former; thus, ActiveRecord increases the functionality of the active record pattern approach to database interaction.&lt;br /&gt;
&lt;br /&gt;
ActiveRecord is the default model component of the Model-view-controller web-application framework Ruby on Rails, and is also a stand-alone ORM package for other Ruby applications. In both forms, it was conceived of by David Heinemeier Hansson, and has been improved upon by a number of contributors.&lt;br /&gt;
Other, less popular ORMs have been released since ActiveRecord first took the stage. Gems like DataMapper and Sequel show major improvements over the original ActiveRecord framework. As a response to their release and adoption by the Rails community, Ruby on Rails v3.0 will be independent of an ORM system, so Rails users can easily plug in DataMapper or Sequel to use as their ORM of choice.&lt;br /&gt;
&lt;br /&gt;
Some of the major features are given below.&amp;lt;sup&amp;gt;[11]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Automated mapping between classes and tables, attributes and columns ====&lt;br /&gt;
	&lt;br /&gt;
Active Record objects don‘t specify their attributes directly. They infer them from the table definition with which they‘re linked. Adding, removing, and changing attributes and their type is done directly in the database. Any change is instantly reflected in the Active Record objects. The mapping that binds a given Active Record class to a certain database table will happen automatically in most common cases, but can be overwritten for the uncommon ones.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
          class Product &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
	&lt;br /&gt;
	 ...is automatically mapped to the table named &amp;quot;products&amp;quot;, such as:&lt;br /&gt;
	&lt;br /&gt;
	 CREATE TABLE products (&lt;br /&gt;
	   id int(11) NOT NULL auto_increment,&lt;br /&gt;
	   name varchar(255),&lt;br /&gt;
	   PRIMARY KEY  (id)&lt;br /&gt;
	 );&lt;br /&gt;
	&lt;br /&gt;
	 ...which again gives Product#name and Product#name=(new_name)&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Associations between objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Associations are a set of macro-like class methods for tying objects together through foreign keys. They express relationships like Project has one Project Manager or Project belongs to a Portfolio. Each macro adds a number of methods to the class which are specialized according to the collection or association symbol and the options hash. It works much the same way as Ruby‘s attr* methods. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
      class Project &amp;lt; ActiveRecord::Base&lt;br /&gt;
        belongs_to              :portfolio&lt;br /&gt;
        has_one                 :project_manager&lt;br /&gt;
        has_many                :milestones&lt;br /&gt;
        has_and_belongs_to_many :categories&lt;br /&gt;
      end	 &lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Aggregations of value objects controlled by simple meta-programming macros ====&lt;br /&gt;
&lt;br /&gt;
Active Record implements aggregation through a macro-like class method called composed_of for representing attributes as value objects. It expresses relationships like &amp;quot;Account [is] composed of Money [among other things]&amp;quot; or &amp;quot;Person [is] composed of [an] address&amp;quot;. Each call to the macro adds a description of how the value objects are created from the attributes of the entity object (when the entity is initialized either as a new object or from finding an existing object) and how it can be turned back into attributes (when the entity is saved to the database). Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
           class Customer &amp;lt; ActiveRecord::Base&lt;br /&gt;
              composed_of :balance, :class_name =&amp;gt; &amp;quot;Money&amp;quot;, :mapping =&amp;gt; %w(balance amount)&lt;br /&gt;
              composed_of :address, :mapping =&amp;gt; [ %w(address_street street), %w(address_city city) ]&lt;br /&gt;
           end	&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Validation rules that can differ for new or existing objects ====&lt;br /&gt;
&lt;br /&gt;
Active Records implement validation by overwriting Base#validate (or the variations, validate_on_create and validate_on_update). Each of these methods can inspect the state of the object, which usually means ensuring that a number of attributes have a certain value (such as not empty, within a given range, matching a certain regular expression).&lt;br /&gt;
Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	    validates_presence_of     :subdomain, :name, :email_address, :password&lt;br /&gt;
	    validates_uniqueness_of   :subdomain&lt;br /&gt;
	    validates_acceptance_of   :terms_of_service, :on =&amp;gt; :create&lt;br /&gt;
	    validates_confirmation_of :password, :email_address, :on =&amp;gt; :create&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Callbacks as methods or queues on the entire lifecycle (instantiation, saving, destroying, validating, etc) ====&lt;br /&gt;
&lt;br /&gt;
Callbacks are hooks into the lifecycle of an Active Record object that allow you to trigger logic before or after an alteration of the object state. This can be used to make sure that associated and dependent objects are deleted when destroy is called (by overwriting before_destroy) or to massage attributes before they‘re validated (by overwriting before_validation).&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   def before_destroy # is called just before Person#destroy&lt;br /&gt;
	     CreditCard.find(credit_card_id).destroy&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
	&lt;br /&gt;
	 class Account &amp;lt; ActiveRecord::Base&lt;br /&gt;
	   after_find :eager_load, 'self.class.announce(#{id})'&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Observers for the entire lifecycle ====&lt;br /&gt;
&lt;br /&gt;
Observer classes respond to lifecycle callbacks to implement trigger-like behavior outside the original class. This is a great way to reduce the clutter that normally comes when the model class is burdened with functionality that doesn‘t pertain to the core responsibility of the class. Example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	 class CommentObserver &amp;lt; ActiveRecord::Observer&lt;br /&gt;
	   def after_create(comment) # is called just after Comment#save&lt;br /&gt;
	     Notifications.deliver_new_comment(&amp;quot;xyz@ncsu.edu&amp;quot;, comment)&lt;br /&gt;
	   end&lt;br /&gt;
	 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Inheritance hierarchies ====&lt;br /&gt;
&lt;br /&gt;
Active Record allows inheritance by storing the name of the class in a column that by default is named &amp;quot;type&amp;quot; (can be changed by overwriting Base.inheritance_column). Example of inheritance:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Company &amp;lt; ActiveRecord::Base; end&lt;br /&gt;
class Firm &amp;lt; Company; end&lt;br /&gt;
class Client &amp;lt; Company; end&lt;br /&gt;
class PriorityClient &amp;lt; Client; end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Transactions ====&lt;br /&gt;
&lt;br /&gt;
Transactions are protective blocks where SQL statements are only permanent if they can all succeed as one atomic action. The classic example is a transfer between two accounts where you can only have a deposit if the withdrawal succeeded and vice versa. Transactions enforce the integrity of the database and guard the data against program errors or database break-downs. So basically transaction blocks are used if there are number of statements that must be executed together or not at all. Example:&lt;br /&gt;
  &lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
	  # Database transaction&lt;br /&gt;
	  Account.transaction do&lt;br /&gt;
	    david.withdrawal(100)&lt;br /&gt;
	    mary.deposit(100)&lt;br /&gt;
	  end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Reflections on columns, associations, and aggregations ====&lt;br /&gt;
&lt;br /&gt;
Reflection allows you to interrogate Active Record classes and objects about their associations and aggregations. This information can, for example, be used in a form builder that took an Active Record object and created input fields for all of the attributes depending on their type and displayed the associations to other objects.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
	  reflection = Firm.reflect_on_association(:clients)&lt;br /&gt;
	  reflection.klass # =&amp;gt; Client (class)&lt;br /&gt;
	  Firm.columns # Returns an array of column descriptors for the firms table&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Data Definitions ====&lt;br /&gt;
&lt;br /&gt;
Data definitions are specified only in the database. Active Record queries the database for the column names (that then serves to determine which attributes are valid) on regular object instantiation through the new constructor and relies on the column names in the rows with the finders.&lt;br /&gt;
   # CREATE TABLE companies (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   client_of int(11),&lt;br /&gt;
   #   name varchar(255),&lt;br /&gt;
   #   type varchar(100),&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record automatically links the &amp;quot;Company&amp;quot; object to the &amp;quot;companies&amp;quot; table&lt;br /&gt;
   class Company &amp;lt; ActiveRecord::Base&lt;br /&gt;
     has_many :people, :class_name =&amp;gt; &amp;quot;Person&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   class Firm &amp;lt; Company&lt;br /&gt;
     has_many :clients&lt;br /&gt;
&lt;br /&gt;
     def people_with_all_clients&lt;br /&gt;
      clients.inject([]) { |people, client| people + client.people }&lt;br /&gt;
     end&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
The foreign_key is only necessary because we didn‘t use &amp;quot;firm_id&amp;quot; in the data definition&lt;br /&gt;
   class Client &amp;lt; Company&lt;br /&gt;
     belongs_to :firm, :foreign_key =&amp;gt; &amp;quot;client_of&amp;quot;&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
   # CREATE TABLE people (&lt;br /&gt;
   #   id int(11) unsigned NOT NULL auto_increment,&lt;br /&gt;
   #   name text,&lt;br /&gt;
   #   company_id text,&lt;br /&gt;
   #   PRIMARY KEY  (id)&lt;br /&gt;
   # )&lt;br /&gt;
&lt;br /&gt;
Active Record will also automatically link the &amp;quot;Person&amp;quot; object to the &amp;quot;people&amp;quot; table&lt;br /&gt;
   class Person &amp;lt; ActiveRecord::Base&lt;br /&gt;
     belongs_to :company&lt;br /&gt;
   end&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=== Datamapper ===&lt;br /&gt;
                                            &lt;br /&gt;
Datamapper is an object-relational mapper library written in Ruby and commonly used with Merb. It was developed to address perceived shortcomings in Ruby on Rails' ActiveRecord library.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Features ====&lt;br /&gt;
&lt;br /&gt;
Some features of Datamapper:&lt;br /&gt;
eager loading of child associations to avoid (N+1) queries&lt;br /&gt;
lazy loading of select properties, e.g., larger fields&lt;br /&gt;
query chaining, and not evaluating the query until absolutely necessary (using a lazy array implementation)&lt;br /&gt;
an API not too heavily oriented to SQL databases.&lt;br /&gt;
&lt;br /&gt;
DataMapper differentiates itself from other Ruby Object/Relational Mappers in a number of ways:&amp;lt;sup&amp;gt;[6][12]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Same API for different datastores ====&lt;br /&gt;
&lt;br /&gt;
DataMapper comes with the ability to use the same API to talk to a multitude of different datastores. There are adapters for the usual RDBMS suspects, NoSQL stores, various file formats and even some popular webservices.&lt;br /&gt;
&lt;br /&gt;
There’s a probably incomplete list of available datamapper adapters on the github wiki with new ones getting implemented regularly. A quick github search should give you further hints on what’s currently available.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Works well with databases ====&lt;br /&gt;
&lt;br /&gt;
With DataMapper you define your mappings in your model. Your data-store can develop independently of your models using Migrations.&lt;br /&gt;
&lt;br /&gt;
To support data-stores which you don’t have the ability to manage yourself, it’s simply a matter of telling DataMapper where to look. This makes DataMapper a good choice when Working with legacy databases&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1   class Post&lt;br /&gt;
 2   include DataMapper::Resource&lt;br /&gt;
 3 &lt;br /&gt;
 4   # set the storage name for the :legacy repository&lt;br /&gt;
 5   storage_names[:legacy] = 'tblPost'&lt;br /&gt;
 6 &lt;br /&gt;
 7   # use the datastore's 'pid' field for the id property.&lt;br /&gt;
 8   property :id, Serial, :field =&amp;gt; :pid&lt;br /&gt;
 9 &lt;br /&gt;
10   # use a property called 'uid' as the child key (the foreign key)&lt;br /&gt;
11   belongs_to :user, :child_key =&amp;gt; [ :uid ]&lt;br /&gt;
12   end&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
DataMapper only issues updates or creates for the properties it knows about. So it plays well with others. You can use it in an Integration Database without worrying that your application will be a bad actor causing trouble for all of your other processes.&lt;br /&gt;
&lt;br /&gt;
DataMapper has full support for Composite Primary Keys (CPK) builtin. Specifying the properties that form the primary key is easy.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class LineItem&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :order_id,    Integer, :key =&amp;gt; true&lt;br /&gt;
5   property :item_number, Integer, :key =&amp;gt; true&lt;br /&gt;
6 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
If we were to know an order_id/item_number combination,  retrieve the corresponding line item from the datastore.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 order_id, item_number = 1, 1&lt;br /&gt;
2 LineItem.get(order_id, item_number)&lt;br /&gt;
3 # =&amp;gt; [#&amp;lt;LineItem @orderid=1 @item_number=1&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Less need for writing migrations ====&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
With DataMapper, you specify the datastore layout inside your ruby models. This allows DataMapper to create the underlying datastore schema based on the models you defined. The #auto_migrate! and #auto_upgrade! methods can be used to generate a schema in the datastore that matches your model definitions.&lt;br /&gt;
&lt;br /&gt;
While #auto_migrate! desctructively drops and recreates tables to match your model definitions, #auto_upgrade! supports upgrading your datastore to match your model definitions, without actually destroying any already existing data.&lt;br /&gt;
&lt;br /&gt;
There are still some limitations to the operations that #auto_upgrade! can perform. We’re working hard on making it smarter, but there will always be scenarios where an automatic upgrade of your schema won’t be possible. For example, there’s no sane strategy for automatically changing a column length constraint from VARCHAR(100) to VARCHAR(50). DataMapper can’t know what it should do when the data doesn’t validate against the new tightened constraints.&lt;br /&gt;
&lt;br /&gt;
In situations where neither #auto_migrate! nor #auto_upgrade! quite cut it, you can still fall back to the classic migrations feature provided by dm-migrations.&lt;br /&gt;
&lt;br /&gt;
Here’s some example code that puts #auto_migrate! and #auto_upgrade! to use.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 require 'rubygems'&lt;br /&gt;
 2 require 'dm-core'&lt;br /&gt;
 3 require 'dm-migrations'&lt;br /&gt;
 4 &lt;br /&gt;
 5 DataMapper::Logger.new($stdout, :debug)&lt;br /&gt;
 6 DataMapper.setup(:default, 'mysql://localhost/test')&lt;br /&gt;
 7 &lt;br /&gt;
 8 class Person&lt;br /&gt;
 9   include DataMapper::Resource&lt;br /&gt;
10   property :id,   Serial&lt;br /&gt;
11   property :name, String, :required =&amp;gt; true&lt;br /&gt;
12 end&lt;br /&gt;
13 &lt;br /&gt;
14 DataMapper.auto_migrate!&lt;br /&gt;
15 &lt;br /&gt;
16 # ~ (0.015754) SET sql_auto_is_null = 0&lt;br /&gt;
17 # ~ (0.000335) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
18 # ~ (0.283290) DROP TABLE IF EXISTS `people`&lt;br /&gt;
19 # ~ (0.029274) SHOW TABLES LIKE 'people'&lt;br /&gt;
20 # ~ (0.000103) SET sql_auto_is_null = 0&lt;br /&gt;
21 # ~ (0.000111) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
22 # ~ (0.000932) SHOW VARIABLES LIKE 'character_set_connection'&lt;br /&gt;
23 # ~ (0.000393) SHOW VARIABLES LIKE 'collation_connection'&lt;br /&gt;
24 # ~ (0.080191) CREATE TABLE `people` (`id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT, `name` VARCHAR(50) NOT NULL, PRIMARY KEY(`id`)) ENGINE = InnoDB CHARACTER SET utf8 COLLATE utf8_general_ci&lt;br /&gt;
25 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
26 &lt;br /&gt;
27 class Person&lt;br /&gt;
28   property :hobby, String&lt;br /&gt;
29 end&lt;br /&gt;
30 &lt;br /&gt;
31 DataMapper.auto_upgrade!&lt;br /&gt;
32 &lt;br /&gt;
33 # ~ (0.000612) SHOW TABLES LIKE 'people'&lt;br /&gt;
34 # ~ (0.000079) SET sql_auto_is_null = 0&lt;br /&gt;
35 # ~ (0.000081) SET SESSION sql_mode = 'ANSI,NO_BACKSLASH_ESCAPES,NO_DIR_IN_CREATE,NO_ENGINE_SUBSTITUTION,NO_UNSIGNED_SUBTRACTION,TRADITIONAL'&lt;br /&gt;
36 # ~ (1.794475) SHOW COLUMNS FROM `people` LIKE 'id'&lt;br /&gt;
37 # ~ (0.001412) SHOW COLUMNS FROM `people` LIKE 'name'&lt;br /&gt;
38 # ~ (0.001121) SHOW COLUMNS FROM `people` LIKE 'hobby'&lt;br /&gt;
39 # ~ (0.153989) ALTER TABLE `people` ADD COLUMN `hobby` VARCHAR(50)&lt;br /&gt;
40 # =&amp;gt; #&amp;lt;DataMapper::DescendantSet:0x101379a68 @descendants=[Person]&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== DataMapper provides data integrity ====&lt;br /&gt;
&lt;br /&gt;
DataMapper makes it easy to leverage native techniques for enforcing data integrity. The dm-constraints plugin provides support for establishing true foreign key constraints in databases that support that concept.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Strategic Eager Loading ====&lt;br /&gt;
&lt;br /&gt;
DataMapper will only issue the very bare minimums of queries to your data-store that it needs to. For example, the following example will only issue 2 queries. Notice how we don’t supply any extra :include information.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 zoos = Zoo.all&lt;br /&gt;
 2 zoos.each do |zoo|&lt;br /&gt;
 3   # on first iteration, DM loads up all of the exhibits for all of the items in zoos&lt;br /&gt;
 4   # in 1 query to the data-store.&lt;br /&gt;
 5 &lt;br /&gt;
 6   zoo.exhibits.each do |exhibit|&lt;br /&gt;
 7     # n+1 queries in other ORMs, not in DataMapper&lt;br /&gt;
 8     puts &amp;quot;Zoo: #{zoo.name}, Exhibit: #{exhibit.name}&amp;quot;&lt;br /&gt;
 9   end&lt;br /&gt;
10 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The idea is that you aren’t going to load a set of objects and use only an association in just one of them. This should hold up pretty well against a 99% rule.&lt;br /&gt;
&lt;br /&gt;
When you don’t want it to work like this, just load the item you want in it’s own set. So DataMapper thinks ahead. We like to call it “performant by default”. This feature single-handedly wipes out the “N+1 Query Problem”.&lt;br /&gt;
&lt;br /&gt;
DataMapper also waits until the very last second to actually issue the query to your data-store. For example, zoos = Zoo.all won’t run the query until you start iterating over zoos or call one of the ‘kicker’ methods like #length. If you never do anything with the results of a query, DataMapper won’t incur the latency of talking to your data-store.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Querying models by their associations ====&lt;br /&gt;
&lt;br /&gt;
DataMapper allows you to create and search for any complex object graph simply by providing a nested hash of conditions. The following example uses a typical Customer - Order domain model to illustrate how nested conditions can be used to both create and query models by their associations.&lt;br /&gt;
&lt;br /&gt;
For a complete definition of the Customer - Order domain models have a look at the Finders page.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 # A hash specifying one customer with one order&lt;br /&gt;
 2 #&lt;br /&gt;
 3 # In general, possible keys are all property and relationship&lt;br /&gt;
 4 # names that are available on the relationship's target model.&lt;br /&gt;
 5 # Possible toplevel keys depend on the property and relationship&lt;br /&gt;
 6 # names available in the model that receives the hash.&lt;br /&gt;
 7 #&lt;br /&gt;
 8 customer = {&lt;br /&gt;
 9   :name   =&amp;gt; 'Dan Kubb',&lt;br /&gt;
10   :orders =&amp;gt; [&lt;br /&gt;
11     {&lt;br /&gt;
12       :reference   =&amp;gt; 'TEST1234',&lt;br /&gt;
13       :order_lines =&amp;gt; [&lt;br /&gt;
14         {&lt;br /&gt;
15           :item =&amp;gt; {&lt;br /&gt;
16             :sku        =&amp;gt; 'BLUEWIDGET1',&lt;br /&gt;
17             :unit_price =&amp;gt; 1.00,&lt;br /&gt;
18           },&lt;br /&gt;
19         },&lt;br /&gt;
20       ],&lt;br /&gt;
21     },&lt;br /&gt;
22   ]&lt;br /&gt;
23 }&lt;br /&gt;
24 &lt;br /&gt;
25 # Create the Customer with the nested options hash&lt;br /&gt;
26 Customer.create(customer)&lt;br /&gt;
27 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
28 &lt;br /&gt;
29 # The same options to create can also be used to query for the same object&lt;br /&gt;
30 p Customer.all(customer)&lt;br /&gt;
31 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
QueryPaths can be used to construct joins in a very declarative manner.&lt;br /&gt;
&lt;br /&gt;
Starting from a root model, you can call any relationship by its name. The returned object again responds to all property and relationship names that are defined in the relationship’s target model.&lt;br /&gt;
&lt;br /&gt;
This means that you can walk the chain of available relationships, and then match against a property at the end of that chain. The object returned by the last call to a property name also responds to all the comparison operators that we saw above. This makes for some powerful join construction!&lt;br /&gt;
&lt;br /&gt;
1 Customer.all(Customer.orders.order_lines.item.sku.like =&amp;gt; &amp;quot;%BLUE%&amp;quot;)&lt;br /&gt;
2 # =&amp;gt; [#&amp;lt;Customer @id=1 @name=&amp;quot;Dan Kubb&amp;quot;&amp;gt;]&lt;br /&gt;
&lt;br /&gt;
You can even chain calls to all or first to continue refining your query or search within a scope.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Identity Map ====&lt;br /&gt;
One row in the database should equal one object reference. Pretty simple idea. Pretty profound impact. If you run the following code in ActiveRecord you’ll see all false results. Do the same in DataMapper and it’s true all the way down.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 @parent = Tree.first(:conditions =&amp;gt; { :name =&amp;gt; 'bob' })&lt;br /&gt;
2 &lt;br /&gt;
3 @parent.children.each do |child|&lt;br /&gt;
4   puts @parent.object_id == child.parent.object_id&lt;br /&gt;
5 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This makes DataMapper faster and allocate less resources to get things done.&lt;br /&gt;
&lt;br /&gt;
==== Lazy Option ====&lt;br /&gt;
Columns of potentially infinite length, like Text columns, are expensive in data-stores. They’re generally stored in a different place from the rest of your data. So instead of a fast sequential read from your hard-drive, your data-store has to hop around all over the place to get what it needs.&lt;br /&gt;
&lt;br /&gt;
With DataMapper, these fields are treated like in-row associations by default, meaning they are loaded if and only if you access them. If you want more control you can enable or disable this feature for any column (not just text-fields) by passing a lazy option to your column mapping with a value of true or false.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 class Animal&lt;br /&gt;
2   include DataMapper::Resource&lt;br /&gt;
3 &lt;br /&gt;
4   property :id,    Serial&lt;br /&gt;
5   property :name,  String&lt;br /&gt;
6   property :notes, Text    # lazy-loads by default&lt;br /&gt;
7 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Plus, lazy-loading of Text property happens automatically and intelligently when working with associations. The following only issues 2 queries to load up all of the notes fields on each animal:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
1 animals = Animal.all&lt;br /&gt;
2 animals.each do |pet|&lt;br /&gt;
3   pet.notes&lt;br /&gt;
4 end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==== Ruby Compatibility ====&lt;br /&gt;
&lt;br /&gt;
DataMapper loves Ruby and is therefore tested regularly against all major Ruby versions. Before release, every gem is explicitly tested against MRI 1.8.7, 1.9.2, JRuby and Rubinius. We’re proud to say that almost all of our specs pass on all these different implementations.&lt;br /&gt;
&lt;br /&gt;
Have a look at the testing matrix for detailed information about which gems pass or fail their specs on the various Ruby implementations.&lt;br /&gt;
&lt;br /&gt;
DataMapper goes further than most Ruby ORMs in letting you avoid writing raw query fragments yourself. It provides more helpers and a unique hash-based conditions syntax to cover more of the use-cases where issuing your own SQL would have been the only way to go.&lt;br /&gt;
&lt;br /&gt;
For example, any finder option that are non-standard is considered a condition. So you can write Zoo.all(:name =&amp;gt; 'Dallas') and DataMapper will look for zoos with the name of ‘Dallas’.&lt;br /&gt;
&lt;br /&gt;
It’s just a little thing, but it’s so much nicer than writing Zoo.find(:all, :conditions =&amp;gt; [ 'name = ?', 'Dallas' ]) and won’t incur the Ruby overhead of Zoo.find_by_name('Dallas'), nor is it more difficult to understand once the number of parameters increases.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
 1 Zoo.first(:name =&amp;gt; 'Galveston')&lt;br /&gt;
 2 &lt;br /&gt;
 3 # 'gt' means greater-than. 'lt' is less-than.&lt;br /&gt;
 4 Person.all(:age.gt =&amp;gt; 30)&lt;br /&gt;
 5 &lt;br /&gt;
 6 # 'gte' means greather-than-or-equal-to. 'lte' is also available&lt;br /&gt;
 7 Person.all(:age.gte =&amp;gt; 30)&lt;br /&gt;
 8 &lt;br /&gt;
 9 Person.all(:name.not =&amp;gt; 'bob')&lt;br /&gt;
10 &lt;br /&gt;
11 # If the value of a pair is an Array, we do an IN-clause for you.&lt;br /&gt;
12 Person.all(:name.like =&amp;gt; 'S%', :id =&amp;gt; [ 1, 2, 3, 4, 5 ])&lt;br /&gt;
13 &lt;br /&gt;
14 # Does a NOT IN () clause for you.&lt;br /&gt;
15 Person.all(:name.not =&amp;gt; [ 'bob', 'rick', 'steve' ])&lt;br /&gt;
16 &lt;br /&gt;
17 # Ordering&lt;br /&gt;
18 Person.all(:order =&amp;gt; [ :age.desc ])&lt;br /&gt;
19 # .asc is the default&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
====  Open Development ====&lt;br /&gt;
DataMapper sports a very accessible code-base and a welcoming community. Outside contributions and feedback are welcome and encouraged, especially constructive criticism. Go ahead, fork DataMapper, we’d love to see what you come up with!&lt;br /&gt;
&lt;br /&gt;
Make your voice heard! Submit a ticket or patch, speak up on our mailing-list, chat with us on irc, write a spec, get it reviewed, ask for commit rights. It’s as easy as that to become a contributor.&lt;br /&gt;
&lt;br /&gt;
=== iBATIS ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
iBATIS is a persistence framework which automates the mapping between SQL databases and objects in Java, .NET, and Ruby on Rails. iBatis for Ruby (RBatis) is a port of Apache's iBatis library to Ruby and Ruby on Rails. It is an O/R-mapper that allows for complete customization of SQL. &amp;lt;sup&amp;gt;[8][9]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
Other persistence frameworks such as Hibernate allow the creation of an object model by the user, and create and maintain the relational database automatically. iBatis takes the reverse approach: the developer starts with an SQL database and iBatis automates the creation of the objects. &lt;br /&gt;
Both approaches have advantages, and iBatis is a good choice when the developer does not have full control over the SQL database schema. For example, an application may need to access an existing SQL database used by other software, or access a new database whose schema is not fully under the application developer's control, such as when a specialized database design team has created the schema and carefully optimized it for high performance.&lt;br /&gt;
&lt;br /&gt;
Essentially, iBatis is a very lightweight persistence solution that gives most of the semantics of an O/R Mapping toolkit. In other words ,iBATIS makes it easy for the development of data-driven applications by abstracting the low-level details involved in database communication (loading a database driver, obtaining and managing connections, managing transaction semantics, etc.), as well as providing higher-level ORM capabilities (automated and configurable mapping of objects to SQL calls, data type conversion management, support for static queries as well as dynamic queries based upon an object's state, mapping of complex joins to complex object graphs, etc.). iBATIS simply maps JavaBeans to SQL statements using a very simple XML descriptor. &lt;br /&gt;
Simplicity is the key advantage of iBATIS over other frameworks and object relational mapping tools.&lt;br /&gt;
&lt;br /&gt;
=== Merb ===&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
Merb, short for &amp;quot;Mongrel+Erb&amp;quot;, is a model-view-controller web framework written in Ruby. Merb adopts an approach that focuses on essential core functionality, leaving most functionality to plugins. Merb is merged into Rails web framework since December 23, 2008.Merb were merged with Rails as part of the Ruby on Rails 3.0 release.&amp;lt;sup&amp;gt;[10]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
The Merb project was started as a &amp;quot;clean-room&amp;quot; implementation of the Ruby on Rails controller stack, but has grown to incorporate a number of ideas which deviated from Rails's spirit and methodology, most notably, component modularity, extensible API design, and vertical scalability. Most of these capabilities have since been incorporated back into Rails during the Rails/Merb merger announced on December 23, 2008.&lt;br /&gt;
Like Rails, Merb can also be used to write sophisticated applications and RESTful Web services. It has been suggested that Merb is more flexible and faster than Rails.&lt;br /&gt;
&lt;br /&gt;
=== Sequel ===&lt;br /&gt;
&lt;br /&gt;
Sequel includes a comprehensive ORM layer for mapping records to Ruby objects and handling associated records.&lt;br /&gt;
Sequel provides thread safety, connection pooling and a concise DSL for constructing SQL queries and table schemas.It supports advanced database features such as prepared statements, bound variables, stored procedures, savepoints, two-phase commit, transaction isolation, master/slave configurations, and database sharding.Currently it has adapters for ADO, Amalgalite, DataObjects, DB2, DBI, Firebird, Informix, JDBC, MySQL, Mysql2, ODBC, OpenBase, Oracle, PostgreSQL, SQLite3, and Swift.&amp;lt;sup&amp;gt;[7]&amp;lt;/sup&amp;gt; &amp;lt;br/&amp;gt;&amp;lt;br/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
==== Sequel Example ====&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
require &amp;quot;rubygems&amp;quot;&lt;br /&gt;
require &amp;quot;sequel&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# connect to an in-memory database&lt;br /&gt;
DB = Sequel.sqlite&lt;br /&gt;
&lt;br /&gt;
# create an items table&lt;br /&gt;
DB.create_table :items do&lt;br /&gt;
  primary_key :id&lt;br /&gt;
  String :name&lt;br /&gt;
  Float :price&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
# create a dataset from the items table&lt;br /&gt;
items = DB[:items]&lt;br /&gt;
&lt;br /&gt;
# populate the table&lt;br /&gt;
items.insert(:name =&amp;gt; 'abc', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'def', :price =&amp;gt; rand * 100)&lt;br /&gt;
items.insert(:name =&amp;gt; 'ghi', :price =&amp;gt; rand * 100)&lt;br /&gt;
&lt;br /&gt;
# print out the number of records&lt;br /&gt;
puts &amp;quot;Item count: #{items.count}&amp;quot;&lt;br /&gt;
&lt;br /&gt;
# print out the average price&lt;br /&gt;
puts &amp;quot;The average price is: #{items.avg(:price)}&amp;quot;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
= References =&lt;br /&gt;
&lt;br /&gt;
*[1]Russ Olsen, Book on Design Patterns in Ruby &lt;br /&gt;
*[2]Chris Richardson, &amp;quot;ORM in dynamic languages&amp;quot;, http://portal.acm.org/citation.cfm?id=1498765.1498783&lt;br /&gt;
*[3]Dr Bruce Scharlau, Paper-Teaching Ruby on Rails&lt;br /&gt;
*[4]http://en.wikipedia.org/wiki/Object-relational_mapping&lt;br /&gt;
*[5]http://en.wikipedia.org/wiki/ActiveRecord_(Rails)#Implementations&lt;br /&gt;
*[6]http://en.wikipedia.org/wiki/Datamapper&lt;br /&gt;
*[7]http://sequel.rubyforge.org/&lt;br /&gt;
*[8]http://ibatis.apache.org/docs/ruby/&lt;br /&gt;
*[9]http://en.wikipedia.org/wiki/IBATIS&lt;br /&gt;
*[10]http://en.wikipedia.org/wiki/Merb&lt;br /&gt;
*[11]http://ar.rubyonrails.org/&lt;br /&gt;
*[12]http://datamapper.org/&lt;/div&gt;</summary>
		<author><name>Csgodbol</name></author>
	</entry>
</feed>