Sometimes null is returned intentionally to account for zero 0 available instances. This practice can lead to denial-of-service vulnerabilities when the client code does not explicitly handle the null return case.
...
This noncompliant code example returns a null ArrayList when the size of the ArrayList is zero0. The class Inventory contains a getStock() method that constructs a list of items that have zero 0 inventory and returns the list of items to the caller. When the size of this list is zero0, a null is returned with the assumption that the client will install the necessary checks. Here, the client omits the check, causing a NullPointerException at runtime.
...
This compliant solution returns an empty list, which is an equivalent, permissible technique.:
| Code Block | ||
|---|---|---|
| ||
public List<String> getStock() {
List<String> stock = new ArrayList<String>();
Integer noOfItems; // Number of items left in the inventory
Enumeration itemkeys = items.keys();
while(itemkeys.hasMoreElements()) {
Object value = itemKeys.nextElement();
if((noOfItems = items.get(value)) == 0) {
stock.add((String)value);
}
}
if(l.isEmpty()) {
return Collections.EMPTY_LIST; // Always zero-length
} else {
return stock; // Return list
}
}
// Class Client ...
|
...
Automatic detection is straightforward, but fixing the problem will , most probably , require human intervention.
Bibliography
| [Bloch 2008] | Item 43, "Return Empty Arrays or Collections, Not Nulls" |
: Return empty arrays or collections, not nulls
...