5 ms·
Yes there are clearly examples where the loop is less clear than the function. But I think they wanted to avoid complex 'functional' code like this: Averag
by IshKebab 10y ago
Yes there are clearly examples where the loop is less clear than the function. But I think they wanted to avoid complex 'functional' code like this:
Averager averageCollect = roster.stream()
.filter(p -> p.getGender() == Person.Sex.MALE)
.map(Person::getAge)
.collect(Averager::new, Averager::accept, Averager::combine);
System.out.println("Average age of male members: " + averageCollect.average());
From here: https://docs.oracle.com/javase/tutorial/collections/streams/reduction.html https://docs.oracle.com/javase/tutorial/collections/streams/...
A lot of the time it is clearer as an explicit loop, especially for other people to read. But it is annoying a lot of the time. I still think they should add generics.
- pjmlp 10y agoI can fully understand that example, only someone without FP knowledge would not get it.
- IshKebab 10y agoExactly the point. And that was a fairly simple example. I've seen much worse in real code.
- konart 10y agoWell, this is not the best example, imo. I have very littile knowledge of Java, but it's clear as day that we filter only entities with male gender, get their age values and return average. I mean... really.
- oconnor663 10y agoI think one of the simple differences between functional and imperative code is just that functional code is less likely to name its intermediate values. Imperative code is probably going to put something in a local variable, which hopefully has a useful name, but functional code is probably going to chain a bunch of generic methods together. This isn't a big deal when what I'm looking at is "students.filter(...MALE)" because that's obviously the "male students". But it quickly gets more confusing. What is "students.filter(... == year - 3)"? Is that "freshman students" or "sophomore students" or something else entirely? Of course there's nothing stopping functional programmers from naming their intermediate results, and nothing stopping imperative programmers from choosing useless 1-letter variable names. But the two different programming styles seem to encourage different things.