35 lines
997 B
Plaintext
35 lines
997 B
Plaintext
== Why is this an issue?
|
|
|
|
In Java 21 the `java.lang.Math` class was updated with the static method `Math.clamp`, to clamp a numerical value between a min and a max value.
|
|
|
|
Using this built-in method is now the preferred way to restrict to a given interval, as it is more readable and less error-prone.
|
|
|
|
== How to fix it
|
|
|
|
Replace your clamp method implementation with the `Math.clamp` method.
|
|
|
|
=== Code examples
|
|
|
|
==== Noncompliant code example
|
|
|
|
[source,java,diff-id=1,diff-type=noncompliant]
|
|
----
|
|
int clampedValue = value > max ? max : value < min ? min : value; // Noncompliant; Replace with "Math.clamp"
|
|
----
|
|
|
|
[source,java,diff-id=2,diff-type=noncompliant]
|
|
----
|
|
int clampedValue = Math.max(min, Math.min(max, value)); // Noncompliant; Replace with "Math.clamp"
|
|
----
|
|
|
|
==== Compliant solution
|
|
|
|
[source,java,diff-id=1,diff-type=compliant]
|
|
----
|
|
int clampedValue = Math.clamp(value, min, max);
|
|
----
|
|
|
|
[source,java,diff-id=2,diff-type=compliant]
|
|
----
|
|
int clampedValue = Math.clamp(value, min, max);
|
|
---- |