Avoiding NullPointerException

surprise

The terrible NullPointerException (NPE in short) is the most frequent Java exception occurring in production, according to a 2016 study. In this article, we'll explore the main techniques to fight it: the self-validating model and the Optional wrapper.

Self-Validating Model

Imagine a business rule: every Customer has to have a birth date set. There are a number of ways to implement this constraint: validating the user data on the create and update use-cases, enforcing it via NOT NULL database constraint and/or implementing the null-check right in the constructor of the Customer entity. In this article, we'll explore the last one.