473,490 Members | 2,487 Online
Bytes | Software Development & Data Engineering Community
Create Post

Home Posts Topics Members FAQ

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
Nov 22 '05 #1
9 5182

Thomas Mlynarczyk wrote:
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


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

Nov 22 '05 #2
Thomas Mlynarczyk wrote:
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


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("theresult" => false);
// or return array("theresult" => 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
Nov 22 '05 #3
Also sprach Erwin Moller:
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?
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?
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.


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

Thanks to both of you!

Greetings,
Thomas


Nov 22 '05 #4
"Thomas Mlynarczyk" <bl*************@hotmail.com> wrote:
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?

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_handler(/*.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_handler( "my_error_handler" );
/*.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

Nov 22 '05 #5
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:
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

Nov 22 '05 #6
Also sprach Umberto Salsi:
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.
That sounds plausible indeed.
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


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
Nov 22 '05 #7
Also sprach Dikkie Dik:
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.
In that case, yes.
It COULD also be that you want your function to return a default (a
NULL object).


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
Nov 22 '05 #8
"Thomas Mlynarczyk" <bl*************@hotmail.com> wrote:
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.


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

Nov 22 '05 #9
From: "Thomas Mlynarczyk" <bl*************@hotmail.com>
Newsgroups: comp.lang.php
Sent: Monday, November 21, 2005 11:31 AM
Subject: Re: Returning NULL vs. returning FALSE

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.)


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.
Nov 22 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
2042
by: kelvSYC | last post by:
What is the best way to create functions that, based on some input, return either structures or a null value if the structure cannot be made? The problem is that the structure has be created...
7
7623
by: Bill Reed via AccessMonster.com | last post by:
I have a field called "Wiring" in a query which is boolean. If I place "True Or False" in the criteria for the field, I get all records (there are no nulls in the recordset). Likewise if I place...
13
4764
by: Jordan Tiona | last post by:
Is this not allowed in C++? I try in MSVC, but I always get an error, and the function no longer shows up in my class view.
3
6930
by: Thirsty Traveler | last post by:
I have a gridview where the datasource is bound after a selection. The result of doing this is that sorting and paging do not work. I was given a sample of how to resolve this, however my attempt...
1
1582
by: macupryk | last post by:
Returns nothing? private DataSet DoQuery() { DataSet ds = null; SqlConnectionStringRG_Study = ConfigService.Instance.GetString("RG10_Study"); try...
8
13919
by: Martin Z | last post by:
INSERT INTO dbo.Transmission (TransmissionDate, TransmissionDirection, Filename, TransmittedData) VALUES (@TransmissionDate,@TransmissionDirection,@Filename,@TransmittedData); SELECT @retVal =...
11
1966
by: =?Utf-8?B?UGF1bA==?= | last post by:
Hi I have the method below that returns a bool, true or false depending on if the conversion to date tiem works. It takes a string input. I am only returning the bool but would also like to...
1
2856
by: bsprogs | last post by:
I am currnetly programming a file hosting website in PHP and I am slowly integrating AJAX into the website. Here is my problem: The user uploads the file. The server processes the file and...
4
1542
by: rbjorkquist | last post by:
This is my first attempt at writing/using web services, so any and all comments will be greatly appreciated. With that said, I am also by no means saying this is the correct either. I have...
0
7112
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
6974
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
7146
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
1
6852
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
7356
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
1
4878
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...
0
4573
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and...
0
1389
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated ...
1
628
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.