rspec/rules/S3039/java/rule.adoc

25 lines
1.2 KiB
Plaintext
Raw Normal View History

2021-04-28 16:49:39 +02:00
Just as you can't cut something into three halves, you can't grab a ``++substring++`` that starts or ends outside the original ``++String++``'s bounds, you can't use ``++substring++`` to get a reversed portion of a ``++String++``, and you can't get the ``++charAt++`` a value that's before the ``++String++`` starts or after it ends.
This rule detects when negative literal or ``++String::length++`` is passed as an argument to the ``++String::substring++``, ``++String::charAt++`` and related methods.
== Noncompliant Code Example
----
String speech = "Now is the time for all good people to come to the aid of their country.";
String substr1 = speech.substring(-1, speech.length()); // Noncompliant; start and end values both bad
String substr2 = speech.substring(speech.length(), 0); // Noncompliant, start value must be < end value
char ch = speech.charAt(speech.length()); // Noncompliant
----
== Compliant Solution
----
String speech = "Now is the time for all good people to come to the aid of their country.";
String substr1 = speech; // Closest correct values to original code yield whole string
String substr2 = new StringBuilder(speech).reverse().toString()
char ch = speech.charAt(speech.length()-1);
----