<?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=Narumug4</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=Narumug4"/>
	<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=Special:Contributions/Narumug4"/>
	<updated>2026-08-08T22:39:50Z</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_2012/ch2a_2w25_nr&amp;diff=68936</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68936"/>
		<updated>2012-10-27T02:54:08Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* DisadvantagesAdvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with?'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages'''==&lt;br /&gt;
The advantages of following Law of Demeter are&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&amp;lt;br&amp;gt; Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;.&lt;br /&gt;
&lt;br /&gt;
=='''Example==&lt;br /&gt;
==='''Java'''===&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
====Customer====&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Wallet====&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
====Paperboy====&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
====Code improvement , better design using Law of Demeter====&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
====The New Customer====&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====The New Wallet====&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
====The New Paperboy====&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
====Reasons that led to better design and code====&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==='''Ruby'''===&lt;br /&gt;
While developing software, Law of Demeter are violated often especially in Ruby on Rails which allows to easily navigate between objects based on table relationships. &lt;br /&gt;
&lt;br /&gt;
For example, if you are working on a partial that displays a charge from a credit card statement it wouldn't be surprising to see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.statement.customer.name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code could be used to display the customer's name in the partial. Unfortunately, it assumes statement will have a customer and customer will have a name. This is easily fixed by changing charge to only talk to it's friends.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.customer_name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The simple fix to support this is to define customer_name in charge, and customer_name in statement&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 def customer_name&lt;br /&gt;
   statement.customer_name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 def customer_name&lt;br /&gt;
   customer.name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This change is simple enough. However, as the list of methods that require delegation grows your class can become littered with delegation code.&lt;br /&gt;
&lt;br /&gt;
Fortunately Forwardable is included in the standard library of Ruby. Forwardable allows you delegate method calls to an object, on a method by method basis. &lt;br /&gt;
&lt;br /&gt;
Using Forwardable the above code becomes:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegators :statement, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegator :customer, :name, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Forwardable becomes even more valuable when you need to delegate several methods def_delegators :amount_info, :units, :fractions, :currency.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68933</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68933"/>
		<updated>2012-10-27T02:53:23Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* AdvantagesAdvantages */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with?'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages'''==&lt;br /&gt;
The advantages of following Law of Demeter are&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&amp;lt;br&amp;gt; Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example==&lt;br /&gt;
==='''Java'''===&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
====Customer====&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Wallet====&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
====Paperboy====&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
====Code improvement , better design using Law of Demeter====&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
====The New Customer====&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====The New Wallet====&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
====The New Paperboy====&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
====Reasons that led to better design and code====&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==='''Ruby'''===&lt;br /&gt;
While developing software, Law of Demeter are violated often especially in Ruby on Rails which allows to easily navigate between objects based on table relationships. &lt;br /&gt;
&lt;br /&gt;
For example, if you are working on a partial that displays a charge from a credit card statement it wouldn't be surprising to see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.statement.customer.name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code could be used to display the customer's name in the partial. Unfortunately, it assumes statement will have a customer and customer will have a name. This is easily fixed by changing charge to only talk to it's friends.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.customer_name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The simple fix to support this is to define customer_name in charge, and customer_name in statement&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 def customer_name&lt;br /&gt;
   statement.customer_name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 def customer_name&lt;br /&gt;
   customer.name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This change is simple enough. However, as the list of methods that require delegation grows your class can become littered with delegation code.&lt;br /&gt;
&lt;br /&gt;
Fortunately Forwardable is included in the standard library of Ruby. Forwardable allows you delegate method calls to an object, on a method by method basis. &lt;br /&gt;
&lt;br /&gt;
Using Forwardable the above code becomes:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegators :statement, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegator :customer, :name, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Forwardable becomes even more valuable when you need to delegate several methods def_delegators :amount_info, :units, :fractions, :currency.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68931</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68931"/>
		<updated>2012-10-27T02:52:06Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Who can class A interact with ?Who can class interact with */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with?'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example==&lt;br /&gt;
==='''Java'''===&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
====Customer====&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Wallet====&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
====Paperboy====&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
====Code improvement , better design using Law of Demeter====&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
====The New Customer====&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====The New Wallet====&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
====The New Paperboy====&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
====Reasons that led to better design and code====&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==='''Ruby'''===&lt;br /&gt;
While developing software, Law of Demeter are violated often especially in Ruby on Rails which allows to easily navigate between objects based on table relationships. &lt;br /&gt;
&lt;br /&gt;
For example, if you are working on a partial that displays a charge from a credit card statement it wouldn't be surprising to see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.statement.customer.name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code could be used to display the customer's name in the partial. Unfortunately, it assumes statement will have a customer and customer will have a name. This is easily fixed by changing charge to only talk to it's friends.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.customer_name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The simple fix to support this is to define customer_name in charge, and customer_name in statement&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 def customer_name&lt;br /&gt;
   statement.customer_name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 def customer_name&lt;br /&gt;
   customer.name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This change is simple enough. However, as the list of methods that require delegation grows your class can become littered with delegation code.&lt;br /&gt;
&lt;br /&gt;
Fortunately Forwardable is included in the standard library of Ruby. Forwardable allows you delegate method calls to an object, on a method by method basis. &lt;br /&gt;
&lt;br /&gt;
Using Forwardable the above code becomes:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegators :statement, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegator :customer, :name, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Forwardable becomes even more valuable when you need to delegate several methods def_delegators :amount_info, :units, :fractions, :currency.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68924</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68924"/>
		<updated>2012-10-27T02:48:11Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Ruby */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example==&lt;br /&gt;
==='''Java'''===&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
====Customer====&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Wallet====&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
====Paperboy====&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
====Code improvement , better design using Law of Demeter====&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
====The New Customer====&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====The New Wallet====&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
====The New Paperboy====&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
====Reasons that led to better design and code====&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==='''Ruby'''===&lt;br /&gt;
While developing software, Law of Demeter are violated often especially in Ruby on Rails which allows to easily navigate between objects based on table relationships. &lt;br /&gt;
&lt;br /&gt;
For example, if you are working on a partial that displays a charge from a credit card statement it wouldn't be surprising to see:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.statement.customer.name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The above code could be used to display the customer's name in the partial. Unfortunately, it assumes statement will have a customer and customer will have a name. This is easily fixed by changing charge to only talk to it's friends.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
charge.customer_name&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
The simple fix to support this is to define customer_name in charge, and customer_name in statement&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 def customer_name&lt;br /&gt;
   statement.customer_name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 def customer_name&lt;br /&gt;
   customer.name&lt;br /&gt;
 end&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
This change is simple enough. However, as the list of methods that require delegation grows your class can become littered with delegation code.&lt;br /&gt;
&lt;br /&gt;
Fortunately Forwardable is included in the standard library of Ruby. Forwardable allows you delegate method calls to an object, on a method by method basis. &lt;br /&gt;
&lt;br /&gt;
Using Forwardable the above code becomes:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Charge&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegators :statement, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&lt;br /&gt;
class Statement&lt;br /&gt;
 extend Forwardable&lt;br /&gt;
 def_delegator :customer, :name, :customer_name&lt;br /&gt;
end&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Forwardable becomes even more valuable when you need to delegate several methods def_delegators :amount_info, :units, :fractions, :currency.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68919</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68919"/>
		<updated>2012-10-27T02:44:56Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Example */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example==&lt;br /&gt;
==='''Java'''===&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
====Customer====&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====Wallet====&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
====Paperboy====&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
====Code improvement , better design using Law of Demeter====&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
====The New Customer====&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
====The New Wallet====&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
====The New Paperboy====&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
====Reasons that led to better design and code====&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==='''Ruby'''===&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68916</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68916"/>
		<updated>2012-10-27T02:37:57Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* When and How to identify Law of Demeter */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
From the above sections we have a good understanding of the law and its benefits, but we haven't yet discussed on how to identify places in existing code where we can apply it and just as important, where not to apply it. The following are the places where we can apply the Law of Demeter&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
The below statement clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
value = object.getName().getCountry().getZip()&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
More number of dots is also an indicator of the violation of law.&lt;br /&gt;
&lt;br /&gt;
===Lots of 'temporary' objects===&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
name = object.getName();&lt;br /&gt;
country = name.getCountry();&lt;br /&gt;
zip = country.getZip();&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
This is equivalent to chained get statement, but broken down into multiple statement, this is little more harder to detect that previous case, but this also clearly violates the law&lt;br /&gt;
&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In Java, there is a rule which states that we only import classes that are actually used. These practises are never followed and we always see something like below in our source code.&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
import java.lang.*&lt;br /&gt;
import java.io.*;&lt;br /&gt;
import java.util.*;&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
With this rule in place, it is not uncommon to see a dozen or so import statements all coming from the same package. If this is happening in our code, it could be a good place to look for obscured examples of violations. If we need to import it, we are coupled to it. If it changes, we may have to change as well. By explicitly importing the classes, we will begin to experience how coupled the classes really are.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example'''==&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
===Customer===&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Wallet===&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
===Paperboy===&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
===Code improvement , better design using Law of Demeter===&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
===The New Customer===&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===The New Wallet===&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
===The New Paperboy===&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
===Reasons that led to better design and code===&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68898</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68898"/>
		<updated>2012-10-27T02:29:38Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
value = object.getName().getCountry().getZip() &amp;lt;br&amp;gt;&lt;br /&gt;
This clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In java we tend to include a lot of libraries, this is also an indication of law violation.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Disadvantages&amp;lt;ref name=&amp;quot;Disadvantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
In order not to expose the internals of the calling class, many layers of wrapper needs to be added. This introduces overhead in maintaining the wrapper and might introduce significant delay since control has to follow all the wrappers.&lt;br /&gt;
&lt;br /&gt;
=='''Example'''==&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
===Customer===&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Wallet===&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
===Paperboy===&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
===Code improvement , better design using Law of Demeter===&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
===The New Customer===&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===The New Wallet===&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
===The New Paperboy===&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
===Reasons that led to better design and code===&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68683</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68683"/>
		<updated>2012-10-27T00:57:14Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
value = object.getName().getCountry().getZip() &amp;lt;br&amp;gt;&lt;br /&gt;
This clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In java we tend to include a lot of libraries, this is also an indication of law violation.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
=='''Example'''==&lt;br /&gt;
Law of Demeter is a technique for reducing the 'coupling' between objects in the code. Here is an example based on Java that illustrates the Law of Demeter.&lt;br /&gt;
&amp;lt;br&amp;gt;&amp;lt;br&amp;gt;&lt;br /&gt;
A ‘Paperboy’ has to get a payment from a ‘Customer’. There has to be a mechanism used by the paperboy for receiving payments from that customer. Lets assume that the paperboy will run a snippet in order to achieve the above. The definition of each Java class for this example is as follows.&lt;br /&gt;
&lt;br /&gt;
===Customer===&lt;br /&gt;
The Customer class can have a first name, a last name, an account number, a shipping address, some method of payment, etc. In this example lets define the customer with just enough functionality to make our illustration of Law of Demeter to work.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
    }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public Wallet getWallet(){&lt;br /&gt;
        return myWallet;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Wallet===&lt;br /&gt;
Each customer is associated with a wallet by which the payment is made. A wallet can have total money, credits cards, drivers license, different types of currency, etc. For this example we design a pretty simplistic wallet.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Wallet {&lt;br /&gt;
    private float value;&lt;br /&gt;
    public float getTotalMoney() {&lt;br /&gt;
        return value;&lt;br /&gt;
    }&lt;br /&gt;
    public void setTotalMoney(float newValue) {&lt;br /&gt;
        value = newValue;&lt;br /&gt;
    }&lt;br /&gt;
    public void addMoney(float deposit) {&lt;br /&gt;
        value += deposit;&lt;br /&gt;
    }&lt;br /&gt;
    public void subtractMoney(float debit) {&lt;br /&gt;
        value -= debit;&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Now that we have all required information about the customer and his wallet. Lets turn our focus on to the paperboy.&lt;br /&gt;
&lt;br /&gt;
===Paperboy===&lt;br /&gt;
In this paperboy class we focus more on the method by which payment is made. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : getPayment() ) which achieves this objective. The typical getPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
Paying the Paperboy - getPayment()&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void getPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
    Wallet theWallet = myCustomer.getWallet(); // Wallet of the corresponding customer who has to pay&lt;br /&gt;
    if (theWallet.getTotalMoney() &amp;gt; payment) {&lt;br /&gt;
        theWallet.subtractMoney(payment);&lt;br /&gt;
    } else {&lt;br /&gt;
        // Other code&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This code snippet gets the wallet from the customer, checks to make sure if the customer has the money and transfers it from the customers wallet into the paperboy's wallet.&lt;br /&gt;
&lt;br /&gt;
Lets analyse what is bad about this code. We can actually translate what the code is actually doing into real-language.  Apparently, when the paperboy stops by and demands payment, the customer is just going to turn around, let the paperboy take the wallet out of his back pocket, and take out two bucks. This is not the typical how some will handle their wallet.&lt;br /&gt;
&lt;br /&gt;
There are a number of 'real-world' problems with this, not to mention we are trusting the paperboy to be honest and just take out what he's owed.  If our future Wallet object holds credit cards, the paperboy has access to those too. The basic problem is that “the paperboy is being exposed to more information than he needs to be”.&lt;br /&gt;
&lt;br /&gt;
The most important concept is the 'Paperboy' class now 'knows' that the customer has a wallet and can manipulate it.  When we compile the Paperboy class, it will need  the Customer class and the Wallet class.  These three classes (Customer, Wallet and Paperboy) are now 'tightly coupled'.  If we change the Wallet class, we may have to make changes to both of the other classes.&lt;br /&gt;
&lt;br /&gt;
There is another classic problem that this can create. The customer wallet can be stolen or lost. In this case we can set the Wallet to null like&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
victim.setWallet(null);&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This seems a reasonable assumption. This code enforces any mandatory value for wallet and there is a certain 'elegance' about using null for this condition but  this never handles the paperboy. The code assumes there will be a wallet so the paperboy will get a runtime exception for calling a method on a null pointer. We could fix this by checking for 'null' on the wallet before we call any methods on it, but this starts to clutter the paperboy's class.  The real-language description is becoming even worse as more and more complex arises. This makes the design and code more convoluted.&lt;br /&gt;
&lt;br /&gt;
===Code improvement , better design using Law of Demeter===&lt;br /&gt;
The example illustrated can be made much better by incorporating proper design and improving the code structures.   The proper way to fix the issue to move along the  'real world' scenario. &lt;br /&gt;
When the paperboy needs payment, he would approach the customer but he is not going to handle the customer wallet. In fact he won't even know whether the customer has a wallet or not even if he does, he can’t be sure that the customer is willing to pay him.&lt;br /&gt;
&lt;br /&gt;
===The New Customer===&lt;br /&gt;
The New customer has design changes such that he no longer has a 'getWallet()' method but it does have a getPayment method. The new customer class is as shown below&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Customer {&lt;br /&gt;
    private String firstName;&lt;br /&gt;
    private String lastName;&lt;br /&gt;
    private Wallet myWallet;&lt;br /&gt;
    public String getFirstName(){&lt;br /&gt;
        return firstName;&lt;br /&gt;
  }&lt;br /&gt;
    public String getLastName(){&lt;br /&gt;
        return lastName;&lt;br /&gt;
    }&lt;br /&gt;
    public float getPayment(float bill) {&lt;br /&gt;
        if (myWallet != null) {&lt;br /&gt;
            if (myWallet.getTotalMoney() &amp;gt; bill) {&lt;br /&gt;
                theWallet.subtractMoney(payment);&lt;br /&gt;
                return payment;&lt;br /&gt;
            }&lt;br /&gt;
        }&lt;br /&gt;
    }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===The New Wallet===&lt;br /&gt;
There won’t be any changes in design or the code of the Wallet as it performs the required function without any hassle in this example.&lt;br /&gt;
&lt;br /&gt;
===The New Paperboy===&lt;br /&gt;
In this new paperboy class we have a method for getting the payment but this done by customer and not the right of the paperboy as per the previous design. In order to get the payment from the customer the paperboy executes a code snippet. The code snippet is some method in the Paperboy class (eg : requestPayment() ) which achieves this objective. The typical requestPayment method for this illustration is as follows&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
void RequestPayment(Customer myCustomer) {&lt;br /&gt;
   payment = 2.00;  // Payment amount&lt;br /&gt;
   paidAmount = myCustomer.getPayment(payment);&lt;br /&gt;
   if (paidAmount == payment) {&lt;br /&gt;
        // Give customer a receipt&lt;br /&gt;
    } else { &lt;br /&gt;
        // Other code&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
This had made the code and design much better. &lt;br /&gt;
&lt;br /&gt;
===Reasons that led to better design and code===&lt;br /&gt;
&lt;br /&gt;
The first reason that this is better is because it better models the real world scenario. The Paperboy code is now 'asking' the customer for a payment. The paperboy does not have direct access to the wallet. &lt;br /&gt;
&lt;br /&gt;
The second reason that this is better is because the Wallet class can now change and the paperboy is completely isolated from that change.  If the interface to Wallet were to change, the Customer would have to be updated, but that's it. As long as the interface to Customer stays the same, none of the client's of Customer will care that he got a new Wallet.  Code will be more maintainable, because changes will not 'ripple' through a large project.&lt;br /&gt;
&lt;br /&gt;
The third and probably most 'object-oriented' answer is that it is now free to change the&lt;br /&gt;
implementation of 'getPayment()'.  In the old example, the assumption was that the Customer would have a wallet.  This led to the null pointer exception.  In the real world though, when the paper boy comes, the customer may actually get the two bucks from a jar of change, search between the cushions of his couch or borrow it from his roommate, whatever.  All of this is 'Business Logic',and is of no concern to the paper boy. All this could be implemented inside of the getPayment() method, and could change in the future, without any modification to the paper boy code.&lt;br /&gt;
&lt;br /&gt;
Those these above discussion have led to lots of advantages we need to accept the fact that it has made the customer a more complex object.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68492</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68492"/>
		<updated>2012-10-26T23:55:03Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low [http://en.wikipedia.org/wiki/Coupling_(computer_programming) coupling] principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
value = object.getName().getCountry().getZip() &amp;lt;br&amp;gt;&lt;br /&gt;
This clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In java we tend to include a lot of libraries, this is also an indication of law violation.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68489</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68489"/>
		<updated>2012-10-26T23:53:56Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low coupling principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?&amp;lt;ref name=&amp;quot;&amp;quot;&amp;gt;[http://aspiringcraftsman.com/tag/law-of-demeter Who can class interact with]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
value = object.getName().getCountry().getZip() &amp;lt;br&amp;gt;&lt;br /&gt;
This clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In java we tend to include a lot of libraries, this is also an indication of law violation.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages&amp;lt;ref name=&amp;quot;Advantages&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Law_of_Demeter Advantages]&amp;lt;/ref&amp;gt;'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD) Law of Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/papers/icse-04-keynote/ICSE2004.pdf Controlling the Complexity of Software Designs]&lt;br /&gt;
#[http://www.ccs.neu.edu/home/lieber/LoD/law_of_demeter_healthy_code-external.pdf Loose Coupling with Demeter]&lt;br /&gt;
#[http://www.ccs.neu.edu/research/demeter/demeter-method/LawOfDemeter/paper-boy/demeter.pdf The Paperboy, The Wallet,and The Law Of Demeter]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68446</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68446"/>
		<updated>2012-10-26T23:38:16Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
[http://en.wikipedia.org/wiki/Law_of_Demeter Law of demeter(LoD)] states &amp;quot;Only talk to your friends&amp;quot;, which means do not talk to friend's friend. By doing this, we don't get to know the internals of our friend. In software terms, a class A should only talk to or invoke methods on closely related classes, class B and should not try to poke around the internals of B to reach a new class C. We have two options in order to achieve this, either class A can directly invoke methods on class C or the interface of class B should be changed to accomodate this call from A, then A will invoke methods on B and B will take care of invoking methods on C internally that would satisfy A's request.&lt;br /&gt;
&lt;br /&gt;
In a way, law of demeter can be thought of a more specialized version of low coupling principle. Object oriented design recommends low coupling for better design and maintainability of software systems. The more loosely the classes are coupled, they become more easily testable. Classes need to directly interact with its collaborators and be shielded from understanding their internal structure. Using the internal knowledge of classes introduces risk of breaking functionality, instead they should talk to well known public interfaces. By doing all this we try to create a more shallow relationship than deeper relationship, which reduces the number of classes which may be affected by changes within the system.&lt;br /&gt;
&lt;br /&gt;
=='''Who can class A interact with ?'''==&lt;br /&gt;
If M is a method belonging to class A, then M may invoke other methods belonging to the following:&lt;br /&gt;
&amp;lt;br&amp;gt; 1. Class A&lt;br /&gt;
&amp;lt;br&amp;gt; 2. Members of A&lt;br /&gt;
&amp;lt;br&amp;gt; 3. Parameters of A&lt;br /&gt;
&amp;lt;br&amp;gt; 4. Objects created by M&lt;br /&gt;
&amp;lt;br&amp;gt; 5. Objects created by other methods of class A called by M&lt;br /&gt;
&amp;lt;br&amp;gt; 6. Globally accessible objects&lt;br /&gt;
&lt;br /&gt;
=='''When and How to identify Law of Demeter'''==&lt;br /&gt;
===Chained 'get' statements===&lt;br /&gt;
value = object.getName().getCountry().getZip() &amp;lt;br&amp;gt;&lt;br /&gt;
This clearly denotes we are violating the law of demeter since we our access crosses the boundary.&lt;br /&gt;
===Importing or including many classes===&lt;br /&gt;
In java we tend to include a lot of libraries, this is also an indication of law violation.&lt;br /&gt;
&lt;br /&gt;
=='''Advantages'''==&lt;br /&gt;
Reusable code&lt;br /&gt;
&amp;lt;br&amp;gt; Better design&lt;br /&gt;
&amp;lt;br&amp;gt; Less risk of breaking functionality&lt;br /&gt;
&amp;lt;br&amp;gt; Modular code&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=68304</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=68304"/>
		<updated>2012-10-26T21:42:42Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w1 rk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w20 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w5 su]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w6 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w4 aj]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w7 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w8 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w9 av]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w10 pk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w11 ap]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w12 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w14 gv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w17 ir]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w22 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 wi]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w31 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w16 br]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1a 1w23 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w24 nr]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w15 rt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w3 pl]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w32 cm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w37 ss]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w67 ks]]&lt;br /&gt;
&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w27 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w29 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w33 op]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w19 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w34 vd]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w35 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w30 rp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w58 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w47 sk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w69 mv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w44 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w45 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w53 kc]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 ar]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w39 sn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w54 go]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w56 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w64 nn]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w66 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w40 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w42 js]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w46 sm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w71 gs]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w63 dv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w55 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w57 mp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w52 an]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch1b 1w38 nm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w60 ac]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1b 1w62 rb]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w29 st]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w30 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w17 pt]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w31 up]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w9 ms]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w19 is]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w26 aj]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w5 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w16 dp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w8 vp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w3 jm]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w23 sr]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w11_aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w15 rr]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch2a 2w33 pv]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w20_aa]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w14_bb]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w21_ap]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w13_sm]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w4_sa]]&lt;br /&gt;
*[[CSC/ECE_517_Fall_2012/ch2a_2w25_nr]]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68302</id>
		<title>CSC/ECE 517 Fall 2012/ch2a 2w25 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch2a_2w25_nr&amp;diff=68302"/>
		<updated>2012-10-26T21:41:55Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: Created page with &amp;quot;'''Law of Demeter'''  =='''Introduction'''==&amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Law of Demeter'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65399</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65399"/>
		<updated>2012-09-21T01:58:55Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Inheritance is white box */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag#Diamond_Problem_in_Detail Diamond Problem]. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is &amp;lt;ref name=&amp;quot;whiteboxwiki&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/White-box_testing white box]&amp;lt;/ref&amp;gt; and not &amp;lt;ref name=&amp;quot;blackboxwiki&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Black-box_testing black box]&amp;lt;/ref&amp;gt;, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Liskov_substitution_principle Liskov substitution principle]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Composition_over_inheritance Composition over Inheritance]&lt;br /&gt;
#[http://www.codeproject.com/Articles/80045/Composition-VS-Inheritance Deciding between Composition vs Inheritance]&lt;br /&gt;
#[http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance Composition vs Inheritance]&lt;br /&gt;
#[http://eflorenzano.com/blog/2008/05/04/inheritance-vs-composition/ Composition over Inheritance]&lt;br /&gt;
#[http://www.jguru.com/faq/view.jsp?EID=27916 Delegation instead of Inheritance]&lt;br /&gt;
#[http://timsbrownbaglunch.blogspot.com/2009/12/design-review-and-delegation-vs.html Delegation vs Inheritance]&lt;br /&gt;
#[http://www.wordiq.com/definition/Delegation_(programming) Delegation]&lt;br /&gt;
#[http://www.ics.uci.edu/~taylor/classes/121/BoochOOD003.pdf Object Oriented Development]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=179804 Decomposition/generalization methodology for object-oriented programming]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=339990 Two object oriented decomposition methods]&lt;br /&gt;
#[http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 Design Patterns]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65398</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65398"/>
		<updated>2012-09-21T01:58:16Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Inheritance is white box */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag#Diamond_Problem_in_Detail Diamond Problem]. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box&amp;lt;ref name=&amp;quot;whiteboxwiki&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/White-box_testing]&amp;lt;/ref&amp;gt; and not black box&amp;lt;ref name=&amp;quot;blackboxwiki&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Black-box_testing]&amp;lt;/ref&amp;gt;, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Liskov_substitution_principle Liskov substitution principle]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Composition_over_inheritance Composition over Inheritance]&lt;br /&gt;
#[http://www.codeproject.com/Articles/80045/Composition-VS-Inheritance Deciding between Composition vs Inheritance]&lt;br /&gt;
#[http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance Composition vs Inheritance]&lt;br /&gt;
#[http://eflorenzano.com/blog/2008/05/04/inheritance-vs-composition/ Composition over Inheritance]&lt;br /&gt;
#[http://www.jguru.com/faq/view.jsp?EID=27916 Delegation instead of Inheritance]&lt;br /&gt;
#[http://timsbrownbaglunch.blogspot.com/2009/12/design-review-and-delegation-vs.html Delegation vs Inheritance]&lt;br /&gt;
#[http://www.wordiq.com/definition/Delegation_(programming) Delegation]&lt;br /&gt;
#[http://www.ics.uci.edu/~taylor/classes/121/BoochOOD003.pdf Object Oriented Development]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=179804 Decomposition/generalization methodology for object-oriented programming]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=339990 Two object oriented decomposition methods]&lt;br /&gt;
#[http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 Design Patterns]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65397</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65397"/>
		<updated>2012-09-21T01:55:24Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag#Diamond_Problem_in_Detail Diamond Problem]. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Liskov_substitution_principle Liskov substitution principle]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Composition_over_inheritance Composition over Inheritance]&lt;br /&gt;
#[http://www.codeproject.com/Articles/80045/Composition-VS-Inheritance Deciding between Composition vs Inheritance]&lt;br /&gt;
#[http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance Composition vs Inheritance]&lt;br /&gt;
#[http://eflorenzano.com/blog/2008/05/04/inheritance-vs-composition/ Composition over Inheritance]&lt;br /&gt;
#[http://www.jguru.com/faq/view.jsp?EID=27916 Delegation instead of Inheritance]&lt;br /&gt;
#[http://timsbrownbaglunch.blogspot.com/2009/12/design-review-and-delegation-vs.html Delegation vs Inheritance]&lt;br /&gt;
#[http://www.wordiq.com/definition/Delegation_(programming) Delegation]&lt;br /&gt;
#[http://www.ics.uci.edu/~taylor/classes/121/BoochOOD003.pdf Object Oriented Development]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=179804 Decomposition/generalization methodology for object-oriented programming]&lt;br /&gt;
#[http://dl.acm.org/citation.cfm?id=339990 Two object oriented decomposition methods]&lt;br /&gt;
#[http://www.amazon.com/Design-Patterns-Elements-Reusable-Object-Oriented/dp/0201633612 Design Patterns]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65396</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=65396"/>
		<updated>2012-09-21T01:51:26Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag#Diamond_Problem_in_Detail Diamond Problem]. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==External Links==&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Liskov_substitution_principle Liskov substitution principle]&lt;br /&gt;
#[http://en.wikipedia.org/wiki/Composition_over_inheritance Composition over Inheritance]&lt;br /&gt;
#[http://www.codeproject.com/Articles/80045/Composition-VS-Inheritance Deciding between Composition vs Inheritance]&lt;br /&gt;
#[http://lostechies.com/chadmyers/2010/02/13/composition-versus-inheritance Composition vs Inheritance]&lt;br /&gt;
#[http://eflorenzano.com/blog/2008/05/04/inheritance-vs-composition/ Composition over Inheritance]&lt;br /&gt;
#[http://www.jguru.com/faq/view.jsp?EID=27916 Delegation instead of Inheritance]&lt;br /&gt;
#[http://timsbrownbaglunch.blogspot.com/2009/12/design-review-and-delegation-vs.html Delegation vs Inheritance]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64673</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64673"/>
		<updated>2012-09-14T23:03:39Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Problem 1: Multiple Inheritance introduces lot more confusionDiamond Problem */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag#Diamond_Problem_in_Detail Diamond Problem]. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64668</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64668"/>
		<updated>2012-09-14T23:02:47Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Delegation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch6_6a_PC Delegation] is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64665</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64665"/>
		<updated>2012-09-14T23:02:15Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Composition */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object [http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch3_S30_SK#Decomposition composition] is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64664</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=64664"/>
		<updated>2012-09-14T23:01:27Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Introduction */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
[http://expertiza.csc.ncsu.edu/wiki/index.php/CSC/ECE_517_Fall_2010/ch1_25_ag Inheritance] plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object composition is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63823</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63823"/>
		<updated>2012-09-13T01:09:42Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object composition is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
[[File:inheritance_uml.png]]&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
[[File:compAgg_uml.png]]&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63822</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63822"/>
		<updated>2012-09-13T01:06:19Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: /* Aggregation */&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object composition is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|right|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63821</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63821"/>
		<updated>2012-09-13T01:05:57Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object composition is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/ref&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/pre&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|right|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63820</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63820"/>
		<updated>2012-09-13T01:05:06Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance in some cases to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall explain and compare these techniques with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and that will inherit its parent’s attributes and behavior &amp;lt;ref name=&amp;quot;inheritance&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(computer_science) Inheritance]&amp;lt;/ref&amp;gt;. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    ...&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    ...&lt;br /&gt;
    //new method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and methods defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
In some cases object composition is an alternative to class inheritance to achieve code re-usability. Here, new complex functionality is achieved by assembling or composing objects &amp;lt;ref name=&amp;quot;objectcomposition&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Object_composition Object Composition]&amp;lt;/ref&amp;gt;. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large container &amp;lt;ref name=&amp;quot;Design Principles&amp;quot;&amp;gt;[http://www.artima.com/lejava/articles/designprinciples4.html Design Principles]&amp;lt;/ref&amp;gt;. Complex functionality is achieved in this larger container by placing smaller closed containers inside it. Every smaller object has its own independent implementation hidden from the outer container. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/pre&amp;gt;. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   protected Seat seat;&lt;br /&gt;
   protected Backrest backrest;&lt;br /&gt;
   protected Leg leg;&lt;br /&gt;
  &lt;br /&gt;
   Chair() {&lt;br /&gt;
      Seat s = new Seat();&lt;br /&gt;
      Backrest b = new Backrest();&lt;br /&gt;
      Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
   }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another concept related to object composition is that of Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair &amp;lt;ref name=&amp;quot;compositionaggregation&amp;quot;&amp;gt;[http://www.adobe.com/devnet/actionscript/learning/oop-concepts/composition-and-aggregation.html Composition and Aggregation]&amp;lt;/pre&amp;gt;. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat, backrest and legs do not have any existence without the chair. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. Delegation involved two objects: a delegator who delegates a operation to another object, the delegatee. This can be compared to inheritance where a subclass &amp;quot;defers&amp;quot; request to the parent class for a method which is not overridden in the subclass &amp;lt;ref name=&amp;quot;Delegation&amp;quot;&amp;gt;[http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf Design Patterns]&amp;lt;/ref&amp;gt;. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time, whereas inheritance causes the relationship to be established statically at compile-time. Although, overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases&amp;lt;ref name=&amp;quot;Limitations&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives Limitations and Alternatives]&amp;lt;/ref&amp;gt;:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion&amp;lt;ref name=&amp;quot;confusions&amp;quot;&amp;gt;[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem Diamond Problem]&amp;lt;/ref&amp;gt;===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|right|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem &amp;lt;ref name=&amp;quot;whitebox&amp;quot;&amp;gt;[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html Inheritance breaks Encapsulation]&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.&amp;lt;ref name=&amp;quot;compositionoverinheritance&amp;quot;&amp;gt;[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance Composition over Inheritance]&amp;lt;/ref&amp;gt;&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;br /&gt;
&lt;br /&gt;
&lt;br /&gt;
=='''UML Representation'''==&lt;br /&gt;
The Unified Modeling Language standard specifies graphical notations for object oriented models. Inheritance is represented using a solid line with a closed, unfilled triangle pointing from the child class to the parent class. For example, following UML represents the inheritance relationship when Dog class subclasses from Pets class.&lt;br /&gt;
&lt;br /&gt;
Composition relationship is represented in UML using a solid line from the parent class to the part class with an unfilled diamond shape on the parent class end. Aggregation has a similar notation with the only difference being that the diamond shape is filled.&lt;br /&gt;
&lt;br /&gt;
==References==&lt;br /&gt;
&amp;lt;references/&amp;gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=63647</id>
		<title>CSC/ECE 517 Fall 2012</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012&amp;diff=63647"/>
		<updated>2012-09-12T02:13:32Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;*[[CSC/ECE 517 Fall 2012/ch1 n xx]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w1 rk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w20 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w5 su]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w6 pp]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w7 am]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w8 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w10 pk]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w14 gv]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w17 ir]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w18 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w22 an]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 aa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w21 wi]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w31 sa]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w16 br]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w23 as]]&lt;br /&gt;
*[[CSC/ECE 517 Fall 2012/ch1 1w24 nr]]&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63645</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63645"/>
		<updated>2012-09-12T02:08:52Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall look at these concepts one at a time and make the differences clear with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and this subclass will inherit its parent’s attributes and behavior. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and method defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
Object composition is an alternative to class inheritance to achieve code reusability. Here, new complex functionality is achieved by assembling or composing objects [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large box. Complex functionality is achieved in this larger box by placing smaller closed boxes inside this larger box. Every smaller box has its own independent implementation hidden from the outer box. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   Seat s = new Seat();&lt;br /&gt;
   Backrest b = new Backrest();&lt;br /&gt;
   Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another related concept is that if Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat. Backrest and legs do not have an existence without the chair. So, the person object is initialized outside the chair class and can be used inside it with its interface. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Delegation involved two objects: a delegator who delegates a operation to another object, the delgatee. This can be compared to inheritance where a subclass defers request to the parent class. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time as against Inheritance which causes the relationship to be established statically at compile-time. Although overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives]:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusion[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem]===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
[[File:DiamondProblem.png|right|Diamond Problem with Inheritance example.]]&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html]&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance]&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:DiamondProblem.png&amp;diff=63644</id>
		<title>File:DiamondProblem.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:DiamondProblem.png&amp;diff=63644"/>
		<updated>2012-09-12T02:08:36Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: uploaded a new version of &amp;amp;quot;File:DiamondProblem.png&amp;amp;quot;&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=File:DiamondProblem.png&amp;diff=63638</id>
		<title>File:DiamondProblem.png</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=File:DiamondProblem.png&amp;diff=63638"/>
		<updated>2012-09-12T01:52:55Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63637</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63637"/>
		<updated>2012-09-12T01:51:44Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall look at these concepts one at a time and make the differences clear with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and this subclass will inherit its parent’s attributes and behavior. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and method defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
Object composition is an alternative to class inheritance to achieve code reusability. Here, new complex functionality is achieved by assembling or composing objects [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large box. Complex functionality is achieved in this larger box by placing smaller closed boxes inside this larger box. Every smaller box has its own independent implementation hidden from the outer box. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   Seat s = new Seat();&lt;br /&gt;
   Backrest b = new Backrest();&lt;br /&gt;
   Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another related concept is that if Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat. Backrest and legs do not have an existence without the chair. So, the person object is initialized outside the chair class and can be used inside it with its interface. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Delegation involved two objects: a delegator who delegates a operation to another object, the delgatee. This can be compared to inheritance where a subclass defers request to the parent class. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time as against Inheritance which causes the relationship to be established statically at compile-time. Although overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives]:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusions[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem]===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato : Fruit {&lt;br /&gt;
}&lt;br /&gt;
or&lt;br /&gt;
class Tomato : Vegetable{&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Composition:&lt;br /&gt;
class Fruit {&lt;br /&gt;
}&lt;br /&gt;
class Vegetable {&lt;br /&gt;
}&lt;br /&gt;
class Tomato {&lt;br /&gt;
  if(some-criteria) {&lt;br /&gt;
     Fruit f = new Fruit();&lt;br /&gt;
  } else {&lt;br /&gt;
     Vegetable v = new Vegetable();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
When inheritance is used class Tomato can either inherit from Fruit or Vegetable, this has to be decide while implementation and cannot be decided during runtime. But when composition is used, based on some condition at run time, Tomato can get behaviour of fruit or vegetable.&lt;br /&gt;
&lt;br /&gt;
===Inheritance is white box===&lt;br /&gt;
Inheritance is white box and not black box, since it exposes lot more details than necessary. This violates the OO concept of encapsulation and data hiding. Composition acts as black box and hence solves this problem[http://blog.billyang.me/2009/11/does-inheritance-breaks-encapsulation.html]&lt;br /&gt;
&lt;br /&gt;
===Huge Explosion in the number of Types===&lt;br /&gt;
There will be a huge explosion if a new type is created for every possible combination of behaviours, this can be avoided with delegation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Base classes:&lt;br /&gt;
class fly {&lt;br /&gt;
}&lt;br /&gt;
class eat {&lt;br /&gt;
}&lt;br /&gt;
class talk {&lt;br /&gt;
}&lt;br /&gt;
class dance {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Sub classes:&lt;br /&gt;
class human : eat, talk {&lt;br /&gt;
}&lt;br /&gt;
class birds : fly, eat {&lt;br /&gt;
}&lt;br /&gt;
class robot : dance, fly {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example for every possible pair of behaviours there might be class like human can eat and talk and not fly, birds can eat and fly but not dance and robots can dance and fly but not eat. This list can keep growing and might become difficult to manage.&lt;br /&gt;
&lt;br /&gt;
==When to use What==&lt;br /&gt;
==='''When to use Inheritance instead of Composition/Aggregation'''===&lt;br /&gt;
Composition or Aggregation can always be good instead of Inheritance because it is flexible and behaviour can be changed on the fly. But there are situations where Inheritance might make more sense.&lt;br /&gt;
&lt;br /&gt;
If type B wants to expose the entire interface of type A and type B can be substituted in place of type A - use Inheritance definitely.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Phone {&lt;br /&gt;
  public dialcall();&lt;br /&gt;
  public receivecall();&lt;br /&gt;
  public savecontacts();&lt;br /&gt;
}&lt;br /&gt;
class SmartPhone : Phone {&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
For example, SmartPhone will require and expose all the functionalities of a Phone like dialing a call, receiving a call and saving contacts in phone. Above these basic functionalities might add more functionality. So SmartPhone should be derived from Phone and must not contain Phone.&lt;br /&gt;
&lt;br /&gt;
==='''When to use Composition/Aggregation instead of Inheritance'''===&lt;br /&gt;
If type B wants to expose only part of the interface of type A - use Composition/Aggregation.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class Dog {&lt;br /&gt;
  eat();&lt;br /&gt;
  play();&lt;br /&gt;
  bark();&lt;br /&gt;
}&lt;br /&gt;
class Cat : Dog {&lt;br /&gt;
  bark() {&lt;br /&gt;
     do nothing&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, class Dog exposes some behaviour and class Cat inherits from Dog. But a cat cannot bark and hence bark method has to be overriden and left empty. Since Cat needs only a part of the behaviour exposed by Dog, it is good to extract out the common functionality and make it a separate interface or class and include in both the classes.[http://stackoverflow.com/questions/49002/prefer-composition-over-inheritance]&lt;br /&gt;
&lt;br /&gt;
==='''When to use Delegation instead of Inheritance'''===&lt;br /&gt;
Only when it is needed to copy the functionality and exposing the base class API is not needed then Delegation is the right thing to do.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Inheritance:&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack : List {&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
Delegation&lt;br /&gt;
class List {&lt;br /&gt;
  public:&lt;br /&gt;
     insert_at_front();&lt;br /&gt;
     insert_at_back();&lt;br /&gt;
     delete_from_front();&lt;br /&gt;
     delete_from_back();&lt;br /&gt;
     insert_at_position();&lt;br /&gt;
     find_loop();&lt;br /&gt;
}&lt;br /&gt;
class Stack {&lt;br /&gt;
  List newlist = new List();&lt;br /&gt;
  public Push() {&lt;br /&gt;
     newlist.insert_at_back();&lt;br /&gt;
  }&lt;br /&gt;
  public Pop() {&lt;br /&gt;
     newlist.delete_from_back();&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In the above example, Stack is implemented with List, if the Stack class inherits from List class, it gets all the List behaviour like find_loop, insert_at_front, delete_at_front, which is not defined by the Stack ADT and so Stack should not expose these methods. Instead Stack can contain an instance of List and expose just two method needed for a Stack, push and pop. Internally the Push call and Pop call can be redirected to the List class with the help of the List instance.&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63629</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63629"/>
		<updated>2012-09-12T01:07:50Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: &lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall look at these concepts one at a time and make the differences clear with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and this subclass will inherit its parent’s attributes and behavior. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and method defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
Object composition is an alternative to class inheritance to achieve code reusability. Here, new complex functionality is achieved by assembling or composing objects [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large box. Complex functionality is achieved in this larger box by placing smaller closed boxes inside this larger box. Every smaller box has its own independent implementation hidden from the outer box. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   Seat s = new Seat();&lt;br /&gt;
   Backrest b = new Backrest();&lt;br /&gt;
   Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another related concept is that if Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat. Backrest and legs do not have an existence without the chair. So, the person object is initialized outside the chair class and can be used inside it with its interface. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Delegation involved two objects: a delegator who delegates a operation to another object, the delgatee. This can be compared to inheritance where a subclass defers request to the parent class. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time as against Inheritance which causes the relationship to be established statically at compile-time. Although overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;br /&gt;
&lt;br /&gt;
=='''Let us convince ourselves that Inheritance is bad at certain places'''==&lt;br /&gt;
Below are the cases[http://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)#Limitations_and_alternatives]:&lt;br /&gt;
&lt;br /&gt;
===Problem 1: Multiple Inheritance introduces lot more confusions[http://en.wikipedia.org/wiki/Multiple_inheritance#The_diamond_problem]===&lt;br /&gt;
One such is Diamond Problem. Two classes B and C inherit from the same base class A and class D inherits from B and C. If D calls a method defined in class A and implemented very differently in classes B and C.&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
Class A {&lt;br /&gt;
  virtual print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class A”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class B : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class B”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class C : A {&lt;br /&gt;
  override print() {&lt;br /&gt;
     cout &amp;lt;&amp;lt; “This is class C”;&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
class D : B, C {&lt;br /&gt;
  A a = new A();&lt;br /&gt;
  a.print();&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
===Inheritance is link time===&lt;br /&gt;
Types are fixed during compile time and super classes cannot be changed dynamically during program execution. Another problem which arises because of static linking is, the changes to super class automatically propagates to the sub-class. In essence inheritance creates a strong coupling. This can be addressed with help of Composition, which allows to change behaviour at runtime.&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
	<entry>
		<id>https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63623</id>
		<title>CSC/ECE 517 Fall 2012/ch1 1w24 nr</title>
		<link rel="alternate" type="text/html" href="https://wiki.expertiza.ncsu.edu/index.php?title=CSC/ECE_517_Fall_2012/ch1_1w24_nr&amp;diff=63623"/>
		<updated>2012-09-12T00:54:12Z</updated>

		<summary type="html">&lt;p&gt;Narumug4: Creating a new page for 1w24 with basic content&lt;/p&gt;
&lt;hr /&gt;
&lt;div&gt;'''Decomposition, message forwarding, and delegation versus inheritance in OOP'''&lt;br /&gt;
&lt;br /&gt;
=='''Introduction'''==&lt;br /&gt;
&lt;br /&gt;
Inheritance plays an important role in designing reusable object oriented software. In this article we will discuss some alternatives to inheritance to achieve object oriented code reusability. Design techniques like composition, message passing and delegation can be used instead of inheritance to achieve the same goals with more cohesion and less coupling. The basic difference in these approaches lies in the separation of interface and implementation. We shall look at these concepts one at a time and make the differences clear with examples.&lt;br /&gt;
&lt;br /&gt;
=='''Definitions'''==&lt;br /&gt;
===Inheritance===&lt;br /&gt;
Inheritance is an object oriented programming concept for code reuse. It says that we can define a subclass on a parent class and this subclass will inherit its parent’s attributes and behavior. Consider the following example:&lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
class A {&lt;br /&gt;
  protected int attribute1, attribute2;&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
  public void method2() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&lt;br /&gt;
class B extends A {&lt;br /&gt;
  public void method1() {&lt;br /&gt;
    //method overriding&lt;br /&gt;
  }&lt;br /&gt;
  public void method3() {&lt;br /&gt;
    //method definition&lt;br /&gt;
  }&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
Here, class B is a subclass that inherits the attributes and method defined by its parent A. The subclass inherits the method interface as well as the implementation from its parent. The subclass may define its own attributes and methods or it may provide its own implementation for its parent’s methods. This is called method overriding.&lt;br /&gt;
&lt;br /&gt;
===Composition===&lt;br /&gt;
Object composition is an alternative to class inheritance to achieve code reusability. Here, new complex functionality is achieved by assembling or composing objects [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Unlike inheritance, composition relies on reuse of interface rather than implementation. Consider the new object as a large box. Complex functionality is achieved in this larger box by placing smaller closed boxes inside this larger box. Every smaller box has its own independent implementation hidden from the outer box. Thus composition provides encapsulation in the true sense. This is why composition is also called the black box approach for code reuse. As an example consider a chair class. A chair is made up of a seat, backrest and four legs. &lt;br /&gt;
&lt;br /&gt;
&amp;lt;pre&amp;gt;&lt;br /&gt;
public class Seat { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Backrest { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Leg { &lt;br /&gt;
   …&lt;br /&gt;
}&lt;br /&gt;
public class Chair {&lt;br /&gt;
   Seat s = new Seat();&lt;br /&gt;
   Backrest b = new Backrest();&lt;br /&gt;
   Leg l = new Leg();&lt;br /&gt;
      …&lt;br /&gt;
}&lt;br /&gt;
&amp;lt;/pre&amp;gt;&lt;br /&gt;
&lt;br /&gt;
In this example since seat, backrest and legs are components of a chair it is better to use composition instead of inheritance. The seat, backrest and legs class have their own implementation which is hidden from the chair class. These components can be used in the chair class with the help of their defined interface. The chair class can communicate with its component objects through message passing. Thus, code reusability is obtained without caring for the implementation of the component objects.&lt;br /&gt;
&lt;br /&gt;
===Aggregation===&lt;br /&gt;
Another related concept is that if Aggregation. Suppose we also use a class Person in the Chair class to represent the person occupying the chair. Then this person is not initialized in the Chair class as a person has an existence irrespective of the chair, whereas the seat. Backrest and legs do not have an existence without the chair. So, the person object is initialized outside the chair class and can be used inside it with its interface. &lt;br /&gt;
&lt;br /&gt;
===Delegation===&lt;br /&gt;
Delegation is a way of making composition as powerful for reuse as inheritance [http://www.whigg.cas.cn/resource/program/CPP/201010/P020101022562155422801.pdf]. Delegation involved two objects: a delegator who delegates a operation to another object, the delgatee. This can be compared to inheritance where a subclass defers request to the parent class. The advantage of delegation over inheritance is that delegation allows composition behavior to occur dynamically at run-time as against Inheritance which causes the relationship to be established statically at compile-time. Although overuse or delegation may make the code hard to understand and may invite runtime inefficiencies.&lt;/div&gt;</summary>
		<author><name>Narumug4</name></author>
	</entry>
</feed>