Posts

How To Avoid NullPointerException? 3 - Optional

HowToAvoidNPE3 Optional is introduced since java 8, what is it and how do we make use of this class to avoid NPE? What is Optional? From Optional java doc A container object which may or may not contain a non- null value. Simply speaking, Optional is just like a single element Collection, the key point is it can only contain non-null value. Optional should never be null Before using Optional , one key point to know is Optional should never be null Please NEVER assign null to Optional . From API Note of Optional: A variable whose type is Optional should never itself be null ; it should always point to an Optional instance. I really hope that compiler actually enforced this, instead of putting such note. But fortunately IDE like IntelliJ will warn you for such cases. When to use Again from API Note of Optional: Optional is primarily intended for use as a method return type where there is a clear need to represent “no result,” and where usin

How To Avoid NullPointerException? 2 - Replace Null by Default Value

HowToAvoidNPE2 We discussed on how to tackle NullPointerException(NPE) in last post, by identifying whether null is allowed. We properly state our assumption and validate not nullable input. We continue on how to eliminate null today. Default instead of null Some Java Class/Interface has good default values: Class Default Value String “” List Collections.emptyList(), new ArrayList<>() Set Collections.emptySet(), new HashSet<>() Map Collections.emptyMap(), new HashMap<>() Array new int[]{}, new Integer[]{}… These Class/Interface can be classified as “Container”. Naturally, “Container” should be empty, instead of null. Initialize the field with default value. For example: public class BankAccount { private Integer accountId ; private String owner = "" ; private BigDecimal balance ; private LocalDate createDate ; private List < Payment > payments = new ArrayList < &g

How To Avoid NullPointerException? 1 - Should we allow Null?

HowToAvoidNPE1 NullPointerException(NPE) is the most common type of Exception we face in Java. How can we avoid NPE? Consider the following example: public class BankAccount { private Integer accountId ; private String owner ; private BigDecimal balance ; // Getter Setter } public class BankService { public void transferAmountTo ( BankAccount from , BankAccount to , BigDecimal amount ) { from . setBalance ( from . getBalance ( ) . subtract ( amount ) ) ; to . setBalance ( to . getBalance ( ) . add ( amount ) ) ; } } What will you do when you see NPE when executing transferAmountTo ? Null Check This is almost the first thing we do when we see NPE. public void transferAmountTo ( BankAccount from , BankAccount to , BigDecimal amount ) { if ( from != null ) { if ( to != null ) { if ( from . getBalance ( ) != null ) { if ( to . getBalance ( ) != null ) { if ( amount !=