George V. Reilly's Technical BLog

Er, er

http://www.georgevreilly.com/blog/content/binary/ErEr.png

I've grown fond of the JavaScript || idiom:

 function FrobImage(img) {
var width = img.width || 400;
var height = img.height || 300;
// ...
}

FrobImage({height: 100, name: "example.png"});

If img.width exists and it's truthy, then width = img.width; otherwise, width = 400. Here, it will be 400 since the img hash has no width property. More than two alternatives may be used: x = a || b || c || ... || q;

A few weeks ago, while cleaning up the error handling in some batch files, I came across a similar idiom:

 foo.exe bar 123 "some stuff"  || goto :Error

Only if foo.exe fails (exit() returns a non-zero value), is the second clause executed.

Perl's die is typically used in a very similar idom:

 chdir '/usr/spool/news' || die "Can't cd to spool: $!\n"

though the or keyword seems to be preferred nowadays to ||.

This morning, I came across the ?? operator in C# 2.0, aka the null coalescing operator:

 Customer cust = getCustomer(id) ?? new Customer();

If getCustomer(id) is not null, then that's the value that cust gets; otherwise it's set to new Customer().

All of these idioms are syntactic sugar and all of them are in my toolbox.

Comments

blake05 said:

I love the null coalescing operator :)

# October 25, 2007 10:37 AM

Paul "TBBle" Hampson said:

"or" is used for this by preference in perl as it has a much lower precedence than "||", so there's no chance of accidentally (for example) trying to assign the value of (expression || die) when you meant to die if assigning a false value.

# November 5, 2007 7:37 PM

J-dawg said:

Yo let's give Lisp props for inventing this one in like 1942 or somethin':

(or (width img) 400)

Cheers!

# February 27, 2008 1:39 AM

acer said:

[...]resource[...]

# July 4, 2008 10:05 PM
Leave a Comment

(required) 

(required) 

(optional)

(required)