Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

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

  public List<String>ArrayList<String> getStock() {
    List<String>ArrayList<String> l = new ArrayList<String>();
    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>ArrayList<String> items = iv.getStock();
    System.out.println(items.size()); // throws a NPE
  }
}

...

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

  public List<String>ArrayList<String> getStock() {
    List<String>ArrayList<String> l = new ArrayList<String>();
    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; // returnReturn list (possibly zero-length arraylist)
  }
}

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

Compliant Solution

...

Code Block
bgColor#ccccff
public List<String>ArrayList<String> getStock() {
  List<String>ArrayList<String> l = new ArrayList<String>();
  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 else{
      return l; // Return list 
  }
}

// Class Client ...

Risk Assessment

Returning null rather than a zero-length array may lead to denial of service vulnerabilities when the client code does not handle null properly.

...