When returning values in php, is it considered good or bad practice to return mixed data types. I'm working on a project where I am constantly faced with methods that return an id number or null
. I'm handling the null
value by checking for null
and returning -1
if it is null
.
Another situation I find myself in a lot is where a method should do something and return a string. But sometimes it's not possible to return the string as it wasn't found or an exception happened. What's the best thing to do here? Return a string like 'failed' or something? This then creates a string coupling between methods, I think, as the calling method has to know exactly the string failure message to check for??
EDIT: OK there are a few different opinions already. I like the idea of returning false on failure and the actual result whatever its data type is on success. But... is there a defacto best practice when it comes to this? I mean, what do programmers in other languages do i.e. java and c++ etc in these situations?
What I usually do is if the method worked, return the value, and if it failed return FALSE. That's what a lot of PHP's built-in methods do. So, then you can just check if the function returned FALSE or not.
Returning mixed type is bad, at least today in 2013. Boom! The way to go is to split this:
BAD, mixed return type style:
function checkResult($data)
{
if ($data) {
...
return $stuff;
} else {
return false;
}
}
People will need additional logic to work checkRsult(), and they never know exactly what type will return.
GOOD, clearly fixed return type style:
Maybe the example is not really good, but it shows the way to go.
function doesResultExist($data)
{
if ($data) {
return true;
}
// default return
return false;
}
function getResultData()
{
...
return $stuff;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With