Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.
Comment: Edited by sciSpider Java v3.0

...

Code Block
bgColor#FFCCCC
class Inventory {
  private final Hashtable<StringHashtable&lt;String, Integer>Integer&gt; items;
  public Inventory() {
    items = new Hashtable<StringHashtable&lt;String, Integer>Integer&gt;();	
  }

  public List<String>List&lt;String&gt; getStock() {
    List<String>List&lt;String&gt; l = new ArrayList<String>ArrayList&lt;String&gt;();
    Enumeration e = items.keys();
    while(e.hasMoreElements()) {
      Object value = e.nextElement();
      if((items.get(value)) == 0) {  		
        l.add((String)value);	 
      }
    }
    
    if(items.size() == 0) {	
      return null;
    } else {
      return l;
    }	
  }
}

public class Client {
  public static void main(String[] args) {
    Inventory iv = new Inventory();  
    List<String>List&lt;String&gt; items = iv.getStock();
    System.out.println(items.size()); // Throws a NPE
  }
}

...

Code Block
bgColor#ccccff
class Inventory {
  private final Hashtable<StringHashtable&lt;String, Integer>Integer&gt; items;
  public Inventory() {
    items = new Hashtable<StringHashtable&lt;String, Integer>Integer&gt;();	
  }

  public List<String>List&lt;String&gt; getStock() {
    List<String>List&lt;String&gt; l = new ArrayList<String>ArrayList&lt;String&gt;();
    Integer noOfItems; // Number of items left in the inventory
    Enumeration e = items.keys();
    while(e.hasMoreElements()) {
      Object value = e.nextElement();
		
      if((noOfItems = items.get(value)) == 0) {  		
        l.add((String)value);	 
      }
    }	
    return l; // Return list (possibly zero-length)
  }
}

public class Client {
  public static void main(String[] args) {
    Inventory iv = new Inventory();  
    List<String>List&lt;String&gt; items = iv.getStock();
    System.out.println(items.size()); // Does not throw a NPE
  }
}

...

Code Block
bgColor#ccccff
public List<String>List&lt;String&gt; getStock() {
  List<String>List&lt;String&gt; l = new ArrayList<String>ArrayList&lt;String&gt;();
  Integer noOfItems; // Number of items left in the inventory
  Enumeration e = items.keys();
  while(e.hasMoreElements()) {
    Object value = e.nextElement();
		
    if((noOfItems = items.get(value)) == 0) {  		
      l.add((String)value);	 
    }
  }	
  
  if(l.isEmpty()) {
    return Collections.EMPTY_LIST; // Always zero-length
  } else {
    return l; // Return list 
  }
}

// Class Client ...

...

Search for vulnerabilities resulting from the violation of this rule on the CERT website.

References

Wiki Markup
\[[Bloch 08|AA. Java References#Bloch 08]\] Item 43: return empty arrays or collections, not nulls

...

MET02-J. Avoid ambiguous uses of overloading      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;12. Methods (MET)      &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;MET04-J. Always provide feedback about the resulting value of a method