Java maths - testing for NaN

2020-02-12 07:27发布

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.

标签: java math nan
5条回答
smile是对你的礼貌
2楼-- · 2020-02-12 08:04

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.

查看更多
Viruses.
3楼-- · 2020-02-12 08:05

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.

查看更多
beautiful°
4楼-- · 2020-02-12 08:19

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.

查看更多
祖国的老花朵
5楼-- · 2020-02-12 08:20

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.

查看更多
Summer. ? 凉城
6楼-- · 2020-02-12 08:25

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.

查看更多
登录 后发表回答