Sobes.tech
Middle

Are you familiar with SOLID principles? Tell me about the Dependency Inversion Principle (DIP).

sobes.tech AI

Answer from AI

The Dependency Inversion Principle (DIP) is one of the five SOLID principles. It states:

  • High-level modules should not depend on low-level modules. Both should depend on abstractions.
  • Abstractions should not depend on details. Details should depend on abstractions.

This helps reduce coupling and increase flexibility of the code.

For example, in a frontend application, instead of a component directly creating an instance of a service, it receives it through an interface or dependency injection. This allows easy swapping of the service implementation without changing the component.

interface IDataService {
  fetchData(): Promise<string[]>;
}

class ApiService implements IDataService {
  fetchData() {
    return fetch('/api/data').then(res => res.json());
  }
}

class Component {
  constructor(private dataService: IDataService) {}

  async render() {
    const data = await this.dataService.fetchData();
    console.log(data);
  }
}

const service = new ApiService();
const component = new Component(service);
component.render();

This approach facilitates testing (you can substitute a mock), improves support, and enhances code extendability.

Are you familiar with SOLID principles? Tell me about… - sobes.tech