Versions Compared

Key

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

...

The erroneous behavior is caused due to the server returning null while the client forgets to add in a check for such a valuesvalue. This non-compliant example shows how the check item != null condition is missing from the if condition in class Client.

Code Block
bgColor#FFCCCC
class Inventory {
  private static int[] item;
    public Inventory() {
    item = new int[20]
  }

  public static int[] getStock() {
    if(item.length == 0)
      return null;
    else
      return item;
  }
}

  public class Client {
    public static void main(String[] args) {
      Inventory iv = new Inventory();
        int[] item = Inventory.getStock();
	  if (Arrays.asList(item[1] == 1 ).contains(1)) {
	    System.out.println("Almost out of stock!" + item);
	  }
    }
}

Compliant Solution

Wiki Markup
This compliant solution eliminates the {{null}} return and simply returns the {{item}} array as is even if it is zero-length. The client can effectively handle this situation without exhibiting erroneous behavior. Be careful that the client does not try to access individual elements of a zero-length array such as {{item\[1\]}} while following this recommendation.

Code Block
bgColor#ccccff
class Inventory {
  private static int[] item;
    public Inventory() {
    item = new int[20];
  }

  public static intitem[2] getStock() {
= 1;  //quantity of if(item.length == 0)
      //handle error2 remaining is 1, almost out! 
  }

  public static else
  int[] getStock() {
    return item; //even if it is zero-length, return as is
  }
}

  public class Client {
    public static void main(String[] args) {
      Inventory iv = new Inventory();
        int[] item = Inventory.getStock();
	    if (Arrays.asList(item[1] == 1 ).contains(1)) {
	      System.out.println("Almost out of stock!" + item);
	    }
    }
}