2023-05-03 11:06:20 +02:00
== Why is this an issue?
2023-08-08 17:30:36 +02:00
Some mathematical operations are unnecessary and should not be performed because their results are predictable.
2021-04-28 16:49:39 +02:00
2023-08-08 17:30:36 +02:00
For instance, `anyValue % 1` will always return 0, as any integer value can be divided by 1 without remainder.
2021-04-28 16:49:39 +02:00
2023-08-08 17:30:36 +02:00
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.
2021-04-28 16:49:39 +02:00
2023-08-08 17:30:36 +02:00
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.
2021-04-28 16:49:39 +02:00
2023-08-08 17:30:36 +02:00
The following operations are unnecessary with certain constants and can be replaced by the result of the operation directly:
2021-04-28 16:49:39 +02:00
2021-06-03 16:43:28 +02:00
[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
|===
2021-04-28 18:08:03 +02:00
2023-08-08 17:30:36 +02:00
== 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
2021-04-28 16:49:39 +02:00
2023-08-08 17:30:36 +02:00
[source,java,diff-id=1,diff-type=compliant]
2021-04-28 16:49:39 +02:00
----
public void doMath(int a) {
2023-08-08 17:30:36 +02:00
double res1 = a; // Compliant
double res2 = 5.0; // Compliant
double res3 = 0.0; // Compliant
2021-04-28 16:49:39 +02:00
}
----
2021-04-28 18:08:03 +02:00
2021-09-20 15:38:42 +02:00
ifdef::env-github,rspecator-view[]
'''
== Implementation Specification
(visible only on this page)
2023-05-25 14:18:12 +02:00
=== Message
2023-08-08 17:30:36 +02:00
Remove this unnecessary call to "Math.xxx".
2023-05-25 14:18:12 +02:00
2021-09-20 15:38:42 +02:00
endif::env-github,rspecator-view[]