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:
โ

โ
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:
โ

โ
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 ๐ค:
โ

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.
โ
