NullPointerExceptions -
- Call equals() and equalsIgnoreCase() method on known String literal rather unknown object -Object unknownObject = null;//wrong way - may cause NullPointerExceptionif(unknownObject.equals("knownObject")){System.err.println("This may result in NullPointerException if unknownObject is null");}//right way - avoid NullPointerException even if unknownObject is nullif("knownObject".equals(unknownObject)){System.err.println("better coding avoided NullPointerException");}
- Prefer valueOf() over toString() where both return same resultBigDecimal bd = getPrice();System.out.println(String.valueOf(bd)); //doesn't throw NPESystem.out.println(bd.toString()); //throws "Exception in thread "main" java.lang.NullPointerException"
- Using null safe methods and libraries -//StringUtils methods are null safe, they don't throw NullPointerExceptionSystem.out.println(StringUtils.isEmpty(null));System.out.println(StringUtils.isBlank(null));System.out.println(StringUtils.isNumeric(null));System.out.println(StringUtils.isAllUpperCase(null));Output:truetruefalsefalse
- Avoid returning null from method, instead return empty collection or empty array (This Java best practice or tips is also mentioned by Joshua Bloch in his book Effective Java) -public List getOrders(Customer customer){List result = Collections.EMPTY_LIST;return result;}
Thanks & Regards
Manish Kumar
No comments:
Post a Comment