-6
interface IRepository {
  Data getData();
}

class BaseRepository implements IRepository {
  public Data getData() {
    ...
  }
}

class CacheRepository implements IRepository {
  private final IRepository mRepository;
  private final ICache mCache;

  public CacheRepository(IRepository repository, ICache cache) {
    mRepository = repository;
    mCache = cache;
  }

  public Data getData() {
    Data data = cache.getData();

    if (data == null)
      data = mRepository.getData();

    mCache.setData(data);
  }
}

The CacheRepository does two things, uses cache and gets data. How to improve it?

gnat
  • 21,442
  • 29
  • 112
  • 288

2 Answers2

3

You improve your life by using common sense.

"Single responsibility" means responsibility for one related set of things. Like the caretaker at a school has the single responsibility for taking care of the school, which consists of gazillions of little things.

Do you see anything bad with this cache apart from your perceived violation of a rule? This class has the single responsibility of delivering data. Caching is an implementation detail.

gnasher729
  • 42,090
  • 4
  • 59
  • 119
0

I think this fulfills SRP by virtue of its one public method

public Data getData();

How it does this (by collaboration between a cache and a repository) doesn't seem unreasonable. Neither are exposed publicly via the CacheRepository interface. You might argue that calling it a CacheRepository in some sense exposes its functionality. I wouldn't but would probably pass references to this as an IRepository - the caching would be a performance enhancement and in most cases of little concern to the client code in terms of functionality.

Brian Agnew
  • 4,676
  • 24
  • 19