Prefer empty items to null ones

There are many cases in which an "empty" object can be used instead of a null object reference. This is usually preferable, since it helps eliminate one of the most common problems encountered during development: the NullPointerException.

The following qualify as "empty" objects:

Example declarations of empty items:

String item = "";
BigDecimal[] items = new BigDecimal[0];
List<Integer> items = new ArrayList<>();
Map<String, Integer> items = new LinkedHashMap<>();

The Collections class contains several type safe methods which return empty items (which are also immutable and Serializable) :

The above methods are occasionally useful.

Example

Here's an example of using an empty, zero-length array instead of a null reference. This simplifies the caller, since they never have to check for null values. (An even better alternative is to use replace the array with a possibly-empty collection.)


import java.util.*;

public final class StockPortfolio {

  //..elided

  /**
  * A field is implemented internally as a Collection,
  * but offered to the user of this class as an Array.
  * This array is never null, even if the underlying Collection is
  * empty.
  */
  public String[] getStocks() {
    /*
    NO_STOCKS plays a double role here. If there are elements in fStocks, then
    toArray will allocate a new array, using NO_STOCKS simply as an indicator
    of the proper type to use. If fStocks has no elements at all, then toArray
    will simply return the NO_STOCKS array itself.
    */
    return (String[]) fStocks.toArray(NO_STOCKS);
  }

  // PRIVATE

  /** The underlying collection. */
  private List fStocks;

  /** A constant, empty array, to be used instead of a null array. */
  private static final String[] NO_STOCKS = new String[0];
} 


See Also :
Prefer Collections over older classes
Avoid null if possible
Would you use this technique?
Yes   No   Undecided   
© 2014 Hirondelle Systems | Source Code | Contact | License | RSS
Individual code snippets can be used under this BSD license - Last updated on September 21, 2013.
Over 2,000,000 unique IPs last year - Built with WEB4J.
- In Memoriam : Bill Dirani -