Java Reference
In-Depth Information
Compliant Solution
In this compliant solution, the definitions reflect the independence of the two constants:
public static final int VOTING_AGE = 18;
public static final int ALCOHOL_AGE = 21;
Bibliography
[JLS 2013]
§4.12.4, “
final
Variables”
41. Return an empty array or collection instead of a null value for
methods that return an array or collection
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 ex-
plicitly handle the null return value case. A null return value is an example of an in-band
error indicator, which is discouraged by
Guideline 52
, “
Avoid in-band error indicators
.
”
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.
Noncompliant Code Example
This noncompliant code example returns a null
ArrayList
when the size of the
Array-
List
is 0. The class
Inventory
contains a
getStock()
method that constructs a list of
items that have 0 inventory and returns the list of items to the caller.
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()) {