Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for validating values provided to a constructor?

Tags:

java

Context: I am writing a semaphore class for school, and one of the requirements is that it may not be initialized with a negative value.

Right now my constructor throws an exception:

/**
 * Constructor
 */
public Semaphore(int value) throws Exception
{   
    if (value < 0)
        throw new Exception("Negative value provided for initial constructor.");
    this.value = value;
}

Handling an exception in order to instantiate a semaphore seems overly heavy to me, so I am considering quietly setting any negative values to zero, ie:

/**
 * Constructor
 */
public Semaphore(int value) 
{   
    if (value < 0)
        this.value = 0;
    else
        this.value = value;
}
like image 760
sfyn Avatar asked Nov 17 '25 22:11

sfyn


2 Answers

You should use the IllegalArgumentException instead. It requires no explicit exception handling and it behaves exactly like you want, that is to signal an illegal argument.

like image 84
Alexis Leclerc Avatar answered Nov 20 '25 12:11

Alexis Leclerc


If you say: Hey, the values are directly from the user. Correct them with a message.

If you say: Hey, the values are generated and a bug produced a negative value.

throw new IllegalArgumentException("Negative Value",
    new IndexOutOfBoundsException(value+""));

If you say: Hey, i like to let the VM decide to throw or correct. Use assert value > 0;.

like image 32
Grim Avatar answered Nov 20 '25 11:11

Grim



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!