George V. Reilly

Er, er

Er, er

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 al­ter­na­tives 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 get­Cus­tomer(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.

blog comments powered by Disqus
Virtualization » « Review: Mr. Vertigo