Instanciate a list VS proxy list VS check null reference?
<p>I code in java but I think this question is not related to only one language.</p>

<p>My question occurs when we were talking with a colleague about List of object which is a field of a class. I was saying that I always initialize List with and empty list. So I can use the getter of this list directly without checking if it is null like this : </p>

<pre><code>myObject.getList().add(o)
</code></pre>

<p>He says me he prefers to not create a getter to the list because he don't want to check if the list is null or not and so he creates a "addItemToMyList" method to add an item to the list. This way, he can control inside this method that the list is not null (and create it if this is the case) and there is no doubt about using the list this way.</p>

<p>I think that it can be a lot of work to write a lot of methods for each list we use (get the size, add, remove...).</p>

<p><strong>Summary :</strong></p>

<hr>

<h2>Case 1 : Always initialize field</h2>

<p><strong>Class :</strong> </p>

<pre><code>class MyObject {
  private List&lt;X&gt; list = new ArrayList&lt;X&gt;();

  public List&lt;X&gt; getList() { return list; }
}
</code></pre>

<p><strong>Usage :</strong> </p>

<pre><code>MyObject myObj = new MyObject();
myObj.getList().add(anObject);
</code></pre>

<hr>

<h2>VS Case 2 : proxy list</h2>

<p><strong>Class :</strong> </p>

<pre><code>class MyObject {
  private List&lt;X&gt; list;

  public void addItemToList(X item) { 
    if (list == null) list = new ArrayList&lt;X&gt;();
    list.add(item);
  }

  ... // methods to get the size, remove item...

}
</code></pre>

<p><strong>Usage :</strong> </p>

<pre><code>MyObject obj = new MyObject();
obj.addItemToList(anObject);
</code></pre>

<hr>

<h2>VS Case 3 : check null reference</h2>

<p><strong>Class :</strong> </p>

<pre><code>class MyObject {
  private List&lt;X&gt; list;

  public List&lt;X&gt; getList() { return list; }
  public List&lt;X&gt; setList(List&lt;X&gt; list) { this.list = list; }
}
</code></pre>

<p><strong>Usage :</strong></p>

<pre><code>MyObject myObj = new MyObject();
if (myObj.getList() == null) myObj.setList(new ArrayList&lt;X&gt;());
myObj.getList().add(anObject);
</code></pre>

<hr>

<p>What's the good way for you with list and generally for complex fields ? </p>
