SOLID & Design Patterns Interview Question #136
How do you decide whether an interface is necessary?
Anti-Patterns, Refactoring, DI Lifetimes & Senior Design Scenarios Senior Advanced
Quick Interview Answer
Create an interface when it represents a meaningful abstraction, multiple implementations are expected or present, a boundary must be inverted, or tests need to replace an external collaborator. Do not create interfaces mechanically for every class.
Detailed Explanation
Create an interface when it represents a meaningful abstraction, multiple implementations are expected or present, a boundary must be inverted, or tests need to replace an external collaborator. Do not create interfaces mechanically for every class.
An interface with one implementation can still be justified at an architectural boundary, but 'every class must have an interface' usually adds ceremony without improving design.
Code Example
// Valuable boundary
public interface IPaymentGateway
{
Task ChargeAsync(Money amount);
}
// A simple internal formatter may not
// need IFormatter merely for convention.