[jira] [Created] (LANG-1479) Add Range.fit(T) to fit a value into a range

classic Classic list List threaded Threaded
1 message Options
Reply | Threaded
Open this post in threaded view
|

[jira] [Created] (LANG-1479) Add Range.fit(T) to fit a value into a range

ASF GitHub Bot (Jira)
Gary Gregory created LANG-1479:
----------------------------------

             Summary: Add Range.fit(T) to fit a value into a range
                 Key: LANG-1479
                 URL: https://issues.apache.org/jira/browse/LANG-1479
             Project: Commons Lang
          Issue Type: New Feature
            Reporter: Gary Gregory
            Assignee: Gary Gregory


Facilitates code like:
{code:java}
         int max = ...;
         int result = max < 0 ? 0 : max > 64 ? 64 : max;
{code}
to simply be:
{code:java}
         static final RANGE = Range.between(16, 64);
         int max = ...;
         int result = RANGE.fit(max);
{code}
Like this:
{code:java}
    /**
     * <p>
     * Fits the given element into this range by returning the given element or, if out of bounds, the range minimum if
     * below, or the range maximum if above.
     * </p>
     *
     * @param element the element to check for, not null
     * @return the minimum, the element, or the maximum depending on the element's location relative to the range
     * @since 3.10
     */
    public T fit(final T element) {
        // Comparable API says throw NPE on null
        Validate.notNull(element, "Element is null");
        if (isAfter(element)) {
            return minimum;
        } else if (isBefore(element)) {
            return maximum;
        } else {
            return element;
        }
    }
{code}



--
This message was sent by Atlassian Jira
(v8.3.2#803003)