I just recently started looking into exceptions and best practices for their use and I wonder what is the correct way of doing this:
Suppose there is a method with multiple arguments. And there are multiple overloads for this method with less parameters, which call the main implementation by providing default values.
Do I validate all arguments in every overload?
public string Translate(string text)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentNullException();
return Translate(text, "english");
}
public string Translate(string text, string language)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentNullException();
// Do the rest of the work
// ...
}
Do I rethrow the exceptions?
public string Translate(string text)
{
try
{
return Translate(text, "english");
}
catch
{
throw;
}
}
public string Translate(string text, string language)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentNullException();
// Do the rest of the work
// ...
}
Or do I completely drop exceptions and try/catch blocks in the overload?
public string Translate(string text)
{
return Translate(text, "english");
}
public string Translate(string text, string language)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentNullException();
// Do the rest of the work
// ...
}
Also, how would the documentation of the two methods look like?
(Using C# XML comments. Especially where I put the <exception> elements.)
I do realize that this is a minor topic, still, I keep wondering everytime I encounter this kind of situation (which is actually quite often).
Optional arguments solves this in a way, then you have only one method:
There are some quirks with optional arguments that are good to know about.