Interface Segregation Principle [ISP]
Clients should not be forced to dpend on methods they do not use. Prefar small cohesive interfaces to large interfaces.
What is an interface?
- C#/Java
interface
- public (or accessible) interface of a class
A type's interface in this context is whatever can be accessed by client code working with an instance of that class.
Detecting ISP violations
- interfaces with more than 5-10 methods
NotImplementedException
highlights methods that aren't being used.- code using a small subset of a larger interface
Can also apply ISP to domain modelling.
Multiple interface inheritance
Interfaces can inherit from multiple interface - this is useful for legacy code that relies on large interfaces. Can split the large interface into smaller interfaces and then recombine them back into a single interface.
Fixing ISP violations
Addressing large interfaces you don't control
- create small cohesive interfaces
- use the Adapter Design Pattern so your code can work with the Adapter.
Where do interfaces live in your application?
Client code should define and own the interfaces it uses. Interaces shouldn't be declared in the same place as the implementation as this affects the directionality of the dependencies by forcing your client to depend on the implementation.