Background
I have been fascinated with Scott WLaschin's Railway Oriented Programming model of handling exceptions: have a side channel, where all the bad stuff will be processed, and keep the good stuff on the main track. Picture below:
Problem
A common pattern that comes up in daily code is like :
- Have a list of data
- Validate each one of them
- The validation can throw exceptions
Question
How to do this in a way that resembles the railway-oriented model discussed above.
Somjit's answer shows correct approach however it uses an outer variable (
errors
) to accumulate the errors. This is, in general, discouraged since we should avoid the global/external state.You can use vavr's
partition
method to split the stream into two: one with errors and one with validated ints. They are both put into a tuple:EDIT Actually there also other options like:
which uses
teeing
which is quite interesting collector from java API. Unfortunately it mixes vavr and java API which is not great, not terrible.And:
which uses vavr API only but underneath uses java
List
since a mutable structure is required here.