PhpRiot
News Archive
PhpRiot Newsletter
Your Email Address:

More information

Shortcuts

Note: This article was originally published at Planet PHP on 3 August 2011.
Planet PHP

Being at OSCON, I've attended one good talk about Python oddities, which got me thinking about language syntax in general.

PHP is notorious among scripting languages for it's verbose syntax - you have to spell out many things that are much shorter in other languages. Some people think it's very bad that they can't be aoexpressivea, meaning writing more clever code with less keystrokes. Sometimes they are right, sometimes they are not. Let's consider two examples:

From PHP:A5.4 has a new array syntax:A['foo', 'bar'] which is the same as array('foo', bar').

I think it's a good shortcut - because [] is a common expression for arrays (or structures that work like PHP arrays) in many languages, and it is obvious for most people how it works.

What's an example a shortcut that isn't good?APython (version 2) has this syntax for exception handling (this was one of the examples in the talk):

except Foo, Bar:

Now what this means: are we catching two exception types, Foo and Bar, or are we catching exception Foo and assigning it to Bar? The correct answer is the latter - it's exception Foo assigned to Bar. I think it's bad shortcut - because it uses a comma - which is common expression for lists and enumeration - to separate the type and the parameter. This leads to people writing things like aoexcept KeyError, IndexErrora which doesn't do what one would expect to.

Pyhton people seem to agree with me, as in Python 3 the syntax has been changed to:

except Foo as Bar:

One could argue it's not as aoexpressivea and more verbose - bu it's definitely much more readable and would lead to less broken code. It'd be even better if they used the word aoexceptiona or try/catch as all the rest of the world does

Some people in PHP community think all aoshortcutsa are best to be avoided. I think some of them could be useful, provided clarity is not sacrificed and there's not aotoo much magica. I know it's subjective but my personal criteria is that if it's not immediately clear what's going on for a person with reasonable knowledge of the matter - it's probably too much magic.