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 ?
It will be better to use the static factory for this purposes. Because throwing an exception from a constructor is not very nice idea.
Yes. I suggest to throw an
Exception
from constructorEdit:
You can also use
IllegalArgumentException
as suggested by Till Helge HelwigConsider this example, this is java.util.HashMap implementation
see more in
Effective Java 2nd Edition, Item 38: Check parameters for validity
by Joshua Bloch, who is also the author of the above codeRather throw
Exception
if parameter is illegal.