seperis: (Default)
seperis ([personal profile] seperis) wrote2011-05-08 01:14 am

random coding note

When you know you've been coding too long.

var x = (condition)?option1:option2;

And here I have been writing my if/else statements out like a sucker. Are they stackable?

You know, there's a fair to good chance I am now thinking in variables. Goddamn googledocs and their addictive google apps scripts. Does anyone else play with them?
synecdochic: torso of a man wearing jeans, hands bound with belt (Default)

[personal profile] synecdochic 2011-05-08 07:53 am (UTC)(link)
Those are known as biconditionals! And depending on the language, they are nestable:

$ret .= condition ? ( condition ? option 1 : option 2) : option 3;

Most people find biconditionals really hard to read, though, and nested biconditionals more so, so it's official DW programming guidelines that you don't nest them (and if you absolutely have to, use formatting and comments to make it clear what you're doing).

And you want to be really careful, actually; if you use the construct like you described it above, there's a nasty problem in perl at least (and possibly other languages; I don't know if it's perl-specific or not) where if you declare the variable inside the biconditional, it's not cleared properly when you exit the routine, and the value persists in different iterations. This caused a massive bug that we took forever to chase down where things were getting set wrong, because someone had done:

my $thing = condition ? option1 : option2;

and the value stuffed into $thing persisted from call to call -- even if it was being called by another process and intended for another user. The thing to do there is declare the variable before you use it:

my $thing;
$thing = condition ? option1 : option2;


(I think that glitch is perl-specific. But it took us forever to chase it down, so I pass on the warning.)
pixel: Adam Lambert looking up with a smile. (glambert: adam OHHAI)

[personal profile] pixel 2011-05-08 01:11 pm (UTC)(link)
Err, what language are you using? In ruby you can do things like:

possibly_something ||= set_it_to_this_if_nil


Which knocked my socks off the first time I saw it...
ext_8753: (Default)

[identity profile] vickita.livejournal.com 2011-05-08 01:20 pm (UTC)(link)

Yes, they are stackable, but pretty soon it becomes unreadable if you're not careful. But yeah, pretty and compact, huh?