What are the best methods if you have a class that accepts some parameters but none of them are allowed to be null ?
The following is obvious, but the exception is a little non-specific:
public class SomeClass { public SomeClass(Object one, Object two) { if (one == null || two == null) { throw new IllegalArgumentException("Parameters can't be null"); }
Here the exceptions let you know which parameter is null, but the constructor is now pretty ugly:
public class SomeClass { public SomeClass(Object one, Object two) { if (one == null) { throw new IllegalArgumentException("one can't be null"); } if (two == null) { throw new IllegalArgumentException("two can't be null"); }
The constructor is more accurate here, but now the constructor code is actually not in the constructor:
public class SomeClass { public SomeClass(Object one, Object two) { setOne(one); setTwo(two); } public void setOne(Object one) { if (one == null) { throw new IllegalArgumentException("one can't be null"); }
Which of these styles is better?
Or is there an alternative that is more widely accepted?
java null constructor coding-style
Peter Jun 08 '10 at 13:39 2010-06-08 13:39
source share