The effective java makes it clear that an assert
be used to verify parameters of a private function. If a method is a public method then the method should throw a NPE if a null is an invalid parameter.
Eg:
public void foo (Sting str) {
char[] ch = str.toCharArray();
}
In the code above, we dont need an explicit check to ensure str
is null, or not as null.toCharArray wil l throw the NPE
But what if the code changes to something like this:
public void foo (String str) {
List<String> strList = new ArrayList<String>();
bar (str, strList);
}
private void bar(String str, strList) {
assert strList != null;
char[] ch = str.toCharArray();
... ... ..
}
In such a code it falls on private function bar to throw a NPE. According to effective java a private code should only verify via an assert. Will the following code be considered a better practice than code above ?
public void foo (String str) {
if (str == null) throw NPE;
List<String> strList = new ArrayList<String>();
bar (str, strList);
}
private void bar(String str, strList) {
assert str != null;
assert strList != null;
char[] ch = str.toCharArray();
... ... ..
}