44 lines
1.6 KiB
Plaintext
44 lines
1.6 KiB
Plaintext
According to its JavaDocs, the intermediate Stream operation ``++java.util.Stream.peek()++`` “exists mainly to support debugging” purposes.
|
|
|
|
A key difference with other intermediate Stream operations is that the Stream implementation is free to skip calls to ``++peek()++`` for optimization purpose. This can lead to ``++peek()++`` being unexpectedly called only for some or none of the elements in the Stream.
|
|
|
|
|
|
As a consequence, relying on ``++peek()++`` without careful consideration can lead to error-prone code.
|
|
|
|
|
|
This rule raises an issue for each use of peek() to be sure that it is challenged and validated by the team to be meant for production debugging/logging purposes.
|
|
|
|
|
|
== Noncompliant Code Example
|
|
|
|
----
|
|
Stream.of("one", "two", "three", "four")
|
|
.filter(e -> e.length() > 3)
|
|
.peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant
|
|
----
|
|
|
|
|
|
== Compliant Solution
|
|
|
|
----
|
|
Stream.of("one", "two", "three", "four")
|
|
.filter(e -> e.length() > 3)
|
|
.foreach(e -> System.out.println("Filtered value: " + e));
|
|
----
|
|
|
|
|
|
== See
|
|
|
|
* https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#peek-java.util.function.Consumer-[Java 8 API Documentation]
|
|
* 4comprehension: https://4comprehension.com/idiomatic-peeking/[Idiomatic Peeking with Java Stream API]
|
|
* Data Geekery: https://blog.jooq.org/2014/06/13/java-8-friday-10-subtle-mistakes-when-using-the-streams-api/[10 Subtle Mistakes When Using the Streams API]
|
|
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
include::comments-and-links.adoc[]
|
|
endif::env-github,rspecator-view[]
|