Java Reference
In-Depth Information
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());
}
}
When the size of this list is 0, a null value is returned with the assumption that the
client will install the necessary checks. In this code example, the client lacks any null
value check, causing a NullPointerException at runtime.
Compliant Solution
Instead of returning a null value, this compliant solution simply returns the List , even
when it is empty.
Click here to view code image
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();
Search WWH ::




Custom Search