this post was submitted on 14 Jul 2023
339 points (90.6% liked)

Programmer Humor

32050 readers
1800 users here now

Post funny things about programming here! (Or just rant about your favourite programming language.)

Rules:

founded 5 years ago
MODERATORS
 
you are viewing a single comment's thread
view the rest of the comments
[–] deaf_fish@lemm.ee 0 points 1 year ago (1 children)

There is usually a safer and more readable way to do what you want to do by chaining ternaries in most languages.

[–] Serdan@lemm.ee 4 points 1 year ago (1 children)
[–] deaf_fish@lemm.ee 1 points 1 year ago* (last edited 1 year ago) (1 children)

Well, if you assume ternary operations work the same in PHP as in c and attempted to write the code demoed by this meme. You would end up with unexpected behavior. Maybe I should have said unexpected behavior instead of unsafe behavior.

[–] Serdan@lemm.ee 1 points 1 year ago (1 children)

PHP is the only language in existence with a left associative ternary operator. Ignoring PHP, the operator has worked exactly the same way for decades. And even PHP has now fixed the operator.

I don't think it's reasonable to avoid a very commonly supported pattern just because a single badly designed language implemented it wrong.

[–] deaf_fish@lemm.ee 1 points 1 year ago (1 children)

Okay, even if I give you the unexpected behavior point. The readability problem remains. Switch statements or tables will work just fine and are easier to read.

To be clear, I am fine with single ternary operations. I think nested ternary operations are harder to read and follow.

[–] Serdan@lemm.ee 1 points 1 year ago

I agree you should use a switch where applicable, but ternaries are the expression equivalent of if-else statements. If I have two conditions and a default, and each branch simply evaluates to a value of the same type, I'll probably just use a ternary.