π±Getting Started
How to get up and running with Results in no time
The best way to think of Results is as a super-powered version of Java's Optionals.
Result builds upon the familiar concept of Optional, enhancing it with the ability to represent both success and failure states.

Optional class is useful for representing values that might be present or absent, eliminating the need for null checks. However, Optionals fall short when it comes to error handling because they do not convey why a value is lacking. Result addresses this limitation by encapsulating both successful values and failure reasons, offering a more expressive way to reason about what went wrong.
Results provide the same methods as Optionals, plus additional ones to handle failure states effectively.
By leveraging Results, you can unleash a powerful tool for error handling that goes beyond the capabilities of traditional Optionals, leading to more robust and maintainable Java code.
Results in a Nutshell
In Java, methods that can fail typically do so by throwing exceptions. Then, exception-throwing methods are called from inside a try block to handle errors in a separate catch block.

This approach is lengthy, and that's not the only problem β it's also very slow.
Conventional wisdom says exceptional logic shouldn't be used for normal program flow. Results make us deal with expected error situations explicitly to enforce good practices and make our programs run faster.
Let's now look at how the above code could be refactored if connect() returned a Result object instead of throwing an exception.

In the example above, we used only 4 lines of code to replace the 10 that worked for the first one. But we can effortlessly make it shorter by chaining methods. In fact, since we were returning -1 just to signal that the underlying operation failed, we are better off returning a Result object upstream. This will allow us to compose operations on top of getServerUptime() just like we did with connect().

Result objects are immutable, providing thread safety without the need for synchronization. This makes them ideal for multi-threaded applications, ensuring predictability and eliminating side effects.
Last updated
Was this helpful?