Coding Range

Clever Code with the Ternary Operator

November 11th, 2013

One of the things I find myself having to use on a semi-regular basis in C# is the null-coalescing operator. It lets you transform the following block into a single line:

if (obj != null)
{
    return obj;
}
else
{
    return someDefault;
}

The single line is as follows:

return obj ?? someDefault;

Today I learned that C has a similar operator with a GNU extension. An expression using the standard ternary operator (?:) such as this one:

x ? x : y

can be rewritten as:

x ?: y

with the expression x only evaluated once, not twice. Extrapolating from here, this means that one could do null-coalescing (or rather, nil coalescing) in Objective-C. The most useful place something like this would occur be in lazy-loaded values. For example, this code:

@implementation Foo
{
    Bar * _bar;
}

- (Bar *) bar
{
    if (_bar != nil)
    {
        _bar = [[Bar alloc] init];
    }
    return _bar;
}

can be rewritten as:

@implementation Foo
{
    Bar * _bar;
}

- (Bar *) bar
{
    return _bar ?: (_bar = [[Bar alloc] init]);
}

This significantly detracts from the readability, but it’s a cool hack of what’s possible. I do think, however, that it’s an example of what one can do, and not of what one should do.