Data validation in constructor
I have a constructor that need to validate passed data.
public Rational(int m, int n)
If n == 0
i should inform user about that.
1) Just make return;
in coustructor
r = new Rational();
r = Rational.GetObject(1,2);
What is the best way to validate data in constructor?
Considering you're dealing with an invalid argument being passed into the constructor, I would probably throw a new ArgumentException
from inside the constructor.
You should throw an ArgumentOutOfRangeException
in the constructor.
(Making sure to specify the parameter name in addition to the exception message)
In addition, you can also make a static TryCreate
method:
public static bool TryCreate(int m, int n, out Rational result);
or
public static Rational? TryCreate(int m, int m);
This method would return false
or null
if the parameters are invalid instead of throwing an exception; similarly to int.TryParse
.
Two things:
- Throw an
ArgumentOutOfRangeException
in the constructor. - Validate the value the user enters before calling the constructor and generate a suitable error message. The exception should be a last resort.
Generate an exception: you can't afford to let the user play with (create) an object that won't work.
I'd go with throwing an System.ArgumentException
from the constructor.
精彩评论