March 20, 2013

Open-Closed Principle and its use in software development

Definition of Open-Closed Principle:

It states that software entities like classes, modules and functions should be open for extension but closed for modifications. It means if you want to add new functionality in your software application than it should not impact your previous functionality because it has already been tested and integrated.

We can take an example which violates the principle:

 public abstract class Animal{}
 
 public class Dog extends Animal{}
 
 public class Horse extends Animal{}
 
 public class AnimalSpeaker
 {
  public void speak(String type)
  {
   if(type equals Dog)
    speakDog();
   
   if(type equals Horse)
    speakHorse();
  }
 
  public void speakDog(){}
 
  public void speakHorse(){}
 
 }


Now suppose I want to add new base class called Cat then I need to create a new subclass Cat and will have to make change in AnimalSpeaker means violating the open-close principle.


Now go through the changes made in this example which is supporting the open-close principle:

public abstract class Animal
{
 public abstract void speak();
}

public class Dog extends Animal{

 public void speak()
 { 
  System.out.println("Dog");
 } 
}

 
public class Horse extends Animal {

 public void speak () 
 {
  System.out.println ("Horse");
 }
}

public class AnimalSpeaker
{
 public void speak(Animal a)
 {
  a.speak();
 }
}

No comments:

Post a Comment