‘Return zero-length arrays, not nulls’

 

Some APIs
intentionally return a null reference to indicate that instances are
unavailable. This practice can lead to denial-of-service vulnerabilities when
the client code fails to explicitly handle the null return value case.

 

For methods that return a set of values
using an array or collection, returning an empty array or collection is an
excellent alternative to returning a null value, as most callers are better
equipped to handle an empty set than a null value.

The below code snippet returns null :

private List cheesesInStock = …;

/**

* @return an array containing all of the
cheeses in the shop,

*        
or null if no cheeses are available for purchase.

*/

public Cheese[] getCheeses() {

    if
(cheesesInStock.size() == 0)

       
return null;

    …

}

 

There is no reason to make a special case
for the situation where no cheeses are available for purchase. Doing so
requires extra code in the client to handle the null return value, for example:

 

Cheese[] cheeses = shop.getCheeses();

if (cheeses != null &&

   
Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON))

    …..

 

INSTEAD best practice is to use :

 

private List cheesesInStock = …;

private final static Cheese[]
NULL_CHEESE_ARRAY = new Cheese[0];

/**

* @return an array containing all of the
cheeses in the shop.

*/

public Cheese[] getCheeses() {

  return (Cheese[])
cheesesInStock.toArray(NULL_CHEESE_ARRAY);

}

 

In this idiom, a zero-length array
constant is passed to the toArray method to indicate the desired return type.
Normally the toArray method allocates the returned array, but if the collection
is empty, it fits in the input array, and the specification for
Collection.toArray(Object[]) guarantees that the input array will be returned
if it is large enough to hold the collection. Therefore the idiom never
allocates a zero-length array but instead reuses the “type-specifier constant.”

 

In summary, there is no reason ever to
return null from an array-valued method instead of returning a zero-length
array.

With this best practice the null check is
not required and below code would do the work :

if
(Arrays.asList(shop.getCheeses()).contains(Cheese.STILTON))

Give some Likes to Authors

whatsq

Support whatsq.com, help community and write on social network.