Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

The "Pre-condition the inputs" technique requires different pre-condition tests for each arithmetic operation. This can be somewhat more difficult to understand than either of the other two approaches.

...

The code example below shows the necessary pre-conditioning checks required for each arithmetic operation on arguments of type int. The checks for the other integral types are analogous. In this example we choose (for simplicity) to throw an exception when integer overflow would occur; any other appropriate error handling is also acceptable.

Code Block
static final preAdd(int left, int right) throws ArithmeticException {
   if (right > 0 ? left > Integer.MAX_VALUE - right : left < Integer.MIN_VALUE - right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preSubtract(int left, int right) throws ArithmeticException {
  if (right > 0 ? left < Integer.MIN_VALUE + right : left > Integer.MAX_VALUE + right) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preMultiply(int left, int right) throws ArithmeticException {
  if (right>0 ? left > Integer.MAX_VALUE/right || left < Integer.MIN_VALUE/right :
       (right<-1 ? left > Integer.MIN_VALUE/right || left < Integer.MAX_VALUE/right :
         right == -1 && left == Integer.MIN_VALUE) ) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preDivide(int left, int right) throws ArithmeticException {
  if ((left == Integer.MIN_VALUE) && (right == -1)) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preAbs(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

static final preNegate(int a) throws ArithmeticException {
  if (a == Integer.MIN_VALUE) {
    throw new ArithmeticException("Integer overflow");
  }
}

...

  1. The number and order of accesses to itemsInInventory remains unchanged from the noncompliant code example.
  2. All operations on the value of itemsInInventory are performed on a temporary local copy of its value.
  3. The overflow check in this example is performed in open inline code, rather than encapsulated in a method call. This is an acceptable alternative implementation. The choice of method call vs. open inline code should be made according to your organization's standards and needs.

...