Sometimes null
is returned intentionally to account for zero 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 zero. The class Inventory
contains a getStock()
method that constructs a list of items that have zero inventory and returns the list of items to the caller. When the size of this list is zero, 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.
Code Block | ||
---|---|---|
| ||
class Inventory { private final Hashtable<String, Integer> items; public Inventory() { items = new Hashtable<String, Integer>(); } public List<String> getStock() { List<String> stock = new ArrayList<String>(); Enumeration itemKeys = items.keys(); while(itemKeys.hasMoreElements()) { Object value = itemKeys.nextElement(); if((items.get(value)) == 0) { stock.add((String)value); } } if(items.size() == 0) { return null; } else { return stock; } } } public class Client { public static void main(String[] args) { Inventory inv = new Inventory(); List<String> items = inv.getStock(); System.out.println(items.size()); // Throws aan NPE } } |
Compliant Solution
...
Code Block | ||
---|---|---|
| ||
class Inventory { private final Hashtable<String, Integer> items; public Inventory() { items = new Hashtable<String, Integer>(); } 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); } } return stock; // Return list (possibly zero-length) } } public class Client { public static void main(String[] args) { Inventory inv = new Inventory(); List<String> items = inv.getStock(); System.out.println(items.size()); // Does not throw aan NPE } } |
Compliant Solution
This compliant solution returns an empty - list, which is an equivalent, permissible technique.
...
Returning null
rather than a zero-length array may lead to denial-of-service vulnerabilities when the client code does not handle null
properly.
...
Wiki Markup |
---|
\[[Bloch 2008|AA. References#Bloch 08]\] Item 43: returnReturn empty arrays or collections, not nulls |
...