Java library for functional style "Railway Oriented Programming"
This library was inspired by Railway Oriented Programming and the Result type of the Rust programming language. It contains utilities that enable functional style programming in Java with under-the-hood error handling without having to define try-catch-blocks or conditionals.
$ cat > Example.java
import de.perschon.resultflow.Result;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
// To build and run:
// javac -cp "target/*" Example.java
// java -cp ".:target/*" Example
public class Example {
public static void main(String[] args) {
Result<String> y = Result
.ok(args)
.map(x -> x[0])
.mapWrap(URL::new)
.mapWrap(URL::openConnection)
.mapWrap(URLConnection::getInputStream)
.mapWrap(InputStream::readAllBytes)
.map(String::new)
.map(x -> x.substring(0, Integer.min(100, x.length())));
if (y.isOk()) {
System.out.println(args[0] + "\n------------------\n" + y.getValue());
} else {
System.err.println("FAIL");
y.getError().printStackTrace();
System.exit(1);
}
}
}
^D
$ javac -cp "target/*" Example.java
$ java -cp ".:target/*" Example
FAIL
java.lang.ArrayIndexOutOfBoundsException: Index 0 out of bounds for length 0
at Example.lambda$main$0(Example.java:15)
at de.perschon.resultflow.Result.map(Result.java:136)
at Example.main(Example.java:15)
$
$ java -cp ".:target/*" Example abc
FAIL
java.lang.RuntimeException: java.net.MalformedURLException: no protocol: abc
at de.perschon.resultflow.Result.mapWrap(Result.java:156)
at Example.main(Example.java:16)
Caused by: java.net.MalformedURLException: no protocol: abc
at java.base/java.net.URL.<init>(URL.java:674)
at java.base/java.net.URL.<init>(URL.java:569)
at java.base/java.net.URL.<init>(URL.java:516)
at de.perschon.resultflow.Result.mapWrap(Result.java:151)
... 1 more
$ java -cp ".:target/*" Example http://example.com
http://example.com
------------------
<!doctype html>
<html>
<head>
<title>Example Domain</title>
<meta charset="utf-8" />
<m
$
-
Railway Oriented Programming. Scott Wlaschin's 2013 blog post that explains a result monad in pictures of rail road tracks.
-
Against Railway-Oriented Programming When a Result monad is not a good fit.
-
kotlin-result active project with a much richer implementation.
-
Macsoftex/result-flow Another result-flow fork that has added apply, fold, flatMap, flatMapFailure, and flatMapOrElse methods.