<p>In Java, I use a class in which some fields can be <code>null</code>. For example:</p>

<pre><code>class Foo {
    String bar;
    //....
}
</code></pre>

<p>I want to write a BarComparator for this class,</p>

<pre><code>    private static class BarComparator
            implements Comparator&lt;Foo&gt; {
        public int compare( final Foo o1, final Foo o2 )
        {
            // Implementation goes here
        }
    }
</code></pre>

<p>Is there a standard way to deal with the fact that any of <code>o1</code>, <code>o2</code>, <code>o1.bar</code>, <code>o2.bar</code> can be <code>null</code>, without writing lots of nested <code>if</code>...<code>else</code>?</p>

<p>Cheers!</p>

I think early return statements would be the other alternative to lots of ifs
e.g.
```
```
if(o1==null) return x;
if(o2==null) return x;
if(o1.getBar()==null) return x;
if(o2.getBar()==null) return x;

// No null checks needed from this point.
```
```