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

后端 未结 4 1482
南笙
南笙 2020-12-17 15:13

In POJO Java beans such code can be beneficial, especially with collections:

class POJO {
    private Collection<         


        
4条回答
  •  醉酒成梦
    2020-12-17 15:45

    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 col  = new SomeCollection();
    
        public Collection getCol() {
            return col;
        }
    }
    

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

提交回复
热议问题