首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在尝试获取数组/集合值之前,是否应该检查它是否存在?

在尝试获取数组/集合值之前,是否应该检查它是否存在?
EN

Stack Overflow用户
提问于 2014-09-19 12:56:58
回答 1查看 831关注 0票数 1

我应该检查一个键是否存在,然后得到它还是只得到它(当我需要得到它,而不是检查它的设置)?

什么更可靠?更安全?更快?

示例:

1) PHP (https://github.com/nicolasff/phpredis)

代码语言:javascript
复制
if ($redis->exists('key'))
    echo $redis->get('key');
// VS
if ($value = $redis->get('key'))
    echo $value;

2) phalcon (http://docs.phalconphp.com/pt/latest/reference/cookies.html)

代码语言:javascript
复制
if ($this->cookies->has('remember-me'))
    echo $this->cookies->get('remember-me')->getValue()
// VS
if ($value = $this->cookies->get('remember-me')->getValue())
    echo $value;

谢谢!

EN

回答 1

Stack Overflow用户

发布于 2014-09-19 13:39:23

我对这个问题的解释是:

我不喜欢写像这样的东西

代码语言:javascript
复制
if ($value = $redis->get('key'))
    echo $value;

这使得代码不清楚。

此外,为什么检查变量是否存在如此重要?,因为它简化了控制流.

让我们考虑一下,您正在从服务中获取一些数据,以便在页面上呈现它。您可以使用多个if编写低质量的代码,但也可以尝试如下所示:

offerServiceImpl.php

代码语言:javascript
复制
class offerServiceImpl implements offerService {

    //... (some methods)

    /**
     * @param int $offerId
     * @return Offer
     * @throws InvalidArgumentException
     * @throws RuntimeException
     */
    public function getOffer($offerId)
    {
        if (!$offerId || !is_numeric($offerId)) {
            throw new InvalidArgumentException("Invalid offer id: " . $offerId);
        }

        $offer = $this->offerDao->get($offerId);

        if (!$offer) {
            //could be your own exception class
            throw new RuntimeException("Could not found offer " . $offerId);
        } else {
            return $offer;
        }
    }

}

offersControler.php

代码语言:javascript
复制
class offersController extends AbstractController{


    public function index($id){

        //... some code
        try{
            $offer = $this->offerService->getOffer($id);
        } catch (InvalidArgumentException $ex) {
            //log error, perform redirect to error 500
        } catch (RuntimeException $ex){
            //log another error, perform redirect to error 404
        } catch (Exception $ex){
            //log error, perform redirect to error 500
        }
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25934473

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档