rspec/rules/S3864/java/rule.adoc

57 lines
1.8 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
2021-04-28 16:49:39 +02:00
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
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.peek(e -> System.out.println("Filtered value: " + e)); // Noncompliant
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
Stream.of("one", "two", "three", "four")
.filter(e -> e.length() > 3)
.foreach(e -> System.out.println("Filtered value: " + e));
----
== Resources
2021-04-28 16:49:39 +02:00
* 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)
include::message.adoc[]
include::highlighting.adoc[]
'''
== Comments And Links
(visible only on this page)
include::comments-and-links.adoc[]
endif::env-github,rspecator-view[]