Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Should you check for wrong parameter values in the constructor?

Do you check for data validity in every constructor, or do you just assume the data is correct and throw exceptions in the specific function that has a problem with the parameter?

like image 750
Yossale Avatar asked Apr 02 '09 12:04

Yossale


2 Answers

A constructor is a function too - why differentiate?

Creating an object implies that all the integrity checks have been done. It's perfectly reasonable to check parameters in a constructor and throw an exception once an illegal value has been detected.

Among all this simplifies debugging. When your program throws exception in a constructor you can observe a stack trace and often immediately see the cause. If you delay the check you'll then have to do more investigation to detect what earlier event causes the current error.

like image 156
sharptooth Avatar answered Oct 14 '22 00:10

sharptooth


It's always better to have a fully-constructed object with all the invariants "satisfied" from the very beginning. Beware, however, of throwing exceptions from constructor in non-managed languages since that may result in a memory leak.

like image 35
Anton Gogolev Avatar answered Oct 14 '22 00:10

Anton Gogolev