Errors Without Exceptions

Functional Programming in Java

Created by Mark Perry, @mprry, G+, Blog, LinkedIn, GitHub, maperry78@yahoo.com.au

Referential Transparency

  • Replace terms with value

    // append not RT
    List<Integer> list1 = new LinkedList<>();
    list1.append(1);
    List<Integer> list2 = list1; // [1]

    List<Integer> list1 = new LinkedList<>();
    list1.append(1);
    List<Integer> list2 = new LinkedList<>(); // []

Exceptions break RT


// always throw exception
int func(int i) {
    int x = raise();
    try {
        return x + 1;
    } catch (Exception e) {
        return 0;
    }
}

int raise() throws Exception {
    throw new Exception("fail!");
}

// substitution for x changes meaning
int func(int i) {
    try {
        return raise() + 1;
    } catch (Exception e) {
        return 0;
    }
}

Exceptions break RT (2)


int func() {
    try {
        return g(throw new Exception1(), throw new Exception2());
    } catch (Exception1 e) {
        return 1;
    } catch (Exception2 e) {
        return 2;
    }
}

int func() {
    try {
        int a = f1(1);
        int b = f2(2);
        int c = a + f3(3);
        return f4(a, b, c);
    } catch (Exception1 e) {
        return 1;
    } catch (Exception2 e) {
        return 2;
    } (catch Exception3 e)
        return 3;
    }
}

Exercises



<B> Validation<E, B> map(F<A, B> f);
<B> Validation<E, B> bind(F<A, Validation<E, B>> f);
Validation<E, A> orElse(Validation<E, A> v);
A orSuccess(A a);
<B, C> Validation<E, C> liftM2(Validation<E, B> v, F2<A, B, C> f);

static <E, A> Validation<E, List<A>> sequence(List<Validation<E, A>>)
static <E, A, B> Validation<E, List<B>> traverse(List<A> list, F<A, Validation<E, B>> f)

Conclusion

  • Option and Validation are:
    • modular
    • compositional
    • simple to reason about
  • Reuse functions that manipulate errors

Afterword

  • Functional Programming in Scala, Chiusano and Bjarnason
  • Chapter 4, Handling Errors Without Exceptions

Created by Mark Perry, @mprry, G+, Blog, LinkedIn, GitHub, maperry78@yahoo.com.au