by CloselyChunky · 5y ago · 0 comments
Then iterate over the tuples, if a predicate fails, return the associated error message and throw an error/display the message to the user.
In the end it looks something like this:
var validators = Stream.of(
Map.entry(user -> user != null, "User must be defined"),
Map.entry(user -> user.firstName != null, "Missing first name"))
validators.filter(e -> e.getKey().apply(userToBeValidated)).map(Map.Entry::getValue).getFirst()
(This example uses Map.entry for tuples as Java lacks native support for tuples)This limits branching and you have all validation criteria neatly organized in the same location.
That approach looks nice though. On that subject, JS has some nice libraries including io-ts[1] which has a functional approach using Eithers to encapsulate errors/success.
validators.reduce(Either.right(user), (acc, next) -> acc.flatMapRight(next))
This way you'll end up with either the validated user, or the first error that occurred and all the other validators were skipped.