Skip to main content

Give an example of an ISP violation

An example of an ISP violation occurs when a single interface forces different classes to implement methods they do not need. A classic example is a "multi-function printer" device.


A "fat" interface - an ISP violation

python
class IMultiFunctionDevice: def print(self, document): pass def scan(self, document): pass def fax(self, document): pass

The problem

Any class that implements this interface must support all three methods, even if it only needs one or two of them.


An implementation that violates ISP

python
class SimplePrinter(IMultiFunctionDevice): def print(self, document): print("Printing document") def scan(self, document): raise NotImplementedError("This printer cannot scan") def fax(self, document): raise NotImplementedError("This printer cannot send faxes")

Why this is an ISP violation:

  1. The class is forced to implement methods it does not need SimplePrinter can neither scan nor send faxes, but the interface forces it to have these methods.
  2. Unnecessary dependencies A client that only needs printing now depends on an interface containing scan and fax methods.
  3. Changing the interface breaks the system If a new method is added, for example copy(), every implementation has to be changed, even those that do not need copying.
  4. Empty and "harmful" methods The scan() and fax() methods in the class are essentially useless stubs and lead to errors when called.

Summary

IMultiFunctionDevice is a typical "fat" interface. SimplePrinter violates ISP because it is forced to support functionality it does not need, which leads to a fragile and inflexible design.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.