Junior — Middle
What is the purpose of the dependency inversion principle in software development?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle states that high-level modules should not depend on low-level modules; both should depend on abstractions. Abstractions should not depend on details, but details should depend on abstractions. This reduces the coupling between components, increases flexibility, and makes testing easier.
For example, instead of a class directly creating an instance of a specific class, it depends on an interface, and the specific implementation is provided externally (via constructor or setter):
from abc import ABC, abstractmethod
class IDataFetcher(ABC):
@abstractmethod
def fetch(self):
pass
class ApiFetcher(IDataFetcher):
def fetch(self):
return "data from API"
class DataProcessor:
def __init__(self, fetcher: IDataFetcher):
self.fetcher = fetcher
def process(self):
data = self.fetcher.fetch()
print(f"Processing {data}")
fetcher = ApiFetcher()
processor = DataProcessor(fetcher)
processor.process()
This approach makes it easier to replace implementations and test with mocks.