Returning NULL vs. returning FALSE

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Thomas Mlynarczyk

    Returning NULL vs. returning FALSE

    Hi,

    It seems to be a generally adopted convention to have a function return
    FALSE in case of an error. But if a function is supposed to return a boolean
    anyway, one cannot distinguish anymore between the "normal" FALSE and the
    "error" FALSE. So why not using NULL instead to indicate an error? Are there
    drawbacks I am not aware of?

    Greetings,
    Thomas


  • chotiwallah

    #2
    Re: Returning NULL vs. returning FALSE


    Thomas Mlynarczyk wrote:[color=blue]
    > Hi,
    >
    > It seems to be a generally adopted convention to have a function return
    > FALSE in case of an error. But if a function is supposed to return a boolean
    > anyway, one cannot distinguish anymore between the "normal" FALSE and the
    > "error" FALSE. So why not using NULL instead to indicate an error? Are there
    > drawbacks I am not aware of?
    >
    > Greetings,
    > Thomas[/color]

    But if a function is supposed to return a value that might be NULL one
    cannot distinguish anymore between the "normal" NULL and the "error"
    NULL.

    just turns around the issue.

    micha

    Comment

    • Erwin Moller

      #3
      Re: Returning NULL vs. returning FALSE

      Thomas Mlynarczyk wrote:
      [color=blue]
      > Hi,
      >
      > It seems to be a generally adopted convention to have a function return
      > FALSE in case of an error. But if a function is supposed to return a
      > boolean anyway, one cannot distinguish anymore between the "normal" FALSE
      > and the "error" FALSE. So why not using NULL instead to indicate an error?
      > Are there drawbacks I am not aware of?
      >
      > Greetings,
      > Thomas[/color]

      As Micha wote: Now you cannot distinguish between an 'error NULL' and 'real
      NULL'.

      And what about a function that could return NULL and false, both as usefull
      values?

      So if you find yourself in such a situation, be creative.
      eg: always return your value in an array (only one element big if needed),
      OR let it return false.

      function myFunc($bla){
      // do stuff
      if (succeeded){
      return array("theresul t" => false);
      // or return array("theresul t" => array(1,4,78));
      // or whatever your function produces
      } else {
      return false; // or NULL, or whatever suits your needs
      }
      }

      In that way you can just check the returnvalue for being an array, and know
      you have a real result (as found in "result")

      That is how I solved that problem once. Maybe not very elaborated, but it
      does the trick.

      Regards,
      Erwin Moller

      Comment

      • Thomas Mlynarczyk

        #4
        Re: Returning NULL vs. returning FALSE

        Also sprach Erwin Moller:
        [color=blue]
        > As Micha wote: Now you cannot distinguish between an 'error NULL' and
        > 'real NULL'.[/color]
        [color=blue]
        > And what about a function that could return NULL and false, both as
        > usefull values?[/color]

        In that case, I suppose, I would really have a problem. Still, it seems to
        me that the case where a function could "legally" return NULL is much rarer
        than that of a function returning a boolean. On the other hand, I just
        realized, if a function would not normally return anything, then booleans
        are "required" to indicate failure (FALSE) or success (TRUE). So that might
        have been a reason, too, for choosing FALSE to indicate an error, I suppose.

        But apart from such considerations - there is thus no technical drawback to
        using NULL instead of FALSE to indicate an error?
        [color=blue]
        > So if you find yourself in such a situation, be creative.
        > eg: always return your value in an array (only one element big if
        > needed), OR let it return false.[/color]

        Indeed, a creative proposal. I will keep this in mind.

        Thanks to both of you!

        Greetings,
        Thomas




        Comment

        • Umberto Salsi

          #5
          Re: Returning NULL vs. returning FALSE

          "Thomas Mlynarczyk" <blue_elephant5 5@hotmail.com> wrote:
          [color=blue]
          > It seems to be a generally adopted convention to have a function return
          > FALSE in case of an error. But if a function is supposed to return a boolean
          > anyway, one cannot distinguish anymore between the "normal" FALSE and the
          > "error" FALSE. So why not using NULL instead to indicate an error? Are there
          > drawbacks I am not aware of?[/color]


          IMHO, the FALSE value as an error indicator is a practice that date
          from the PHP 3 era, when the NULL value was not available. Today, with
          PHP 4 and 5, new software (either new PHP extensions and PHP scripts)
          might certainly adopt the NULL value in place of FALSE.

          But instead to encode the error inside the returned value, there are
          better solutions:

          * using PHP 5 exceptions;

          * writing your error handling function that sets a global flag on error,
          something like this:


          /*. require_module 'standard'; .*/

          $err = FALSE;
          $err_msg = "";

          function my_error_handle r(/*.int.*/ $type, /*.string.*/ $msg)
          {
          $GLOBALS["err"] = TRUE;
          $GLOBALS["err_msg"] = $msg;
          if( error_reporting () == 0 )
          # inside "@..." - do not report the err
          return;
          error_log( date("m-d,H:i:s ") . $msg );
          }


          set_error_handl er( "my_error_handl er" );


          /*.bool.*/ function got_err()
          # An error occurred?
          {
          if( $GLOBALS["err"] ){
          $GLOBALS["err"] = FALSE; # reset err flag
          return TRUE;
          } else {
          return FALSE;
          }
          }




          /*.float.*/ function div(/*.int.*/ $a, /*.int.*/ $b)
          {
          $GLOBALS["err"] = FALSE;
          if( $b == 0 ){
          trigger_error(_ _FUNCTION__."() : division by zero");
          return 0.0;
          }
          return $a/$b;
          }


          # Unhandled error - will be logged:
          $x = div(3, 0);

          # Handled error - not logged:
          $y = @div(3, 0);
          if( got_err() )
          echo "ERROR: ", $err_msg;

          $f = @fopen("do-not-exists", "r");
          if( got_err() )
          echo "Sorry, can't open the file: ", $err_msg;
          else
          do that and that with $f


          Regards,
          ___
          /_|_\ Umberto Salsi
          \/_\/ www.icosaedro.it

          Comment

          • Dikkie Dik

            #6
            Re: Returning NULL vs. returning FALSE

            What do you WANT your function to return? If (presuming PHP5 here) there
            is a real error and the function cannot reasoable be expected to return
            anything, throw an exception.

            An exception communicates: "This is not my responsibility" . It is the
            same situation like in a company, an employee hands back a task to his
            boss, saying "I cannot do this in the current situation".
            It is now the calling code that can take action (with a catch block) or
            step aside and let the exception pass to its calling code.
            If I would have to find a better name for an exception,I would have
            called it an "objection" . Like in the american court-of-law TV series.
            If someone raises an objection, the judge (the calling code) decides:
            forget the question, ask the question differently, ask it to someone
            else, or retry and ask again.

            It COULD also be that you want your function to return a default (a NULL
            object). Suppose you write an application involving customer objects.
            You have some function (method of a collection class) that takes the
            customer number and returns the customer with that number from the
            database. Now a new customer uses the application and no customer number
            is given. You could have your lookup function return a new blank
            customer object.

            Look at what the requesting code does after it receives the FALSE or
            NULL value. If it always creates some new, blank structure, have it
            returned by the lookup function.

            Best regards.

            Thomas Mlynarczyk wrote:[color=blue]
            > Hi,
            >
            > It seems to be a generally adopted convention to have a function return
            > FALSE in case of an error. But if a function is supposed to return a boolean
            > anyway, one cannot distinguish anymore between the "normal" FALSE and the
            > "error" FALSE. So why not using NULL instead to indicate an error? Are there
            > drawbacks I am not aware of?
            >
            > Greetings,
            > Thomas
            >
            >[/color]

            Comment

            • Thomas Mlynarczyk

              #7
              Re: Returning NULL vs. returning FALSE

              Also sprach Umberto Salsi:
              [color=blue]
              > IMHO, the FALSE value as an error indicator is a practice that date
              > from the PHP 3 era, when the NULL value was not available.[/color]

              That sounds plausible indeed.
              [color=blue]
              > But instead to encode the error inside the returned value, there are
              > better solutions:
              > * using PHP 5 exceptions;
              > * writing your error handling function that sets a global flag[/color]

              It depends on the error. If the script does not depend upon a successful
              completion of a particular function, then it would be simpler to just return
              an indicating value.

              Greetings,
              Thomas


              Comment

              • Thomas Mlynarczyk

                #8
                Re: Returning NULL vs. returning FALSE

                Also sprach Dikkie Dik:
                [color=blue]
                > What do you WANT your function to return? If (presuming PHP5 here)
                > there is a real error and the function cannot reasoable be expected
                > to return anything, throw an exception.[/color]

                In that case, yes.
                [color=blue]
                > It COULD also be that you want your function to return a default (a
                > NULL object).[/color]

                In that case the function would always return a valid result, hence no need
                for a special return value indicating an error. In other words: the function
                would fix the error by itself.

                What I'm looking for is the best suited general return value for cases where
                an operation could not be successfully completed as expected and the
                function is not able to fix the error by itself and the error is of a nature
                where "drastic measures" like throwing an error or an exception would be
                inappropriate.

                Greetings,
                Thomas


                Comment

                • Umberto Salsi

                  #9
                  Re: Returning NULL vs. returning FALSE

                  "Thomas Mlynarczyk" <blue_elephant5 5@hotmail.com> wrote:
                  [color=blue]
                  > What I'm looking for is the best suited general return value for cases where
                  > an operation could not be successfully completed as expected and the
                  > function is not able to fix the error by itself and the error is of a nature
                  > where "drastic measures" like throwing an error or an exception would be
                  > inappropriate.[/color]

                  You might return the handle to an object created specifically to indicate
                  the error condition:

                  class Err
                  {
                  static $raised = NULL;

                  function __construct()
                  {
                  self::$raised = $this;
                  }
                  }

                  new Err();


                  function myfunc($n)
                  {
                  if( invalid $n )
                  return Err::$raised;
                  else
                  return something;
                  }

                  $res = myfunc(123);
                  if( $res === Err::$raised )
                  echo "Error!";

                  The value Err::$raised cannot be confused with any other value a function
                  may return.

                  Regards,
                  ___
                  /_|_\ Umberto Salsi
                  \/_\/ www.icosaedro.it

                  Comment

                  • Dana Cartwright

                    #10
                    Re: Returning NULL vs. returning FALSE

                    From: "Thomas Mlynarczyk" <blue_elephant5 5@hotmail.com>
                    Newsgroups: comp.lang.php
                    Sent: Monday, November 21, 2005 11:31 AM
                    Subject: Re: Returning NULL vs. returning FALSE

                    [color=blue]
                    > Yes, but I meant a situation where an "error" can be handled easily by the
                    > calling function, like "Call function to get some data from a file, but if
                    > the specified file doesn't exist (function returns error), use some
                    > default
                    > instead." (The case of a function returning a default value was mentioned
                    > earlier in this thread, but assuming the function can be called for
                    > reading
                    > files in different contexts, each requiring its own "default values", then
                    > the function cannot return a default value as it doesn't know from which
                    > context it is called.)
                    >[/color]

                    Well, in that case, why don't you pass a suitable default value as a
                    parameter to the function? Then it either returns a good value, or it
                    returns the default that you've supplied to it. You can then of course
                    supply different defaults in different contexts.

                    Done right, you might not ever have to test the result of the function, as
                    it *always* returns something that you can use.


                    Comment

                    Working...