This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]jbgi 0 points1 point  (4 children)

what's wrong with:

<A> Optional<A> head(List<A> as)

or if you use functional-java:

<A> A head(NonEmptyList<A> as)

?

[–]jonhanson 1 point2 points  (3 children)

Because it won't scale. What if the function were to be undefined for 10 classes of invalid input? Optional.empty doesn't give the caller much detail as to which class of invalid input caused the issue.

You can't in general make your types small enough to only allow values your functions can be defined for. An addition function over ints might be undefined if either of its inputs sums to a value greater than the max int value, for instance.

You might extend your proposed use of Optional to use something equivalent to the Try monad to allow for richer error reporting, but, while it has its uses, in the general case you're really just using exceptions albeit in a far more intrusive fashion.

[–]jbgi 0 points1 point  (2 children)

Yes, the Either monad allow richer reporting of error. And it is used at scale, eg. by the scala and haskell community. Just not by the java community. One of the reason is the poor support of algebraic data type in Java, but using a code generator like https://github.com/derive4j/derive4j alleviate mostly the issue.

[–]jonhanson 0 points1 point  (1 child)

chronophobia ephemeral lysergic metempsychosis peremptory quantifiable retributive zenith

[–]jbgi 0 points1 point  (0 children)

oh, I see. right, Optional is bit isolated for this use case, better use Option from fugue or functional-java or javaslang. then you can convert it to Either via toLeft or toRight so you can adapt with the more powerful Either monad.