Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
Loading...
We can use to obtain a boolean
value that represents whether a result is successful.
We can also use to find out if a result contains a failure value.
We discussed how to determine the state of a Result object using and . These methods provide a straightforward way to identify the outcome of an operation, helping you make decisions based on the outcome.
How to handle success and failure scenarios
We'll now delve into a set of methods that allow you to take conditional actions based on the state of a result. They provide a cleaner and more expressive way to handle success and failure scenarios, eliminating the need for lengthy if/else blocks.
In this example, ifSuccess
ensures that the provided action (adding the success value to the list) is only executed if the parsing operation is successful.
Here, ifFailure
ensures that the provided action (adding the failure value to the list) is only executed if the parsing operation fails.
In this example, ifSuccessOrElse
simplifies conditional logic by providing a single method to handle both success and failure scenarios, making the code more concise and readable.
We explained how to handle success and failure scenarios using these three methods. They provide a powerful way to perform conditional actions based on the state of a Result, streamlining your error handling and making your code more readable and maintainable.
How to get values out of Result objects
In essence, a Result
object is just a container that wraps a success or a failure value for us. Therefore, sometimes you are going to want to get that value out of the container.
We explored various ways to retrieve values from results. Using these methods you can efficiently access the underlying data within a Result object, whether it's a success or a failure.
A Java library to handle success and failure without exceptions
Wave goodbye to slow exceptions and embrace clean, efficient error handling by encapsulating operations that may succeed or fail in a type-safe way.
Result
objects represent the outcome of an operation, removing the need to check for null. Operations that succeed produce results encapsulating a success value; operations that fail produce results with a failure value. Success and failure can be represented by whatever types make the most sense for each operation.
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.
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.
Read the guide and transform your error handling today.
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.
How to reject success values and accept failure values
The following methods allow you to run inline tests on the wrapped value of a result to dynamically transform a success into a failure or a failure into a success.
This can be used to enforce additional validation constraints on success values.
In this example, we use a lambda expression to validate that the success value inside result
is even. Since the number is odd, it transforms the result into a failure.
Note that it is illegal for the mapping function to return null
.
This method is useful for implementing fallback mechanisms or recovery strategies, ensuring the application logic remains resilient and adaptable.
In this example, we use method references to check if the failure value equals OK
and then transform the result into a success.
How to instantiate new Result objects
There are several ways to create result objects.
Failure values cannot be null
either.
This method enables compatibility with legacy or third-party code that uses exceptions to indicate operation failure.
We've covered how to create new instances of Result
using various factory methods provided by the Results
class. Each method serves a specific purpose, allowing you to select the most suitable one based on the situation.
How to transform values wrapped inside Results
Transforming result objects is a key feature that enables you to compose complex operations in a clean and functional style. There are two primary techniques used for these transformations.
Mapping involves applying a function to the value inside a result to produce a new result object.
In this example, we wrap a String
inside a Result
object and invoke mapSuccess
to calculate its length and wrap it inside a new Result
object.
Here, we invoke mapFailure
to transform the failure type of the result from String
to Boolean
for demonstration purposes.
Flat-mapping is used to chain operations that return results themselves, flattening the nested structures into a single result object. This allows you to transform a success into a failure, or a failure into a success.
To illustrate flat-mapping concepts, the next examples will follow a familiar "pet store" theme. This involves three Java types: Pet
, PetError
, and PetStore
. These types will help us demonstrate the effective use of flat-mapping methods.
With these types defined, we'll explore how to use various flat-mapping methods to transform result objects and manage pet-related operations in our imaginary pet store.
This example starts with a successful result containing a wrong pet ID (not found in the pet store). When we flat-map it with the store's find
method reference, the final result contains a pet error.
Here we start with a failed result containing a pet error. When we flat-map it with the store's getDefaultPetId
method reference, the final result contains the ID of the default pet in the store.
This example starts with a successful result containing a wrong pet ID (not found in the pet store). When we flat-map it with the store's find
method reference, the final result contains a pet error.
Here we start with a failed result containing a pet error. When we flat-map it with the store's getDefaultPetId
method reference, the final result contains the ID of the default pet in the store.
We demonstrated how to transform results in a concise and functional manner, enhancing the clarity and flexibility of your error-handling and data-processing logic.
How to defer expensive calculations with Results
Lazy results optimize performance by deferring costly operations until absolutely necessary. They behave like regular results, but only execute the underlying operation when an actual check for success or failure is performed.
Add this Maven dependency to your build:
com.leakyabstractions
result-lazy
This sample method simply increments and returns a counter for brevity. However, in a typical scenario, this would involve an I/O operation.
In this example, the expensive calculation is omitted because the lazy result is never fully evaluated. This test demonstrates that a lazy result can be transformed while maintaining laziness, ensuring that the expensive calculation is deferred.
Here, the expensive calculation is executed because the lazy result is finally evaluated.
In this test, we don't explicitly unwrap the value or check the status, but since we want to consume the success value, we need to evaluate the lazy result first.
Furthermore, even if we wanted to handle the failure scenario, we would still need to evaluate the lazy result.
We learned how to defer expensive calculations until absolutely necessary. By leveraging lazy results, you can optimize performance by avoiding unnecessary computations and only evaluating the operation's outcome when needed.
Measuring performance to find out how fast Results are
Throughout these guides, we have mentioned that throwing Java exceptions is slow. But... how slow? According to our benchmarks, throwing an exception is several orders of magnitude slower than returning a failed result.
This proves that using exceptional logic just to control normal program flow is a bad idea.
The first scenarios compare the most basic usage: a method that returns a String
or fails, depending on a given int
parameter:
The next scenarios do something a little bit more elaborate: a method invokes the previous method to retrieve a String
; if successful, then converts it to upper case; otherwise transforms the "simple" error into a "complex" error.
We provided insights into the Result library's performance through benchmarking. While our metrics corroborate that most codebases could benefit from using this library instead of throwing exceptions, its main goal is to help promote best practices and implement proper error handling.
How to assert Result objects fluently
Add this Maven dependency to your build:
com.leakyabstractions
result-assertj
We covered how to use fluent assertions for Results. This approach allows you to write clear and expressive tests, enhancing the maintainability of your unit tests while ensuring that Result objects behave as expected.
How to serialize Result objects with Jackson
Add this Maven dependency to your build:
com.leakyabstractions
result-jackson
Let's start by creating a class ApiResponse
containing one ordinary and one Result
field.
Then we will take a look at what happens when we try to serialize and deserialize ApiResponse
objects.
Now, let's instantiate an ApiResponse
object.
This is Jackson's default serialization behavior. But we'd like to serialize the result
field like this:
Now, let's reverse our previous example, this time trying to deserialize a JSON object into an ApiResponse
.
This behavior again makes sense. Essentially, Jackson cannot create new result objects because Result
is an interface, not a concrete type.
What we want, is for Jackson to treat Result
values as JSON objects that contain either a success
or a failure
value. Fortunately, there's a Jackson module that can solve this problem.
Alternatively, you can also make Jackson auto-discover the module.
Regardless of the chosen registration mechanism, once the module is registered all functionality is available for all normal Jackson operations.
Now, let's try and serialize our ApiResponse
object again:
If we look at the serialized response, we'll see that this time the result
field contains a null failure
value and a non-null success
value:
Next, we can try serializing a failed result.
We can verify that the serialized response contains a non-null failure
value and a null success
value.
Finally, let's repeat the test again, this time with a failed result. We'll see that yet again we don't get an exception, and in fact, have a failed result.
We can use to specify an action that must be executed if the result represents a successful outcome. This method takes a that will be applied to the success value wrapped by the result.
On the other hand, we can use method to define an action that must be taken when the result represents a failure. This method also takes a that will be applied to the failure value inside the result.
Finally, allows you to specify two separate actions: one for when the operation succeeded and another for when it failed. This method takes two : the first for handling the success case and the second for handling the failure case.
The most basic way to retrieve the success value wrapped inside a result is by using . This method will return an optional success value, depending on whether the result was actually successful or not.
Similarly, we can use to obtain the failure value held by a Result
object.
Unlike , these methods are null-safe. However, in practice, we will not be using them frequently. Especially, since there are more convenient ways to get the success value out of a result.
We can use to provide an alternative success value that must be returned when the result is unsuccessful.
The method is similar to , but it takes a mapping instead of a . The function will receive the failure value to produce the alternative success value.
Finally, we can use and to wrap the value held by an instance of Result
into a possibly-empty object.
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 .
Also available as an ebook in multiple formats.
Not a fan of reading long docs? No worries! Tune in to Deep Dive, a podcast generated by . In just a few minutes, you'll get the essential details and a fun intro to what this library can do for you!
The method allows you to transform a success into a failure based on certain conditions. It takes two parameters:
A to determine if the success value is acceptable.
A mapping that will produce a failure value if the value is deemed unacceptable.
The method allows you to transform a failure into a success based on certain conditions. It also receives two parameters:
A to determine if the failure value is recoverable.
A mapping that will produce a success value from the acceptable failure value.
We covered how to filter out unwanted success values and accept failure values using and . These methods enable you to refine results based on specific criteria, ensuring that only the relevant values are processed down the line.
A successful result contains a non-null value produced by an operation when everything works as intended. We can use to create a new instance.
Note that we can invoke or to check whether a result is successful or failed (more on this in the ).
On the other hand, a failed result holds a value representing the problem that prevented the operation from completing. We can use to create a new one.
When we need to create results that depend on a possibly null value, we can use . If the first argument is null
, then the second one will be used to create a failed result.
We can also use to create results that depend on an value. If the first argument is an empty optional, then the second one will be used to create a failed result.
The second argument can be a too.
Finally, if we have a task that may either return a success value or throw an exception, we can encapsulate it as a result using so we don't need to use a try-catch block.
We can use to apply a function to the success value of a result, transforming it into a new success value. If the result is a failure, it remains unchanged.
Next up, we can use to apply a function to the failure value, transforming it into a new one. If the result is a success, it remains unchanged.
The method simultaneously handles both success and failure cases by applying two separate functions: one for transforming the success value and one for transforming the failure value.
Use to chain an operation that returns a result object. This method applies a mapping function to the success value, replacing the original result with the new one returned by the function. If the result is a failure, it remains unchanged.
Use to chain a result-bearing operation. This method also replaces the original result with the new one returned by the mapping function. If the result is a success, it remains unchanged.
The method handles both success and failure cases by applying the appropriate function based on the status of the original result.
provides snippets for different build tools to declare this dependency.
We can use to create a lazy result.
While can return a fixed success or failure, lazy results shine when they encapsulate time-consuming or resource-intensive operations.
The advantage of lazy results is that they defer invoking the provided for as long as possible. Despite this, you can screen and transform them like any other result without losing their laziness.
Finally, when it's time to check whether the operation succeeds or fails, the lazy result will execute it. This is triggered by using any of the terminal methods, such as .
By default, , , and are treated as terminal methods. This means they eagerly evaluate the result and then perform an action based on its status.
In this other test, we use instead of . Since the lazy result is evaluated to a success, the failure consumer is never executed.
When these conditional actions may also be skipped along with the expensive calculation, we can encapsulate them into a instead of a regular . All we need to do is to create the consumer using . Lazy consumers will preserve the laziness until a terminal method is eventually used on the result.
Here, we use a lazy consumer with so the expensive calculation is skipped because the lazy result is never fully evaluated.
The full source code for the examples is .
This library comes with when using results versus when using exceptions.
You can use fluent assertions for Result objects to enhance the readability and expressiveness of your unit tests. These assertions are based on , an open-source Java library that offers a fluent API for writing assertions in test cases.
features a comprehensive and intuitive set of strongly-typed assertions for unit testing. It is a popular choice among Java developers due to its effective features and compatibility with various testing frameworks like and .
provides snippets for different build tools to declare this dependency.
You can use in your tests to create fluent assertions for result objects.
If, for any reason, you cannot statically import assertThat
, you can use instead.
The full source code for the examples is .
When using Result objects with we might run into some problems. The solves them by making Jackson treat results as if they were ordinary objects.
is a Java library for parsing and generation. It is widely used for converting Java objects to JSON and vice versa, making it essential for handling data in web services and RESTful APIs.
provides snippets for different build tools to declare this dependency.
And finally, let's try serializing it using an .
We'll see that now we get an .
While this may look strange, it's the expected behavior. When Jackson examined the result object, it invoked and received an optional string value. But Jackson will not handle JDK 8 datatypes like Optional
unless you register .
We'll see that we get another . Let's inspect the stack trace.
Once we have , all we need to do is register ResultModule
with our object mapper.
Now, let's repeat our tests for deserialization. If we read our ApiResponse
again, we'll see that we no longer get an .
We learned how to serialize and deserialize Result objects using , demonstrating how the provided datatype module enables Jackson to treat Results as ordinary objects.
The full source code for the examples is .
This library adheres to to communicate the backwards compatibility of each version.
The latest releases are available in .
provides snippets for different build tools to declare this dependency.
To use Result
, we can add a dependency to our project.
We can also add Result
as a dependency.
This is the most common configuration for projects using Result
internally. If we were building a library that exposed Result
in its public API, .
We learned how to add the library to your project using either or . By including the correct dependencies, you're now ready to start leveraging the power of Results in your applications.
Boost Performance
Avoid exception overhead and benefit from faster operations
Simple API
Leverage a familiar interface for a smooth learning curve
Streamlined Error Handling
Handle failure explicitly to simplify error propagation
Safe Execution
Ensure safer and more predictable operation outcomes
Enhanced Readability
Reduce complexity to make your code easier to understand
Functional Style
Embrace elegant, functional programming paradigms
Lightweight
Keep your project slim with no extra dependencies
Open Source
Enjoy transparent, permissive Apache 2 licensing
Pure Java
Seamless compatibility from JDK8 to the latest versions
How to solve simple use-case scenarios
In this section, we'll cover foundational use cases, including checking the status of a result, unwrapping the value inside a result, and taking different actions based on success or failure.
These basics will help you handle errors more cleanly and efficiently without cluttering your code with try-catch blocks.
How to take Result objects to the next level
The most idiomatic approach to handling results involves screening them and applying various mapping and flat-mapping methods to transform and compose behavior.
This section will guide you through these powerful tools, demonstrating how to manipulate results effectively so you can craft more robust and maintainable Java applications.
Level up and lessons learned
Congratulations on reaching the end of this guide! By now, you should have a solid understanding of how to use results in your Java applications effectively. Here's a brief recap of what you've learned:
Getting Started: You learned how to integrate result objects into your codebase and instantiate new ones.
Basic Usage: You explored foundational operations like checking statuses, unwrapping values, and executing conditional actions based on result status, enabling you to respond dynamically to success and failure scenarios.
Advanced Usage: You delved into more sophisticated techniques like screening results to transform successes and failures based on conditions, and leveraging mapping and flat-mapping methods to compose behaviors in a functional style.
Next, we'll introduce additional resources where you can further enhance your understanding and skills. Let's continue expanding your knowledge!
How to declare dependencies without having to worry about version numbers
The basic idea is that instead of specifying a version number for each Result library in your project, you can use this BOM to get a complete set of consistent versions.
Add this Maven dependency to your build:
com.leakyabstractions
result-bom
We discussed the benefits of using the Bill of Materials for managing dependencies in your project. With the BOM, you can eliminate the hassle of manually specifying version numbers, ensuring consistency and compatibility across all Result libraries.
Check out some REST APIs that consume and produce Result objects
These projects illustrate how to develop powerful APIs using Result objects. Follow the examples to create resilient web services that elegantly handle success and failure scenarios.
Take a look at a Spring Boot-based REST API leveraging Result objects
We use a @Bean
to register the datatype module.
API responses contain a Result
field, encapsulating the outcome of the requested operation.
Results have different success types, depending on the specific endpoint. Failures will be encapsulated as instances of ApiError
.
Controllers return instances of ApiResponse
that will be serialized to JSON by Spring Boot.
Since failures are expressed as ApiError
objects, endpoints invariably return HTTP status 200
.
The application can be built and run with Gradle.
This will start a stand-alone server on port 8080.
Once started, you can interact with the API.
You should see a JSON response like this:
Take a look at a Micronaut-based REST API leveraging Result objects
API responses contain a Result
field, encapsulating the outcome of the requested operation.
Results have different success types, depending on the specific endpoint. Failures will be encapsulated as instances of ApiError
.
Controllers return instances of ApiResponse
that will be serialized to JSON by Micronaut:
Since failures are expressed as ApiError
objects, endpoints invariably return HTTP status 200
.
The application can be built and run with Gradle.
This will start a stand-alone server on port 8080.
Once started, you can interact with the API.
You should see a JSON response like this:
How to serialize Result objects with Micronaut
Add this Maven dependency to your build:
com.leakyabstractions
result-micronaut-serde
Let's start by creating a record ApiOperation
containing one ordinary and one Result field.
We will take a look at what happens when we try to serialize and deserialize ApiOperation
objects with Micronaut.
Now, let's create a Micronaut controller that returns an instance of ApiOperation
containing a successful result.
And finally, let's run the application and try the /operations/last
endpoint we just created.
This is Micronaut's default serialization behavior. But we'd like to serialize the result
field like this:
Now, let's reverse our previous example, this time trying to receive an ApiOperation
as the body of a POST
request.
What we want, is for Micronaut to treat Result values as JSON objects that contain either a success
or a failure
value. Fortunately, there's an easy way to solve this problem.
Now, let's try and serialize our ApiOperation
object again.
If we look at the serialized response, we'll see that this time the result
field contains a success
field.
Next, we can try serializing a failed result.
We can verify that the serialized response contains a non-null failure
value and a null success
value:
Finally, let's repeat the test again, this time with a failed result. We'll see that yet again we don't get an exception, and in fact, have a failed result.
Feel free to tweak and share — no strings attached
This library is licensed under the Apache License, Version 2.0 (the "License"); you may not use it except in compliance with the License.
Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and limitations under the License.
Permitted
Commercial Use: You may use this library and derivatives for commercial purposes.
Modification: You may modify this library.
Distribution: You may distribute this library.
Patent Use: This license provides an express grant of patent rights from contributors.
Private Use: You may use and modify this library without distributing it.
Forbidden
Trademark use: This license does not grant any trademark rights.
Liability: The library author cannot be held liable for damages.
Warranty: This library is provided without any warranty.
While understanding the basics provides a solid foundation, the true potential of result objects is unlocked through their functional capabilities. Mastering these techniques enables concise and readable error handling by leveraging the power of .
For more details on the Result API, you can read the .
The full source code for the examples is .
Tracking multiple add-on versions for your project can quickly become cumbersome. In that situation, you can use the convenient to centralize and align their versions. This ensures compatibility and simplifies dependency maintenance.
's Bill of Materials POMs are special POM files that group dependency versions known to be valid and tested to work together, reducing the chances of having version mismatches.
To , use the following:
To , use the following:
To help you become familiar with this library, you can explore two demo projects that showcase how to handle and serialize Result
objects within popular frameworks like and . Each project provides a working example of a "pet store" web service that exposes a REST API for managing pets. They are based on and you can interact with them using .
is a widely-used, JVM-based framework designed to simplify the development of stand-alone, production-ready applications. It emphasizes convention over configuration, allowing developers to get started quickly with minimal setup. Known for its extensive ecosystem and robust community support, Spring Boot streamlines the creation of microservices and enterprise applications, leveraging the powerful Spring Framework while minimizing boilerplate code.
is a modern, JVM-based framework for building lightweight microservices and serverless applications. It focuses on fast startup times and low memory usage. Although not as widely adopted as , it has gained popularity for its performance and innovative features.
This demo project demonstrates how to handle and serialize Result
objects within a application. It provides a working example of a "pet store" web service that exposes a REST API for managing pets.
The project was generated via including features: web and cloud-feign.
Then was manually added as a dependency to serialize and deserialize Result
objects.
You can navigate to to inspect the API using an interactive UI
The full source code for the example application is .
This demo project demonstrates how to handle and serialize Result
objects within a application. It provides a working example of a "pet store" web service that exposes a REST API for managing pets.
The project was generated via including features: annotation-api, http-client, openapi, serialization-jackson, swagger-ui, toml, and validation.
Then was manually added as a dependency to serialize and deserialize Result
objects.
That's all we need to do to make Micronaut treat results as .
You can navigate to to inspect the API using an interactive UI.
The full source code for the example application is .
When using Result objects with , we might run into some problems. The support for Result solves them by making Micronaut treat results as (so they can be serialized and deserialized).
is a modern, JVM-based framework for building lightweight microservices and serverless applications. It focuses on fast startup times and low memory usage. Although not as widely adopted as , it has gained popularity for its performance and innovative features.
provides snippets for different build tools to declare this dependency.
We'll see that we get a Micronaut CodecException
caused by a .
Although this may look strange, it's actually what we should expect. Even though we annotated ApiOperation
as , Micronaut doesn't know how to serialize result objects yet, so the data structure cannot be serialized.
We'll see that now we get an . Let's inspect the stack trace.
This behavior again makes sense. Essentially, Micronaut cannot create new result objects, because Result
is not annotated as or .
All we need to do now is . Once the is in the classpath, all functionality is available for all normal Micronaut operations.
Now, let's repeat our tests for deserialization. If we read our ApiOperation
again, we'll see that we no longer get an .
We learned how to serialize and deserialize Result objects using , demonstrating how the provided enables Micronaut to treat Results as objects.
The full source code for the examples is .
You may obtain a copy of the License at