Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Collections.emptyList() and null handling

Tags:

java

null

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

like image 868
Spring Avatar asked Nov 01 '12 12:11

Spring


2 Answers

In general, null and "empty" can have different semantics: null means "it's not there", while "empty" means "it's there, but there's nothing in it".

If your class is such that there is no semantic difference between "not there" and "empty", then returning an empty collection is better: it saves an if statement in all of your callers, making their code look cleaner. Moreover, in this case I would initially set this.reference to Collections.emptyList(), and removed an if from the getter. Of course in this case your setter would need to null-check its argument.

like image 153
Sergey Kalinichenko Avatar answered Nov 13 '22 18:11

Sergey Kalinichenko


In my experience "Programming by contract" or "Design by contract" (Link) is used when coding Java.
This means, in your example, that if your reference is not set by an outer entity then you simply return a null.

like image 3
Strike Avatar answered Nov 13 '22 19:11

Strike