15
I particularly like the use of ternary condition, but I see many developers saying no, there is even a 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);
Apart from 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 structure if/else
I don’t see any problem in the above code, maybe a better formatting at most, 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 it is so bad to use ternaries nested with a good identation?
I agree with you that debugging in JS would be an almost impossible task unless you isolate on consoles.log each of the ternary ifs, now with the current Java Ides you don’t even need to use sysout (equivalent to a console.log) for this. But I liked the use of parentheses to emphasize the ternary.
– Philippe Gioseffi