Sobes.tech
Senior

Какой принцип SOLID нарушен в текущей реализации, где сервис жёстко завязан на конкретной реализации хранилища (ArrayList)?

sobes.tech AI

Answer from AI

In this case, the Dependency Inversion principle (D from SOLID) is violated. This principle states that high-level modules should not depend on low-level modules directly, but both should depend on abstractions. If a service is tightly coupled to a specific storage implementation, such as ArrayList, then it depends on a concrete class rather than an interface or abstraction.

A correct approach is to define an interface for storage (for example, Repository or Storage), and use this interface in the service. This allows changing the storage implementation without modifying the service, increasing testability and code flexibility.

Example:

interface Storage<T> {
    void add(T item);
    T get(int index);
}

class ArrayListStorage<T> implements Storage<T> {
    private List<T> list = new ArrayList<>();
    public void add(T item) { list.add(item); }
    public T get(int index) { return list.get(index); }
}

class Service {
    private Storage<String> storage;
    public Service(Storage<String> storage) {
        this.storage = storage;
    }
    // use storage
}

Thus, the service depends on the Storage abstraction, not on the specific ArrayList.