开发者

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.

I know 3 ways to do that.

1) Just make return; in coustructor

2) Generate an exception

3) Cre开发者_如何学Goate a static method that will create an object

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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜