Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Instead of using null, you could use some version of the "null object" design pattern. For example:</p> <pre><code>public class Family { private final PersonList people; public Family(PersonList people) { this.people = people; } public PersonList getPeople() { if (people == null) { return PersonList.NULL; } return people; } public boolean isNull() { return false; } public static Family NULL = new Family(PersonList.NULL) { @Override public boolean isNull() { return true; } }; } import java.util.ArrayList; public class PersonList extends ArrayList&lt;Person&gt; { @Override public Person get(int index) { Person person = null; try { person = super.get(index); } catch (ArrayIndexOutOfBoundsException e) { return Person.NULL; } if (person == null) { return Person.NULL; } else { return person; } } //... more List methods go here ... public boolean isNull() { return false; } public static PersonList NULL = new PersonList() { @Override public boolean isNull() { return true; } }; } public class Person { private Address address; public Person(Address address) { this.address = address; } public Address getAddress() { if (address == null) { return Address.NULL; } return address; } public boolean isNull() { return false; } public static Person NULL = new Person(Address.NULL) { @Override public boolean isNull() { return true; } }; } etc etc etc </code></pre> <p>Then your if statement can become:</p> <pre><code>if (!family.getPeople().get(0).getAddress().getPostalCode.isNull()) {...} </code></pre> <p>It's suboptimal since:</p> <ul> <li>You're stuck making NULL objects for every class,</li> <li>It's hard to make these objects generic, so you're stuck making a null-object version of each List, Map, etc that you want to use, and</li> <li>There are potentially some funny issues with subclassing and which NULL to use.</li> </ul> <p>But if you really hate your <code>== null</code>s, this is a way out.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload