Re: use of assert in Java [vs. exceptions]
Stefan Ram wrote:
I have two thoughts on this.
1.) Assume ?div(x,y)? had undefined behaviour when y == 0,
and we wanted to do this in an application:
for( x = 0; x < HUGE; ++x )div( x, y );
The application knows that in the case of y being 0, the
best thing to do is ?f()?, so
if( y )for( x = 0; x < HUGE; ++x )div( x, y ); else f();
. We can see that it is sufficient to do the test /once
outside of the loop/ for a primitive variable ?y? in a
single-threaded application. If the test would be done
inside of ?div? instead, it would not be possible to move
it outside of the loop.
2.) Assume ?div(x,y)? had undefined behaviour when y == 0.
One can always write a wrapper ?defensiveDiv(x,y)? that has
defined behaviour for y == 0 and otherwise the same behavior
as ?div(x,y)?, while it might be slower than ?div(x,y)?.
On the other hand, given only ?defensiveDiv(x,y)? it is not
possible to write a wrapper to get the behavior and run-time
properties of ?div(x,y)?.
Giovanni Azua wrote:
Good insight indeed, very nice!
In Java, if the arguments are integers then division by 0 with the '/'
operator throws an 'ArithmeticException'. Is that "defensive programming"?
Does it make the '/' operation slow?
In Java, if the arguments are of a floating-point type, e.g., 'double', then
division by zero yields a double value ('NaN' or signed infinity). Is that
"defensive programming"? Does it make the '/' operation slow?
It seems that Java is able to define arithmetic '/' such that it can handle
all possible inputs without running into the performance problems that some
seem to think are a risk. If one wants to modify the behavior of division by
zero, say with integers to avoid causing an 'ArithmeticException', one can do
the optimized value check that Stefan suggests. Presumably this would be
inside a method that accepts a value for 'y' and forwards the action to 'f()'
or '/' as needed. Is that "defensive programming", or is the check outside
the loop for 'y == 0' and corresponding delegation to 'f()' just "good
programming"?
--
Lew