iex
01/22/2020, 3:02 PMfor (handler in handlers) {
if (handler.handle(uri)) break
}
spand
01/22/2020, 3:03 PMhandlers.any { it.handle(uri) }
maybe?spand
01/22/2020, 3:04 PMDico
01/22/2020, 3:13 PM.find {}
would also workDico
01/22/2020, 3:14 PMstreetsofboston
01/22/2020, 3:15 PMhandlers.takeWhile { !it.handle(uri) }
streetsofboston
01/22/2020, 3:18 PMhandlers.forEach {
if (it.handle(uri)) return@outerScope
}
spand
01/22/2020, 3:25 PMspand
01/22/2020, 3:25 PMspand
01/22/2020, 3:27 PMiex
01/22/2020, 3:56 PMbreak
version seems actually better 🙂iex
01/22/2020, 3:56 PMBob Glamm
01/22/2020, 4:15 PMIn general I dont understand why people go to such lengths to avoid a simple for loopAnswer #1: which is easier to read? The
for
loop or handlers.find { it.handle(uri) }
?
Answer #2: Assuming handlers have side-effects, then lurking under that for loop is the possibility of an unlimited number of side-effects. So instead of being able to look at just the for loop to determine where an error lies the entire application may need to be deconstructed to find it.
With those unconstrained effects comes an inability to usefully and completely test the code in question since there are now no rules about what can actually happen in that for loop. Unit and integration testing likely cannot cover all possible side-effects.
Writing the code as a tail-recursive find in an effect management system (such as Arrow) constrains the side-effects to be well-defined, proven correct-by-construction by the compiler, and requires only property-based tests to test - specifically, the property that at most a single handler is run.iex
01/22/2020, 4:30 PMfind
isn't semantically correctiex
01/22/2020, 4:31 PMCasey Brooks
01/22/2020, 4:33 PM.find
as-opposed to a for-loop. You can cause the exact same kinds of side effects in both, but in the .find
case it’s harder to even know that side-effects are happening. With a for-loop, running code and breaking in the middle is much more obvious what’s going on. In the find
case, it kind-of looks like the values have been precomputed, when in reality its computing them right there with the possibility of causing side-effects