I have a POJO class, say Foo, which has a Set of other entity instances, say bars.
Also there are standart misc classes for such project: service and dao for both Foo and Bar.
I want BarService to get the Set of Bar instances associated with some Foo. Now I have the following code, wich I believe is conceptually bad.
public class Foo {
Set<Bar> bars;
public Set<Bar> getBars() {
if (bars == null)
return ( bars = new HashSet() );
return bars;
}
}
public class BarServiceImpl {
public List<Bar> getListOfBars(Foo foo) {
return new ArrayList(foo.getBars());
}
}
3 questions:
Where it is better to initialize Foo’s Set?
What specific Sets and Lists are better for such purposes?
What conceptual issues has my current implementation, and how to do better?
Thanks in advance.
Most of time, I initialize a collections when declaring it, which is what Hibernate recommends. Quoting the documentation:
If leaving it
nullis part of your business, my suggestion would be to initialize it in a (common) link management methods:It all depends on the semantics you need. A
Setdoesn’t allow duplicates, aListallows duplicates and introduces positional indexing.nullat that point, let it benull.foo.getBars()?