Ternary Operators and Other Less-Used Control Structures

I like my code to take up as little space as possible. I believe that compact code is more readable and more importantly navigation is easier.

I tend to write my if statements on a single line when there is only one statement in the block:

if($var) echo "Hooray";

Another thing I love to use are ternary operators:

$win = ($validation) ? "Yes" : "No";

The only problem with ternary operators seems to be that a certain proportion of developers refuse to use them. Most often than not, it’s fear of doing things ‘differently’; they’re used to if-else control structures and anything else is new and scary.

I’ve often heard the excuse that developers don’t want to write code which others won’t be able to pick up. In my opinion, that’s a total and utter cop-out! If a developer were to pick up my code and see something they don’t recognise, there’s a chance that they’ll look into it and learn something new, even if only to understand the code they are working with. Surely, that’s a good thing.

Developers need to be adaptable and open to new coding practices otherwise they stagnate and they stop learning. What’s the point in having 10 years of experience if the code you’re writing hasn’t evolved?

I look back at the code I wrote when I got my first commercial web development job and it’s vastly different to the code I write now. I’m also constantly reviewing the way I structure the PHP, SQL and Javascript code which I churn out. For instance, I recently had the revelation that rather than doing something like:

$win = ($validation && $winning == 'yes') ? TRUE : FALSE;
if($validation && $winning == 'yes') $win = TRUE;
else $win = FALSE;

I can just do this:

$win = ($validation && $winning == 'yes');

Any expression (so I believe; comment if I’m wrong) within the parentheses will assign a boolean value. How clean is that?

Share Button