What's the best way to lazily initialize a collection, I'm specifically looking at Java. I've seen some people decide to do this in modification methods (which seems a bit yucky), as follows:
public void addApple(final Apple apple) {
if (this.apples == null) {
apples = new LinkedList<Apple>();
}
this.apples.add(apple);
}
You could refactor the initialization into a method and call it from add/delete/update etc... but it seems a bit yuck. It's often compounded by the fact that people also expose the collection itself via:
public Collection<Apple> getApples() {
return apples;
}
which breaks encapsulation and leads to people accessing the Collection directly.
The purpose for lazy initialization is purely performance related.
I'm curious to see what other peoples proposed approaches are for this. Any ideas?