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;
	private List<Payment> payments = new ArrayList<>();
	...

When your class has a List, set it to Collections.emptyList or new ArrayList<>() depends on how you are change the list. If the caller will retrieve the list and then add/remove element, then use new ArrayList<>(). When you list is write protected, and supposed to be changed through setter, you may use Collections.emptyList().

Return default value instead of null.

public class BankService {
	private List<BankAccount> allBankAccounts = new ArrayList<BankAccount>();

	public List<BankAccount> getBankAccountsCreatedOn(LocalDate createDate) {
		// Save time for filtering
		if (createDate.isAfter(LocalDate.now())) {
			return Collections.emptyList();
		}
		return allBankAccounts.stream().filter((bankAccount) -> bankAccount.getCreateDate().equals(createDate))
				.collect(Collectors.toList());
	}

You may encounter following situations, early return for special condition, or returning no record found. Don’t return null, return the default value instead. Caller will appreciate your work as they don’t need to check null on the return value.

Conclusion

For “Container” Class/Interface, always use default value, in local variable/field initialization, return value, method parameter, null will be eliminated in our program, and hence NPE.

Feel free to put any comment.

Comments