Uploaded image for project: 'Commons Lang'
  1. Commons Lang
  2. LANG-1479

Add Range.fit(T) to fit a value into a range

    XMLWordPrintableJSON

Details

    • New Feature
    • Status: Closed
    • Major
    • Resolution: Fixed
    • None
    • 3.10
    • None
    • None

    Description

      Facilitates code like:

               int max = ...;
               int result = max < 0 ? 0 : max > 64 ? 64 : max;
      

      to simply be:

               static final RANGE = Range.between(16, 64);
               int max = ...;
               int result = RANGE.fit(max);
      

      Like this:

          /**
           * <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;
              }
          }
      

      Attachments

        Activity

          People

            ggregory Gary D. Gregory
            ggregory Gary D. Gregory
            Votes:
            0 Vote for this issue
            Watchers:
            1 Start watching this issue

            Dates

              Created:
              Updated:
              Resolved: