To adhere to ISP, you can break down large interfaces into smaller, more specific ones. Here are a few examples to illustrate how you can apply ISP in C#.
Consider an interface that defines various methods for a printer.
public interface IPrinter
{
void Print(string content);
void Scan(string content);
void Fax(string content);
}
public class MultiFunctionPrinter : IPrinter
{
public void Print(string content)
{
// Print logic
}
public void Scan(string content)
{
// Scan logic
}
public void Fax(string content)
{
// Fax logic
}
}
public class SimplePrinter : IPrinter
{
public void Print(string content)
{
// Print logic
}
public void Scan(string content)
{
throw new NotImplementedException();
}
public void Fax(string content)
{
throw new NotImplementedException();
}
}
In this design, the SimplePrinter class is forced to implement Scan and Fax methods that it does not need, violating ISP.
public interface IPrinter
{
void Print(string content);
}
public interface IScanner
{
void Scan(string content);
}
public interface IFax
{
void Fax(string content);
}
public class MultiFunctionPrinter : IPrinter, IScanner, IFax
{
public void Print(string content)
{
// Print logic
}
public void Scan(string content)
{
// Scan logic
}
public void Fax(string content)
{
// Fax logic
}
}
public class SimplePrinter : IPrinter
{
public void Print(string content)
{
// Print logic
}
}
In this design, the SimplePrinter class only implements the IPrinter interface and is not forced to depend on methods it does not use. The MultiFunctionPrinter class implements all three interfaces, adhering to ISP.