Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Returning False VS echoing out an error

I'm trying to understand the main difference between returning false from a statement as oppose to echoing out an error promoting the user to correct their submission.

Lets take the following function that is used to get the Google Currency Convert API URL and parse in another 3 parameters, $amount, $from, $to. I use explode to obtain the numeric values returned within "" by the API.

function currency_convert($googleCurrencyApi, $amount, $from, $to) {

    $result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
    $expl = explode('"', $result);

    if ($expl[1] == '' || $expl[3] == '') {
        return false;
    } else {
        return array(
            $expl[1],
            $expl[3]
        );
    }
}

What is the advantage of returning false if the statement is true compared to echoing out a a constructive message? I see return false regularly used on many forums etc.

Thanks in advance.

like image 523
keenProgrammer Avatar asked Feb 21 '23 13:02

keenProgrammer


1 Answers

Neither, we're in 2012, throw an Exception and handle it in any way you want.

function currency_convert($googleCurrencyApi, $amount, $from, $to) {

    $result = file_get_contents($googleCurrencyApi . $amount . $from . '=?' . $to);
    $expl = explode('"', $result);

    if ($expl[1] == '' || $expl[3] == '') {
        throw new Exception('An error has occured. Describe the error here');
    }
    return array(
        $expl[1],
        $expl[3]
    );
}

Than, when you call the function:

try { currency_convert($googleApi, $amount, $from, $to) }
catch (Exception $e) { /* Do whatever you want with $e */ }

Read about Exceptions and the try, catch block here

Advantages

  • If unhandled, will halt the script, quickly pinpointing where the problem is.
  • If handled, it can easily by treated as if a return false happened.
  • Exception halts the function, meaning the return statement will never arrive.
  • An Exception can display a constructive message to the user, and it can be helpful for developers to see what the error was.
  • Exceptions are Objects whose Classes can be extended, so you can effectively create multiple types of errors and exceptions such as but not limited to: IllegalArgumentException, MathException, FileReadException, ReallyAwesomeException, and then handle each differently

    try { /* Code Here */ }
    catch (IllegalArgumentException $e) { echo 'Illegal Argument!'; }
    catch (Exception $e) { echo 'General Error! '. $e->getMessage(); }
    
like image 121
Madara's Ghost Avatar answered Mar 06 '23 03:03

Madara's Ghost