initialization block vs constructor vs variable initialization
hibernate, java, spring
Solution
private Set<OherClass> others;
{
if (others == null)
others = new HashSet<OtherClass>();
}
The above code was written without an understanding of Java semantics. `others == null` will always be `true`. Therefore this is nothing but a very convoluted and confused way of writing
private Set<OherClass> others = new HashSet<OtherClass>();
Hibernate will indeed wrap some "magic" around the object construction, but it will still need to obtain an instance from the default constructor. At that point all the instance initializers have run.
On a more general note, always prefer to immediately initialize collection-valued variables with constant expressions and, even better, make the field `final`. That's one less worry for the rest of your code.
With the above you still have all the options open on how to populate the set, which can differ from constructor to constructor.
Problem
I'm trying to clean the code of a class that use initialization bloks in a manner I would never do, and I'm just wondering if I am missing some informations. The code looks like this: ``` @Entity class MyClass extends BaseClass { @ManyToMany(fetch=FetchType.EAGER) private Set<OherClass> others; { if (others == null) others = new HashSet<OtherClass>(); } public MyClass(){ super(); } //getters, setters and other stuff follows } ``` I think there is no reason to prefer the above code against this: ``` @Entity class MyClass extends BaseClass { @ManyToMany(fetch=FetchType.EAGER) private Set<OherClass> others = new HashSet<OtherClass>(); } ``` Or this: ``` @Entity class MyClass extends BaseClass { @ManyToMany(fetch=FetchType.EAGER) private Set<OherClass> others; public MyClass(){ this.others = new HashSet<OtherClass>(); } } ``` I asked my college, but the only thing he was able to answer is how initialization block works and other things I already know. I wonder if there are some subtle misbehaviour of java (even old one already fixed) or frameworks (hibernate, spring) in case of serialization, reflection, database persistence, injection or any unusual situation that could make that code necessary.