For example,
public class Test {
Test() {
if(xxx)//do some check here
//reject instancing class test.
}
}
I think I can throw a exception to reject it, is there any other way? I am not sure what's the effect of instancing been rejected, but I think a natural way is:
Test test = new Test();//return null here indicating instancing rejected.
I expect java and C++ all should have this "reject" feature.
If you want to return null you could get use of Factory pattern. E.g. instead of Test test = new Test(); you could write Test test = TestFactory.CreateTest();, and implement all the checks you need in TestFactory.CreateTest.
new Test() always returns a non-null instance of Test (at least in Java).
You can't return null from a constructor, but you can (as you suggest) throw an exception.
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