Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Incorrect data in Constructor

I have a class

class Rational
{
   private int _n;
   private int _m;

   public Rational(int n, int m)
   {
      _n = n;
      _m = m;
   }
}

But m should be > 0. What should I do to notify user that he enter incorrect data to constructor?

like image 974
Sergey Gavruk Avatar asked Dec 06 '25 09:12

Sergey Gavruk


1 Answers

You could throw an ArgumentException or add a contract requiring m > 0

if(m <= 0) throw new ArgumentException("Denominator must be positive");

or

public Rational(int n, int m)
{
    Contract.Requires(m > 0);
    _n = n;
    _m = m;
}
like image 89
Lee Avatar answered Dec 08 '25 23:12

Lee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!