== Why is this an issue?

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

[source,java]
----
Stream.of("one", "two", "three", "four")
         .filter(e -> e.length() > 3)
         .peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant
----


=== Compliant solution

[source,java]
----
Stream.of("one", "two", "three", "four")
         .filter(e -> e.length() > 3)
         .foreach(e -> System.out.println("Filtered value: " + e));
----


== Resources

* 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[]

'''
== Implementation Specification
(visible only on this page)

=== Message

Challenge this use of "Stream.peek".


=== Highlighting

The "Stream.peek" invocation


'''
== Comments And Links
(visible only on this page)

=== on 4 Jan 2021, 17:52:38 Sebastien Lesaint wrote:
Hi,


I got a notification of a change on this ticket and reread the description.


This made me realize that the example is misleading in the same way the description text was: it's focused on the missing terminal operation, which is the scope of https://rules.sonarsource.com/java/RSPEC-3958, not of this rule.


I don't have an example to suggest, nothing obvious comes to my mind. Which leads me to wonder whether the difficulty of finding an example could be a smell of the rule being a bit fragile...

endif::env-github,rspecator-view[]
