Handle NullPointerException

Stop with this class-oriented madness, this is not Sparta.

Calofir Emil
2 min readDec 19, 2020

Most data comes through the wire via HTTP. You should consume it as you want. Data is JSON, data is just nested maps. Data exists at a moment in time or not. Dealing with missing data is what a system should be able to handle.

Java 8+ and Typescript (delicious) have powerful tools for consuming external data and branching logic. Why bother with concretions (classes) and exceptions? Try to make your code as functional as you can. Monads, baby, function composition.

Optional and Stream to process your data flow, and @FunctionlInterface to expand your language. These patterns are all you need to build your backend.

Java 8+

//Retrive nested data with null check and default value
Optional.ofNullable().map().orElse()
//Nested data
String postalCode = Optional.ofNullable(cust)  .map(Customer::getAddress)  .map(Address::getPostalCode)  .orElse("DefaultCode");
//Branching logic on your data availability
if(Objects.isNull(cust))...
if(Objects.nonNull(cust))...

As for your frontend …. Typescript

// This is beautiful. Read nested data from the server response.
const fieldError = errors && errors["msg"] && errors["msg"]["field1"] || ""

With this small API, you can consume data from any source.
Avoid throwing exceptions, try-catch-resolve them in place.

It is best to try-catch the third-party library function calls if you don’t have time to dive into the implementation.

--

--