rspec/rules/S5361/java/rule.adoc

35 lines
1.4 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
The underlying implementation of ``++String::replaceAll++`` calls the ``++java.util.regex.Pattern.compile()++`` method each time it is called even if the first argument is not a regular expression. This has a significant performance cost and therefore should be used with care.
When ``++String::replaceAll++`` is used, the first argument should be a real regular expression. If its not the case, ``++String::replace++`` does exactly the same thing as ``++String::replaceAll++`` without the performance drawback of the regex.
This rule raises an issue for each ``++String::replaceAll++`` used with a ``++String++`` as first parameter which doesnt contains special regex character or pattern.
== Noncompliant Code Example
----
String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
String changed = init.replaceAll("Bob is", "It's"); // Noncompliant
changed = changed.replaceAll("\\.\\.\\.", ";"); // Noncompliant
----
== Compliant Solution
----
String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
String changed = init.replace("Bob is", "It's");
changed = changed.replace("...", ";");
----
Or, with a regex:
----
String init = "Bob is a Bird... Bob is a Plane... Bob is Superman!";
String changed = init.replaceAll("\\w*\\sis", "It's");
changed = changed.replaceAll("\\.{3}", ";");
----
== See
* S4248 - Regex patterns should not be created needlessly