If this API is not understood then the code feels convoluted.
Therefore such projects have to contain a document that will explain the most common usage of the API to the newcomer. I think that this would remove most of the confusion.
Naturally it would be good if we had one most widely standardized API that most of the people are familiar with (like they are with if and for).
I think there is more going on here. For the sake of eliminating an if, you are lifting everything else into what is effectively a separate language with the original code embedded in that language. Overall, that doesn't look like a win to me.
After all, what is the actual domain logic? Is it flatMap().map().flatMap().map()? Or is it validate().businessLogic().generate() ?
That doesn't mean that what is going in isn't useful, but it seems to me we need to have a way to specify the lifting without writing it down everywhere, so that the actual code can be expressed at the base level again.
for(blah blah blah)
tells the reader nothing more than there's going to be a loop, but map(blah blah blah)
tells the reader one sequence is going to be transformed into another by applying a function to each item. That's more informative to the reader if used for its intended purpose. It has the opposite effect if abused to repeatedly call a function mainly for its side-effects.All programming techniques should be viewed as means to write code that's some combination of readable, reliable and performant, not as ends themselves.
Except in this case it wasn't actually a sequence, but an Optional/Either and it wasn't about transforming that sequence but about error handling. So in a way the code wasn't even not intention-revealing, it was actually deceptive.
However, just as I also wrote, that's not an actual sequence of values, it's a single wrapped value (or none).
Optional can generally be thought of as a "sequence" of one or zero values. You could use an array of "[some]" or "[] /* none */" to manage control flow in an almost identical way (you'd just be adopting and managing an API that doesn't statically ensure that these arrays never have more than 1 value).
"map/flatMap" are predictable functions that can be used to manage the transformation of data (which is generally the entire point of code). The type/context that a computation is lifted into communicates a lot: Optional, for example, can be returned for a computation that may or may not return a value, and it can be "mapped" into another value by a pure computation that _always_ returns a value, or "flat-mapped" through a computation that may produce another nullable value. Anyone familiar with these basic functions can jump in, read the code, and generally know that every computation lifted into "map" can't fail, while every computation that is "flat-mapped" can. And in static languages it's all checked by the type system! No testing for "null" everywhere!
I don't use partial application/currying that much, but more and more over time.
All in all I feel that doing these things have greatly improved my code and efficiency, and I'm kind of waiting for some downtime to get back into learning the more 'hardcore' functional languages.
It might be said that any such example would be too complex and drawn-out for an article like this, but if so, then to me that is like the drunk looking for his keys under the lamp-post: writing an article that claims a simple example shows a profound difference, when it does not, suggests that the Emperor's wardrobe is threadbare. The thing to do is to provide links to articles where this is worked out in sufficient depth, and I would like to see some of those links here.
* Mapping (producing a data structure of the same size/type)
* Filtering (producing a data structure of the same type buy smaller)
* Side effects
* Collecting (producing a different data structure)
If you're incredibly unlucky or foolish a for loop might be doing more than one operation at a time!
Assuming you're only using the return types, map, filter, and collect are very clear about having only one purpose.
If that's not telling you more I don't know what is.
A more useful question is how can map, used properly, make things better, and I stand by my claim that the simple examples of the sort given in this article, and articles like it, fail to make that case.
I have no such expectations of a loop until I've read and understood its body. I hardly have any expectations of a loop at all until I've understood the whole thing.
And that's how map, used properly makes things better. It communicates what kinds of things the reader should expect it to do and not do. It reduces the cognitive load of reading the program, as if, for example, you're scanning for where a certain side effect happens, you can skip the function called by 'map' on your first pass through. It shouldn't happen there; maybe it could, but it should be pretty far down the list of places to check.
Mea culpa: I have to admit that I have sometimes used side-effects in map to modify the members of a list returned by a function reading data from a stream.
Whenever I write Java (or Java-like OO), I always have this exact "separate language within a language" feeling.
I'm supposedly working in a high-level, object-oriented, loosely-coupled, message-passing/dynamically-dispatching world of classes and instances; yet an awful lot of code is actually written in a separate language of "primitive values" with opaque control structures like if/then/else, for/while, etc.
Compare this to e.g. Smalltalk, where "ifTrue" is a method on boolean objects, "timesRepeat" is a method on integer objects, etc.
Having "for" not be a method on an object means it's something completely different: a magical keyword control structure, a gift from the irreproachable language designers to the lowly language users; since mere users cannot be trusted to make such decisions for themselves.
Is the potential of failure part of my domain? Or is it something I have to handle in order to avoid errors?
Should .businessLogic() have to handle the case if .validate() failed? Or should it only be called if validate succeeded?
Using a common API (Either is not new or novel, it's all over the place) to separate success from failure lets me write code that is only concerned with its side of the success/fail tree without polluting it with null checks and error handling that belongs elsewhere.
There are subtle variations in naming like Java's Map is Select in C# because Microsoft modeled its functional API on SQL, but you have the same differences for iteration and selection (the things you are referring to for and if).
For example you have 'for (int i = 0; i < n; i++)' in C, but you don't have the exact same way of doing it in Python, where you have to use a range: 'for num in range(0, n):' or you can write a 'while' loop in Java but not in Go where it's a 'for' with a single expression.
I would choose a functional version over a three level nested for loop monster any day.
I'm a fairly decent programmer and I never worked with map or flatmaps outside of examples.
I have however significantly simplified two significant code bases, made and maintained for years a webapp that users loved etc.
Very often I feel it is just people wanting to sell something and it wouldn't surprise me if many of the people who sell functional are the same who sold object oriented back in the day.
This article was actually a bit refreshing IMO.
That being said, I love map/filter/flatMap. Look at them as higher level loops.
For example: A while loop is very general, you can implement any kind of loop with it. This makes it harder to understand the meaning of the loop. Therefore, when you want to iterate a constant number of times, you'll likely use a for loop. It expresses your intent better. Map, filter, and flatMap are just extending this principle to more specialised use cases. The advantage for a reader is that the one word "map" already tells them a lot about what the loop body is good for.
An added bonus is that null elements are sorted and that you HAVE to separate data manipulation operations. You have to filter, map and apply sorting separately, not mix all three in a triple for loop with several branches.
Of course, if you're writing actual code, now -- what I'm saying doesn't help you much. But if you're looking at a new language, it might be important to remember: not "filter" is broken that way, it's just the implementation on the JVM.
It's often justified to do that. For instance, we model stuff as matrices or graphs to gain access to their mathematical properties or because we have specialized hardware for matrix operations.
The big debate right now is whether the mathematical properties of functional programming are useful enough to move further away from natural language for general purpose programming.
We probably think something like this:
Parse and validate the request
If that fails then
return 400, "invalid request: " + err
Run business logic to get a result
If that fails then
return 500, "logic failed: " + err
return 200, result as JSON
So should we use a formal language that looks similar to that or are there good reasons to use a chain of map and flatMap calls to hide the branching logic?I can dream up APIs which will keep confusing you, no matter how long you use them (hello Android SDK!). Or which have difficult to memorize syntax (hello Bash!).
Over the past two decades I've internalized the value of writing code that's very easy to understand. Otherwise 6 months later I can't figure things out myself. This Java style reminds me very much of Scala which seemed like a decent language until I saw how people actually use it in practice. Noped right out of that in a hurry.