gpt4 book ai didi

php - 标准化的返回值——这是好主意还是坏主意

转载 作者:可可西里 更新时间:2023-11-01 13:11:26 24 4
gpt4 key购买 nike

我在 PHP 中工作(但在这种情况下我认为编程语言并不重要),在我的类方法中我通常会遇到以下情况:

  1. 方法必须返回truefalse
  2. 方法必须返回true错误信息
  3. 方法必须返回 true + 成功消息false + 错误消息
  4. 方法必须返回 true + 成功结果(对象、数组等)false
  5. 方法必须返回 true + 成功结果(对象、数组等)false + 错误消息
  6. 等等

我的问题是,当我在我的代码中的某处使用此类方法时,我总是必须回到类中,并检查实际返回的方法是什么:简单地 true falsetrue错误信息

标准化返回值是个好主意吗?如果是,如何?

我的想法是:

  1. 如果函数必须返回 truefalse 则只需返回 truefalse
  2. 如果函数必须返回true错误消息 那么:

    if (success)
    {
    return array(
    TRUE,
    null
    );
    }
    else
    {
    return array(
    FALSE,
    $error_message
    );
    }
  3. 如果函数必须返回 true + 成功消息错误消息 那么:

    if (success)
    {
    return array(
    TRUE,
    $success_message,
    );
    }
    else
    {
    return array(
    FALSE,
    $error_message
    );
    }
  4. 等等

我希望你们理解我的问题,即使我的解释不太好:)您有什么建议或最佳做法?我该如何处理?

更新:让我们举一个简单的例子:

function login($username, $password) 
{
// Login logic here ..
if ($logged_in)
{
return TRUE;
}
{
return $error_message;
}
}

所以正确的做法是:返回true,或者抛出异常,并且在调用登录方法时使用try catch。因此,当出现问题(验证失败等)时,我应该使用异常。

最佳答案

我会说返回 bool 值 其他东西的前提是错误的。

功能应该有明确的目的和明确的结果。如果可以达到这个结果,则返回结果。如果无法实现结果,则函数返回 false 或抛出异常。哪个更好取决于具体情况和您的一般错误处理理念。无论哪种方式,让函数返回错误消息通常都没有用。该消息对调用该函数的代码没有用。

PHP 除了返回false 结果外,还有自己的输出错误信息的机制:trigger_error。虽然它纯粹是一个帮助调试的工具,但它并没有取代标准的返回值。它非常适合您希望显示错误消息纯粹是为了帮助开发人员的情况。

如果一个函数足够复杂,可能会导致需要以不同方式处理的几种不同类型的错误,那么您应该使用异常来做到这一点。

例如,一个非常简单的函数,目的明确,只需要返回truefalse:

function isUserLoggedIn() {
return $this->user == 'logged in';
}

具有可能无法实现该目的的功能:

function convertToFoo($bar) {
if (!is_int($bar)) {
return false;
}
// here be dragons
return $foo;
}

也触发消息的相同函数,对调试很有用:

function convertToFoo($bar) {
if (!is_int($bar)) {
trigger_error('$bar must be an int', E_USER_WARNING);
return false;
}
// here be dragons
return $foo;
}

一个函数可能会合法地遇到调用代码需要知道的几种不同类型的错误:

function httpRequest($url) {
...

if (/* could not connect */) {
throw new CouldNotConnectException('Response code: ' . $code);
}

...

if (/* 404 */) {
throw new PageNotFoundException('Page not found for ' . $url);
}

return true;
}

我也会在这里粘贴这条评论:

It should not be the responsibility of the function to prepare, return or display an end-user error message. If the purpose of the function is to, say, fetch something from the database, then displaying error messages is none of its business. The code that called the fetch-from-database function merely needs to be informed of the result; from here there needs to be code whose sole job it is to display an error message in case the database function cannot get the required information. Don't mix those two responsibilities.

关于php - 标准化的返回值——这是好主意还是坏主意,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9580112/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com