Question

Suppose I have created interface IFolderRepository with methods like that:

IEnumerable<Folder> GetAllFolders();
Folder GetFolderWithId(int id);
void AddFolder(Folder newFolder);
void ModifyFolder(Folder folderToModify, Folder folderAfterModification);
void RemoveFolder(Folder folderToRemove);

and I've implemented DatabaseFolderRepository and lets say CacheFolderRepositoryDecorator. Now 'hundreds of lines later' I'd like to add SkyDrive folders functionallity so I'm ready to add SkyDriveFolderRepository. Unfortunately while DatabaseFolderRepository implementation used synchronous methods to talk with database, skydrive one uses a lot of async and await. What to do in such case? In case of void methods marking it async is not a solution (need to exception handling). Should I change interface to return Task<T>? Sure it will work in above example but they're just 2 interface implementation classes. Or should most of my interfaces have Task return types (against you aren't gonna need it rule)?

Was it helpful?

Solution

You will probably find this MSDN article about Asynchronous practices to be a good read.

You asked:

Unfortunately while DatabaseFolderRepository implementation used synchronous methods to talk with database, skydrive one uses a lot of async and await.

This is where the sub-section Async All the Way in the MSDN article I linked will be pertinent to your situation.

In particular, it’s usually a bad idea to block on async code by calling Task.Wait or Task.Result. This is an especially common problem for programmers who are “dipping their toes” into asynchronous programming, converting just a small part of their application and wrapping it in a synchronous API so the rest of the application is isolated from the changes. Unfortunately, they run into problems with deadlocks.

Since you have at least one interface that needs to be asynchronous, YAGNI is reversed. You are gonna need to make changes so that your interfaces are consistent. Yes, it will create more effort up front for you. But the benefit is less risk of deadlock; less complex debugging; and more predictable blocking (when it actually needs to occur).

I'm skipping over some of the other questions you asked as I think I addressed the core of your question. Deal with the core and the rest of your questions fall away. The article is fairly involved and addresses the other points you brought up as well as pointing out additional pitfalls.

Asynchronous programming is one of those where you have to embrace the whole concept and just go with it. Trying to just "dip your toes in" on a piecemeal basis ends up being a lot more complicated then just jumping straight in.

Licensed under: CC-BY-SA with attribution
scroll top