In POJO Java beans such code can be beneficial, especially with collections:
class POJO {
private Collection<X> col;
public Collection<X> getCol() {
if (col == null)
col = new SomeCollection<X>();
return col;
}
}
It makes possible for the code using POJO to call pojo.getCol().isEmpty() without an additional null check, thus making the code clearer.
Suppose the POJO class is a JPA entity, is it still safe to do that? By initializing the collection from null to an empty one the persistent data won’t be changed, but still, we are modifying the object and thus the persistence provider may run some side effects upon flushing the persistence context. What do we risk? Portability maybe?
I would strongly discourage lazy initialization for properties in an ORM entity.
We had a serious issue when doing lazy initialization of an entity property using Hibernate, so I would strongly discourage it. The problem we saw was manifest by a save taking place when we were issuing a search request. This is because when the object was loaded the property was null, but when the getter was called it would return the lazy initialized object so hibernate (rightly) considered the object dirty and would save it before issuing the search.