Android异常--空指针异常

总结自: Java Tips and Best Practices to avoid NPE in Java Applications

  1. Call equals() and equalsIgnoreCase() method on known String literal rather unknown object
Object unknownObject = null;

//wrong way - may cause NullPointerException
if(unknownObject.equals("knownObject")){
   System.err.println("This may result in NullPointerException if unknownObject is null");
}

//right way - avoid NullPointerException even if unknownObject is null
if("knownObject".equals(unknownObject)){
    System.err.println("better coding avoided NullPointerException");
}
  1. Prefer valueOf() over toString() where both return same result
BigDecimal bd = getPrice();
System.out.println(String.valueOf(bd)); //doesn’t throw NPE
System.out.println(bd.toString()); //throws "Exception in thread "main" java.lang.NullPointerException"
  1. Using null safe methods and libraries
//StringUtils methods are null safe, they don't throw NullPointerException
System.out.println(StringUtils.isEmpty(null));
System.out.println(StringUtils.isBlank(null));
System.out.println(StringUtils.isNumeric(null));
System.out.println(StringUtils.isAllUpperCase(null));

Output:
true
true
false
false
  1. Avoid returning null from method, instead return empty collection or empty array.
public List getOrders(Customer customer){
   List result = Collections.EMPTY_LIST;
   return result;
}
  1. Use of annotation @NotNull and @Nullable
  2. void unnecessary autoboxing and unboxing in your code
Person ram = new Person("ram");
int phone = ram.getPhone();
  1. Follow Contract and define reasonable default value
  2. Use Null Object Pattern

你可能感兴趣的:(Android异常--空指针异常)