Home > Articles > Software Development & Management

  • Print
  • + Share This
Like this article? We recommend

Interface Segregation Principle

I have seen the violation of the Interface Segregation (IS) Principle numerous times in code. This principle states that classes should not be forced to depend (or implement) interface method declarations they do not need, which is often a result of trying to make one interface a one-size-fits-all interface to disparate classes or clients of those classes.

Check out the following example:

Interface Animal {
     public void eat();
     public void sleep();
     public void meow();
     public void bark();
}
class Dog implements Animal{
     public void eat(){ code here };
     public void sleep(){ code here };
     public void meow(){ empty, not needed };
     public void bark(){ code here };
}
class Cat implements Animal{
     public void eat(){ code here };
     public void sleep(){ code here };
     public void meow(){ code here};
     public void bark(){empty, not needed };

}

The Cat and Dog classes share the same interface, but the Cat does things that the Dog doesn't do. The Dog class is still required to implement what the Cat does, even if it will be empty.

An easy fix is to create a separate interface for each type of Animal. In doing so, we reduce “interface pollution,” which is all too common.

  • + Share This
  • 🔖 Save To Your Account