[doc] [java] SimplifyStartsWith: update description and example, fixes #1868

This commit is contained in:
Mateusz Stefanski
2020-08-23 19:20:17 +02:00
parent 0889b94aa5
commit c161e57c1d

View File

@ -699,7 +699,8 @@ public class C {
externalInfoUrl="${pmd.website.baseurl}/pmd_rules_java_performance.html#simplifystartswith">
<description>
Since it passes in a literal of length 1, calls to (string).startsWith can be rewritten using (string).charAt(0)
at the expense of some readability.
at the expense of some readability. To prevent IndexOutOfBoundsException being thrown by the charAt method,
ensure that the (string) is not empty by making an additional check first.
</description>
<priority>3</priority>
<properties>
@ -730,7 +731,7 @@ public class Foo {
}
boolean fasterCheckIt(String x) {
return x.charAt(0) == 'a'; // faster approach
return !x.isEmpty() && x.charAt(0) == 'a'; // faster approach
}
}
]]>