Sobes.tech
Senior

How to fix a violation of the dependency inversion principle — suggest a refactoring with the separation of a separate storage?

sobes.tech AI

Answer from AI

The violation of the Dependency Inversion Principle often manifests when high-level modules depend directly on low-level modules instead of abstractions.

To fix this, a separate storage interface should be defined and implemented in a separate class. Then, the high-level module will depend on the interface, not on the specific implementation.

Example in Java:

// Storage interface
public interface UserRepository {
    User findById(String id);
    void save(User user);
}

// Storage implementation
public class UserRepositoryImpl implements UserRepository {
    // implementation of database access methods
}

// Service depending on abstraction
public class UserService {
    private final UserRepository userRepository;

    public UserService(UserRepository userRepository) {
        this.userRepository = userRepository;
    }

    public User getUser(String id) {
        return userRepository.findById(id);
    }
}

This refactoring allows changing the storage implementation without modifying business logic and simplifies testing through dependency substitution.