4 ms·
groovy helps a bit with this when you use the jvm -- lots of their operators are null aware [1], ie max([3, null, 4]) == 4 and they have a null-safe derefer
by earl 15y ago
groovy helps a bit with this when you use the jvm -- lots of their operators are null aware [1], ie
max([3, null, 4]) == 4
and they have a null-safe dereference operator [2], so returning null is actually reasonable as an error
def user = User.find( "admin" ) //this might be null if 'admin' does not exist
def streetName = user?.address?.street
Collapsable to:
def streetName = User.find("admin").?address.?street
It's not perfect, but it's a lot better than plain java. Compare to:
String street = null;
User user = User.find("admin");
if (user != null) {
Address addr = user.address;
if (addr != null)
street = addr.street;
}
// or even
String street = null;
if (User.find("admin") != null && User.find("admin").address != null)
street = User.find("admin").address;
I think one of my biggest complaints -- and the reason I think Gosling is a moron -- is how programmer unfriendly java is. Some syntactical sugar as above, so you don't have to nest null checks, goes a long way towards making languages more friendly to devs. Even simple things like in ruby being able to say
1_000_300_233 == 1000300233
makes it a lot nicer to read big numbers. Sigh. If Gosling actually wrote code instead of doing whatever he wastes his time doing, you'd think that's the sort of thing you could just add to the language.
[1] http://groovy.codehaus.org/Null+Object+Pattern http://groovy.codehaus.org/Null+Object+Pattern
[2] http://groovy.codehaus.org/Operators#Operators-SafeNavigationOperator%28%3F.%29 http://groovy.codehaus.org/Operators#Operators-SafeNavigatio...