rspec/rules/S1157/java/rule.adoc
2023-06-09 16:36:32 +02:00

74 lines
2.2 KiB
Plaintext

== Why is this an issue?
Using `toLowerCase()` or `toUpperCase()` to make case insensitive comparisons is inefficient because it requires the creation of temporary, intermediate `String` objects.
=== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
private void compareStrings(String foo, String bar){
boolean result1 = foo.toUpperCase().equals(bar); // Noncompliant
boolean result2 = foo.equals(bar.toUpperCase()); // Noncompliant
boolean result3 = foo.toLowerCase().equals(bar.toLowerCase()); // Noncompliant
}
----
=== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
private void compareStrings(String foo, String bar){
boolean result1 = foo.equalsIgnoreCase(bar); // Compliant
}
----
=== Exceptions
No issue will be raised when a locale is specified because the result could be different from `equalsIgnoreCase()`. (e.g.: using the Turkish locale)
[source,java]
----
private void compareStrings(String foo, String bar, java.util.Locale locale){
boolean result1 = foo.toUpperCase(locale).equals(bar); // Compliant
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace "[toUpperCase()|toLowerCase()]" and "equals()" calls with a single call to "equalsIgnoreCase()".
'''
== Comments And Links
(visible only on this page)
=== on 29 Jul 2013, 14:10:11 Dinesh Bolkensteyn wrote:
This one is interesting, I made the mistake a few times I think ;-)
=== on 29 Jul 2013, 14:10:24 Dinesh Bolkensteyn wrote:
Implemented by \http://jira.codehaus.org/browse/SONARJAVA-245
=== on 29 Jul 2013, 23:56:51 Ann Campbell wrote:
Dinesh went a lot of rounds on this one. It'll probably kill him that I still made a change.
=== on 30 Jul 2013, 08:21:27 Dinesh Bolkensteyn wrote:
Not at all Ann ;-) I didn't yet commit the implementation, so your change did not take any additional effort to apply! Thanks!
=== on 31 Jul 2013, 00:10:00 Ann Campbell wrote:
Sorry Dinesh, but I missed a spot yesterday. :-(
=== on 7 Aug 2013, 05:52:30 Dinesh Bolkensteyn wrote:
Thanks, I've just applied your changes!
endif::env-github,rspecator-view[]