I have a class that runs as a service and returns html code of a website when supplied with a URL.
The code:
public interface IHtmlDownloader
{
IWebProxy Proxy { get; set; }
string UserAgent { get; set; }
string GetHtml(string url)
}
public class HtmlDownloader : IHtmlDownloader
{
WebClient _client;
public IWebProxy Proxy
{
get { return _client.Proxy; }
set { _client.Proxy = value; }
}
public string UserAgent
{
get
{ return _client.Headers[HttpRequestHeader.UserAgent].ToString(); }
set
{ _client.Headers[HttpRequestHeader.UserAgent] = value; }
}
public HtmlDownloder()
{
_client = new WebClient();
}
public string GetHtml(string url)
{
this.CheckValidity(url);
var htmlOfWebsite = _client.DownloadString(url);
return htmlOfWebsite;
}
}
Now I am not sure how exactly I should validate the URL. I know that it should not be null or whitespace or anything else, but should I validate that it is indeed a properly built URL?
Doing so would result in a method which would perform the validation. I could simply create a public static method inside HtmlDownloader
so that the caller can validate the URL, or maybe even not a static one (GetUrl(string url)
is after all called after the object has been instantiated), but it would be wrong for at least two reasons:
- It would be a validator applicable in so many places, and it should be available to other classes.
- I can't contract a static method with an interface.
Furthermore, it shouldn't be made static, but rather a service, so I could unit test HtmlDownloader
(service would be injected through the constructor).
All of those ideas are quite dreadful and I am starting to think, that I shouldn't validate anything, but simply create a try/catch
block that would catch the proper exception and then throw a UrlNotFoundException with the original exception supplied through InnerException.
Still, it would be nice to check for the validity of the URL. But to whom and how? Should the caller be injected with the proper service? But then, what if the URL is generated higher than the caller and the caller simply passes it on to the HtmlDownloader? Where should I validate the URL? Or is the simple fact that the URL have to passed through a few levels a code smell?
mailto:
toftp:
to a local destination. Since I want to be sure that it's ahttp:
orhttps:
Uri.