Don't get your ternary operators in a twist: Objective-C and the NYTimes Style Guide

The New York Times recently released its style guide for Objective-C on GitHub. And one of the first pull requests was related to the use of ternary operators. Something that is incredibly difficult to search for in the documentation when you don't know their name, because the defining elements of the operators are a question mark (?) and a colon (:).

 a==b ? NSLog(@"it's a match") : NSLog(@"boo, no match");

// Ternary operator meaning if a is equal to b then print "it's a match" in the console, else print "boo, no match"

For this reason alone they are probably best accompanied by a comment with the words "ternary operator" before or after them, but this aside, they are an interesting case along with using:

id a = @"string";
id b = @[@"an",@"array"];
id c = @{@"key":@"value"};

Ignoring the @ sign, the above examples are familiar to most programmers as indicating strings, arrays and dictionaries in some language/form or another.

These shortcuts share in common with ternary operators a lack of verbosity. And the logic of Objective-C is always to make code as human readable as possible. There are some people to this end who not only dislike code abbreviations such as these, but also switch statements.

But taking against the switch statement to my mind goes too far, since often a switch can be clearer than writing if and else statements. As regards ternary operators, I'm undecided because of the difficulty in discovering their meaning if you don't already know it.


Endorse  on Coderwall

Comments