A discussion has come up in my office about the use of ternary operators. There are two sides to this discussion.
Side 1) That ternary operators are easy to write and read, therefore convenience is a net cost-savings.
Side 2) That ternary operators are difficult to maintain because they require excess code-churn should they ever need to be modified to be even the slightest bit more complex.
Extra nerd points if you can cite any actual studies done by a top-tier institution on this subject... I'm very interested to see hard data on this.
My theory is that the best code is code that can change and adapt easily, and that the less complexity that change requires, the less chance there is for a break. Example:
$id = $user->isRegistered() ? $user->id : null;
Ok, so this is completely valid, but what happens when the code needs to change to become something slightly more complex?
$id = null;
if ($user->isRegistered() || $user->hasEmail()) {
$id = $user->id;
}
Any sane programmer would look at the ternary and convert to standard if/else. However, this required a 4-line change versus starting with:
if ($user->isRegistered()) {
$id = $user->id;
}
Which would only require a 1-line change.
Thoughts? Opinions? Flame throwers?