Mywiki2: Difference between revisions

From Expertiza_Wiki
Jump to navigation Jump to search
 
(44 intermediate revisions by 2 users not shown)
Line 1: Line 1:
===Subclassing===
=='''Subclassing'''==


Subclassing is the concept of creating a specialization(subclass/ derived class) of a base class(superclass/ parent class) by inheriting the methods and instance data from the base class.
Subclassing is a principle of creating a specialization(subclass/ [http://www.webopedia.com/TERM/D/derived_class.html derived class]) of a [http://www.webopedia.com/TERM/B/base_class.html base class](superclass/ parent class) by inheriting the methods and instance data from the base class.


==Why do we Subclass?==
1. Code reuse
2. Specialization: A subclass can define new methods it's superclass does not handle.
3. Method Overriding: An overridding method can either have minor modifications or be completely changed from its parent class'
implementation.


===Is Subclassing same as Subtyping?===


==Subtyping==
==Why do we Subclass?==
A is said to be a type of B if A's specification is same as B's. Subtypes should satisfy the Liskov Substitution Principle which states,
* Code reuse
* Specialization: A subclass can define new methods it's superclass does not handle.
* Method Overriding: An overridding method can either have minor modifications or be completely changed from its parent class' implementation.


  If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of 
  P is unchanged when o1 is substituted for o2, then S is a subtype of T.


In most programming languages,for example java, ruby, C++, subclassing does not essentially mean subtyping. For a class to be a  subtype, the subclass must follow the Liskov Substitution Principle. However it is easy to override a method with a completely new implementation and fewer constraints. This is not checked by the compiler and we can create subclasses which are not subtypes. 


==Is Subclassing same as Subtyping?==


===Subtyping===
A is said to be a type of B if A's specification is same as B's. Subtypes should satisfy the '''Liskov Substitution Principle(LSP)''' which states,


==Subclassing==
  If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of
Declaring one class to be a subclass of another class there by allowing a
  P is unchanged when o1 is substituted for o2, then S is a subtype of T.


subclass to inherit the functionality from its super class is called
In most programming languages,for example java, ruby, C++, subclassing does not essentially mean subtyping. For a class to be a subtype, the subclass must follow the Liskov Substitution Principle. However it is easy to override a method with a completely new implementation and with stronger constraints. This is not checked by the compiler and we can create subclasses which are not subtypes. This is considered a bad approach, one of the reasons being, an argument to a method may be declared of one class A, but the method may be called with an argument of some subclass B. If we do not know if B is a true subtype of A, then we cannot assume that the behavior guaranteed by A is actually guaranteed by B, and so we cannot reason locally about this method[link mit reference].


subclassing.


/* we can include here the 4 perspectives of  inheritance  and then mention


LP principle , principle of least astonishment and
'''Subclass not Subtype'''
some other solid principles of inheritance like the The Open-Closed


Principle and The Single Responsibility Principle.
  class A {
  */
    int x;
Links for the solid principles...
    int get_x()
http://www.objectmentor.com/resources/articles/ocp.pdf
    {
http://www.objectmentor.com/resources/articles/srp.pdf
      return x;
    }
    int sum(A a) { return x + a.x }
  }


===Subclassing in Java===
  class B {
    int y;
    int get_y()
    {
      return y;
    }
    int sum(B b)
    {
      if(y > 0)
        return x + b.x + y + b.y;
      else
        return 0;
    }
  }


====Extends Keyword====
'''Subtype'''
The extends is a Java keyword, which is used in inheritance process of
  class A {
    int x;
    int get_x()
    {
      return x;
    }
    int sum(A a) { return x + a.x }
  }


Java. It specifies the superclass in a class declaration using extends
  class B {
 
    int y;
keyword.To inherit a class, you simply incorporate the definition of one
    int get_y()
 
    {  
class into another by using the extends keyword.
      return y;
 
    }
<pre>
    int product(B b)  
public class A
    {  
{  
      return x * y * b.x * b.y;
  int a;
    }
  char b;
  }
  void method1()
  {
  }
}
class B extends A    //class B inherits the properties of class A
{
  void method2()
  {
  }
}
</pre>
 
===Abstract classes===
 
Abstract classes in Java are used to declare common characteristics of
 
subclasses. An abstract class cannot be instantiated i.e an object of an
 
abstract class cannot be created. It can only be used as a superclass for
 
other classes that extend the abstract class. Abstract classes are declared
 
using the abstract keyword. Abstract classes are used to provide a template
 
or design for concrete subclasses down the inheritance tree.
 
An abstract class can contain fields that describe the characteristics and
 
methods that describe the actions that a class can perform. An abstract
 
class can include methods that contain no implementation. These are called
 
abstract methods.If a class has any abstract methods, whether declared or
 
inherited, the entire class must be declared abstract. Abstract methods are
 
used to provide a template for the classes that inherit the abstract
 
methods.
 
Abstract classes cannot be instantiated; they must be subclassed, and


actual implementations must be provided for the abstract methods. Any


implementation specified can, of course, be overridden by additional sub-
==Four perspectives of Inheritance==
The four perspectives help in determining when to subclass


classes. An object must have an implementation for all of its methods. You
===Code Reuse===


need to create a subclass that provides an implementation for the abstract
Code reuse is the practice of using the same segment of code in multiple applications.


method.
''''Is Code Reuse alone a sufficient reason to use Inheritance?''''
No It is not.


Consider the following example.
<pre>
<pre>
abstract class A
class Automobile_Part
{
{
  void method1()
    String name;
  {
    String manufacturer_name;
     ...
    int part_id;
     ...
   
     ...
    void setManufacturerName(String mname)
  }
    {manufacterer_name=mname;
  abstract void method2();
     }
      
     int getPartID()
    {return part_id;
    }
   
}
}
class B extends A
 
class Medicine extends Automobile_Part
{
{
    void method2()
    String cures_disease;
    {
    String getDiseaseName()
         ...
    {
        ...
         return cures_disease;
    }  
    }
   
}
}
</pre>
</pre>


If the class B does not implement the method "method2" then even class B
Here the Medicine class extends the Automobile_Part class in order to reuse the attributes "name" and "manufacturer_name" and "setManufacturerName" method. But it also inherits the "getPartID" method which is not appropriate for the Medicine class.
   
So Code Reuse is in itself not a sufficient reason for using inheritance.


has to be declared as an Abstract class.
So if one wants to only achieve code reuse ,they can do so using Composition rather than Inheritance.  


Rules that should be followed before subclassing
''''Then what is Inheritance for?''''


===Subclassing vs Subtyping===
Inheritance is a mechanism used to facilitate polymorphism and to achieve categorization. By using inheritance one can build a hierarchy of concepts separated in categories at different levels of abstraction. By doing this, you can efficiently use another OOP concept, polymorphism, which allows the same control code to manage all objects in a category even if they are different in their implementation.




===Is-A Perspective===
Now let us consider both "[http://en.wikipedia.org/wiki/Is-a is-a]" relationship and Code reuse perspectives.


''''Is the combination of code reuse and the “is-a” relationship among the classes a sufficient reason for using subclassing?''''


===The Liskov Substitution Principle in class typed languages===
Consider the following example.
The Liskov Substitution Principle is a way of ensuring that inheritance is
<pre>
 
used correctly.
 
It states that, in a computer program, if S is a subtype of T, then
 
objects of type T may be replaced with objects of type S (i.e., objects of
 
type S may be substitutes for objects of type T) without altering any of
 
the desirable properties of that program (correctness, task performed,
 
etc.).
 
If for each object o1 of type S there is an object o2 of type T such that
 
for all programs P defined in terms of T, the behavior of P is unchanged
 
when o1 is substituted for o2, then S is a subtype of T.
 
In less formal terms, it says that if a client (program) expects objects of
 
one type to behave in a certain way, then it’s only okay to substitute
 
objects of another type if the same expectations are satisfied.
 
Consider the following example which satisfies the Liskov Substitution
 
Principle
 
class Bird
class Bird
{
{
   String name;
   String name;
   void fly()
   String getName()
  {
      ...
  }
  void altitude()
   {
   {
      ...
      return name;
   }
   }
}
class Sparrow extends Birds
{
Example which does not satisfy the Liskov Substitution Principle
class Bird
{
  String name;
   void fly()
   void fly()
   {
   {
Line 204: Line 145:
   }
   }
}
}
class Penguin extends Birds
class Penguin extends Birds
{
{
Line 217: Line 159:
   
   
}
}
If an override method does nothing or just throws an exception, then you’re
</pre>
Even though Penguin is a Bird and Penguin class re uses the code in Bird class ,it is not appropriate to use inheritance here because the behavior of the inherited code is being changed.
 
Consider the case where a user invokes the method "altitude" in the Penguin class .The "altitude" method in Penguin class when invoked instead of displaying the altitude at which the bird flies it throws an exception thereby confusing the user.Code is not considered elegant if the user of that code is surprised or confused by the behavior of that code.
 
This violates the Principle of Least Astonishment
 
  If a client thinks he has a reference to an object of type A but actually has a reference to an object of subtype B,
  there should be no surprises when he sends messages to the object.
 
So according to Principle of Least Astonishment whenever a sub class inherits functionality from the Super class.The subclass is not allowed to change the existing behavior by over ridding the inherited methods.
 
This also violates the Liskov Substitution Principle because both the "fly" and "altitude" methods of Penguin class doesn't do everything that "fly" and "altitude" methods of its parent class Bird does. 
 
Therefore the combination of code reuse and “is-a” relationship among the classes is not a sufficient reason for using subclassing.


probably violating the LSP.
Therefore,this does not satisfy the Liskov Substitution Principle though


penguin "is-a" bird.


/* This is a direct lift off so we need to paraphrase it*/
===Public Interface Perspective/ Behavioral subtyping===


The Liskov Substitution Principle in duck typed languages
Classes are programmed to interfaces and interfaces might have an overlap in functionality. One interface(subinterface) can extend another(superinterface).
In programming languages with duck typing (e.g. Ruby, Python, Smalltalk)


classes don’t really define types. There is no type checking when assigning


objects to variables or passing objects as method arguments. There is a
  interface B{
      void common_method1(B b);
  }
  interface A extends B,C{
      void common_method2(A a);
      void common_method3();
  }
  A a = …;
  A a1 = …;
  a.common_method1(a1); // Behavioral subtyping – Argument of type B is replaced by its
                                        // subtype A
 
 
Interface A includes methods from B and C and transitively above B and C. An interface is considered a type. When A does everything B does and more, A can replace B wherever it is used. This is called '''behavioral subtyping''', and A is a subtype of B. For behavioral subtyping, LSP has to be followed.
 
[http://cs.colby.edu/djskrien/ Dale Skrien], in his [http://search.barnesandnoble.com/Object-Oriented-Design-Using-Java/Dale-Skrien/e/9780072974164?cm_mmc=borders-_-sku-_-NA-_-NA&redir=borders book], suggests the following guideline for subclassing,
"If a class B models a role played by class A, especially a temporary role,then  B should not be a subclass of A. Instead objects of class B should have references to objects of class A."
 
An example why inheritance should not be applied when the public interfaces for concerned classes are same but the above guideline does not hold
 
  class Person{
  String name;
  ...
  ...
  }
 
  class Student extends Person{
  ...
  }
 
  class Employee extends Person{
  ...
  }


kind of type checking when a method is called. It is checked that the
Here the student and employee classes inherit from Person. "Student" could be an "Employee". Since both student and Employee classes extend Person, they have the data fields of Person duplicated. A reference to a Person object would be a better option than inheritance.


method exists with a matching number of parameters.
Since classes don’t define types, inheritance in duck typed languages has


nothing to do with the subtype relation or the LSP.
===Polymorphism===
In a way clients define interfaces in an implicit way. Let’s look at an


example:
If all occurences of class A could be substituted by class B then it's good to have class B subclass A to avoid code duplication and by this we follow the LSP principle.
def my_method1(a) do
    a.m1()
    a.m2()
    my_method2(a)
end


def my_method2(a) do
==Conclusion==
  a.m3()
end
Calling my_method1 with an object a will succeed if the object a provides


the three methods m1, m2 and m3. This is the implicit interface the object
===Is Liskov Substitution Principle restrictive?===


a needs to implement. And with this implicit interface comes the clients
It depends,
If the developer in solely interested in reusing the code rather than keeping the behaviour or semantics of the methods intact, then he can do so by using sub-classing .But one can also achieve code reuse using [http://en.wikipedia.org/wiki/Delegation_(programming) Delegation] and [http://en.wikipedia.org/wiki/Composition_over_inheritance Composition] which are relatively difficult to implement when compared to inheritance .But it is a good practice not to violate LSP principle while subclassing as it is one of the most powerful OO design principles which leads to good OO design.Furthermore,it provides more clarity to the user about the behaviour of the inherited methods inside the sub classes.Violation of LSP principle leads to messing up of class hierarchies. Mess being that whenever a subclass instance was passed as parameter to any method, strange behavior would occur.


expectation about the behaviour of m1, m2 and m3. That’s just the same as
/* This talks about behavioral subtyping which has almost same constraints as LSP Dont think we can mention it here*/
But again, if the developer is solely interested in achieving code reuse and if he finds Liskov Substitution Principle to be too restrictive then he can achieve the same using alternative methodologies such as [http://en.wikipedia.org/wiki/Design_by_contract  Design By Contract]. The idea of DBC is to specify that part of the behaviour which must remain unchanged (by means of assertions and suchlike). This leads to a more precise notion of subtype. When using Design by Contract, subclasses in an inheritance hierarchy are allowed to weaken preconditions (but not strengthen them) and strengthen postconditions and invariants (but not weaken them). These rules approximate behavioral subtyping.
 
LiskovSubstitutionPrinciple is about subtyping, which relates strongly to polymorphism. Polymorphism is the source of most of the power of OO and the power comes from the re-use that comes from subclassing. Polymorphism is what makes it possible for the clients of an interface (those dependent on a type) to not care which implementation is used at any point in the code. Subclassing makes it possible to re-use the methods provided by a superclass to provide different behavior.


with the Java interface. If an object b provides m1, m2 and m3 but doesn’t


fit the expected behaviour, the LSP is violated.
==References==
* http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=%2Fcom.ibm.aix.cbl.doc%2Ftpoot30.htm


* http://courses.csail.mit.edu/6.170/old-www/2001-Spring/recitations/recitation4.html


The LSP isn’t tied to inheritance or class based typing. It applies to duck
* http://en.wikipedia.org/wiki/Code_reuse


types languages as well as to systems without inheritance. LSP is a concept
* http://www.isase.us/wisr3/7.pdf


that applies to all kinds of polymorphism. Only if you don’t use
* http://littletutorials.com/2008/06/23/inheritance-not-for-code-reuse/


polymorphism of all you don’t need to care about the LSP.
* [http://dl.acm.org/citation.cfm?id=62141 Keynote address - data abstraction and hierarchy], Barbara Liskov, MIT Laboratory for Computer Science, Cambridge, Ma.


===References===
* http://c2.com/cgi/wiki?LiskovSubstitutionPrinciple
http://publib.boulder.ibm.com/infocenter/comphelp/v7v91/index.jsp?topic=%2Fcom.ibm.aix.cbl.doc%2Ftpoot30.htm


http://courses.csail.mit.edu/6.170/old-www/2001-Spring/recitations/recitation4.html
* http://www.objectmentor.com/resources/articles/lsp.pdf

Latest revision as of 15:52, 17 November 2011

Subclassing

Subclassing is a principle of creating a specialization(subclass/ derived class) of a base class(superclass/ parent class) by inheriting the methods and instance data from the base class.


Why do we Subclass?

  • Code reuse
  • Specialization: A subclass can define new methods it's superclass does not handle.
  • Method Overriding: An overridding method can either have minor modifications or be completely changed from its parent class' implementation.


Is Subclassing same as Subtyping?

Subtyping

A is said to be a type of B if A's specification is same as B's. Subtypes should satisfy the Liskov Substitution Principle(LSP) which states,

 If for each object o1 of type S there is an object o2 of type T such that for all programs P defined in terms of T, the behavior of 
 P is unchanged when o1 is substituted for o2, then S is a subtype of T.

In most programming languages,for example java, ruby, C++, subclassing does not essentially mean subtyping. For a class to be a subtype, the subclass must follow the Liskov Substitution Principle. However it is easy to override a method with a completely new implementation and with stronger constraints. This is not checked by the compiler and we can create subclasses which are not subtypes. This is considered a bad approach, one of the reasons being, an argument to a method may be declared of one class A, but the method may be called with an argument of some subclass B. If we do not know if B is a true subtype of A, then we cannot assume that the behavior guaranteed by A is actually guaranteed by B, and so we cannot reason locally about this method[link mit reference].


Subclass not Subtype

 class A {
   int x;
   int get_x()
   { 
     return x;
   }
   int sum(A a) { return x + a.x }
 }
 class B {
   int y;
   int get_y()
   { 
     return y;
   }
   int sum(B b) 
   { 
     if(y > 0)
       return x + b.x + y + b.y;
     else
       return 0;
   }
 }

Subtype

 class A {
   int x;
   int get_x()
   { 
     return x;
   }
   int sum(A a) { return x + a.x }
 }
 class B {
   int y;
   int get_y()
   { 
     return y;
   }
   int product(B b) 
   { 
     return x * y * b.x * b.y;
   }
 }


Four perspectives of Inheritance

The four perspectives help in determining when to subclass

Code Reuse

Code reuse is the practice of using the same segment of code in multiple applications.

'Is Code Reuse alone a sufficient reason to use Inheritance?' No It is not.

Consider the following example.

class Automobile_Part
{
    String name;
    String manufacturer_name;
    int part_id;
    
    void setManufacturerName(String mname)
    {manufacterer_name=mname;
    }
    
    int getPartID()
    {return part_id;
    }
    
}

class Medicine extends Automobile_Part
{
     String cures_disease;
     String getDiseaseName()
     {
        return cures_disease;
     }
}

Here the Medicine class extends the Automobile_Part class in order to reuse the attributes "name" and "manufacturer_name" and "setManufacturerName" method. But it also inherits the "getPartID" method which is not appropriate for the Medicine class.

So Code Reuse is in itself not a sufficient reason for using inheritance.

So if one wants to only achieve code reuse ,they can do so using Composition rather than Inheritance.

'Then what is Inheritance for?'

Inheritance is a mechanism used to facilitate polymorphism and to achieve categorization. By using inheritance one can build a hierarchy of concepts separated in categories at different levels of abstraction. By doing this, you can efficiently use another OOP concept, polymorphism, which allows the same control code to manage all objects in a category even if they are different in their implementation.


Is-A Perspective

Now let us consider both "is-a" relationship and Code reuse perspectives.

'Is the combination of code reuse and the “is-a” relationship among the classes a sufficient reason for using subclassing?'

Consider the following example.

class Bird
{
   String name;
   String getName()
   {
       return name;
   }
   void fly()
   {
      ...
   }
   void altitude()
   {
      ...
   }
}

class Penguin extends Birds
{
   void fly()
   {
      throw new Exception();
   }

   void altitude()
   {
     throw new Exception();
   }  
 
}

Even though Penguin is a Bird and Penguin class re uses the code in Bird class ,it is not appropriate to use inheritance here because the behavior of the inherited code is being changed.

Consider the case where a user invokes the method "altitude" in the Penguin class .The "altitude" method in Penguin class when invoked instead of displaying the altitude at which the bird flies it throws an exception thereby confusing the user.Code is not considered elegant if the user of that code is surprised or confused by the behavior of that code.

This violates the Principle of Least Astonishment

 If a client thinks he has a reference to an object of type A but actually has a reference to an object of subtype B,
 there should be no surprises when he sends messages to the object.

So according to Principle of Least Astonishment whenever a sub class inherits functionality from the Super class.The subclass is not allowed to change the existing behavior by over ridding the inherited methods.

This also violates the Liskov Substitution Principle because both the "fly" and "altitude" methods of Penguin class doesn't do everything that "fly" and "altitude" methods of its parent class Bird does.

Therefore the combination of code reuse and “is-a” relationship among the classes is not a sufficient reason for using subclassing.


Public Interface Perspective/ Behavioral subtyping

Classes are programmed to interfaces and interfaces might have an overlap in functionality. One interface(subinterface) can extend another(superinterface).


 interface B{
     void common_method1(B b);
 }
 interface A extends B,C{ 
     void common_method2(A a);
     void common_method3();
 }
 A a = …;
 A a1 = …;
 a.common_method1(a1); // Behavioral subtyping – Argument of type B is replaced by its 
                                        // subtype A


Interface A includes methods from B and C and transitively above B and C. An interface is considered a type. When A does everything B does and more, A can replace B wherever it is used. This is called behavioral subtyping, and A is a subtype of B. For behavioral subtyping, LSP has to be followed.

Dale Skrien, in his book, suggests the following guideline for subclassing, "If a class B models a role played by class A, especially a temporary role,then B should not be a subclass of A. Instead objects of class B should have references to objects of class A."

An example why inheritance should not be applied when the public interfaces for concerned classes are same but the above guideline does not hold

 class Person{
  String name;
  ... 
  ...
 }
 class Student extends Person{
  ...
 }
 class Employee extends Person{
  ...
 }

Here the student and employee classes inherit from Person. "Student" could be an "Employee". Since both student and Employee classes extend Person, they have the data fields of Person duplicated. A reference to a Person object would be a better option than inheritance.


Polymorphism

If all occurences of class A could be substituted by class B then it's good to have class B subclass A to avoid code duplication and by this we follow the LSP principle.

Conclusion

Is Liskov Substitution Principle restrictive?

It depends, If the developer in solely interested in reusing the code rather than keeping the behaviour or semantics of the methods intact, then he can do so by using sub-classing .But one can also achieve code reuse using Delegation and Composition which are relatively difficult to implement when compared to inheritance .But it is a good practice not to violate LSP principle while subclassing as it is one of the most powerful OO design principles which leads to good OO design.Furthermore,it provides more clarity to the user about the behaviour of the inherited methods inside the sub classes.Violation of LSP principle leads to messing up of class hierarchies. Mess being that whenever a subclass instance was passed as parameter to any method, strange behavior would occur.

/* This talks about behavioral subtyping which has almost same constraints as LSP Dont think we can mention it here*/ But again, if the developer is solely interested in achieving code reuse and if he finds Liskov Substitution Principle to be too restrictive then he can achieve the same using alternative methodologies such as Design By Contract. The idea of DBC is to specify that part of the behaviour which must remain unchanged (by means of assertions and suchlike). This leads to a more precise notion of subtype. When using Design by Contract, subclasses in an inheritance hierarchy are allowed to weaken preconditions (but not strengthen them) and strengthen postconditions and invariants (but not weaken them). These rules approximate behavioral subtyping.

LiskovSubstitutionPrinciple is about subtyping, which relates strongly to polymorphism. Polymorphism is the source of most of the power of OO and the power comes from the re-use that comes from subclassing. Polymorphism is what makes it possible for the clients of an interface (those dependent on a type) to not care which implementation is used at any point in the code. Subclassing makes it possible to re-use the methods provided by a superclass to provide different behavior.


References