Re: Where should I throw RuntimeException
On May 22, 1:44 pm, "Giovanni Azua" <brave...@hotmail.com> wrote:
The page 13 of these slides depict what I meant:http://se.inf.ethz.ch/tea=
ching/ss2005/0250/lectures/oosc_13_dbc_1up.pdf
There are some notes on defensive programming in page 17.
Now I see what you meant and where you got your terminology.
Your view: API clients should guarantee preconditions.
If the Java method Math.sqrt() relied on that, what would it return
for 'Math.sqrt( -1 )'?
According to you, that would never happen. How do you guarantee
that? What would the result be?
My view, what you like to call "defensive programming": either the
method throws an exception or it tests the value and returns a
suitable value. The actual Java method 'Math.sqrt(double)' does the
latter; it returns 'Double.NaN'.
The method must handle the illegal input. No amount of concern for
"performance" relieves it of responsibility to handle a negative
input.
The problem with the Eiffel view of DbC, reflected in your remarks,
for Java is that programs cannot afford to fail in weird ways if a
client violates the contract. The supplier must handle whatever input
the client gives it; that's the nature of an exported API (i.e., all
public and protected methods). The usual Java mechanism to let a
client know it has violated its contract is a runtime exception such
as NPE. Sometimes it can do what the slides call a "tolerant"
approach, return a suitable value, as with 'Math.sqrt(double)'. You
just cannot prevent all future code written by all future programmers
from providing an illicit input.
Consider the Java method 'Arrays.binarySearch()'
static <T> int binarySearch( T[] a, int fromIndex, int toIndex, T
key,
Comparator<? super T> c )
et al.
Within the code there is an explicit check that 'fromIndex' is not
greater than 'toIndex'. From what you said, all client code should
enforce that, and relieve the library routine of the supposed
inefficiency of that check. How is it more efficient for a gazillion
callers to do a check centralized in one place in the 'Arrays' class,
as a private method, that alerts clients to their violation of the
contract via an 'IllegalArgumentException'?
How would you do it instead?
--
Lew