Beefy Boxes and Bandwidth Generously Provided by pair Networks
Problems? Is your data what you think it is?
 
PerlMonks  

Re: Mr. Ternary is greater than Mrs. If Else

by tilly (Archbishop)
on May 20, 2007 at 23:24 UTC ( [id://616484]=note: print w/replies, xml ) Need Help??


in reply to Mr. Ternary is greater than Mrs. If Else

Short answer, because some programmers understand enough to be more concerned with maintainability than cleverness.

First of all your overuse of eval has just killed your exception reporting unless you put in a check for $@ or die. (Which your code examples didn't.) By the time you've added that, you've just made your code longer and more obscure than the original if/else construct would have. (As several have noted, you could solve that problem by using do.)

Secondly there is great value in having code with recognizable intent. For most use cases, ternary operations do not communicate intent as well as the traditional if/else. And this is not just a familiarity issue. An important principle is to put the most significant thought in the line of code first because that is what you'll notice when you're scanning through it. When you're scanning code, one of the most significant things to be aware of is the flow of control. The fact that the flow branches at an if statement is a critical fact, so you should start your line of code by communicating that fact clearly. Ternary statements don't do that, they bury the control of flow into easily missed punctuation. Occasionally this choice of emphasis is appropriate, but usually it is not.

Thirdly, it is important for programmers to work well with others. An idiosyncratic coding style is a barrier for others who want to work with you. Sure, people's styles vary. But you had better have a very good reason to pick a style that nobody else uses. And your reasons for doing that are frankly not good enough.

And finally, good programmers have to program in many different languages over the course of their careers. It is therefore wise to at least think about how well your style will work in many different languages. And the truth is that if/else style coding works appropriately in more languages than ternary operations do. Which is a reason why it is wise to use if/else whenever appropriate.

  • Comment on Re: Mr. Ternary is greater than Mrs. If Else

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://616484]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others learning in the Monastery: (2)
As of 2024-04-19 01:37 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found