Standardized return values ​​are a good or bad idea.

I work in PHP (but in this case I think the programming language does not matter), and in my class methods I usually come across the following situations:

  • The method should return true or false
  • The method should return true or an error message
  • The method should return a True + error message or a ++ error message
  • The method should return true + success results (object, array, whatever) or false
  • The method should return true + success results (object, array, whatever) or false message + message
  • and etc.

My problem is that when I use the methods of this class in my code somewhere, I always need to go back to the class and check what the method returns: just true or false, true or an error message, etc.

Is it good to standardize return values? If so, how?

My idea:

  • If the function should return true or false, then just return true or false
  • if the function should return true or an error message, then:

    if (success)
    {
        return array(
            TRUE,
            null
        );
    }
    else
    {
        return array(
            FALSE,
            $error_message
        );      
    }
    
  • if the function should return an error message + successful message or error message:

    if (success)
    {
        return array(
            TRUE,
            $success_message,
        );
    }
    else
    {
        return array(
            FALSE,
            $error_message
        );      
    }
    
  • and etc.

I hope you guys understand my problem, even thought that my explanation is not so good :) What are your suggestions or recommendations? How should I do it?

UPDATE: Take a simple example:

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

, : return true throw exception, try catch. , somethong ( ..), .

+5
7

, - .

. , . , false . . , , . , .

PHP false: trigger_error. , , . , , .

, , -, .

, , true false:

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;
}

:

, . , , - , . , fetch-from-database ; , , . .

+6

, , . .

:

  • .

, , , .

, .

. :

if (!$something)
{
    return FALSE;
}

//do some other stuff
return 'great, it worked';

. .

, Messenger, , .

function login($username, $password) 
{
    // Login logic here ..
    if ($logged_in) 
    {
        $this->messenger->addMessage('success', 'You are loggend in.');
        return TRUE;
    }
    {
        $this->messenger->addMessage('error', $message);
        return FALSE;
    }
}
+4

( , #) Do/TryDo.

/**
 * @param  MyInput $input
 * @return MyOutput
 * @throws MyException
 */
function myOperation(MyInput $input) 
{

}

myOperation (MyException ), . (MyOutput ).

/**
 * @param  MyInput  $input
 * @param  MyOutput $output
 * @return bool
 */
function tryMyOperation(MyInput $input, &$output = null) 
{

}

tryMyOperation , . ( ). ($output ), . try* try*.

:

/**
 * @param  string $input
 * @return string
 * @throws TypeException
 */
function stringToUpper($input) 
{
    if (!is_string($input)) 
    {
        throw new TypeException('String expected');
    }
    return strtoupper($input);
}

/**
 * @param  string $input
 * @param  string $output
 * @return boolean
 */
function tryStringToUpper($input, &$output) 
{
    try 
    {
        $output = stringToUpper($input);
        return true;
    } 
    catch (TypeException $exception) 
    {
        $output = null;
        return false;
    }
}

:

try 
{
    $output = stringToUpper($input);
    // use $output
} 
catch (TypeException $exception) 
{
    // recover
}

if (tryStringToUpper($input, &$output)) 
{
    // use $output
} 
else 
{
    // recover
}

, . , myOperation() catch . , - , - , tryMyOperation().

+3

. . , , :

canWriteFile() { return true or false }
writeFile() { should return void }

writeFile() , , , . , .

bool, - , , .

3 :

1) /

$error = "";
function foo() {
  if($somethingBad) $error = "error occured";
  return !$somethingBad;
}

2)

function handleError($message) {
  ...
}

function foo() {
  if($somethingBad) handleError("error occured");
  return !$somethingBad;
}

3) , , (.. )

function foo() {
  try {
    // dangerous code here
  }
  catch($e) {
    // handle error here
  }
  return !$somethingBad
}
+1

Try

Exceptions, . -, : .

-, : , , , .

, . , .

, . , , , , .

: ? , , , . , ( ), .

+1

, -, : false.
.

-1

, . REST API, , API, . , :

  • /, .
  • OK - 1, " " - 0, .
  • 0.
  • , , .
  • .
  • 2 OK($errorCode) FAIL($errorCode), if s

class Error {

    const OK = 1;
    //general error
    const FAIL = 0;
    //invalid url
    const RequestParseError = -1;
    //resource not found
    const ResourceNotFound = -2;

    ....

    static public function _($errCode) {

        switch ($errCode) {

            case Error::OK:
                return "OK";

            case Error::FAIL:
                return "General Failure";

            case Error::RequestParseError:
                return "Request Parse Error";

        .....
    }

}

in this way, each level of the application can return an error code and it will bubble up as much as you want. and the OK () and FAIL () functions are compatible with logical return functions.

-2
source

All Articles