2023-05-03 11:06:20 +02:00
== Why is this an issue?
2021-04-28 16:49:39 +02:00
In Java 15 Text Blocks are official and can be used just like an ordinary String. However, when they are used to represent a big chunk of text, they should not be used directly in complex expressions, as it decreases the readability. In this case, it is better to extract the text block into a variable or a field.
This rule reports an issue when a text block longer than a number of lines given as a parameter is directly used within a lambda expression.
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
----
listOfString.stream()
.map(str -> !"""
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
""".equals(str));
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
=== 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
----
String myTextBlock = """
<project>
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-app</artifactId>
<version>1</version>
</parent>
<groupId>com.mycompany.app</groupId>
<artifactId>my-module</artifactId>
<version>1</version>
</project>
""";
listOfString.stream()
.map(str -> !myTextBlock.equals(str));
----
2021-04-28 18:08:03 +02:00
2023-05-03 11:06:20 +02:00
== Resources
2021-04-28 16:49:39 +02:00
* https://openjdk.java.net/jeps/378[JEP 378: Text Blocks]
2023-02-27 15:16:49 +01:00
* https://openjdk.org/projects/amber/guides/text-blocks-guide[Programmer's Guide To Text Blocks], by Jim Laskey and Stuart Marks
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
2021-09-20 15:38:42 +02:00
2023-05-25 14:18:12 +02:00
Move this text block out of the lambda body and refactor it to a local variable or a static final field.
=== Parameters
.MaximumNumberOfLines
****
----
5
----
The maximum number of lines in a text block that can be nested into a complex expression.
****
=== Highlighting
Text block
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]