In the Dependency Inversion Principle, who should own the interface: the high-level or the low-level module?
The high-level module. It declares the interface in terms of what it needs, and low-level modules implement it. That is what inverts the dependency direction.
Explain it simply
A company that needs couriers writes a requirement: "pick-up, deliver, give a receipt". Any courier service can then apply. If the courier firm defines its own rules and the company must follow them, the company is now dependent on the courier.
In code, if the interface sits next to SmsGateway, your business logic still depends on the gateway's package. If it sits next to the business logic, the gateway depends on the business logic's contract.
Example
Without inversion:
orders (high-level) ---> smsgateway (low-level)
With inversion:
orders (high-level) owns interface OrderNotifier
smsgateway (low-level) implements OrderNotifier
orders <--- smsgateway (arrow now points toward the business code)// in package orders
public interface OrderNotifier { void orderPlaced(String orderId); }
// in package smsgateway
public class SmsNotifier implements OrderNotifier {
public void orderPlaced(String orderId) { /* call vendor API */ }
}Swapping the SMS vendor changes only smsgateway. Nothing in orders is recompiled or edited.
What to say in the interview
"The high-level policy module owns the abstraction, shaped around its own needs. Low-level details depend on it by implementing it. That reverses the usual source-code dependency direction, which is why it is called inversion."
Common mistakes
- Placing the interface in the low-level library and calling it DIP.