Is returning Double.NaN from method a good practice to indicate invalid double value

java

Solution

In general, the practice of using a special return value for exceptional situations goes against the grain with Java's way of informing the caller about exceptional situations. To that end, strategies #1 and #3 are equivalent, because both of them result in caller code like this:

// This could be double or Double
double res = Newtons_method(pmt, guess);
// This could be res==null check or Double.isNaN(res) call
if (!checkResult(res)) {
    // Do something else
}
// Do regular processing

This is error-prone, because inevitably somebody will forget to do the check, causing errors down the road. This tends to happen more when method calls are nested, as in

double res = doStuff(Newtons_method(pmt1, guess), Newtons_method(pmt2, guess));

An incorrect result makes it into parameters of the next-level function call, forcing either an argument exception (if the coder is very good about his argument checking) or a hard to debug error down the road.

Your strategy #2 is better, because callers cannot simply "forget" to catch the exception: they would have to either catch and process it, or add `throws` to their own method.

Problem

Currently, I'm implementing a method with the following signature `public static double Newtons_method(double[] payments, double[] days, double guess)` Sometimes, the calculation will fail. There are several ways to indicate failure. - Change returned type to `Double`, and return as null. - Throws exception. - Return `Double.NaN` and use `Double.isNaN(double)` to test against it. However, there are several concern. - I prefer not to return Object, for performance purpose. I need to do a lot of box and unboxing if `Double` is used. - I prefer not to throw an exception, for performance purpose. Also, `try` `catch` makes code looks messy. Not, in `Newtons_method`, there are quite a number common cases where such algorithm will fail. So, it might not appropriate to consider them as `exception` How about 3rd approach, returning `Double.NaN`? Is that consider a good practice? Here's the source code for your reference. https://github.com/yccheok/xirr/blob/master/src/org/yccheok/quant/XIRR.java#L56 Note that, there isn't any error checking being implemented yet. So, `err` might never further reduced, and the method might go into infinity loop.

Original source