php – 方法可以返回错误或数组 – 糟糕的实现?
发布时间:2020-12-13 22:50:14 所属栏目:PHP教程 来源:网络整理
导读:我正在阅读 Code Complete并且其中有声明警告不要使用具有双重用途的变量,例如: 1) If a variable is a number,it contains error code.2) If a varibale is array,it contains data. 这正是我在我的程序中使用下面的代码片段中的变量$text进行的操作: $te
我正在阅读
Code Complete并且其中有声明警告不要使用具有双重用途的变量,例如:
1) If a variable is a number,it contains error code. 2) If a varibale is array,it contains data. 这正是我在我的程序中使用下面的代码片段中的变量$text进行的操作: $text = $editor->getTextForLinking($data_array['idText']); if (Arr::is_array($text)) { ... } else { Log::instance()->add(Log::Error,$text); $this->response->body("Text can't be retrieved"); } 我可以访问方法getTextForLinking(),因此可以更改它.如何改变以排除双重目的的不良情况? 我不想使用这样的例外: $text = Array(); try { $text = $editor->getTextForLinking($data_array['idText']); } catch(SomeException $e) { Log::instance()->add(Log::Error,$text); $this->response->body("Text can't be retrieved"); } 解决方法
我认为很清楚,如果getTextForLinking()返回的任何东西,这不是一个数组,应该被认为是一个错误(记录) – 所以我不完全相信你的例子保证这样的改变.
据说,无论你发送什么数据,保持函数的返回签名都是相同的数据类型(数组)可能是一种改进.这样它将是一致的(您不需要$text = Array();)并且您不必根据它是否出错来制作特殊情况. $results = $editor->getTextForLinking($data_array['idText']); if (empty($results)) { Log::instance()->add(Log::Error,$data_array['idText']); } else { // Handle results array } 更新 如果您在函数中设置错误消息,则违反了single responsibility principle – 函数/方法应该只有一个作业.就$editor-> getTextForLinking()而言,它将始终返回一个文本数组,而不是处理错误的返回. 错误消息应取决于上下文(使用方法的位置).如果在某个时刻空数组无效句柄/设置错误(消息)在函数之外,如上所示. 这样做允许$编辑器忽略返回结果的有效性,并允许您在其他地方重用该函数,其中空数组不被视为错误. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |