rspec/rules/S2153/java/rule.adoc

86 lines
2.0 KiB
Plaintext
Raw Normal View History

== Why is this an issue?
Boxing is the process of putting a primitive value into a wrapper object, such as creating an `Integer` to hold an `int` value.
Unboxing is the process of retrieving the primitive value from such an object.
Since the original value is unchanged during boxing and unboxing, there is no point in doing either when not needed.
2021-04-28 16:49:39 +02:00
Instead you should rely on Java's implicit boxing/unboxing to convert from the primitive type to the wrapper type and vice versa, for better readability.
2021-04-28 16:49:39 +02:00
=== Noncompliant code example
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public void examinePrimitiveInt(int a) {
2021-04-28 16:49:39 +02:00
//...
}
public void examineBoxedInteger(Integer a) {
2021-04-28 16:49:39 +02:00
// ...
}
public void func() {
int primitiveInt = 0;
Integer boxedInt = Integer.valueOf(0);
2021-04-28 16:49:39 +02:00
double d = 1.0;
int dIntValue = Double.valueOf(d).intValue(); // Noncompliant; should be replaced with a simple cast
2021-04-28 16:49:39 +02:00
examinePrimitiveInt(boxedInt.intValue()); // Noncompliant; unnecessary unboxing
examinePrimitiveInt(Integer.valueOf(primitiveInt)); // Noncompliant; boxed int will be auto-unboxed
2021-04-28 16:49:39 +02:00
examineBoxedInteger(Integer.valueOf(primitiveInt)); // Noncompliant; unnecessary boxing
examineBoxedInteger(boxedInt.intValue()); // Noncompliant; unboxed int will be autoboxed
2021-04-28 16:49:39 +02:00
}
----
=== Compliant solution
2021-04-28 16:49:39 +02:00
2022-02-04 17:28:24 +01:00
[source,java]
2021-04-28 16:49:39 +02:00
----
public void examinePrimitiveInt(int a) {
2021-04-28 16:49:39 +02:00
//...
}
public void examineBoxedInteger(Integer a) {
2021-04-28 16:49:39 +02:00
// ...
}
public void func() {
int primitiveInt = 0;
Integer boxedInt = Integer.valueOf(0);
2021-04-28 16:49:39 +02:00
double d = 1.0;
int dIntValue = (int) d;
examinePrimitiveInt(primitiveInt);
examinePrimitiveInt(boxedInt);
2021-04-28 16:49:39 +02:00
examineBoxedInteger(primitiveInt);
examineBoxedInteger(boxedInt);
2021-04-28 16:49:39 +02:00
}
----
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
=== Message
Remove the [un]boxing of "xxx".
'''
== Comments And Links
(visible only on this page)
=== on 15 Oct 2014, 22:14:41 Freddy Mallet wrote:
I would remove the tag 'bug' on this rule because this doesn't impact the behavior at execution time.
endif::env-github,rspecator-view[]