What is the best practice for constructor parameter validation? Suppose a simple
ID: 642689 • Letter: W
Question
What is the best practice for constructor parameter validation?
Suppose a simple bit of C#:
public class MyClass
{
public MyClass(string text)
{
if (String.IsNullOrEmpty(text))
throw new ArgumentException("Text cannot be empty");
// continue with normal construction
}
}
Would it be acceptable to throw an exception?
The alternative I encountered was pre-validation, before instantiating:
public class CallingClass
{
public MyClass MakeMyClass(string text)
{
if (String.IsNullOrEmpty(text))
{
MessageBox.Show("Text cannot be empty");
return null;
}
else
{
return new MyClass(text);
}
}
}
Explanation / Answer
I tend to perform all of my validation in the constructor. This is a must because I almost always create immutable objects. For your specific case I think this is acceptable.
if (string.IsNullOrEmpty(text))
throw new ArgumentException("message", "text");
If you are using .NET 4 you can do this. Of course this depends on whether you consider a string that contains only white space to be invalid.
if (string.IsNullOrWhiteSpace(text))
throw new ArgumentException("message", "text");
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.