Wednesday, October 15, 2014

Argument against Ternary Conditional Operators

Time to get up on my soapbox...

I was just doing the CodeSchool JavaScript best practices course and the very first item in is it something I could not disagree with more.

The Ternary Conditional Operator is one of the worst things to allowed in common programming language syntax.  Unless you trying to write your code to be as minimalist as possible to save every possible byte in your source files it should not be used.  The reduction of readability and maintainability when using the ternary operator far out weighs the advantages  of being less verbose and requiring less lines of code.

var isHero = true;
var canFly = true;

//normal if else 
var name;
if (isHero && canFly) {
   name = "Superman"
} else {
   name = "Vader"

//ternary conditional operator
var name = isHero && canFly ? "Superman" : "Vader";

Yes, it the ternary conditional operator is quicker and dare I say easier.  However I will wager that 100% of the engineers in the world can understand the standard if/else and just a glance where as with the ternary operator some of them will confuse the result and the majority will have to pause for a second or two to try to make sure the way ternary operators work in their head.  Does it mean you are smarter than the rest of the your team if you use ternary operators? No. It just means like pavlov's dog you have been trained to translate the syntax into an if/else without needing to think about it.  When debugging a complex important issue the majority of people do not wish to waste time translating code so they can understand it.  It slows the team down and frankly increases the chances of defects.  I would love it if I could ban ternary operators from use in all languages but Assembly.

...stepping off my soapbox.

No comments:

Post a Comment