rspec/rules/S6913/java/rule.adoc

67 lines
2.0 KiB
Plaintext

== Why is this an issue?
Java 21 introduces the new method `Math.clamp(value, min, max)` that fits a value within a specified interval.
Before Java 21, this behavior required explicit calls to the `Math.min` and `Math.max` methods, as in `Math.min(max, Math.max(value, min))`.
If `min > max`, `Math.clamp` throws an `IllegalArgumentException`, indicating an invalid interval.
This can occur if the `min` and `max` arguments are mistakenly reversed.
Note that `Math.clamp` is not a general substitute for `Math.min` or `Math.max`, but for the combination of both.
If `value` is the same as `min` or `max`, using `Math.clamp` is unnecessary and `Math.min` or `Math.max` should be used instead.
== How to fix it
- If 2nd argument > 3rd argument, use `Math.clamp(value, min, max)` instead of `Math.clamp(value, max, min)`.
- If `value` is the same as `min`, fix the logic or use `Math.min(value, max)` instead.
- If `value` is the same as `max`, fix the logic or use `Math.max(min, value)` instead.
- If `min` is the same as `max`, fix the logic because `Math.clamp(value, x, x)` will always return `x`.
=== Code examples
==== Noncompliant code example
[source,java,diff-id=1,diff-type=noncompliant]
----
Math.clamp(red, 255, 0); // Noncompliant, [255,0] is not a valid range
----
==== Compliant solution
[source,java,diff-id=1,diff-type=compliant]
----
Math.clamp(red, 0, 255); // Compliant
----
==== Noncompliant code example
[source,java,diff-id=2,diff-type=noncompliant]
----
Math.clamp(red, red, 255); // Noncompliant, use Math.min(red, 255)
----
==== Compliant solution
[source,java,diff-id=2,diff-type=compliant]
----
Math.min(red, 255); // Compliant
----
==== Noncompliant code example
[source,java,diff-id=3,diff-type=noncompliant]
----
Math.clamp(red, 0, red); // Noncompliant, use Math.max(red, 0)
----
==== Compliant solution
[source,java,diff-id=3,diff-type=compliant]
----
Math.max(red, 0); // Compliant
----
== Resources
* Java Documentation - https://docs.oracle.com/en/java/javase/21/docs/api/java.base/java/lang/Math.html#clamp(long,int,int)[Math.clamp]