by gburt · 15y ago · 0 comments
-----
The following things are considered to be empty:
- "" (an empty string)
- [...]
--> "0" (0 as a string) <--
- [...]
- var $var; (a variable declared, but without a value in a class)
-----
Why the heck is "0" considered empty?
making the switch in if() be a boolean only pushes the problem off to the programmer, who will often choose the wrong function or expression to do the conversion
What exactly is the alternative?
If there's any problem here it's automatic coercion.
In ruby, everything except false and nil is true. Easy.
Unless you override the == method of course. With great power...
For instance, 0 == false isn't too crazy, it's like C. But automatic coercion of string values to ints makes "0" == false which is sometimes what you want and sometimes not.
Practically this burns people in form validation code because often you want to test if a field is an empty string and if you do the obvious thing you can end up kicking out "0".
When I write PHP I have my own "PHP on nails" library that has functions that smooth out most of the things that are wrong with the language, and one of them is a comparison operator that is somewhere between "==" and "===" that most frequently does what you want it to do.
most languages have some screwed-uppedness about collections, both intrinsic to the language and that gets introduced by people who make APIs that aren't well designed. for instance, arrays and Lists are often not quite perfectly uniform (and it's often a thoughtless arbitrary choice if people decide to return you one or the other) Scala introduces it's own collections that provide more confusion when you're working with Java. The .NET framework has a great implementation of generics (makes Java and Scala look like a joke) but there are still many legacy APIs in the .NET framework that use non-generic collections.
One result is that it's not always obvious what the right way to test for "empty" is. One of the worst of them is that pretty frequently APIs will give you a null when they ought to be sending you an empty collection, so you need to check for null.
Either the types that are returned are scala collections, or they're java collections. If you want to treat java collections like scala collections you can always `import JavaConversions._` and huzzah, shallow conversions and collection uniformity.
Finally, if something has the possibility of being null, you can use the option construct, e.g.
if (Option(someListThatMightBeNull).getOrElse(List()).isEmpty) { ... }
Or more likely: Option(someListThatMightBeNull) match {
case Some(list) => // do something...
case None => // do something else...
}
More than likely if you're dealing with scala libs, things that can be "null" are returning options anyway.