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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With