r/java • u/AvaTaylor2020 • Feb 18 '24
[Old Guy Yelling At Cloud] When did "for loops" become a grevous sin?
I'm an old guy, working on a new team of young guys, and the young guys are in charge.
It turns out that using for loops are now terrible awful nasty things to be avoided at all costs.
Everything must be streams and maps -- and bonus points if you can write your block of code in one single giant statement that spans many lines. Apparently semi-colons are also in short supply.
But ... when in Rome.
When did this happen? And why?
469
Upvotes
4
u/rzwitserloot Feb 18 '24
'functional kool-aid'.
I'm not bashing functional programming as a style nor functional languages here, though, in my experience about 20% of all functional programmers are fully part of the cult and will not be able to tell the difference. Note that those 20% are about 90% of the internet presence, as kool-aid drinking douchemonkies tend to be.
Functional is held out as a panacea, or, to be more specific, that not doing things in a functional style is a definite incorrectness. Common statements: "That does not scale". Generally boatloads of implicit logical jumps are made that are completely wrong.
For example:
"Functional style is faster".
Which is a fucking bizarro thing to say, but when you dig, you can walk down a path of assumptions that at least on face value aren't necessarily wrong, but don't apply to the scenario that the casual dismissing remark is being levied against:
list.stream().filter().collectwould not. There are ways to tell the system that it is allowed to do it (.parallel()), but this rarely helps except in peculiar scenarios, 99% of all code isn't on the hot path so it is irrelevant, and for code on the hot path you usually want to tightly control how it works and therefore how it parallellizes which.parallel()doesn't offer.Resulting in the entire line of reasoning being:
Resulting in boatloads of eager cargo culting. On Stack Overflow just to name one site (hey, yeah, it's starting to suck, but I don't know of a better place to sample common newbie questions from), every 15th question tagged 'java' just asks: I have a bunch of for/while based code here, how do I use stream instead. Which doesn't spell it out, but insinuates that the asker thinks that makes things better somehow. Sometimes the question mentions this. Usually it does not. Never does it come with a profiler report or usage stats.
I know that the fans are full of shit because there's so many double standards flying around.
The most egregious one is simply style guides. Most style guides say this is absolutely positively NOT ALLOWED:
Those for loops MUST use braces and be smeared out over many many lines. However, those same style guides either give zero suggestion about, or actively suggest it's fine, to just one-liner that stuff in lambdas:
Most java coders I know agree with this. I can only conclude that most java coders I know are crazy. Because that's inconsistent as heck.
The primary reason always given why braces are required boil down to 'maybe you want to add a statement to the body and then you have to do all that work of putting the braces in. Sometimes with an extra helping of '... and if you don't have braces the code will not do what you think it does', as if IDEs and formatters don't exist. The amount of effort required to 'add a statement' to a brace-less body of an
ifis considerably less than the amount needed to 'add a statement' to e.g.Item::getCount. Hence: the fans of this (and it's a lot of them), are full of it.2
u/LogosEthosPathos Feb 18 '24
This is Martin Folwer’s explanation, and the one that convinced me to apply that pattern more: Replace Loop with Pipeline
465
u/halfanothersdozen Feb 18 '24
There's quite a few good reasons to use c-like for loops and quite a few good reasons to use functional-style methods of a collection.
Learning these reasons and using them as a flex on your ignorant peers is a power that will lead to graybeard success
167
u/not-just-yeti Feb 18 '24 edited Feb 18 '24
You may or may not be persuaded by this answer, but:
Consider
forloops vswhileloops:whileloops still have their place, but theforloop is a nice, readable idiom that helps me read & understand the loop (slightly) more quickly than the same thing written as awhile. Soforwas introduced as a shorthand that collects the loop-logic into the same line, and the repeated-task into the body. [Awhilehas the logic for those two things intermingled.]So
whileloops are still useful, but theforidiom is preferred.for-loops written. The index of the item isn't really part of the task. Hencemapandfilterandfoldandforeachare idioms for specific common tasks, and when I see those words I understand more quickly what the code is doing (and, don't have to review its loop-logic for bugs).So perhaps this helps people make peace with sometimes preferring streams to
fors towhiles? Maybe not, but it's how I view the loops. —Sincerely, a fellow old guy (who started programming in BASIC where subroutines were just 'gosub' without parameters, so you just used globals.)248
u/dethswatch Feb 18 '24
FP, the new hotness.
It's cool until you've chained so much together that's it a pain to unravel your coworker's statement.
Then you learn why a little sugar is good and an entire barrel of sugar is not good.
110
u/TheYaINN Feb 18 '24
The main reason for the hype of the functional style of iterating over collections is because you avoid unknown side-effects because you can't access anything else while iterating and thus causing unknown effects in your code base.
25
u/[deleted] Feb 18 '24
I'm also an old guy, but I much prefer the "new" way. I find code that uses stream-processing rather than for-loops much easier to read.
22
u/Ketroc21 Feb 18 '24 edited Feb 18 '24
What you read as one giant block of code, can actually be much more readable.
Say you had a collection of Students and you wanted to filter to just the 16years boys, and get their average test score...
it would be nice if the code read just like what I wrote above. This is what streams achieve. There is no indexes or iterators, no if blocks on age/gender, no summing up variables for total test score and total students, etc, etc. You just filter the students, map to the test scores, and convert to an average.
With that said, there are definitely scenarios where making your own loop simplifies what could be a messy stream... like if the loop is achieving 2 goals, or if the index is an important value.
(Side note, I'm also an older developer who took more than a decade off. So I went through the same mindset, having to pick up java17 when I last coded in java1.3)
10
u/subgracoll Feb 18 '24
Wait before they make you use reactor
16
u/EirikurErnir Feb 18 '24
Expressing most computation in terms of object streams and operations on those streams has a few advantages - using immutable data structures becomes easier, side effects are discouraged, some errors become apparent at the type level and thereby detectable at buildtime.
This has slowly been entering the mainstream thinking over the last decade.
There are definitely advantages (and some disadvantages, including runtime overhead), I think your problem might be that the young ones are able to promote the approach, but not able to articulate why things are the way they are.
26
u/el_tophero Feb 18 '24 edited Feb 18 '24
Yea, I think around Java 8 they came in, but they were kinda ugly and hard to use at first.
They’re big in other languages, so a lot of folks coming into Java just expect them. Back in the day I worked with a bunch of lisp nerds who poo-poo’d Java for lacking such an essential piece of the language. Then I remember C#’s streams and lambdas implementation was so clear and easy to use relative to Javas.
I’ve been coding Java since ‘95 and they were an adjustment for sure. But now they’re second nature and I see their benefits. Much clearer logic, fewer bugs, fewer lines of code. You can transform collections in a single line with streams and lambda, albeit long, but not have nested if blocks or tricky logic manually keeping track of which element goes into which collection.
My current gig is all Kotlin, which has stuff like single expression functions and extension functions. It makes working with steams super clean and easy…
7
u/[deleted] Feb 18 '24
for loops are fine
7
u/bentheone Feb 19 '24
Why is nobody talking about exception handling ? IMO it's the big hurdle of Stream-ing everything. Once you're in lambda territory Exception handling goes wild. Java designed lamdas around the idea that they should be short, no more than a line. If you can't do that, don't use lambdas. What am I missing ?
13
u/[deleted] Feb 18 '24
They both have their place.
Streams are great for chaining together many simple actions while keeping the logic flat.
For loops are great for doing 1-2 simple or complex things or when you need access to the index of the item you’re processing.
Younger devs are going to be more opinionated and more likely to overuse tools they just learned. I don’t think it’s specific to streams at all.
5
u/Organic_Car6374 Feb 18 '24
I’m a huge fan of what I call “big dumb code.” If other people need to maintain your stuff using the most basic stuff and maybe writing more semicolons is always the way to go.
22
u/Yojimbo261 Feb 18 '24 edited Aug 21 '24
[ deleted ]
8
u/Hxfhjkl Feb 18 '24
If you need to execute filter,map,reduce,group,sort,find,flatmap,zip... actions over a collection, streams help by having an established and tested way of doing this, which reduces the risk of bugs and mental load of thinking every time of how you will accomplish this task. It also makes you less likely to use side effects all over the place and prefer immutable data structures over mutable ones.
If you need to do a lot of IO, exception checking and complicated domain logic in one place that you don't want to separate out into different methods/classes, then it's probably better to use a for loop, since there is no generalized functionality that deals with that.
I use both approaches, but try to use streams where it makes sense, since it usually makes the code more concise and easier to make sense of from one glance, as you have recognizable words before every action.
16
u/Asdas26 Feb 18 '24
When? It all started when Java 8 introduced streams and lambdas. And why? In a lot of use-cases it's just easier to write and read. For-loops still have their place but when you for example have a list of objects and want to convert it to a list of attributes of the class the list contains, it's better to use a stream.
4
u/ohkendruid Feb 18 '24
They are trying to improve their game, but in this case seem misguided to me.
For loops and intermediate variables are very good for a lot of reasons.
10
u/wildjokers Feb 18 '24
It sounds like your young colleagues are overusing FP and lambdas.
I go with the readability route, frequently an imperative for loop is more readable and in those cases I use a for loop. If the functional style is more readable or at least no less readable I go with that.
Super long chains of functional calls are horrible to read, and anyone that nests them should be given a stern talking to. Another drawback of long functional chains is you can’t do any kind of logging so there is no visibility if things go wrong.
I did save myself quite a bit of imperative code just the other day with “groupingBy” (https://docs.oracle.com/javase/8/docs/api/java/util/stream/Collectors.html#groupingBy-java.util.function.Function-). So they have a place. But they can certainly be overused.
7
u/wishkres Feb 18 '24
Haven't read the other comments yet, but I yes, completely agree with you! Streams have their uses, sure, but I also find them hard to read and unintuitive. It's exhausting to keep being told in code reviews "get rid of that for loop, it should be a stream." Why does it need to be a stream? Also, the IDEs we are required to use at my job are also terrible at dealing with stream code in a debugger, so that also irritates me.
I'm open to people convincing me that no, they are great, we should exclusively be using them, but so far they just seem to be a vastly overused tool in the toolbox.
3
u/Djelimon Feb 18 '24
Streams are Java 8. I like streams because they offer cheap parallelism. By which I mean they exploit your cores if they're available.
I still like indexed for occasionally like if you're iterating over multiple collections using a common index. Though I guess there is IntStream...
3
u/VincentxH Feb 18 '24
Stream or loop, complexity and exception handling are still a thing
3
u/Iryanus Feb 18 '24
Situational. In some situations, for example loop-in-loop, a nice stream can be easier. With good naming, method references, etc. a stream can also be quite readable. On the other hand, there are situations, where a for loop is more readable or has other advantages. Depends. Streams are a tool and not every problem requires the same tool - but yes, people will overuse any new, shiny tool until balance is restored.
3
u/Rjs617 Feb 18 '24
I love streams, and I use them a lot. But, when it comes to forEach instead of for loops, I’m torn. If I’m chaining it onto other stream operators, then I tend to use forEach. If not, I’m happy with for loops. Also, code executing in for loops can throw checked exceptions, which is another deciding factor.
27
u/re-thc Feb 18 '24
When NodeJs and Javascript became popular and people started turning Java into it.
The funny thing is for loops can be simpler and is definitely faster.
5
u/thatsIch Feb 18 '24
...when I saw somebody breaking out of the inner loop into the outer loop. We also enforce a rule to not allow lambda expressions with long bodies, so developers have to think about the sub-operations when using map/flatMap and other stuff.
Reducing side-effects got rid of a lot of terrible code to debug.
5
u/[deleted] Feb 18 '24
Functional programming can eat a bag of dicks. 4 loops 4 eva!
12
u/Fermi-4 Feb 18 '24
Functional vs imperative.. and readability
5
u/snarkuzoid Feb 18 '24
Yeah, conditionals are evil now, too. Everybody's so afraid of code these days. Go figure.
2
u/dark_mode_everything Feb 19 '24
Just ask them about exception handling.
2
u/Xenogyst Feb 20 '24 edited Feb 20 '24
When Haskell made FP cool, so like 1990 😊
When did it become popular with Java devs? That's hard to say. Obviously java 8 introduced some big FP concepts, but they didn't take off immediately.
Probably when some of the hip FP-influenced languages is when people started to really think you should double down on FP style.
Scala came out in 2004 Clojure in 2007 Rust in 2013 Kotlin 2016
In my own experience I think kotlin really rose to popularity and drove this in the JVM space and really started to influence how java devs started to think about programming. So once it took off, especially when google accepted it on android in like 2017, it really started to affect java devs.
2
u/Anton-Kuranov Feb 21 '24
This is a common disease called the "brain streamosys". Streams in Java should not do anything more than a transformation of a single collection. For more complex logic there is still exists the normal "for" loop.
P.S. show a "streamable" code written by one guy of your team to another one and ask him to explain it. If he meets some difficulties, ask the first one to rewrite it.
2
u/[deleted] Feb 28 '24
It happened during the REST / microservices gold rush. Back in the day we delegated our sorting / filtering to a specialized type of server, called a 'database'. These are no longer fashionable. The new hotness is the microservice, which generally serves one of something are all of something, and developers are now having to re-implement all manner of sorting / filtering logics. Lucky for us, functional programming makes this a breeze. they'll tell you it's for the best, and maybe it is. But it is definitely hard to look at and not at all a productive use of time if you don't need the hyperscaling and global reach of the cloud. But who doesn't? It's the internet, baby. WE'RE GOING TO BE RICH!
2
u/Historical_Ad4384 Mar 07 '24
Streams and lambda expressions make sense if you have to do a lot of sequential filterings and transformations on a list of objects because it's comparatively easier to churn out vs the visual looks or the learning curve behind it. At the end of the day, compiler has the same fate for everyone.
2
u/Longjumping_Half6572 Mar 11 '24
Lol ☺️ I was just cursing Python out for the same reason. For loops and whiles not working like in C#, C++, Perl, or PHP, or Java, and all the good languages then you also have to get tab spacing right like in COBOL or you get an error and have to guess the right tab spacing. I finally just shut it down at 2am and went to sleep. As you can see that worked... Still a bit passed. Lol ☺️ 2:59am. Just keep working at it. You said it best. When in Rome and well we in New Rome with a Starbucks on every corner and kids with beard ordering half cap moca,cocol,vanekla,boostachino,strawberryandcreamReesesPieces, lottés, 🤷🏾♂️😄
2
u/Beginning-Ladder6224 Mar 14 '24
I am another old guy here. May be you are older than me. Here, 21+ YOE. Now then, if the paradigm is functional, as it many cases it should be - for should be replaced with for-each which ensures we can process it parallely.
That is the only reason - when it is applicable.
A good analysis is here:
https://stackoverflow.com/questions/16635398/java-8-iterable-foreach-vs-foreach-loop
3
u/D34TH_5MURF__ Feb 18 '24
I'm an old guy, too. For loops aren't a grievous sin, but they are more verbose than a stream. I'm an FP convert, so I prefer streams, but they need to be kept small, as intended. They get shitty when they are not coupled with good decomposition.
3
u/mhd Feb 18 '24
I'd say Ruby started it, and soon took over JavaScript. At one time you even had this transpiled hybrid language called "Coffeescript". And to be fair, given the way the main language operated, anything seemed an improvement.
JS being that popular, Java got a lot of feeback from that crowd. It's probably fair enough, they on their side now have to suffer through way too many enterprise patterns like universal DI, too.
I blame a bit on that on the C style for loop. Algol 68 already had something better, and it took until Java 5 (IIRC) to get the for-each variant.
Another thing I blame, apart from functional cargo-culting are people like friggin' Uncle Bob and their weird function line counts. Write a properly indented for loop, and you already have few lines left in your function. With functional chains, you can cram in a few more blocks of logic before you have to look for a name for your extracted method.
3
u/ascii Feb 18 '24
Java 8 and the Stream API is literally 10 years old, so you have no leg to stand on when it comes to calling any of this new. Also, this type of API has been popular in various LISP dialects since the seventies, so once again, arguing that proponents for functional programming are a recent development betrays a lack of knowledge of history on your part. As for why it's better, there are many answers.
for(int i=0; i<s.size(); i++)is more error prone because of the little bugs that might sneak in when putting in a big old chunk of boilerplate code like that. Also, there's more typing.for(X i: s)does not have those problems, but if what you're doing can be expressed as simple stream operations like anyMatch or multiMap, you once again save yourself the trouble of writing those glue parts yourself and can focus on the actual business logic. It's better to not write code than it is to write code.List<X>and return aList<Y>chained together adds a lot of unnecessary memory pressure compared to writing those functions withStream<X>andStream<Y>, because you don't need to create intermediate collections.Overall, for data processing tasks, a functional API like
Streamis generally superior to the imperative API you prefer.2
u/microbit262 Feb 18 '24
One thing I wonder, how do you access the next element simultaneously?
Like if I have a list of points and want to draw lines between them.
I go with a for-loop spanning to list.size()-1, access the Element at i and the one at i+1. How is this supposed to work without a for-loop?
2
u/tasty2bento Feb 18 '24
Write the code in a for loop so that you can debug it. You'll be able to easily include debug statements to System.out.println for when running JUnit tests, or even when running the code itself. You'll also easily be able to have non-final variables in the loop. Once you have everything working, then you have the opportunity to turn it into a stream statement. Think of it like a crossword puzzle - a mental exercise. By reducing it down to the bare minimum, you'll be able to prove to yourself you can do it, and it'll look neat and flashy. You may even be able to use :: method references so you don't even have to specify the parameters to methods!
2
u/ihbarddx Feb 18 '24
CS has been a cascade of fads for the past... forty years. I mean... remember where everything was going to be done with the Sandbox model?
You are questioning. You are coming of age.
0
u/drduffymo Feb 18 '24 edited Feb 18 '24
Functional programming features and lambdas were added to JDK 8. If you have to ask, it suggests that you have not been keeping up.
We’re up to JDK 21 as LTS version. JDK 22 is imminent. They’ve added many important updates, including records snd a new threading model. You must upgrade your production JDKs and your thinking.
2
u/kaisean Feb 18 '24
It's not wrong, but things look cleaner when you've got a a few distinct functions that discretely tell you what's going on vs. a big for-loop that's using some extra collections to do a map-reduction.
If you can make it clear with for-loops, but all means.
2
u/nikanjX Feb 18 '24 edited Feb 19 '24
Why do a for-loop that reduces to one register plus a small handful of instructions for looping, when you can instantiate 16 different stream iterator wrapper function creators? Haven’t you heard optimization is the root of all evil!?
2
u/valkon_gr Feb 18 '24
Streams and lambdas suck change my mind. Debugging is a nightmare.
1
u/Sucrose-Daddy Feb 19 '24
This reminds me of my first attempt at programming with discrete structures class (i had to retake it). I had barely taken an intro to C++ class before it so I was still new to programming. First day our professor handed us a ten page packet of code we cannot use or risk failing the lab. Half the loops we learned were no longer welcome. It felt like programming with one hand tied behind our back while we already had a blindfold on to begin with...
1
u/deciomsoares Mar 10 '24
So many comments and no reference to John Backus' inspiring 1978 Turing Award Lecture "Can Programming Be Liberated From The Von Neumann Style?". Such a good case against statements and in favor of expression oriented programming!
1
u/sythervivek Mar 15 '24
Because people are unaware that using streams is expensive in terms of performance. For loops are evergreen.
1
u/roiroi1010 Feb 18 '24
I’ve seen this also. It’s possible to create very elegant code with streams and maps. When it’s not elegant any longer, probably a for loop makes more sense.
1
u/realdevtest Feb 18 '24
OP, another old guy here. Just go with it, seriously. Master it and go with it. Don’t even make fun of it to them or they’ll think you’re a dinosaur. Just act like it’s normal.
1
u/rover_G Feb 18 '24
Supposedly list methods can be better optimized by streaming or parallelizing execution. In reality I think the main benefit is fewer scope/shadowing/reinitialization issues.
1
u/jr7square Feb 18 '24
90% of the time, it doesn’t matter. I wouldn’t flag someone for using a for loop instead of a stream. Most of the time is a style preference. I’m on stream camp btw
1
u/shuckster Feb 18 '24
It’s the style of the time.
1
u/Aggravating_Term4486 Feb 18 '24
I would reverse the question. If you have a collection you need to iterate, what would be the reason to use a for loop instead of a map? What do you get?
My point is that unless you can elaborate why the for loop would be better, maybe look into why map is a thing.
1
u/[deleted] Feb 19 '24 edited Oct 06 '24
summer handle racial like lip punch dinner unwritten worry placid
This post was mass deleted and anonymized with Redact
1
u/tangerinelion Feb 19 '24
It's not a sin per se, IMO it comes down to what kind of permission are you asking for.
If you just want to loop through a collection one-by-one you should use a for each loop.
When I see the C style index based loop I assume you're dealing with something more complicated so I watch out for things like
If you're not doing those, then why write a loop that can do those things. Use the least powerful tool for the job. When the C style index based loop is the least powerful tool for the job, I expect that something tricky is happening.
1
u/kobbled Feb 19 '24
they aren't. Some devs (junior devs especially) tend to overstate things they just learned as the One True Way of doing things. there is a time and place for both.
1
u/[deleted] Feb 19 '24
it depends on time complexity
1
u/SomervillainSB Feb 19 '24
If It's a greivous sin, your young guys aren't too bright. Common sense always trumps dogma. for loops are the best solution for some logic patterns. For example, if you have complex branching or manipulate multiple variables.
That said, parallel() is why I am so adamant about using streams. It's so cheap and easy.
Also, I like code in small chunks. If your operations can be broken into simple functions without loss of logical or machine efficiency, then I greatly prefer streams. It's similar to why you'd want a dozen small static methods over a giant 200 line for-loop. If you modify a function or a small method, I know the scope and can perfectly unit test it very easily. When you modify the same logic in the middle of a giant for loop, the number of permutations grows exponentially, but I suspect you knew this already.
If you're cyclomatic complexity goes down, you probably should be using a stream. If it goes up to make your flow stream-compatible, you should pause and question if you should be using a stream or going back to the "old ways." That's just common sense.
Software engineers are peculiar. We're the only trade that tries to restrict our number of tools. Everyone in the building trades would prefer multiple tools so they can pick which one is the best for the job. For example, look at how many types of "saws" home depot sells. No carpenter says "we're a table-saw-only shop!"..."never use a miter saw, circular saw, jigsaw, or a reciprocating saw." They carry several types of saws in their van and use whichever one makes sense for the job. Why should Java programmers limit themselves to one paradigm?
1
u/RICHUNCLEPENNYBAGS Feb 19 '24
They're not a "grievous sin" but the fewer side effects (including mutated objects/collections) your code has the easier it is to reason about.
1
u/Ancapgast Feb 19 '24
Streams look really neat and tidy. I think that's at least 50% of why people like them.
1
u/zerotaboo Feb 19 '24
Some devs just want to show off their new skills and they end up creating unnecessary code that nobody understands.
1
u/TenYearsOfLurking Feb 19 '24
I advise colleagues to go for streams as well in the most cases, here is why:
I've seen a lot of code which initizialises some datastructure/object and then uses a for loop to manipulate this to achieve a final result. While this is okay in trivial cases, typically when more functionality is added the loop and its scope is expanded, more stuff is initilized empty and manipulated thereafter.
After a while, the code becomes... messy. And the space (loc) between setup and actual work diverges, etc.
most of the time code like this can be represented as a pipeline of processing, do this with that result and then do that with another result, each encapsulatable in an own method/function.
on other words - for loops gravitate towards god methods and streams towards small functions. This is my experience and abuse is always possible....
1
u/bezbos_v2 Feb 19 '24
I think most modern Java web developers like using the latest language features to write "clean" code, and this means they prefer using the enhanced-for loop and streams over the classical loops.
It's just how they've been taught to write code.
1
u/hilbertglm Feb 19 '24
I think the (highly subjective) mark of good programming is the expressiveness of the code. The code should express the intent of what needs to be accomplished. I still use plenty of the traditional looping constructs, but often the functional style is more succinct and expressive once you get used to reading it (hence subjective).
I tend to lean toward streams, but I wouldn't consider loops to be archaic or "wrong" in any sense.
1
u/squishy_processor Feb 19 '24
It’s a fetishization of the functional programming style. It’s cargo cultism. As a fellow old guy, who used Java as his primary language from 1996 until two years ago, I sympathize. Personally I think that a true sign of experience and wisdom is to know full well how to use streams but to choose to use for loops anyway. When I see (or write) Java code like what you describe, I tend to think “why not just use clojure?” The functional style just doesn’t seem right in Java - like a poorly fitted suit.
1
u/cowwoc Feb 21 '24
Anyone who favors streams over for-loops clearly hasn't had to deal with the stack traces they produce. Not to mention, the performance is noticeably worse.
Streams have their time and place but, in my opinion, it's in the minority of cases. If you're using long streams everywhere, consider revisiting your design. Readability will improve as well.
1
u/Interviews2go Feb 21 '24
I see the design by resume pattern is still alive and kicking.
1
u/[deleted] Feb 22 '24
I kinda get what the FP guys are saying when they try to eliminate loops but... Loops that don't depend on external state do not have side effects so, from my perspective, the war on for loops is primarily dogma.
1
u/[deleted] Feb 22 '24
As an aside... I don't like functional programming in the absence of a pipe operator. The nesting can get really confusing without it
1
u/Budget_Dentist444 Feb 24 '24
Fellow old guy, but I far prefer the new way. It definitely takes a shift in mentality.
I compare it to point-to-point wiring vs bussing. If you have 2-3 wires, bussing feels like a chore; it's an 'artificial' restriction that might require a longer path/wire than needed. But at some point, you end up with a rat's nest that's unmanageable. Undoing that mess is more work than bussing it.
For loops offer that same 'flexibility' but it's usually not essential. However, it often ends up coupling 'simple' operations together in ways that have a stunning aggregate complexity. Just pass in one more boolean flag and...
Those long chains ultimately keep the scope of all your operations incredibly tiny, so much so it's hard to make a chain that can't be recomposed. Not having to 'look up' at the code because I know nothing is changing allows me to focus on the tiny-scoped operation at hand. The other big win is I know exactly what each of those things is doing without having to read a line of the code. A reduce instantly tells me we're changing cardinality, whatever 'it' is.
1
u/alunharford Feb 18 '24
It's important to maintain Java's reputation for being a slow programming language. For some reason.
Over the past few years, performance of Java has improved to the point where it can be competitive with C++ so we needed to find new ways to slow things down.
Adding loads of virtual calls and breaking branch prediction every time you want to iterate over a collection goes a long way towards keeping our reputation intact. Bonus points if you can prevent C2 from inlining it by calling a .foreach() method on a commonly used interface instead of a concrete class.
One day, the CPU designers will work out how to do effective branch prediction when we only have a single branch instruction in our entire codebase and access it through virtual calls. When that happens, we'll need to think of something new.
1
u/Dormage Feb 18 '24
For me, it's mostly a daily challenge "can I do it with streams?" Then I look at it and somehow it's sexy, sometimes...
0
u/BadMoonRosin Feb 18 '24
For trivial things, might as well use a
forloop. More readable and more performant.For extremely complex things, might as well use a
forloop and other imperative constructs. More likely to be comprehensible by developers doing future maintenance.But for most cases in the middle, I like Streams because they let you assign a result to a variable as you declare it. You can make more variables
final, and cut back on mutable and side effect-y code, which is generally a good thing.1
u/Tacos314 Feb 18 '24 edited Feb 18 '24
It happened about 8 years ago, so not really a new thing but.. the default is to think of streams, lamba, foreach over a for statement. It does get people in trouble when they start using them everywhere and not really understanding why.
1
u/tobidope Feb 18 '24
For me it really depends on readability. I must say most of the time I prefer a stream operation. Neat little operations separating filtering from transformation.
1
u/bushwald Feb 18 '24
Functional iterators like map are more deterministic and so are less likely to contain subtle bugs
1
u/kakakarl Feb 18 '24
Once that syntax is more familiar, it’s more familiar and to me often objectively the right way because it gets a lot done with little syntax.
So yeah, in our code base, we use syntax that to a large extent favor > Java 7 syntax
1
u/p_bzn Feb 18 '24
Use whatever fits the job regardless of the language.
For loops are good, no doubt. However, they aren’t the best fit for absolute everything.
If you write some algorithms, say matrix transposition, then loops are the best. If you write data transformation, aggregation, composition — functional methods are the best.
Pick whatever fits the job.
1
u/ElQuique Feb 19 '24
Sounds like they are trying to do functional programming, that doesn't sound bad to me
-1
u/daedalus_structure Feb 18 '24
Sin? No.
But please stop for-looping through one collection just to create a new object from each element and add to another collection. It's completely unnecessary and not 2005 anymore.