Re: Arithmetic overflow checking
In article <015aeb15-57db-48ab-9cd4-
77f8448b632f@w24g2000yqw.googlegroups.com>, rop049@gmail.com says...
Hi,
If I want to have arithmetic-overflow checking in all parts of an
application,
what is the most practical, simple, efficient way to achieve this?
Id like to clutter the code as little a possible...
Is there any way to instruct the JVM to include it?
Not automagically, at least if you want to avoid building a sourcecode-
preprocessor or tool that instruments your bytecode at class loading
time.
You could use your very own math-methods and discourage the use of the
operators "+","-" throughout your code by convention.
public final class OverflowUtil{
public static void passIntRangeCheck(final long x){
if( x > Integer.MAX_VALUE)
throw new ArithemticException("int overflow");
if if( x < Integer.MIN_VALUE)
throw new ArithemticException("int underflow");
}
public static void passLongRangeCheck(final BigInteger x){
if( x.compareTo(BigInteger.valueOf(Long.MAX_VALUE)) > 0)
throw new ArithemticException("long overflow");
if( x.compareTo(BigInteger.valueOf(Long.MIN_VALUE)) < 0)
throw new ArithemticException("long underflow");
}
//... same for byte and short
}
import static OverflowUtil.*;
public class OverFlowSafe{
static int add(final int a, final int b){
final long x = a+b;
passIntRangeCheck(x);
return (int)x;
}
static long add(final long a, final long b){
final long x = BigInteger.valueOf(a).add(BigInteger.valueOf(b);
passLongRangeCheck(x);
return x.longValue();
}
//.... other operations..
}
To be used like:
void foo(){
final int x = Integer.MAX_VALUE;
final int y = 1L;
final int sum = OverflowSafe.add(x,y);
System.out.println(sum);
}
The code not tested and hacked in a hurry, varargs would probably be
nicer. The upside to any instrumentation or preprocessing tool is that
you can distinguish safe from unsafe code with a blink of an eye.
Kind regards,
Wanja
--
...Alesi's problem was that the back of the car was jumping up and down
dangerously - and I can assure you from having been teammate to
Jean Alesi and knowing what kind of cars that he can pull up with,
when Jean Alesi says that a car is dangerous - it is. [Jonathan Palmer]
--- Posted via news://freenews.netfront.net/ - Complaints to news@netfront.net ---