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;
img.width
width = img.width
width = 400
400
img
width
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.
foo.exe
exit()
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 ||.
or
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().
getCustomer(id)
null
cust
new Customer()
All of these idioms are syntactic sugar and all of them are in my toolbox.
Page rendered at Friday, December 05, 2008 11:55:09 AM (Pacific Standard Time, UTC-08:00)
Disclaimer The opinions expressed herein are my own personal opinions and do not represent my employer's view in anyway.
E-mail