1

这不一定只适用于 PHP,但这是我关心的领域。

我最近一直在写一些检查函数,它们得到一些参数,然后以各种方式检查它的有效性。比如, checkXmlString($xml) 将检查给定的字符串是否包含格式良好的 xml 文档等。

问题是,这些函数是否应该返回布尔值,或者抛出异常并且在成功时不返回任何内容。

所以

function checkAbc($arg) { if ($arg is invalid) return false; else return true; }

更确切地说

function checkAbc($arg) { if ($arg is invalid) throw new Exception(...); }
4

6 回答 6

0

问题是,这些函数是否应该返回布尔值,或者抛出异常并且在成功时不返回任何内容。

首先确定 If It is an exception 情况而不是使用 exception 。你的情况似乎不是例外,它只是一个条件,所以把它当作一个条件。如果它是正确的但在某些情况下失败,你可能不会识别得比您可能考虑使用异常更好。

访问这两个链接并了解有关异常的更多信息

PHP 5.3 中的异常最佳实践

PHP异常入门

于 2015-11-11T11:51:43.593 回答
0

There is generally 2 types of function regarding your question:

  • Pure function that tests whether a condition holds.

  • Function that ensures a condition holds and alters control flow if it does not.

Different programming language may have different conventions about the naming of both types. Take C++ as an example, one common naming is CHECK_XXX for type 2 and IsXXX for type 1. Here is an example taken from a tutorial of the google-log library:

CHECK(fp->Write(x) == 4) << "Write failed!";
CHECK_NE(1, 2) << ": The world must be ending!";

Another example is the maktaba utility library for Vimscript , where maktaba#value#IsXXX() is used to test whether the argument is of a certain type while maktaba#ensure#IsXXX() is used to ensure IsXXX holds and throws an exception otherwise.

function! TakeAString(name)
  " Ensure argument type is String.
  let name = maktaba#ensure#IsString(a:name)
endfunction

if maktaba#value#IsString(name)
  " Branch if name is a String.
  echo name
endif

So here is the point: choose the one that suits your need best and name the function according to the convention of the language. In terms of use cases of both, roughly, use the type 2 to check pre-condition like argument type and use the type 1 in conditional statements.

于 2018-06-14T12:25:12.503 回答
0

这当然有点基于意见,但问问你自己,对像这样的函数有什么期望checkEmail()?该方法的目的是验证某些东西,因此您可能期望得到这个问题的答案。

$isValid = checkEmail($arg);

我认为大多数开发人员期望一个 bool 作为返回值,它使代码可读。错误的值是预期的,所以如果传递了一个无效的参数,就不能说这是一个例外。要返回错误消息,我将使用 out 参数:

function checkAbc($arg, &$errorMessage)
{
  if ($arg is invalid)
  {
    $errorMessage = 'The argument is invalid because of...';
    return false;
  }
  else
  {
    $errorMessage = '';
    return true;
  }
}
于 2015-11-11T11:54:10.360 回答
0

您可以抛出InvalidArgumentException来检查参数是否不正确,但我认为对于您的情况,如果您正在编写“检查器”,它们应该返回一个布尔值,以便您知道不要继续操作,例如,如果 foobar.xml 实际上是您的 CSV 文件不想继续您的操作,但您也不想遇到异常

<?php 
class Checker {
    function validXml($string)
    {
        if(!(bool)$string) throw new \InvalidArgumentException("Cannot pass empty string as argument", 1);
        // Check
        // Is valid XML ? Return True : return false
    }
}
try {
    if(new Checker->validXml($xmlString))
    {
        // Continue Operation
        // return 
    }
    // Notify User of invalidity
    // return
} catch (\InvalidArgumentException $e) {
    // Log args 
    // 
}
于 2015-11-11T11:54:45.580 回答
0

我真的不太确定通常哪种形式更可取。

一方面,如果发生错误,您需要一条有用的消息,因此您最终会得到混合返回(true/string),这很丑陋,或者返回一个数组(甚至更丑陋)。一个例外是免费为您提供的。

另一方面,不应期望名为 check...() 的函数抛出异常,因为发现“这不是一个有效的东西”并不是什么异常,也不是错误。

第三种方法是称它为“throwIfFalse”,但这也很丑......

唔....

一种可能的解决方案:

interface Checker {
  public function check();
  public function getMessage();
}
class WhateverChecker implements Checker { ... }

class ClientOfChecker {
  public function doStuff() {
     $checker = new Checker();
     if (! $checker->check() )
        throw new Exception($checker->getMessage());
  }
}

然而,这似乎非常冗长,而且,我可以说,对我来说,Javaesque。

于 2015-11-11T11:41:30.680 回答
0

根据几乎所有关于该主题的书籍,尤其是根据逻辑,名称应该是函数功能的最大暗示。在这种情况下,只有第一个选项适用。正如 Bet Lamed 之前所说,名为“check”的函数不应该抛出异常,只是为了让您知道检查是否正常。

如果你想要例外,你可能想把它重命名为 DeserialisationToAbc() 或 TryParseAbc() 或类似的东西。

于 2015-11-11T11:48:39.027 回答