SOLID Principles by Examples: Interface Segregation
In this post, we continue our analysis of the SOLID principles of programming with the Interface Segregation Principle, or ISP.
Join the DZone community and get the full member experience.
Join For FreeThis post continues the analysis of the SOLID principles and it's about the Interface Segregation Principle (ISP).
Definition
"The interface-segregation principle (ISP) states that no client should be forced to depend on methods it does not use."
The Bad Example
Here we examine an interface that violates ISP:
interface ISmartDevice
{
void Print();
void Fax();
void Scan();
}
This interface states that a smart device is able to print, fax, and scan. An implementation of this interface could be an AllInPrinter class:
class AllInOnePrinter : ISmartDevice
{
public void Print()
{
// Printing code.
}
public void Fax()
{
// Beep booop biiiiip.
}
public void Scan()
{
// Scanning code.
}
}
Simple, isn't it? Right. Now suppose we need to handle a dumb device (EconomicPrinter class) that can only print. We're forced to implement the Whole interface, for example:
class EconomicPrinter : ISmartDevice
{
public void Print()
{
//Yes I can print.
}
public void Fax()
{
throw new NotSupportedException();
}
public void Scan()
{
throw new NotSupportedException();
}
}
This is not very good.
The Good Example
Here we apply the ISP and we separate the single ISmartDevice interface into three smaller interfaces: IPrinter, IFax, and IScanner.
interface IPrinter{
void Print();
}
interface IFax{
void Fax();
}
interface IScanner{
void Scan();
}
This way, it's easier to implement classes that do not need to handle all the original functionalities of the ISmartDevice, interface like our EconomicPrinter. Our code is more decoupled and easier to maintain. Let's re-implement our EconomicPrinter with this architecture:
class EconomicPrinter : IPrinter
{
public void Print()
{
// Printing code.
}
}
The original AllInOnePrinter now looks like this:
class AllInOnePrinter : IPrinter, IFax, IScanner
{
public void Print()
{
// Printing code.
}
public void Fax()
{
// Beep booop biiiiip.
}
public void Scan()
{
// Scanning code.
}
}
TL;DR
The ISP guides us to create many small interfaces with coherent functionalities instead of a few big interfaces with lots of different methods. When we apply the ISP, class and their dependencies communicate using focused interfaces, minimizing dependencies. Smaller interfaces are easier to implement, improving flexibility and the possibility of reuse.
Published at DZone with permission of Michele Ferracin, DZone MVB. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments