Andreas Lundblad
Jun 28, 2016

A generic fail method

I’m a fan of expressing this

if (conditionA) {
    return a;
} else if (conditionB) {
    return b;
} else if (conditionC) {
    return c;
} else {
    return null;
}

like this

return conditionA ? a
      : conditionB ? b
      : conditionC ? c
      : null;

But sometimes the last part actually looks like

    ...
} else {
    throw new AssertionError("Unexpected condition");
}

in which case you can’t directly translate the whole thing to a conditional expression, since this doesn’t compile:

     ...
     : throw new AssertionError("Unexpected condition");

Here’s where this little utility method comes in handy:

public static <R, T extends Throwable> R fail(T t) throws T {
    throw t;
}

which allows you to write

return conditionA ? a
      : conditionB ? b
      : conditionC ? c
      : fail(new AssertionError("Unexpected condition");

The generic return type ensures that the method always fits in as an expression. Unfortunately JUnits Assert.fail doesn’t follow this pattern!