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.
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.
Read the guide and transform your error handling today.
Also available as an ebook in multiple formats. Download your free copy now!
This library adheres to Pragmatic Versioning.
Artifacts are available in Maven Central.
Here you can find the full Javadoc documentation.
You may want to visualize the latest benchmark report.
We’d love to help. Check out the support guidelines.
If you’d like to contribute to this project, please start here.
This project is governed by the Contributor Covenant Code of Conduct. By participating, you are expected to uphold this code.
Copyright 2024 Guillermo Calvo.
This library is licensed under the Apache License, Version 2.0 (the “License”); you may not use it except in compliance with the License.
You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
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:
Required:
Forbidden: