Interface Segregation Principle

LinkedIn
Hacker News

This article explains interface segregation principle and its uses. Interface segregation is a design principle that deals with the disadvantages of “fat” interfaces. Interfaces containing methods that are not specific to it are called polluted or fat interfaces.

“Clients should not be forced to depend upon interfaces that they don’t use.”

Let us take the example of a multi purpose machine developed by Xerox. This super xerox system could do a wide variety of jobs like printing, scanning, stapling, photocopying, etc. They can be implemented as a IMachine interface and XeroxMachine implementation as shown below.

public interface IMachine {
	public void print();
	public void staple();
	public void scan();
	public void photoCopy();
}

XeroxMachine implementation

public class XeroxMachine implements IMachine {

	@Override
	public void print() {
		System.out.println("Printing Job");
	}

	@Override
	public void staple() {
		System.out.println("Stapling Job");
	}
	
	@Override
	public void scan() {
		System.out.println("Scan Job");
	}

	@Override
	public void photoCopy() {
		System.out.println("Photo Copy");
	}
}

The super machine is developed and working great. Now company is getting requests for making a machine that do only print function. Management has decided to develop a specialized print machine. Now developers want to write Printer class that implements IMachine interface. Did you notice any problem? Although you need only print function, you have to implement all other methods of IMachine interface. Now IMachine interface is not following interface segregation principle and called fat interface.

We can breakdown the IMachine into multiple special purpose interfaces as shown below.

public interface IPrinter {
	public void print();
}

public interface IScanner {
	public void fax();
}

public interface IStapler {
	public void staple();
}

public interface IPhotoCopier {
	public void photoCopy();
}

Notes:

  1. What if you are dealing with existing legacy application where interface is a fat interface? How do deal with such situation? Well, you can always use adapter design pattern for segregation.
  2. Interface segregation brings implementation simplicity and makes easy to debug and maintain.
  3. Interface segregation principle is easy to understand and sounds great in theory, but often difficult to identify the distinct interfaces and it can also end up with proliferation of interfaces.
Tagged in OOADSOLID

Nilanchala

A blogger, a bit of tech freak and a software developer. He is a thought leader in the fusion of design and mobile technologies. He is the author of Xamarin Mobile Application Development for Android Book (goo.gl/qUZ0XV3), DZone MVB and founder of stacktips.com.

Join The Discussion

Please note: We reserve the right to delete comments that contains snarky remarks, offensive or off-topic. To know more read our comments policy.