Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is StringUtils.isNumeric() method specification logically correct?

Apache's StringUtils.isNumeric() method specification says:
Checks if the String contains only unicode digits. A decimal point is not a unicode digit and returns false. Null will return false. An empty String ("") will return true.

Is this logically right? Why do they see empty string as numeric?

like image 292
Andriy Sholokh Avatar asked Oct 20 '10 12:10

Andriy Sholokh


1 Answers

The behavior changed in 3.0. From What's new in Commons Lang 3.0?:

StringUtils.isAlpha, isNumeric and isAlphanumeric now all return false when passed an empty String. Previously they returned true.

Keeping old answer below, for reference and for pre 3.0 users.


Is this logically right?

We have

  1. the behavior of the method
  2. the documentation of the method (which is often viewed as the specification or contract)
  3. the name of the method

In this case 1 and 2 agree with each other; All characters in the empty string are unicode digits. (Or equivalently, no characters in the empty string are not unicode digits.) This what logicians call vacuously true and somewhat counter intuitive. It's like saying that all elephants in my apartment are green. It's true, since there are no elephants in my apartment.

Item 3 however (the name of the method) is naturally interpreted as a method that returns true if the given string represents a number.

So, either it's a documentation and implementation bug, or it's a naming bug. There's no right or wrong answer to that.

A bug was filed here. The maintainers take the stand point that it's intended behavior.

Why do they see empty string as numeric?

While the name of the method may lead you to believe the method should return true only for strings that represents a number, the spec actually says it should return true for if the string contains only unicode digits.

You say,

I'm confused because specification says: "Checks if the String contains only unicode digits." I don't see that "" contains digits....

Note that the empty string does not contain anything else than unicode digits. Therefore the method returns true.

like image 138
aioobe Avatar answered Oct 06 '22 17:10

aioobe