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 its 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.
...
This compliant solution eliminates the null
return and simply returns the List
, even if it is zero-length. The client can effectively handle this situation without being interrupted by runtime exceptions. When arrays are returned instead of collections, care must be taken so to ensure that the client does not access individual elements of a zero-length array.
...
Returning null
rather than a zero-length array may lead to denial of service vulnerabilities when the client code does not handle null
properly.
...