Stop checking for nulls in Java

Stop checking for nulls in Java

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;

No alt text provided for this image

Using Objects#nonNull

Or you could use Optional…

No alt text provided for this image

And this is all good and readable. But when we are dealing with objects inside objects, things get hideous really fast.

No alt text provided for this image

You could try statically importing?Object's?nonNull?method to make it more readable, too.

No alt text provided for this image

But this is just a little better. You could also try using?Optional#ofNullable


No alt text provided for this image

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:

No alt text provided for this image

And this is how you would implement it:

No alt text provided for this image

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.



Nehal Baig

Mentor | Sr Automation | Selenium 4 | Appium 2 | WebDriverIO | BrowserStack | Bitrise | Jenkins | Agile Practitioner

2 年

Thanks!

回复
Imran Yusubov

Co-Founder at Ingress Group

2 年

Excellent article

Waleed Alabed

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?

要查看或添加评论,请登录

Omar Ismail的更多文章

社区洞察

其他会员也浏览了