What is the Interface Segregation Principle?
Quick Answer
No client should be forced to depend on methods it doesn't use. Prefer several small, focused (“role”) interfaces over one large one. A class implementing IRepository with 15 methods when it only needs 2 — or with methods that throw NotImplementedException — is the smell.
Interface Segregation says a client shouldn't have to depend on parts of an interface it doesn't use. So instead of one big IRepository with every CRUD method plus reporting queries, I'd have IReadRepository and IWriteRepository, and a service that only reads depends on just the read one. The smell is a class implementing an interface where half the methods throw “not implemented.” Smaller interfaces are easier to implement and mock. The balance is not to go so far that you've got fifty one-method interfaces — you segregate by the role the client plays.
- Split
IRepositoryintoIReadRepositoryandIWriteRepository; a read-only service depends only on the first. - Small interfaces are easier to implement, mock in tests, and reason about.
- Connects to LSP: a class forced to implement methods it can't support often ends up throwing, which breaks substitutability.
- Don't shatter interfaces so far that you have dozens of single-method contracts with no cohesion — segregate by client role, not by method count.