【问题标题】:Which of these line of code is "better,” and why?哪一行代码“更好”,为什么?
【发布时间】:2020-01-07 05:16:07
【问题描述】:

第一:

 protected function isValid($orderIds)
 {
     ......

     $orderCount = Some Calculation... ; 

     return ( $orderCount == count($orderIds) );
 }

第二:

 protected function isValid($orderIds)
 {
     ......

     $orderCount = Some Calculation... ; 

     return ( $orderCount == count($orderIds) ) ? 1 : 0;
 }

我就是这样使用这个功能的

......

$isValid = $this->isValid($orderIds);
if($isValid) {
   // do some thing here
}

请看上面写的代码。如果我选择第一个功能而不是第二个功能,有什么问题吗?

【问题讨论】:

  • 不知道为什么人们不赞成我的问题
  • 我删除了无效的 CakePHP 标签。一般来说:您应该专注于 SO 的 nano opt 或主观代码风格主题以外的其他事情。

标签: php


【解决方案1】:

第一种方法只会返回 boolean & 在第二种方法中,您只是增加了返回 1 or 0 的开销。如果您只需要检查该方法是否已成功完成其工作,那么我建议您使用第一种方法。

【讨论】:

  • 我可以补充一点,“isValid”当然需要一个布尔值。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-06
  • 1970-01-01
  • 2012-07-15
相关资源
最近更新 更多