Interface Segregation Principle (ISP)
Interface
Segregation Principle (ISP)
The Interface
Segregation Principle states: Do not force a class to
implement interfaces it does not use. Instead of having one large,
general-purpose interface, it is better to have smaller, specific
interfaces that are client-focused.
Real-Time
Example: Multifunction Printer
Imagine
designing an interface for printers in an office automation system:
Violates
ISP (Bad Design):
public
interface IPrinter
{
void
Print(Document doc);
void
Scan(Document doc);
void
Fax(Document doc);
}
Now
imagine a basic printer that can only print —
not scan or fax. Still, it must implement the whole interface:
public
class BasicPrinter : IPrinter
{
public
void Print(Document doc)
{
Console.WriteLine("Printing
document...");
}
public
void Scan(Document doc)
{
throw
new NotImplementedException(); // Not supported
}
public
void Fax(Document doc)
{
throw
new NotImplementedException(); // Not supported
}
}
This
violates ISP because BasicPrinter is forced to implement methods it
doesn’t need or support.
Follows
ISP (Good Design):
Split
the large interface into smaller, more specific ones:
public
interface IPrinter
{
void
Print(Document doc);
}
public
interface IScanner
{
void
Scan(Document doc);
}
public
interface IFax
{
void
Fax(Document doc);
}
Now
different classes can implement only what they need:
public
class BasicPrinter : IPrinter
{
public
void Print(Document doc)
{
Console.WriteLine("Basic
printing...");
}
}
public
class MultiFunctionPrinter : IPrinter, IScanner, IFax
{
public
void Print(Document doc)
{
Console.WriteLine("Printing...");
}
public
void Scan(Document doc)
{
Console.WriteLine("Scanning...");
}
public
void Fax(Document doc)
{
Console.WriteLine("Faxing...");
}
}
Now,
each class only depends on the interfaces relevant to it, making
the design cleaner and more maintainable.
Why
Interface Segregation Principle Matters
- Encourages modular,
flexible interfaces
- Avoids unnecessary code
and exceptions
- Makes unit testing easier (mock
only the required interfaces)
- Reduces tight coupling and code
bloat
This
principle is particularly helpful in large-scale applications and systems
with diverse or evolving functionalities. It enables each class to
grow independently based on its own needs.
Comments
Post a Comment