Terminally Incoherent

Utterly random, incoherent and disjointed rants and ramblings...

Friday, April 21, 2006

Java ?: operator

One of the least understood, and most underestimated Java language constructs is the ?: operator. Most people never even seen it in action. And those who did, never actually used it to do anything meaningful. Imagine something like this:

public generateFoo(int threshold)
{
    if(threshold > MIN_THRESHOLD)
       return new Foo();
    else
       return null;
}


In this snippet of code we have a function which generates a new Foo object if the passed argument is greater than some minimal threshold. If it is below threshold we return null. This is not an uncommon scenario... But with the ?: operator we could accomplish all of this on a single line.

public generateFoo(in threshold)
{
    return (threshold > MIN_THRESHOLD) ? new Foo() : null;
}


If you didn't catch that let me show you something simpler:

int foo = bar ? a : b;

Java expects to a boolean or an expression evaluating to a boolean before the question mark. If that expression is true, then the whole statement evaluates to a. Else it evaluates to b.

It is elegant, produces a lean code and saves you one return statement. It is a good coding practice to have one return statement per method when possible. I think more Java programmers should embrace this little syntactic sugar. It saves you allot of typing when used appropriately.

0 Comments:

Post a Comment

<< Home