Stop checking for nulls in Java
Omar Ismail
Senior Software Engineer @ Digitinary | Java & Spring Expert ? | AWS & Microservices Architect ? | FinTech & Open Banking Innovator ?? | Digital Payments Expert ?? | Top 200 IT Content Creator in Jordan ?? | 40K+ ??
Thanks to original article and writer :
https://towardsdev.com/stop-checking-for-nulls-in-java-593a1f1a0c2f
The biggest problem I had coming back to Java was that I had to deal with the NullPointerException again — not really, you always need to sanitize input and output. Explicitly checking for nulls all the time is going to make your high-level code look lower-level than it is, and your low-level code even harder for others to understand.
For single objects, there are simple ways to deal with it. For example;
Using Objects#nonNull
Or you could use Optional…
And this is all good and readable. But when we are dealing with objects inside objects, things get hideous really fast.
You could try statically importing?Object's?nonNull?method to make it more readable, too.
But this is just a little better. You could also try using?Optional#ofNullable
But that’s still a lot of work. What if you just want to access a value without all these methods in your way? Presenting to you, safeEval:
And this is how you would implement it:
The idea is pretty simple. All you need to do is wrap your get method and if it throws a NullPointerException you catch it. This is not going to be acceptable on every project, though. In this case, I would go for the?Optional#mapapproach.
Mentor | Sr Automation | Selenium 4 | Appium 2 | WebDriverIO | BrowserStack | Bitrise | Jenkins | Agile Practitioner
2 年Thanks!
Co-Founder at Ingress Group
2 年Excellent article
Senior Backend Application Engineer
2 年Thats a great idea, however you'd lose the lombok project functionality if used, im waiting for the day java does implement the safe call operator, kotlin did it and they both work on the JVM, PHP, JS and many other languages support it, why not java?