86 lines
2.3 KiB
Plaintext
86 lines
2.3 KiB
Plaintext
== Why is this an issue?
|
|
|
|
Some mathematical operations are unnecessary and should not be performed because their results are predictable.
|
|
|
|
For instance, `anyValue % 1` will always return 0, as any integer value can be divided by 1 without remainder.
|
|
|
|
Similarly, casting a non-floating-point to a floating-point value and then passing it to `Math.round`, `Math.ceil`, or `Math.floor` is also unnecessary, as the result will always be the original value.
|
|
|
|
The following operations are unnecessary when given any constant value: `Math.abs`, `Math.ceil`, `Math.floor`, `Math.rint`, `Math.round`.
|
|
Instead, use the result of the operation directly.
|
|
|
|
The following operations are unnecessary with certain constants and can be replaced by the result of the operation directly:
|
|
|
|
[frame=all]
|
|
[cols="^1,^1"]
|
|
|===
|
|
|Operation|Value
|
|
|
|
|acos|0.0 or 1.0
|
|
|asin|0.0 or 1.0
|
|
|atan|0.0 or 1.0
|
|
|atan2|0.0
|
|
|cbrt|0.0 or 1.0
|
|
|cos|0.0
|
|
|cosh|0.0
|
|
|exp|0.0 or 1.0
|
|
|expm1|0.0
|
|
|log|0.0 or 1.0
|
|
|log10|0.0 or 1.0
|
|
|sin|0.0
|
|
|sinh|0.0
|
|
|sqrt|0.0 or 1.0
|
|
|tan|0.0
|
|
|tanh|0.0
|
|
|toDegrees|0.0 or 1.0
|
|
|toRadians|0.0
|
|
|===
|
|
|
|
== How to fix it
|
|
|
|
Ask yourself if the questionable operation represents the desired calculation or if a value used is erroneous.
|
|
If the calculation is correct, replace it with the result to avoid having to perform the unnecessary operation at runtime.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
public void doMath(int a) {
|
|
double res1 = Math.floor((double)a); // Noncompliant, the result will always be equal to '(double) a'
|
|
double res2 = Math.ceil(4.2); // Noncompliant, the result will always be 5.0
|
|
double res3 = Math.atan(0.0); // Noncompliant, the result will always be 0.0
|
|
}
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
public void doMath(int a) {
|
|
double res1 = a; // Compliant
|
|
double res2 = 5.0; // Compliant
|
|
double res3 = 0.0; // Compliant
|
|
}
|
|
----
|
|
|
|
ifdef::env-github,rspecator-view[]
|
|
|
|
'''
|
|
== Implementation Specification
|
|
(visible only on this page)
|
|
|
|
=== Message
|
|
|
|
Remove this unnecessary call to "Math.xxx".
|
|
|
|
'''
|
|
== Comments And Links
|
|
(visible only on this page)
|
|
|
|
=== on 21 Nov 2024, 16:48:00 Alban Auzeill wrote:
|
|
[test-code-support-investigation-for-java] Decision for scope: Main -> All.
|
|
|
|
endif::env-github,rspecator-view[]
|