views:

94

answers:

3

Ok, lets say i have a DataRepository class with the methods, getNames() and getStates(). lets say this data is stored in a webservice or database that is an expensive operation.

once the first query is run and returned, when a consumer asked for these methods its returned immediately as the results are cached in the DataRepository class.

the issue is, for the first call you would want to behavior to be async to avoid blocking on this expensive call. What is the best way to code this? Is the fact that this DataRepository class is doing both actual cross boundry retrieving and caching breaking Single Respnosibility Principle.

any other thoughts on best practices here?

+1  A: 

Is it really the repository's responsibility of knowing if it is getting called async or not? I would think it would just make its call and return its data, how it is getting called is not its care. I also dont think it is its responsibility to store the data....if you want the data stored, the caller (some intermediary possibly) can store it. The repository should be pretty simple....ask for data and return data. Or even return IQueryable and let the piece that needs the data actually get the data...

CSharpAtl
A: 

If you have to make the first call async, you may as well make all calls async. This will make your code easier to write and understand. You won't have to deal with 2 different call patters.

The data repository should be responsible for one thing: Getting the data to the user. It retrieves the data from a data store. That data store could be the expensive call to WS or DB or the cheap call from cache. The data repository can check for the existence of the data in the cache and return that or get the data from the WS or DB, put it in the cache and then return it.

Matthew
+1  A: 

for the first call you would want to behavior to be async to avoid blocking on this expensive call. What is the best way to code this?

That's a caller's concern. It's best to provide both synchronous and asynchronous interfaces so clients can decide which is appropriate for their situtation.

Is the fact that this DataRepository class is doing both actual cross boundry retrieving and caching breaking Single Responsibility Principle.

Yes it breaks the SRP if the repository class itself is involved in the retrieval and caching implementation. What's more, the decision about which source to hit usually requires significant logic, which is another good reason to separate these functions into different classes. (With the standard caveat: if YAGNI, then don't do it!)

Jeff Sternal