Junior — Middle
What is the significance of following the dependency inversion principle when designing modular systems?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is important for creating flexible and easily maintainable modular systems. It states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions (such as interfaces or abstract classes). This allows:
- Isolating changes — changing the implementation of one module does not lead to changes in others.
- Facilitating testing — dependencies can be replaced with mocks.
- Increasing code reusability — abstractions allow for different implementations.
In Python, this is often implemented using abstract base classes (ABC) or protocols from the typing module.
Example:
from abc import ABC, abstractmethod
class Storage(ABC):
@abstractmethod
def save(self, data):
pass
class FileStorage(Storage):
def save(self, data):
with open('data.txt', 'w') as f:
f.write(data)
class DataProcessor:
def __init__(self, storage: Storage):
self.storage = storage
def process(self, data):
# data processing
self.storage.save(data)
# Now, DataProcessor depends on the abstraction Storage, not on a specific implementation
processor = DataProcessor(FileStorage())
processor.process('sample data')