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 :
- the empty String
- zero-length arrays
- collections containing 0 items
- maps containing 0 items
Example declarations of empty items :
String item = ""; BigDecimal[] items = new BigDecimal[0]; List<Integer> items = new ArrayList<Integer>(); Map<String, Integer> items = new LinkedHashMap<String, Integer>();
The Collections class contains several type safe methods which return empty items (which are also immutable and Serializable) :
- Collections.emptyList()
- Collections.emptySet()
- Collections.emptyMap()
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.
(Another alternative is to use replace the array with a possibly-empty collection.)
import java.util.*; public 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 :
Would you use this technique?
|
|