Junior — Middle
What approaches and techniques ensure adherence to the dependency inversion principle in system design?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle in system design is achieved through the following approaches and techniques:
- Using abstractions instead of concrete implementations. Classes should depend on interfaces or abstract classes, not on concrete classes.
- Dependency Injection. Dependencies are passed into a class from outside (via constructor, properties, or methods), rather than being created inside it.
- Inversion of Control (IoC). Control over object creation and binding is delegated to an external container or framework.
Example in C# with dependency injection:
public interface ILogger
{
void Log(string message);
}
public class ConsoleLogger : ILogger
{
public void Log(string message) => Console.WriteLine(message);
}
public class UserService
{
private readonly ILogger _logger;
public UserService(ILogger logger)
{
_logger = logger; // dependency is passed from outside
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
This approach facilitates testing, extensibility, and code maintenance.