tags:

views:

265

answers:

5

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.

+3  A: 

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.

danben
+1  A: 

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.

nanda
+1  A: 

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.

Milan Ramaiya
Thanks - that's interesting.
Pool
+1  A: 

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.

McDowell
+1  A: 

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.

Andreas_D