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


Should I check if array/collection value exists before trying to get it?

我应该检查一个键是否存在,然后获取它,还是只获取它(当我需要获取它时,不检查它是否已设置)?

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

示例:

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

if ($redis->exists('key'))
    echo $redis->get('key');
// VS
if ($value = $redis->get('key'))
    echo $value;

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

if ($this->cookies->has('remember-me'))
    echo $this->cookies->get('remember-me')->getValue()
// VS
if ($value = $this->cookies->get('remember-me')->getValue())
    echo $value;

谢谢!

我对这个问题的解释是:

我不喜欢写类似的东西

if ($value = $redis->get('key'))
    echo $value;

这使得代码变得不清晰。

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

让我们考虑一下,您正在从服务中获取一些数据,以便将其呈现在页面上。你可以用多个if编写低质量的代码,但你也可以尝试这样的东西:

offerServiceImpl.php

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;
        }
    }
}

offersController.php

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
        }
    }
}