โ† Back

JellyTech Perspective -> Java trick(s) ๐Ÿค“

NullPointerExceptionโ€ฆ the nightmare of every Java developer. To the rescue comes a solution known since Java 8 โ€” the Optional class. But what is the best way to use this class?

Let's look at the following code snippet:

โ€

Code snippet

โ€

The UserRepository interface describes a method called "findByName", which should return Optional<User>. Is this really a good practice? ๐Ÿค” Classes implementing the above interface will expose a rather inconvenient method whose result may not contain a value, so it will need to be checked to avoid a NullPointerException. Example code might look like this:

โ€

Code snippet

โ€

whether the Optional wrapper contains the requested object, and in case it's missing โ€” for example, throw an exception.

But perhaps it's worth considering a different solution ๐Ÿค”:

โ€

Code snippet

And this is exactly where we arrive at the question: if we always want to throw a standard exception when an object is not found โ€” an exception we should, of course, catch (a separate topic ๐Ÿ˜Š) โ€” then perhaps this is the better solution?

โ€

The default method will aim to validate as quickly as possible, and in case the object is not found, it will throw an exception โ€” which is explicitly declared in the method's signature.

Thanks to this change, calling the "findOrThrow" method will be a single line, and when writing business logic we get a very readable code. Clean Code Rules!!! ๐Ÿ˜Š๐Ÿ˜Š๐Ÿ˜Š

โ€

The example presented here is an invitation to think more deeply about the topics of readability, simplicity, and continuous improvement of your own code.

โ€

Photo Gallery

Video