Junior — Middle
Explain the relationship between dependency injection principles and inversion of control in programming.
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is one of the five SOLID principles, which states that:
- High-level modules should not depend on low-level modules.
- Both should depend on abstractions.
- Abstractions should not depend on details, and details should depend on abstractions.
Dependency Injection (DI) is a specific way to implement the Dependency Inversion Principle. DI means that an object's dependencies are provided to it from outside (for example, through a constructor, setter, or interface), rather than being created inside the object.
Thus, the relationship:
- DIP is an architectural principle that sets the rule for how dependencies between modules are constructed.
- DI is a pattern or technique that helps implement DIP in practice, making it easier to replace dependencies and improve code testability.
Example in Python:
class Database:
def query(self):
pass
class MySQLDatabase(Database):
def query(self):
print("Querying MySQL")
class Service:
def __init__(self, db: Database): # Dependency injection via constructor
self.db = db
def do_something(self):
self.db.query()
mysql_db = MySQLDatabase()
service = Service(mysql_db) # Dependency injection
service.do_something()