Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing instantiation of a class if argument to constructor is illegal?

Tags:

I have a public constructor which takes a parameter (int age) to create an object. I want to check if the passed parameter is legal or not, for example age cannot be negative. If its illegal, then don't create an object/instance. If legal, no problem.

I can only think of one way to do this -

Make constructor private. Create a static method with parameter (int age) to do all the checking and return a null if you pass it an illegal value. If you pass it a legal value, then create an object and return its reference. Is there any other way of doing it ? Maybe from inside the constructor itself ?

EDIT : I thought of one problem with the above method. The factory method/object creator method can only be a static method for obvious reasons. What happens if the factory method has to access a member variable (to do some checking) to create an object ? Then, we will be forced to make that member variable static. This may not be okay in all cases.

Does it make sense ?