0

This is in PHP, but it should (I think) apply to any language with a ternary operator.

I have a simple line with a ternary operator assigning a string to a value. The strings ended up being a little too long to put it on one line, though, so the end result looks like this:

$resultingString = ($isValid) ?
    "This statement is true."
    :
    "This statement is false."
;

The code runs perfectly, but it just looks... weird... Is this bad practice? The only alternative I can think of is this:

if ($isValid) {
    $resultingString = "This statement is true.";
} else {
    $resultingString = "This statement is false.";
}

Which is slightly less DRY.

  • I definitely wouldn't say the top one is bad practice, neither is the bottom. I would favor the top one because I use ternary heavily, both I think are equally legible and self explanatory. I would note that for your if then, if you are just doing one conditional, you don't need the bracing, you could just use if($isValid) $resultString = "This statement is true."; else $resultString = "This statement is false"; – slackOverflow Jul 22 '17 at 22:40
  • https://stackoverflow.com/questions/243217/which-coding-style-you-use-for-ternary-operator – Posttwo Jul 22 '17 at 22:40
  • If you have bigger line or multiple lines, it's better to go with if blocks. These operators won't provide any benefits other than readability. – Prajwal Jul 22 '17 at 22:41
  • Never omit the braces, that really is bad practice. – Doug Jul 23 '17 at 09:12

2 Answers2

2

This is an opinion based topic, but I tend to think it is mostly just important to be consistent in your codebase. One possible style similar to your original (that to me reads cleaner):

$resultingString = ($isValid)
    ? "This statement is true."
    : "This statement is false.";

I avoid these when possible and avoid 'else' as a general practice so i would probably do:

$resultingString = "This statement is false.";
if ($isValid) {
    $resultingString = "This statement is true.";
}
D Lowther
  • 1,609
  • 1
  • 9
  • 16
  • This second example is so much more readable and easy to understand imo. – Steve Chamaillard Jul 22 '17 at 23:19
  • The main downside of the 2nd example is that ``$resultingString`` is mentioned twice, and that can lead to problems, e.g. if you rename the variable but mistakenly change only one of them. The only good reason to do it this way would be if the block of code in the braces consisted of more than just a single statement that assigned a new value to ``$resultingString``. – kmoser Aug 28 '17 at 19:03
0

I prefer:

$resultingString = (
    $is_valid
        ?
    "This statement is true."
        :
    "This statement is false."
);
kmoser
  • 8,780
  • 3
  • 24
  • 40