35. Checking sub-range in the range from 0 to length

Checking that a given sub-range is in the range from 0 to the given length is a common check in a lot of problems. For instance, let’s consider that we have to write a function responsible to check if the client can increase the pressure in a water pipe. The client gives us the current average pressure (avgPresure), the maximum pressure (maxPressure), and the amount of extra pressure that should be applied (unitsOfPressure).But, before we can apply our secret algorithm, we have to check if the inputs are correct. So, we have to ensure that none of the following cases happens:

avgPresure is less than 0

unitsOfPressure is less than 0

maxPressure is less than 0

The range [avgPressure, avgPressure + unitsOfPressure) is out of bound represented by maxPressure

So, in code lines, our function may look as follows:

public static boolean isPressureSupported(
      int avgPresure, int unitsOfPressure, int maxPressure) {
  if(avgPresure < 0 || unitsOfPressure < 0 || maxPressure < 0
    || (avgPresure + unitsOfPressure) > maxPressure) {
    throw new IndexOutOfBoundsException(
           “One or more parameters are out of bounds”);
  }
  // the secret algorithm
  return (avgPresure + unitsOfPressure) <
    (maxPressure – maxPressure/4);
}

Writing composite conditions such as ours is prone to accidental mistakes. It is better to rely on Java API whenever possible. And, for this use case, it is possible! Starting with JDK 9, we have in java.util.Objects the method checkFromIndexSize(int fromIndex, int size, int length), and starting with JDK 16, we also have a flavor for long arguments, checkFromIndexSize(int fromIndex, int size, int length). If we consider that avgPressure is fromIndex, unitsOfPressure is size, and maxPressure is length then checkFromIndexSize() performs the arguments validation and throws an IndexOutOfBoundsException if something goes wrong. So, we write the code as follows:

public static boolean isPressureSupported(
      int avgPresure, int unitsOfPressure, int maxPressure) {
      
  Objects.checkFromIndexSize(
    avgPresure, unitsOfPressure, maxPressure);

  // the secret algorithm
  return (avgPresure + unitsOfPressure) <
    (maxPressure – maxPressure/4);
}

In the bundle code, you can see one more example of using checkFromIndexSize().Besides checkFromIndexSize(), we can find in java.util.Objects several other companions that cover common composite conditions such as checkIndex(int index, int length) – JDK 9, checkIndex(long index, long length) – JDK 16, checkFromToIndex(int fromIndex, int toIndex, int length) – JDK 9, and checkFromToIndex(long fromIndex, long toIndex, long length) – JDK 16. These methods are covered in Java Coding Problems, First Edition, Problems 44, and 45.

Leave a Reply

Your email address will not be published. Required fields are marked *