Pool
Pool

Reputation: 12342

Java maths - testing for NaN

I would like to have some kind of project-wide fail fast mechanism (maybe a RuntimeException) for any code that causes assignment of NaN.

In my project NaN is never a valid value.

I realise I could add asserts (using isNaN) or other tests throughout but I want to know if there is a more elegant way.

Upvotes: 6

Views: 5877

Answers (5)

Andreas Dolk
Andreas Dolk

Reputation: 114757

Just another approach - you could integrate code checkers like PMD into your build process and create a rule that reports every assignment of Double.NaN.

It will not be perfect, because it can't catch NaN's you get from the outside (database, connections) or that someone creates through bit manipulation but at least you can assure that Double.NaN can't be assigned to a variable or be used as a method parameter or inside an evaluation.

Defining the rules might be challenging - but at least - it's another approach. The simplest rule could be to forbid Double.NaN at all.

Upvotes: 2

McDowell
McDowell

Reputation: 108859

Technically, it would be possible to create an agent to do this by instrumenting the code in question to inject assert or if tests automatically. This would involve a bit of bytecode inspection and transformation (e.g. using ASM). In my opinion, it would take extraordinary circumstances to warrant this. You'd have to be careful not to instrument any classes that rely on being able to process NaN internally.

I'm not aware that anyone has written such an agent. If you're looking for a silver bullet, I don't think there is one.

Upvotes: 2

Reverend Gonzo
Reverend Gonzo

Reputation: 40811

Yes, you can use AspectJ (aspect oriented programming) to throw an error whenever a value is set to NaN.

Essentially, you want to intercept whenever a value is set, and perform some other function.

We've done similar things in our codebase ... but I can't give you much help outside of that.

Upvotes: 4

nanda
nanda

Reputation: 24788

If you ready to sacrifice the performance of the application, you can create a wrapper for Double (or other numeric object you want to use) and throw exception when NaN is set.

Upvotes: 2

danben
danben

Reputation: 83220

No - because NaN IS a valid value, using it won't cause any exceptions to be thrown. Without any ubiquitous monitoring mechanisms to use, you would have to test explicitly at the points where it might be assigned or returned from a method.

Upvotes: 4

Related Questions