Junior — Middle
What is meant by the term inversion in the dependency inversion pattern?
sobes.tech AI
Answer from AI
The term "inversion" in the dependency inversion pattern refers to changing the direction of dependency between modules or components. Instead of high-level modules depending on low-level ones, dependencies are "reversed": both high-level and low-level modules depend on abstractions (such as interfaces), rather than directly on each other.
This reduces component coupling and increases code flexibility. Abstractions manage dependencies, and concrete implementations are injected from outside (for example, through constructors or dependency injection containers).
Example in Python:
from abc import ABC, abstractmethod
class Database(ABC):
@abstractmethod
def save(self, data):
pass
class MySQLDatabase(Database):
def save(self, data):
print(f"Saving {data} to MySQL")
class Service:
def __init__(self, db: Database):
self.db = db
def process(self, data):
self.db.save(data)
# Dependency inversion: Service depends on the abstraction Database, not on a specific implementation
mysql_db = MySQLDatabase()
service = Service(mysql_db)
service.process('data')