I was playing with IntelliJ - which, by the way, is awesome - and one of the things it does is to keep pointing me to refactor a certain map/getOrElse patter to use a fold.
I mean it certainly sounds reasonable and reduces some clutter, if not lines of code, but... BUT! This is what is called "negative logic" where you basically worry about the negative outcome rather than the positive
For instance, a simple example:
wl.wlink.page.map { wlp =>
Redirect(routes.Wiki.wikieEdit(WID("WikiLink", wl.wname)))
} getOrElse {
Msg2("Already added!", Some("/"))
}
It would like this to become:
wl.wlink.page.fold (
Msg2("Already added!", Some("/"))
) { wlp =>
Redirect(routes.Wiki.wikieEdit(WID("WikiLink", wl.wname)))
}
... it really is the same as writing an if backwards, i.e. instead of the "positive logic" :
if(wl.wlink.page.isDefined) {
Redirect(routes.Wiki.wikieEdit(WID("WikiLink", wl.wname)))
} else {
Msg2("Already added!", Some("/"))
}
write it backwards by negating the condition:
if ( ! wl.wlink.page.isDefined) {
Msg2("Already added!", Some("/"))
} else {
Redirect(routes.Wiki.wikieEdit(WID("WikiLink", wl.wname)))
}
Note that this is never going to compile: I just put an if there...
This is in fact one of the anti-patterns I had, because our brains are wired to consider positive outcomes and it is easier to follow positive conditions when reading/writing code than putting the exception cases first.
I realize that's classic if/else structured programming thinking and not pure functional where folding over an Option probably makes total sense, but what do you think?