Versions Compared

Key

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

...

This compliant solution uses the safeAdd() and safeMultiply() methods defined in the "Precondition Testing" section to perform secure integral operations or throw ArithmeticException on overflow.:

Code Block
bgColor#ccccff
public static int multAccum(int oldAcc, int newVal, int scale)
                  throws ArithmeticException {
  return safeAdd(oldAcc, safeMultiply(newVal, scale));
}

...

This compliant solution uses the BigInteger technique to detect overflow.:

Code Block
bgColor#ccccff
private static final BigInteger bigMaxInt = 
  BigInteger.valueOf(Integer.MAX_VALUE);
private static final BigInteger bigMinInt =    
  BigInteger.valueOf(Integer.MIN_VALUE);

public static BigInteger intRangeCheck(BigInteger val)
                         throws ArithmeticException {
  if (val.compareTo(bigMaxInt) == 1 ||
      val.compareTo(bigMinInt) == -1) {
    throw new ArithmeticException("Integer overflow");
  }
  return val;
}

public static int multAccum(int oldAcc, int newVal, int scale)
                            throws ArithmeticException {
  BigInteger product =
    BigInteger.valueOf(newVal).multiply(BigInteger.valueOf(scale));
  BigInteger res = 
    intRangeCheck(BigInteger.valueOf(oldAcc).add(product));
  return res.intValue(); // Safe conversion
}

...