Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

java ternary hack

So I'm not going for maintainability or elegance here.. looking for a way to cut down on the total tokens in a method just for fun. The method is comprised of a long nested if-else construct and I've found that (I think) the way to do it with the fewest tokens is the ternary operator. Essentially, I translate this:

String method(param) {

    if (param == null)
        return error0;

    else if (param.equals(foo1))
        if (condition)
            return bar1;
        else
            return error1;

    else if (param.equals(foo2))
        if (condition)
            return bar2;
        else
            return error1;

    ...


    else
        return error;

}

to this:

String method(param) {

    return 

        param == null ?
            error0 :

        param.equals(foo1) ?
            condition ?
                bar1 :
                error1 :

        param.equals(foo2) ?
            condition ?
                bar2 :
                error2 :

        ...

        error

    }

However, there are a couple cases where in addition to returning a value I also want to change a field or call a method; e.g.,

    else if (param.equals(foo3))
        if (condition) {
            field = value;
            return bar3;
        }
        else
            return error3;

What would be the cheapest way to do this token-wise? What I'm doing now is ugly but doesn't waste too many tokens (here the field is a String):

        param.equals(foo3) && (field = value) instanceOf String ?
            condition ?
                bar2 :
                error2 :

Again, the point is not good coding, I'm just looking for hacks to decrease the token count. If there's a shorter way to write the entire thing I'm open to that as well. Thanks for any suggestions.

Edit: Each word and punctuation mark counts as one token. So, for example, "instanceOf String" is two tokens, but "!= null" is three. The main things I can see for possible improvement are the "&&" and the parentheses. Is there a way to put "field = value" somewhere besides the conditional, and if not is there a construct that makes "field = value" a boolean without the need for parentheses?

like image 553
daltonb Avatar asked Aug 19 '26 04:08

daltonb


1 Answers

(field = value) instanceof String

Assuming that it already satisfies your needs (and it thus includes returning false when value is null), a shorter alternative would then have been

(field = value) != null

Or if you actually overlooked that and want to make null return true as well, then use

(field = value) == value

This can be made much shorter if you use 1-letter variable names.

Further I don't see other ways and I agree with most of us that this all is somewhat nasty ;)

like image 82
BalusC Avatar answered Aug 20 '26 19:08

BalusC



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!