Posts

Showing posts from July, 2024

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

HowToAvoidNPE2 How To Avoid NullPointerException? 2 - Replace Null by Default Value 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 ;

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

HowToAvoidNPE1 How to avoid NullPointerException 1 - Should We Allow Null? 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

Go Problem - FIVE

Image
Question1 Go Problem - FIVE Black First