Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
347 views
in Technique[技术] by (71.8m points)

java - Is it good practice to initialize fields inside a JPA entity getter?

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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I do not see it as a good practice, more as some very rarely needed optimization. Maybe lazy initialization can make sense if SomeCollection is extremely heavy to create. Instead you can initialize it when declared (code is cleaner at least for my eyes):

class POJO {
    private Collection<X> col  = new SomeCollection<X>();

    public Collection<X> getCol() {
        return col;
    }
}

There is no side effects in flush or portability issues and you have one null check less.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...