Speaking of best practices to handle “nulls” in Java(especially “List” returns), is it a good practise to return “Collections.emptyList()” from an entity class’s getMethod? or should we keep the entity/data classes/methods neat and clean and always return whatever its value is(even its null) then handle that null somewhere else in the code, for example;
Class Reference{
private Reference reference;
@XmlElement(name = "Reference")
public List<Reference> getReference() {
if(reference==null){
return Collections.emptyList();
}
return reference;
}
public void setReference(List<Reference> reference) {
this.reference = reference;
}
}
Or better to handle that null “after” I use a basic get method?
EDIT/WARNING: just for my scenario I noticed this approach crashs my code I dont why, when I later call;
References ref= (References) jaxbUnmarshaller.unmarshal(xmlReader)
I get an unsupported operation exception, but works ok when I clean my getMethod from collections.emtpyList. So caution when using with a @XmlElement tag
It’s indeed good practice to return a non-null collection. It saves every caller from doing
So the above code is fine. But it would be even finer to disallow any null value in the
referencevariable. If you have a setter for the list, make it throw an exception if the passed list is null, or transform null into an empty collection. This way, even the code inside your class won’t have to bother with the reference variable being null.If you need to distinguish between null and empty list, consider using Guava’s
Optionalclass, which makes things much clearer.Just a note: since you have a list, the variable should be named
references(with a final s), and the accessors should be namedgetReferencesandsetReferences.