¿Tres estados en una línea de verificación de estado? (con respecto a la sintaxis de Java)

That the code snippet

if (addMore) {
    y = x + moreValue;
} else {
    y = x;
}

can be compressed into:

y = (addMore ? x + moreValue : x);

Is familiar to most programmers with a some experience with Java. But I was wondering if more than two states can be compressed into one line, eg:

if (addMore) {
    y = x + moreValue;
} else if (50 < x) {
    y = 50;
} else {
    y = x;
}

How can this (if possible that is) be compressed into one statement, something like:

y = (addMore ? x + moreValue {SOMETHING IN HERE} : x);

preguntado el 31 de julio de 12 a las 10:07

Leave your if statements as they are. They're much more readable than nested ternary expressions. -

Yes, you can, but why would you want to? Chances are it'll execute exactly the same code but it'll be far harder to read. -

5 Respuestas

condition1 ? (condition1-2 ? action 1-2: action-not-1-2) : action-not-1

Respondido 31 Jul 12, 10:07

+1 Thanks, I was unaware that you could break in up like that. - ajetreo de Android

I use such a construct regurarly, it is reminiscent of Clojure's cond:

y = 
  addMore ? x + moreValue :
  50 < x  ? 50            :
            x;

I find no issues with readabiility, quite to the contrary. I like that I can be sure this whole construct is about assigning a value to y. That is not at all obvious with the classic if-else if combination.

Respondido 31 Jul 12, 11:07

+1 I agree, I don't have problems seeing how the statement connects. - ajetreo de Android

In fact, the advantage gets even more pronounced when there are more of these else-parts, like 5 or more. In that case with if-else if there's a whole lot of code involved and you must painstakingly make sure that the whole block is indeed all about assigning to y and no other stuff besides. - Marko Topolnik

Frankly, if there are more than 2 or 3 blocks, you'd better use y = computeValue(x, addMore); - JB Nizet

1. A infamous proverb..... "Any fool can write a code that computer can understand, but only good programmer writes code that human can understand...."

2. Its more about readability y understandability.

But still here is your answer....

(addMore ? x + moreValue : (50 < x ? 50 : x)) // Assign this to y

Respondido 31 Jul 12, 10:07

Using Ternary operator, more than one condition can check.
if First condition is true then compare with second value.

y = (addMore ? x + moreValue : (50 < x ? 50 : x));

Respondido 31 Jul 12, 11:07

y = (addMore ? x + moreValue : (50 < x ? 50 : x));

But as said in the comments, this is far less readable than the if..else statement so I think it should be avoided.

Respondido 31 Jul 12, 12:07

+1 Thank you, I realize it would be hard to read. I'd say I was more interested in knowing how to do it rather than practising it. - ajetreo de Android

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.