Sergey Gavruk
Sergey Gavruk

Reputation: 3568

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) Create 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?

Upvotes: 3

Views: 2759

Answers (5)

Justin Niessner
Justin Niessner

Reputation: 245489

Considering you're dealing with an invalid argument being passed into the constructor, I would probably throw a new ArgumentException from inside the constructor.

Upvotes: 8

naacal
naacal

Reputation: 620

I'd go with throwing an System.ArgumentException from the constructor.

Upvotes: 0

SLaks
SLaks

Reputation: 888205

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.

Upvotes: 2

Mark Byers
Mark Byers

Reputation: 839144

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.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 755044

Generate an exception: you can't afford to let the user play with (create) an object that won't work.

Upvotes: 1

Related Questions