Video in progress
For a codebase that several teams work on, what rules would you write for using streams and lambdas, and how would you enforce them?
The rules should be few and clear: pipelines without side effects, no business logic in peek, parallel streams only by agreement, long lambdas moved into named methods. Enforcement comes through a linter, ArchUnit and a code review checklist, and style matters are settled by an automatic formatter.
📖 Answer
I split such rules into "what is forbidden" and "what is a matter of taste". The first prevents bugs and is checked automatically. On the second, the team shouldn't waste time arguing.
Hard rules (they lead to bugs):
- don't modify outside mutable state inside
forEach/map: get the result withcollect; peekonly for debugging;parallelStream()only after an architecture review and with a comment, and it should be findable across the codebase;- I/O-backed streams (
Files.lines, a repositoryStream<T>) only inside try-with-resources; Optionalnot as a field or a parameter;- no
toMapwithout a merge function if a duplicate key is even theoretically possible.
Recommendations (for readability):
- if a lambda goes past 3–4 lines, make it a named method;
- if a pipeline is longer than 5–6 stages, use an intermediate variable or split it into methods;
- if you need an index, a
breakor several accumulators, don't be ashamed of aforloop.
Enforcement:
@ArchTest
static final ArchRule noParallelStreams = noClasses()
.should().callMethod(Collection.class, "parallelStream")
.because("parallel stream uses the common pool, see ADR-014");
Sonar and Error Prone have ready-made rules: an Optional parameter, a method call inside orElse, a stream that wasn't closed. I raise them to the level that fails the build, but only a few: hundreds of warnings turn into noise nobody reads.
The rest I turn into examples, not rules: "good/bad" pairs in the wiki and short stories from real incidents. People remember an example like "this is how it broke in our prod" better than a rule. Every six months we review the list: when the Java version is upgraded, some rules go stale (for example, after toList() appeared).
Sign up to mark studied questions and save your progress.