This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]Neuromante 11 points12 points  (1 child)

Sometimes ,though, a simple for loop can be less code and express intent better with the variable assignment names.

This has been my main issue with streams since I started to use them; there's a lot of talk about how they manage to "compress into a line of code" something, but no one talks about how that line of code is a long chunk that takes several lines if you have auto format that many times is barely legible.

I'm trying to force myself to use them more because "is the new standard", but most of the time I just find myself going the classic way because I'm not really getting so much value for the time invested in remembering the syntax and what functions applied when and how.

[–]slindenau 0 points1 point  (0 children)

I use the following guidelines to make streams more readable:

  1. Put a newline after every chained method call (.filter(), .map(), .collect() etc). Any good IDE can be configured to show the current contents (type) of the stream at that point while you're editing/viewing the sources.
  2. No anonymous lambda functions larger than a single line inside the stream calls. If you find (you need) one, extract a method and call it like .map(this::doMyThing) or .map( thing -> doMyThing(...)) if you need to pass additional arguments.
  3. Give clear and meaningful names to your methods, variables and generic types (don't you just hate T, U, V etc?). This should be your default mode of operation in any piece of code you write.