你怎么看这段代码?最好只编写一个方法 getByPoint() 并向其传递另一个字符串参数 'open', 'close'?
否则包装器函数getTOpenByPoint()和getClosedByPoint()是否合理?
感谢您回答;)
/**
* Get all opened verbals, not cancelled, for a point
* @param type $point_id
* @return array
*/
public function getOpenedByPoint($point_id = null)
{
$conditions = array('Verbal.cancelled' => 0, 'Verbal.close' => 0);
return $this->getByPoint($point_id, $conditions);
}
/**
* Get all closed verbals, not cancelled, for a point
* @param type $point_id
* @return array
*/
public function getClosedByPoint($point_id = null)
{
$conditions = array('Verbal.cancelled' => 0, 'Verbal.close' => 1);
return $this->getByPoint($point_id, $conditions);
}
/**
* Get all verbals for a point
* @param type $point_id
* @return array
*/
public function getByPoint($point_id = null, $conditions = array())
{
if($point_id) {
$conditions = Hash::merge(array('Verbal.point_id' => $point_id), $conditions);
return $this->find('all', array(
'contain' => array('Driver','Car'),
'fields' => array('Verbal.number','Verbal.year','Verbal.data_out','Driver.cognome','Driver.nome','Car.model','Car.plate'),
'conditions' => $conditions,
'order' => array('Verbal.data_out' => 'ASC')
));
}
return array();
}
- 这比传入"关闭"或"打开"参数更具可读性。
- 如果 $point_id 对 getByPoint 函数很重要,为什么在所有函数中都将其默认为 null?这里的气味是,当您从getByPoint函数返回一个空数组时,您将不知道是否未找到任何结果,或者传入的$point_id无效。因此,设置检查点是一种更好的做法,这样,如果某些内容中断,您将知道它是无效point_id而不是数据库中没有结果。
如果您维护当前代码,我会将 getByPoint 的可见性更改为私有,以便您强制从控制器使用 getClosedByPoint() 或 getTOpenByPoint()。
如果我是你,我只会使用一个函数。
另一个想法是将不同的状态定义为参数,例如:
public function getByPoint($point_id = null, $open = true, $cancelled = false) {
...
}
若要提高调用 getByPoint()
方法的代码的可读性,可以定义具有不同状态的类常量。然后,方法调用将如下所示:
$this->Verbal->getByPoint(123, Verbal::OPEN, Verbal::NOT_CANCELLED);