Middle
Tell me about the Dependency Inversion principle (DIP) from SOLID with an example.
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) from SOLID states that high-level modules should not depend on low-level modules directly. Instead, both should depend on abstractions (e.g., interfaces). Abstractions should not depend on details, but details should depend on abstractions.
Example in frontend: suppose we have a component that sends data to a server. Instead of directly using a specific HTTP client, we create an IDataSender interface and implement it in different ways (e.g., via fetch or axios). The component depends on the interface, not on the specific implementation.
interface IDataSender {
send(data: any): Promise<void>;
}
class FetchSender implements IDataSender {
async send(data: any) {
await fetch('/api', { method: 'POST', body: JSON.stringify(data) });
}
}
class Component {
constructor(private sender: IDataSender) {}
async save(data: any) {
await this.sender.send(data);
}
}
// Usage
const sender = new FetchSender();
const component = new Component(sender);
component.save({ name: 'Test' });
This way, we can change the sending implementation without modifying the component, which makes testing and maintenance easier.