242 points · by sidcool · 5y ago · 110 comments
1. The intention of the code is obscured by more layers of abstraction, increasing complexity.
2. Small changes to what the code is conceptually doing tend to lead to larger changes to the actual code than with imperative code.
For the first point, reading through this post and the previous post linked, the code is doing the following:
Taking the entries of a map of product to count. Turning those entries into a different class, a row of each product and count. Then it collects this list on one hand. On the other hand, it sums the total, based on the per product cost and the count of the product in the cart. Then it combines the row list and the total cost into one object, returning it.
Deconstructed, half of this code is just unnecessary complexity. A map of products to count, and a list of unique product/count tuples are theoretically identical. You can iterate over them, find specific products, etc. There /might/ be a reason to specifically desire a list; However why would that code be coupled with code to sum the cost of the cart?
All in all, why is the code not just:
public BigDecimal sumPrice(Cart cart) {
BigDecimal sum = BigDecimal.ZERO;
for (Map.Entry<Product,Integer> entry : cart.getProducts.entrySet()) {
sum = sum.add(entry.getKey().getPrice().multiply(new BigInteger(entry.getValue())
}
return sum;
}
For the second point, briefly: Consider how code would have to change to calculate a deal, such as Buy One Get One Free. Such code to do this calculation would add another layer to the collector with another function defined somewhere (or hidden in some other existing abstraction, such as OP's CartRow::getRowPrice) instead of just visible in the function that calculates a cart subtotal. If the deal relied upon concepts not limited to one row at a time, eg buy any two flavors of chips for %25 off, the proposed solution would have to be completely rewritten. ...stream().
map(e -> e.getKey().getPrice().multiply(new BigDecimal(e.getValue()))).
reduce(BigDecimal.ZERO, BigDecimal::add)
The problem here is not the use of streams but that the author goes at the problem in a confusing and round about way.The first thing you do is unravel all that crap to a normal loop so you can debug it properly.
And when you're done, you really don't want to go back to the stream way of doing just in case it breaks again and you need to start debugging once more.
>> ...stream().
map(e -> e.getKey().getPrice().multiply(new BigDecimal(e.getValue()))).
reduce(BigDecimal.ZERO, BigDecimal::add)
>That's very pretty to look at and easy to read. But it's a huge pain in the ass to debug when getPrice starts failing.The trick with java and chaining calls is that you have to do the chain on each line, so the stack track can pinpoint the line it failed at.
so instead of the above, write the code as:
...stream().
map(e -> e.getKey()
.getPrice()
.multiply(new BigDecimal(e.getValue())))
.reduce(BigDecimal.ZERO, BigDecimal::add)
And the stack trace will tell you if the getKey() or getPrice() failed or the multiply(...) failed.Where it goes wrong IMO is where a mix of styles and too many inline lambdas splatter a mess of logic into some god-method.
As other comments note, good formatting will help with intelligibility of failures - and IMO sensible logging (at least of error paths) makes it all rather noce to debug.
sum(key.price * val for (key, val) in cart.items())
But the Java example makes me think "Wait, what?"Personally, the lesson I'm drawing is that your library shouldn't actively fight the native syntax of the language you are using - just use what your language provides, that's the cleanest and easiest way to do it.
But I guess people's tastes are different.
I use Joda Money and frequently find myself doing:
final Money bucks = stream.map(Thing::getPrice).reduce(Dollars.ZERO, Money::plus);
If you don't pass in a baseline, you get optional: final Optional<Money> bucks = stream.map(Thing::getPrice).reduce(Money::plus);
Also, StreamEx improves the ergonomics of Java streams. The way I would implement the original example: EntryStream.of(cart.getProducts())
.mapKey(Product::getPrice)
.mapValue(BigDecimal::new)
.mapKeyValue(BigDecimal::multiply)
.reduce(BigDecimal.ZERO, BigDecimal::add);
Unfortunately BigDecimal is not especially ergonomic (it could use a `multiply(long)` method, which would eliminate the annoying `mapValue()` above). But unlike the python version of this, it will preserve scale. And streams work as-is on Money types.Now, the first two are very fair not to want in a language because they allow programmers to bring in an unlimited amount of user-defined complexity.
Some destructuring however, would just make it easier to work with what's already in the language and libraries.
In a more complex example, with multiple steps and potentially multiple streams, using the Streams API allows the algorithmic and business logic parts of the whole calculation to be kept separate, more visible and more maintainable/adaptable as a result. Imperative code in such cases usually involves factoring out chunks of the for-loop into separate functions or classes which IME goes in the opposite direction.
In general, though, streaming abstractions leave that paradigm in the dust once things get become just a tad more complicated.
Using streaming abstractions, you can reason about the flow of your data at a much higher level and create abstractions which would require 100s or 1000s of lines of code to duplicate.
For example, if he decides he needs to buffer the stream, then perform processing on it, then send it out into to the world, he can do all of this super easily by using a few streaming combinators while everything is super clear and type-safe.
I would like to see an example of this, I just don't think streaming libraries, or abstractions in general, can get rid of that much complexity. In most cases, abstractions can't really get rid of complexity, they just move it around.
The issue I have with streaming abstractions is that the implementation tends to be overly complex. For instance, Rx libraries tend to be thousands of lines of code, and they're often written in ways that make it impossible to trace code or understand a call-stack. It makes some things easier, but when you run into a problem it becomes a nightmare to debug.
I'm just not sure it's warranted a majority of the time. Those libraries tend to be huge because they have to cover every single use-case, and they work at a very high level of abstraction. When you're working with stream-like domains, it's often possible to implement the subset of what you would need of that streaming abstraction with normal code, and in a way which is much easier to understand and debug.
People say this pithy truism all the time, and it's just not true. You're probably just talking about indirection and encapsulation.
Real abstractions by their very nature reduce complexity. You could say "No true Scotsman" but I deal with actual abstractions in Haskell all the time and it only simplifies code.
So maybe Java is just deficient in its abstraction capability, but parametric polymorphism and pure streams sound like a good start to me. If a steam makes you uncomfy because it's doing O(n) things "under the hood" and you "like to know what the computer is doing" that's probably just a personal comprehension issue.
this happens sometimes due to both java being a PITA to do functional programming with, and also partly due to the initial programmer of the streaming logic not breaking down into composable functions.
And with most people being more familiar with imperative style, it makes the functional style harder to maintain _for them_.
As for your second point, you could easily add such functionality to the code with a stateful mapping operation that sets the price to 0 for every other item encountered. In your code, you'd have to add another pass of the loop or you'd have to stick the logic for computing the price inside your for loop.
Personally, I've found that decomposing problems into stream based pipelines makes it much easier to decorate additional functionality than imperative code but that's just my personal experience.
public PriceAndRows getPriceAndRows(Cart cart) {
DiscountApplier discounts = new DiscountApplier()
return cart.getProducts()
.entrySet()
.stream()
.map(CartRow::new)
.map(cartRow -> discounts.apply(cartRow)) // Stateful discount application logic
.collect(Collectors.teeing(
Collectors.reducing(BigDecimal.ZERO, CartRow::getRowPrice, BigDecimal::add),
Collectors.toList(),
PriceAndRows::new
));
}You probably want to check all 'rebate rules' attached to all products in the cart whenever one is added/removed. An active rebate will then modify the price of the cart item, and the sum method can be stupidly simple.
There's nothing wrong with passing in a function other than `CartRow::getRowPrice`. That's one of the beautiful things about functional programming, you can alter behavior by passing different functions as parameters.
However, as someone who writes ecommerce code that deals with exactly this situation all the time, I can tell you that the question doesn't really make sense. Discounts are usually represented by data in the cart - either a special field, or a negative line item that gets summed along with the others. You don't just mysteriously have a second cheaper item in the cart.
I have encountered dozens of places where streaming API calls have been reworked into imperative by whoever ends up maintaining it just so they can figure out why the hell it is breaking in some unforseen edge case.
Because it's hard to review, too many things are happening on one line.
What if you have to negate multiplication? You're messing that line even more, with streams, you're adding one line that's easy to read, easier to review, track changes.
Add sum *= -1; on the next line if you think the line is already too complex.
Or just do return -sum;
On the other hand, in Clojure they are totally natural.
In the other code, you could substitute parallelStream for stream and have it execute in parallel for "free".
> liftA2 :: (x -> y -> z) -> Fold a x -> Fold a y -> Fold a z
The "teeing" functionality is actually one of the "selling points" of the Collector-like library, not a hidden gem:
> This module provides efficient and streaming left folds that you can combine using Applicative style.
It's curious how the same abstraction can have different emphases across languages.
Collectors are also Comonads:
- You can always extract a value of the type that parameterizes the Collector, just by "closing" it.
> extract :: Fold a x -> x
- You could, in theory, "duplicate" a Collector<X> and get a Collector<Collector<X>>. This seems like a dumb function, but it would allow you for example to feed different Streams to the "same" collector, by duplicating it before consuming a Stream, the taking the result Collector, duplicating it again, passing it to another Stream...
> duplicate :: Fold a x -> Fold a (Fold a x)
http://hackage.haskell.org/package/foldl-1.4.11/docs/Control...
list.stream().functionalOperations.collect(Collectors.toList())
whereas in Haskell you can just do whatever on your lists and it should fuse... or so I thought. Clearly I don't know too much about which way is the "right way" in Haskell since I haven't used Control.Foldl before and I just sort of assumed fusion would happen at least for most list operations.
It would be like a function that takes
- a Collector that produces an X
- a function that takes an X and returns a Collector that produces an Y
and returns a Collector that produces an Y.
The thing is: while being fed, the result Collector should first feed the initial Collector and, at some time, "switch" to the Collector produced by the function. But when to perform the switch?
tee - read from standard input and write to standard output and files
It's a proper vintage tool, listing RMS as an author.
Edit: less repetitive repetition, added coreutils link.
grep "error\|warning" log.txt | tee /tmp/issues.txt
would find mentions of the terms "error" and "warning" in a file and both print them to the terminal window as well as write them to the file /tmp/issues.txt. This can be quite handy at times.According to Wikipedia, the name "tee" is a reference to a T-splitter used in plumbing, which makes sense.
But the reverse is not true, an arbitrary set of for-loops can not be translated into a set of streamers. Right?
That means that the structure of your program is much more constrained when you compose it out of streams, than if you compose it out of arbitrary for-loops.
And if you know that your program obeys a set of constraints imposed on it by the connected streams, the program becomes easier to understand, because you can RE-use your knowledge of how those streams always work to understand every component of the system, meaning every stream-component of it.
Replace streams with "operator". All your program code can be written as operators like dot or plus, and since those operators gave constraints, then the whole program will be simpler, right?
If that were true, we'll still be writing code in assembly, managing registers by hand. Because hey, just 256 registers means that you can reuse your knowledge of registers everywhere, which means programs will be easier to understand again, right?
There are examples in threads which show real examples where plain code is better.
Think Unix pipes they are easy to understand because they all behave similarly.
Yes sometimes plain code is better sure but in cases where streams fit the job they are better.
I guess the main point is that streams operate on multiple elements and they operate the same on every element. Therefore you don't need to reason what happens to every element that goes through the pipe.
It is a bit like adding and multiplying matrices, you can understand the calculation without having to mentally follow how each matrix element is processed.
Here is the part about teeing https://youtu.be/pGroX3gmeP8?t=5499
But then I tried to think of a code where I would rather use this than a list comprehension or yield and a more manual control flow.
And I couldn't.
Those streams are elegant when the business logic flows perfectly like a river. Unfortunately, reality is messy, and production code will have matching, conditions, casting, extractions and transformations all over the place, leading to:
- very long chains of calls
- hard to change code when feedback pushes for it
- limiting your tooling (specially debuggers) to stuff that have exceptional support of chaining, and it's rare
[0]: https://www.jetbrains.com/help/idea/analyze-java-stream-oper...
But i find a lot of programmers don't do that - but instead write a first version which they don't truly understand (or understand completely), and then use stepped debugging to tweak the program until they get to a verison that works to their desired outcome.
That's why practicality beats purity in the vast majority of situations.
There is a place for purity, but you need a hell of a setup.
Notice that the author uses the word price (or row price) for two different things: the price of a product and the total (price * quantity) in a shopping cart line (cart row).
The set of CartRow can be calculated as a straight forward entrySet().map(...) of the shopping cart in products map form (Map<Product, Integer>).
The PriceAndRows object is really the total for all the cart rows and the union of all the cart rows. Both things can be calculated as a straight forward map / reduce.
But I find the opposite to be true; it's hard to reason about where/when the entire result might need to be collected, and the streaming APIs cannot really match the query language underneath (SQL, e.g.). Instead, streaming APIs are frankly confusing, and less efficient than just doing the straightforward for loops, IMHO. Especially when things get complicated, with multiple joins and map/reduce.
[1] Another way to achieve the incremental streaming result effect is to write everything in terms of generators. It is sooo much clearer to see a loop over a data structure and a yield to know how much the computation is actually incrementalized, IMHO.
.Aggregate(new PriceAndRows(),
//here result is the PriceAndRows instance and next is a cart row.
(result,next) =>
{
result.Price+=next.Price;
result.Rows.Add(next);
return result;
})
I'm trying to think of a better use case where multiple collectors would be cleaner than LINQ but LINQ has a lot of tools in the toolbox, SelectMany, Aggregate, temporary anonymous types, etc.However, even in the Java side, the example could be done with reduce alone, I think.
That’s my point: teeing itself is not aggregate/reduce. If after the branching the streams differ in size, reduce no longer applies, for example.
map(merge_func, zip(X,Y))?
https://docs.python.org/3/library/itertools.html#itertools.t...
def teeing(reducer1, reducer2):
return lambda acc,elem: (
reducer1(acc[0],elem),
reducer2(acc[1],elem)
)
functools.reduce(
teeing(
(lambda l,elem: [elem] + l),
(lambda l,elem: elem.price + l)
),
cart.getProducts(),
([], 0)
)"Idomatic python" is dead, and lives now only as a pretty dumb ideology which states: everything must be phrased as a naively-typed naively-imperative program. Python is being made, retroactively, a bad imperative programming language: largely because its creator always thought that's what he'd made (he is wrong).
It's a great tragedy "pythonic" has become this: a back-reaction against the times (of increasing adoption of functional programming driven by increasing data-transformation needs).
To me, the features you cite seem to fit the Pythonic approach intuitively.