When to use ternary condition?

15

I particularly like the use of ternary condition, but I see a lot of developers out there saying, there's even rule in CheckStyle when validating your code that encourages you not to use.

See the example below:

var idElemento = $(this).attr("id");
var isDataInicial = idElemento.contains("Inicial");
$("#" + (isDataInicial ? idElemento.replace("Inicial", "Final") : idElemento.replace("Final", "Inicial"))).datepicker("option", isDataInicial ? "minDate" : "maxDate", selectedDate == "" ? null : selectedDate);

Taking the fact that if something else has to be implemented when the condition is true and / or false we will have more work to undo the ternary and create the if/else structure I do not see any problem in the above code, maybe better formatting in the maximum, but in a row was solved the problem that without the ternary we would have something like:

if ((idElemento.contains("Inicial")) {
    if (selectedDate == "") {
        $("#" + idElemento.replace("Inicial", "Final")).datepicker("option", "minDate", null);
    } else {
        $("#" + idElemento.replace("Inicial", "Final")).datepicker("option", "minDate", selectedDate)
    }
} else {
    if (selectedDate == "") {
        $("#" + idElemento.replace("Final", "Inicial")).datepicker("option", "maxDate", null);
    } else {
        $("#" + idElemento.replace("Final", "Inicial")).datepicker("option", "maxDate", selectedDate)
    }
}

So the question remains, when should we use the ternary? And is it so bad to use ternaries nested with a good indentation?

    
asked by anonymous 31.01.2014 / 21:09

4 answers

13

Your proposed if string is not the only way to represent the same code:

var idElemento = $(this).attr("id");
var isDataInicial = idElemento.contains("Inicial");

var idEscolhido, opcaoDP, data;
if ( isDataInicial ) {
    idEscolhido = idElemento.replace("Inicial", "Final");
    opcaoDP = "minDate";
}
else {
    idEscolhido = idElemento.replace("Final", "Inicial");
    opcaoDP = "maxDate";
}
if ( selectedDate == "" )
    data = null;
else
    data = selectedDate;

$("#" + idEscolhido).datepicker("option", opcaoDP, data);

The code above is more extensive, but more readable than both alternatives. Only in the case of data , would you gain something using the ternary operator:

var data = (selectedDate == "" ? null : selectedDate);

(optional parentheses, but I always put it when I use the ternary operator in a single line for emphasis)

That said, I have nothing against using the ternary operator whenever this brings clarity and conciseness to your code. Even in the case of multiple conditions, it can be placed in a well-formatted, easy-to-read format:

int result = FirstCheck() ? 1 : 
             SecondCheck() ? 2 : 
             ThirdCheck() ? 3 : 
             0;

What makes your original example problematic is that you used 3 times the ternary operator on a single line . This not only makes it difficult to read but also difficult to debug (ie if you need to put a breakpoint and / or a console.log to inspect the behavior of your program, it is unfeasible to do so in that format ).

    
31.01.2014 / 23:29
11

I recommend using it only when the resulting statement is extremely short and represents a significant increase in conciseness over the equivalent if / else without sacrificing readability.

Good example:

int result = Check() ? 1 : 0;

Bad example:

int result = FirstCheck() ? 1 : SecondCheck() ? 1 : ThirdCheck() ? 1 : 0;

Before using the ternary operator, you should consider the complexity of the situation at hand. Avoid nesting or stacking your operations even if you are comfortable with them as this can lead to a very confusing code and unintuitive results. It is still better to use IF statements for complex situations. Above all, have a nice code for the next guy who will tinker and try to keep your code clean and easy to understand.

    
31.01.2014 / 21:16
11

Robert Cecil Martin, author of the Clean Code book, immediately suggests the following metric for source code quality in the first chapter: how many times do you listen to your colleagues say "WTF" while reviewing your code !).

Now for the computer, whatever. As you yourself expounded somewhat on the question, in general the form:

a ? b : c;

It is equivalent to:

if (a) { b; } else { c; }

Since the machine is indifferent, what defines the "best" and "worst" shape for each case is readability and ease of maintenance. This varies from situation to situation. It is possible for the two to alternate as the "best" shape at different points in the same code file. If you program as a team, talk to your peers so that they reach a consensus and pattern. If you program by yourself, reread codes you have written in the past, and see the form that is easiest to understand.

Looking better at the question, I can think of two situations in which one form is better than the other.

When we have many conditions that we want to test , a if may be more readable.

if ((a == null &&
        b != null &&
        c ^ d) ||
        (e && !f) ||
        g)
{
    foo();
}
else
{
    bar();
}

If written ternary, it would look like:

((a == null && b != null && c ^ d) || (e && !f) || g) ? foo() : bar;

You can continue adding conditions until the expression is larger than the screen. Breaking into lines may get strange in ternary form.

Note that this was a hypothetical and illustrative case . It is much better to create a boolean variable calculated as a result of all conditions, if there are many, and then use that variable in if or ternary expression.

Online Code is where the ternary expression proves particularly useful. For example:

int a = foo(b ? c : d);

It's more compact than:

int a;
if (b)
{
    a = foo(c);
}
else
{
    a = foo(d);
}

Although this looks like the previous comparison, note the subtle difference: you can not use a if block within the call of a method or function (at least in most languages in the C - I can not make a strong statement for all languages).

    
01.02.2014 / 00:02
1

I have doubts about the use of the ternary and, considering the great ease that the ternary can bring, besides having improved the visualization today (this stack is about Javascript, but PHP brings in some new paradigms), the following structure:

var valor = (acao == 1)
    ? primeiroValor
    : ((acao == 2)
        ? segundoValor
        : terceiroValor);

With these standardizations, as I mentioned PHP, there are the PSR , which seek to standardize the code and, seeing that a unit exists between the community, decreasing the calls " Taste Questions "

    
18.08.2016 / 19:32