Junior — Middle
What is the main reason for applying the dependency inversion principle in software architecture?
sobes.tech AI
Answer from AI
The Dependency Inversion Principle (DIP) is used to reduce coupling between system components and to increase its flexibility and testability.
The main reason for applying DIP is to make high-level modules independent of low-level modules, by making both depend on abstractions (interfaces), rather than on concrete implementations. This allows for easy replacement of implementations, simplifies maintenance, and enhances code extensibility.
Example in C#:
public interface ILogger
{
void Log(string message);
}
public class FileLogger : ILogger
{
public void Log(string message) { /* write to file */ }
}
public class UserService
{
private readonly ILogger _logger;
public UserService(ILogger logger)
{
_logger = logger; // dependency through abstraction
}
public void CreateUser(string name)
{
// user creation logic
_logger.Log($"User {name} created.");
}
}
Here, UserService depends on the ILogger interface, not on the specific implementation FileLogger. This makes it easier to replace the logger, for example, with a DatabaseLogger, without changes to UserService.