Hacker News new | ask | show | jobs
by ajuc 3647 days ago
I agree in general case, but this example

     transactions.stream()
                 .filter(t -> t.getType() == Transaction.GROCERY)
                 .sorted(comparing(Transaction::getValue).reversed())
                 .map(Transaction::getId)
                 .collect(toList());
seems to be net improvement to me. It reads like SQL, and eliminates many causes of error (wrong indexing variables, off-by-one, copy-paste error in boilerplate).

Yes it requires learning several new concepts, but in the end it pays off.

BTW I wouldn't switch old code to this style, because there never seems to be time for that. But new code written like that is perfectly OK IMHO.

EDIT: I really should've checked the code more carefully - the initial version had no indexing variables. Still, it reads better and has less boilerplate.

2 comments

While some people may like to read code that looks like SQL, I've found Java 8 features like this are poorly supported by the debugger, so debugging stuff like this tends to require "horse whispering" or rewriting the logic into something that can be stepped through.
GNU Gremlin is a stream API to traverse graphs.
That reads more like Haskell than like SQL. (Doesn't have any bearing on the rest of your point one way or another.)
I think it reads better with intermediary variables. Granted sometime you go to name an intermediary variable that does two things (just like male_siblings = (2 * (X + Y)) if I have a brillant idea for the variable name.