Is this syntactically correct?
I noticed this piece of code in using CodeIgniter database migrations:
$this->migrations->verbose AND print "Creating table '{$table}'...";
$verbose
is a config value.
We had a debate in the office about whether or not this is valid and readable code. It basically replaces the need for an IF statemen开发者_StackOverflow社区t as it executes the 2nd part of the condition if the first part is true. I actually quite like it, but the guys in the office think it's an accident that it works and that this would be more readable:
if( $this->migrations->verbose ) print "Creating table '{$table}'...";
What do you think?
This is called 'short-circuit evaluation', and the technique is frequently used in shell scripts - for example:
rm thing_to_delete || exit 1
It's more common in some languages than others, and a lot of people do see it as something to be avoided, as it can be confusing. (People usually assume that logical expressions don't have side effects.)
It's valid, but it sure isn't readable. I don't think trying to introduce Perl-style syntax constructs into PHP, even if they do work, is a good idea.
It's absolutely valid. Whether or not it's readable is purely subjective. :)
"Is this syntactically correct?"
Of course it is :) Otherwise PHP would give you a parse error. The code works and is also semantically correct PHP. It's a lot like using: $v = $v || "default value";
To assign a default value to $v
if there isn't one already.
So, whilst the two snippets have the same effect, I'd vote strongly for the second (if (…) print ...
). Code is about communicating to other programmers as much as it is about communicating to the machine. If the idioms of the language (and thus the programmers using it) were to use short circuit evaluation for such situations, then it would probably be fine. However, PHP does not generally use short-circuit evaluation in statements - most PHP programmers (and indeed, programmers in general) would do a double-take here.
Code for least surprise, and code your exact meaning. If this is a conditional test that should execution only if some variable is true, make it a real conditional test using the conditional test construct - that is, here, if
.
Logic operators are short circuiting and evaluation operands from left to right, so this code does exactly what the version with if
statement.
It's a completely valid code, and if you have good developers it should be also readable to all of them. If it causes confusion in the team then don't use it, but it would be better to teach them what it actually does.
If readability is the code's likeness to the natural-language-description of what the code is actually doing, then using if
is more readable.
精彩评论