I'm trying to figure out how this would be done in practice, so as not to violate the Open Closed principle.
Say I have a class called HttpFileDownloader that has one function that takes a url and downloads a file returning the html as a string. This class implements an IFileDownloader interface which just has the one function. So all over my code I have references to the IFileDownloader interface and I have my IoC container returning an instance of HttpFileDownloader whenever an IFileDownloader is Resolved.
Then after some use, it becomes clear that occasionally the server is too busy at the time and an exception is thrown. I decide that to get around this, I'm going to auto-retry 3 times if I get an exception, and wait 5 seconds in between each retry.
So I create HttpFileDownloaderRetrier which has one function that uses HttpFileDownloader in a for loop with max 3 loops, and a 5 second wait between each loop. So that I can test the "retry" and "wait" abilities of the HttpFileDownloadRetrier I have the HttpFileDownloader dependency injected by having the HttpFileDownloaderRetrier constructor take an IFileDownloader.
So now I want all Resolving of IFileDownloader to return the HttpFileDownloaderRetrier. But if I do that, then HttpFileDownloadRetrier's IFileDownloader dependency will get an instance of itself and not of HttpFileDownloader.
So I can see that I could create a new interface for HttpFileDownloader called IFileDownloaderNoRetry, and change HttpFileDownloader to implement that. But that means I'm changing HttpFileDownloader, which violates Open Closed.
Or I could implement a new interface for HttpFileDownloaderRetrier called IFileDownloaderRetrier, and then change all my other code to refer to that instead of IFileDownloader. But again, I'm now violating Open Closed in all my other code.
So what am I missing here? How do I wrap an existing implementation (downloading) with a new layer of implementation (retrying and waiting) without changing existing code?
Here's some code if it helps:
public interface IFileDownloader
{
string Download(string url);
}
public class HttpFileDownloader : IFileDownloader
{
public string Download(string url)
{
//Cut for brevity - downloads file here returns as string
return html;
}
}
public class HttpFileDownloaderRetrier : IFileDownloader
{
IFileDownloader fileDownloader;
public HttpFileDownloaderRetrier(IFileDownloader fileDownloader)
{
this.fileDownloader = fileDownloader;
}
public string Download(string url)
{
Exception lastException = null;
//try 3 shots of pulling a bad URL. And wait 5 seconds after each failed attempt.
for (int i = 0; i < 3; i++)
{
try { fileDownloader.Download(url); }
catch (Exception ex) { lastException = ex; }
Utilities.WaitForXSeconds(5);
}
throw lastException;
}
}