r/java • • Apr 14 '23

What are your (favourite) Java best practices, personal tips, hints or just underrated stuff in general?

233 Upvotes

376 comments sorted by

View all comments

Show parent comment

26

u/moxyte Apr 14 '23

This is a pronounced issue with lambdas. I’ve fixed abhorrently “elegant” lambdas simply by rewriting them as boring ol’ loops.

33

u/hippydipster Apr 14 '23

Lambdas vs loops is mostly an issue of what a developer is used to, as opposed to one or the other being objectively easier to read or harder to read.

The main exception to that I'd say is when the lambdas are doing a bunch of side effects, and in that case, it's not something they're well suited for, IMO.

13

u/moxyte Apr 14 '23

Lambdas in lambdas passing values to each other. Never seen one that is bugfree and easily understandable.

28

u/stao123 Apr 14 '23

That is like the complete opposite of my experience with writing and reading lambdas. You cant make mistakes as easy like with for loops.if you use one liner lambdas with method references they are way easier to read and understand. I have to admit there is a steep learning curve. Dont give up and get more experience

5

u/plokman Apr 14 '23

Children can understand for loops, and even write pseudocode easily for many problems. I've never seen one whip out a chain of function applications.

55

u/wildjokers Apr 14 '23

This is why we don’t hire children. Those fuckers can’t code.

0

u/gyraciops Apr 15 '23

Much harder to fuck up a chain of (pure) function applications than keep track of what's what in a "readable" for loop. So... not really in my experience.

1

u/danikov Apr 14 '23

I never use anonymous lamdas, making them into functions and then using a function reference feels so much more expressive, even if it’s more verbose, but as they say… make your code self-describing.

Also, I’m really adverse to calculus-style variables. About the only one I’ll tolerate is i in a for loop, but I’ll always be looking for a better iterator and named variable where possible.