Java trernary hack

So, I'm not going to be refurbished or elegance here. Looking for a way to reduce common tokens in a method just for fun. The method consists of a long nested if-else construct, and I found that (I think) the way to do this with the smallest tokens is a ternary operator. Essentially, I will 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;

}

:

String method(param) {

    return 

        param == null ?
            error0 :

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

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

        ...

        error

    }

However, there are several cases where, in addition to returning a value, I also want to change the field or call the method; eg.

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

What will be the cheapest way to make this token? What I'm doing now is ugly, but not spending too many tokens (here the field is a string):

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

Again, it's not about good coding, I'm just looking for hacks to reduce the number of tokens. If there is a shorter way to write the whole thing, I am also open to this. Thanks for any suggestions.

: . , , "instanceOf String" - , "!= Null" - . , , - "& &" . "field = value" - , , , " = " ?

+3
2
(field = value) instanceof String

, (, , false, value is null),

(field = value) != null

, null return true,

(field = value) == value

, .

, , ;)

+2

null, return 0
case/switch/select . .

+2

Source: https://habr.com/ru/post/1731903/


All Articles