9 ms·
That’s what disappoints me in modern Java. There is practically no ifs. It makes it inaccessible to beginners on the project, and the streams are about twice as
by laurent92 5y ago
That’s what disappoints me in modern Java. There is practically no ifs. It makes it inaccessible to beginners on the project, and the streams are about twice as slow… just because devs think they are more clever if they pile 7 “.map()” to transform a list.
list.stream().filter(Objects::nonNull).map(User::getUsername).filter(Objects::nonNull).filter(name -> name.contains(searchString)).map(name -> “We have found your user: “ + name).orElse(“We haven’t found”);
Basically unreadable.
for (User user : list)
if (user != null && user.getName() != null && user.getName().contains(searchString))
return “Found it!”;
return “Not found”;
- ineedasername 5y agoJava has never really liked to do in 10 characters anything that could be done in 30 characters instead, especially if it obfuscated things a bit more at the same time.
- the_gipsy 5y agoYou forgot to add null-check ifs for `list` and `searchString`. Oh and check-wrap for exceptions too!
- peoplefromibiza 5y agothe two snippets you posted do different things In a list John Jonhatan Joy searching for "Jo" returns all three of them in the first example, it stops when the first has been found in the second. Start including the tedious bits about adding found items to the list and the waste of intermediate variables and your "clear" code is wrapped around a lot of repetitions, that only add noise. It just happens that you are more familiar with the second style, but pipelines are better in many other ways, clarity of intentions being one of them.
- RHSeeger 5y agoThe code he posted isn't actually valid because you can't "orElse" a list. That being said, I would presume it was meant to include a "findFirst". Something like list.stream().filter(Objects::nonNull) .map(User::getUsername).filter(Objects::nonNull) .findFirst(name -> name.contains(searchString)) .map(name -> “We have found your user: “ + name) .orElse(“We haven’t found”);
- peoplefromibiza 5y agoexactly, that was the catch. the point I wanted to make is that the snippets presented seem carefully crafted to make pipelines look bad, but usually that's not the case.
- freidenker 5y agoThe snippets actually do the same thing, as long as you add a .findFirst() to the first example to make it valid Java code. Intermediate stream operations like map or filter are always lazy. And .findFirst() is a short-circuiting terminal operation, that does not need to consume all stream elements. https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/stream/package-summary.html https://docs.oracle.com/en/java/javase/11/docs/api/java.base...
- peoplefromibiza 5y agoobviously that was the point, if you don't even care to write correct code, you can make every piece of code look bad. Truth is java streams and, even more, reactive java are the only two things that make java bearable, god save who invented them. If I had to program java with for loops and list.add or null checks everywhere, I would probably kill myself on the spot. But the amount of programmers taught to program like it's still 1995 it's so damn high And I am closer to my 50s than my 40s, I can't understand why people fresh from uni say they can't understand something like list.stream() .map(this::maybeGetUser) .filter(maybeUser -> userIsPresentAndNameStartsWith(maybeUser, prefix)) .findFirst() .orElseThrow(new UserNotFoundException()); with the benefit of being lazy and only inspecting list items up to the first one that matches (and if you don't mutate any data, easily parallelizable)
- filoeleven 5y agoThat’s a failure of Java’s language design, not a failure of the functional/declarative paradigm. Your for loop can do all kinds of damage to the list, and you have to read it all to find out what it does. Saner languages make the functional version more expressive.p: return first(users.filter(u => contains(u.name, searchString)) I’m not saying JS is a sane language; it has an anemic standard library without a robust “first()” or “contains()”. But that code gets you the first user where the name matches, without resorting to indexes or null checks or worrying about how a for loop can mutate lists that it should not. EDIT: I should have used filter(list fn) here, I was trying to write something plausible in JS instead of a purer functional language and misses that translation.
- usrbinbash 5y ago>and you have to read it all to find out what it does. Which isn't a problem, because as long as its all loops'n branches, the code is easy to understand.
- filoeleven 5y agoHard disagree. For loops do not have guarantees about in-place mutation; that’s why they require a full read. Anything that starts with a map/filter is guaranteed to only apply to the thing that it is assigned to. That’s more than worth its weight in grey hairs. EDIT: “full read” includes “everywhere else this array is used, which can have far-reaching consequences if it was passed into the containing function by reference.”
- jstimpfle 5y agoMost temporary variables are single assignment, and many newer procedural languages do have variable declaration syntax for single-assignment variables. Such as Javascript's `let`. Another wide-spread syntax feature is for-loops over collections like `for item in list`, again being extremely easy to read and not requiring any assignments. So, accidental in-place mutation is not an issue in practice. But, in-place mutation can be very useful to express logic in an easy to understand way. Coincidentally my main language does not have any of these features, and in-place mutation is like 0.1% of all my problems. (And notably, memory management is < 5% of my problems). These are all just theoretic problems, what really matters is developer experience. You can write terrible bug-ridden convoluted code in any language, ESPECIALLY with many filters and lambdas and callbacks. The issue with the functional style is that it becomes harder to see the control flow and run-time characteristics. I'm sure functional style is great to express set operations (like DB queries) but IME they tend to optimize for source code brevity and pessimize for runtime performance.
- cmeacham98 5y agoI don't write java, but assuming it has a null coalescing operator you can likely do all that in a single map in a way that is (in my opinion) cleaner and easier to read than both of your examples.
- erik_seaberg 5y agoKotlin does but sadly Java’s Optional<T> has no syntactic sugar, so it ends up looking like Optional.ofNullable(user).map(User::getUsername).map(name -> name.contains(searchString))
- AtlasBarfed 5y agoGroovy is still far better and more readable. And with @CompileStatic it is basically the same speed.
- angelzen 5y agoCoding is values, arrays, dicts, ifs, loops and functions. An expressive set-like operations library over arrays (& dicts) gives superpowers.
- MattPalmer1086 5y agoI just started using Java's functional side a few weeks ago. Lambdas are really nice and often make the code clearer. I like writing more declaratively. But the stream interface is just horrible. I had to read a lot before I understood how to just filter a list and collect the results. And even after that, it still somehow didn't scream out what it was doing to me. I guess you get used to it.
- benwaffle 5y agoScala is super readable users.find(_.name.contains(str))
- raxxorrax 5y agoModern Java looks horrible to be honest. I create abominations like this in JS pretty often, but it isn't good code. Best if wrapped in a huge try/catch where the error case juwt prints "didn't work for some reason...". https://esolangs.org/wiki/Pancake_Stack https://esolangs.org/wiki/Pancake_Stack Pancake stack doesn't need this hipster crap like functional programming or ifs or fors.