开发者

Bad practice with the ternary operator [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance. 开发者_高级运维 Closed 11 years ago.

While writing some PHP, I needed to iterate over a function call that could also return null, so I used the following construct:

foreach (($object->method() ? : array()) as $thing)
{
    // Insert code here
}

My project manager was not fond of this practice and insisted I write something more verbose. I understand his perspective, but if it were up to me, I would leave it as is. What do others think of this practice?


Do you have access to modify method() ? It seems like the preferred solution would be to make it return an empty array instead of null.

Edit

If that isn't possible, I think you should do as the project manager suggests or take a decision in the team if this use of ternary operators is ok. I am not a php programmer, and I was a little confused by the semantics of the empty true branch.

An alternative to a is_null() wrapper around the foreach loop could be a clearly-named wrapper function around method() that returns the empty array if method() is null.


It's perfectly cromulent. While this will lead to a PHP 5.3 dependency, it's short and still readable. I guess he took exception to its occurence in foreach, where complex expressions are somewhat uncommon, and hencewhy frowned upon.

Anyway, I sometimes use casting there, which is not more readable, but useful for parameter flexibility (treating a single string as array), not sure if that's really "better" in this case:

 foreach ( (array)$object->method() as $xy )
 {

Obviously, only works if the method returns nothing (NULL). If you can help it, make the method itself return an empty array instead (as good as a boolean false).


I am going to guess that most likely the manager is against using ternary operators because they can be harder to read. When skimming through the code doing updates, or when code is being reviewed by another programmer, the intent is not usually immediately obvious.

Also, in PHP 6, the ternary operator is being changed from ?: to ??::, which means that if the platform you are programming for will be upgraded to PHP6, this line will need to be recoded.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜