Do or Do Not: Patterns and Antipatterns with the Try type
The Try type is a really useful mechanism for handling the possibility of errors in Java, Groovy, Scala, and other languages. It originates (as far as I can tell) in Scala, a functional programming language where it fits comfortably among other functors and monads (don’t worry, it doesn’t matter); it’s been incorporated into imperative languages like Java, but the procedural baggage of those languages contain hidden dragons for its use.
In this article, we’ll go over a brief explanation of the Try type then explore some antipatterns that are commonly encountered with it and wrap up with some more appropriate patterns for its use.
What is Try?
First things first: let’s distinguish the Try type — which is the subject of this article — from the try statement. Both deal with exceptions, but the former is a type (e.g., an interface or a class) introduced into the language by a library, while the latter is a keyword integrated into the language’s grammar. Values of type Try can be passed around like any other and are of no special significance to the runtime, whereas try indicates a statement, which has its unique flow control baked into the runtime.
A Try is just an object that represents the results of an operation that may have failed. It contains exactly one of two…