Re:Using the switch(true) pattern in JavaScript
by harg on Monday April 12, 2021 @12:12PM
(#26781118)
Sure, if you're validating some data there're loads of better ways to do it than a bunch of conditionals. I was purely commenting on the switch(true) pattern vs some "if"s.
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.
Re:Using the switch(true) pattern in JavaScript
by CloselyChunky on Monday April 12, 2021 @12:16PM
(#26781193)
Sure, if you have an either/result type, the whole thing becomes a fold, where each validator is a function from user to Either<Error, User> and then
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.
Re:Using the switch(true) pattern in JavaScript
by wvenable on Monday April 12, 2021 @06:06PM
(#26785768)
If you are using a language with yield you can make this simpler (and more flexible) by using a generator.
Re:Using the switch(true) pattern in JavaScript
by fl0wenol on Monday April 12, 2021 @02:12PM
(#26782956)
Agreed, +1
This pattern goes beyond JS and is very helpful for supporting tests; you've already factored out your validators. There's always going to be stragglers but you can define and push in an extra check on the spot (i.e. using lambda funcs at least in JS).
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:
(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.