Functional - Result, the tuned Optional

if we wantb to avoid exceptions and never wantb to give back null, we have to find a solution. One could be the bevaviort to use collections for every result. But this ist def. not what we want. ;-) But if we reduce the collection to one element, we are on the road to the Null-Object. After 7 versions of Java, we got the Optional...

Optional

The Optional is a class that is working as a holder for a typed value. So we are able to ask to instance of the Optional if a Value is Present, of how to get an alternative result.

How to use it

update with Java9

With Java 9 we got a few extensions to this class. For example, something like a flat map or better, convert to a Stream. Even with no value you could avoid the typical cycle in a stream of filter(isPresent) in combination of map(optional.get())

Result

The Optional is a good thing so far, and it is part of the JDK. But it is a final class. So, any extensions that you would like to add depending on your project needs.. forget it ;-)

Same happened to me so I introduced the class Result. Result is a tuned Optional, and it is not defined final.

The result could be saked ifPresent or ifAbsent, so noo need to invert yourself.

To work with the value, there are the methods

get() or getOrElse(..) to get the value, or you could define a Consumer and use it with the method ifPresent(consumer)

To create an instance of Result with a value ( even if it is null), there is the method ofNullable(value).

To Combine a Result with an other value and a function that is dealing with both input values, there is the possiblity to add a BiFunction with the method thenCombine. Or use the method thenCombineAsync if yoiu want to go reactive.

    Result<String> hello = Result.success("Hello");
    Result<String> world = hello.thenCombine("World", (s, s2) -> Result.success(s + " - " + s2));
    Assert.assertEquals("Hello - World", world.get());