rspec/rules/S1317/java/rule.adoc

75 lines
2.4 KiB
Plaintext

This rule raises an issue when the `StringBuilder` or `StringBuffer` constructor is called with a single character as an argument.
== Why is this an issue?
When a developer uses the `StringBuilder` or `StringBuffer` constructor with a single character as an argument,
the likely intention is to create an instance with the character as the initial string value.
However, this is not what happens because of the absence of a dedicated `StringBuilder(char)` or `StringBuffer(char)` constructor.
Instead, `StringBuilder(int)` or `StringBuffer(int)` is invoked,
which results in an instance with the provided `int` value as the initial capacity of the `StringBuilder` or `StringBuffer`.
The reason behind this behavior lies in the automatic widening of `char` expressions to `int` when required.
Consequently, the UTF-16 code point value of the character (for example, `65` for the character `'A'`)
is interpreted as an `int` to specify the initial capacity.
== How to fix it
If the argument is a `char` literal, use a string literal instead:
[source,java,diff-id=1,diff-type=noncompliant]
----
StringBuffer foo = new StringBuffer('x'); // Noncompliant, replace with String
----
[source,java,diff-id=1,diff-type=compliant]
----
StringBuffer foo = new StringBuffer("x"); // Compliant
----
If the argument is it is a non-literal `char` expression, convert it to `String` using the `String.valueOf()` method:
[source,java,diff-id=2,diff-type=noncompliant]
----
StringBuffer foo(char firstChar) {
return new StringBuffer(firstChar); // Noncompliant
}
----
[source,java,diff-id=2,diff-type=compliant]
----
StringBuffer foo(char firstChar) {
return new StringBuffer(String.valueOf(firstChar)); // Compliant
}
----
== Resources
=== Documentation
- https://docs.oracle.com/javase/specs/jls/se10/html/jls-5.html#jls-5.1.2[Oracle - Java Language Specification, section 5.1.2. Widening Primitive Conversion]
=== Articles & blog posts
- https://www.w3schools.com/java/java_type_casting.asp[W3schools - Java Type Casting]
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Replace the constructor character parameter 'X' with string parameter "X".
'''
== Comments And Links
(visible only on this page)
=== on 15 Oct 2013, 08:54:16 Freddy Mallet wrote:
Is implemented by \http://jira.codehaus.org/browse/SONARJAVA-359
endif::env-github,rspecator-view[]