3

Suppose I have a program that returns data from an API. If its cache of the data is too old, the program downloads more data from the API, caches it, and outputs the new data. Else, the program outputs the cached data.

Should the function that downloads the data be separate from the function that caches the data? Should the function that caches the data be separate from the function that returns the data?

1
  • yes single responsibility. perhaps you could elaborate on where you see a conflict of interest or problem?
    – Ewan
    May 16, 2022 at 22:12

2 Answers 2

10

The SRP is first and foremost a principle for classes and/or modules, not for functions. Hence it is debatable if your case really applies to the SRP. My recommendation here is: do yourself a favor and stop thinking in terms like "how do I follow this principle" - better think in terms like "what makes most sense for my case".

In this case, in can perfectly make sense to have

  • one function that downloads data
  • a second function which caches the downloaded data
  • a third function which tests if the cache data is "too old"
  • and a fourth function which just calls the other three, coordinates them and returns either the cached or the downloaded data (this might also be the public entry point, whilst the other functions stay private)

But for deciding if that's a useful structure, I personally would prefer to look at the real code, not make some hypothetical discussion.

1
  • "what would make this easily testable?" is a good question to ask yourself too
    – igrossiter
    May 23, 2022 at 7:51
-1

So, StackExchange's own single-responsibility tag helped clarify the single-responsibility principle: Wherever I can logically decouple the tasks to be performed, those tasks should be their own functions.

In this example, caching the data and retrieving the cached data are separate, relatively independent, tasks and should probably be separate functions.

3
  • As a user of the code, I don't care about caching - I just want the data, and I want it fast. There is no way I should ever have to call a function specifically for caching.
    – gnasher729
    May 16, 2022 at 23:26
  • 1
    @gnasher729 But having a separate function dedicated to a self contained task does not mean that you, as a user of the data retrieval service/component that utilizes it, will have to call (or know about) that function. May 17, 2022 at 1:47
  • If it is public, I need to know it because other code could call it.
    – gnasher729
    May 17, 2022 at 7:18

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.