patternphpMinor
Is the way I use my pattern good enough?
Viewed 0 times
thewaygooduseenoughpattern
Problem
For quite a long, I have been using a pattern to make my life a bit easier. please help me evaluate how good or bad my approach is and how can I improve it.
I have a static class for just returning values:
usage example:
To get the returned value:
I have a static class for just returning values:
class ReturnValue {
const STATUS_SUCCESS = "SUCCESS";
const STATUS_FAIL = "FAILED";
public static function doReturn($funtionName, $status = NULL, $value = NULL, $message = NULL) {
if ($status == NULL) {
$status = self::STATUS_FAIL;
}
$return = array(
action => $funtionName,
status => $status,
message => $message,
returnValue => $value
);
return (object) $return;
}
}usage example:
function add($val, $val2) {
if (empty($val)) {
return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val must be a number');
}
if (empty($val2)) {
return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_FAIL, '', 'Val2 must be a number');
}
$sum = $val + $val2;
return ReturnValue::doReturn(__FUNCTION__, ReturnValue::STATUS_SUCCESS, $sum, "$val + $val2 = $sum");
}To get the returned value:
$add = add(1, 2);
print $add->returnValue; // Gives 1 + 2 = 3
print $add->message; // Gives "Val2 must be a number"
print $add->status; // FAILED
//OR to make an error
$add = add(1, ''); // an empty param is passed
print $add->returnValue;//Gives 3
print $add->message; // Gives "1 + 2 = 3"
print $add->status; // SUCCESSSolution
I would prefer:
The exception can then be caught at a level where you know how to deal with it.
Usage:
The calls to
function add($left, $right) {
if (!(isset($left, $right) && is_numeric($left) && is_numeric($right)))
{
throw new InvalidArgumentException(
__METHOD__ . ' Left and Right arguments must be numeric.');
}
return $left + $right;
}The exception can then be caught at a level where you know how to deal with it.
Usage:
try
{
print add(1, 2) . "\n";
print add(1, '') . "\n";
}
catch (Exception $e)
{
echo $e->getMessage();
}The calls to
add are not mixed in with custom error handling, making it easier for other people to understand your code. It also removes the dependency on your ReturnValue class which makes your code more reusable. The exception allows you to let the code get back to an appropriate level where you can deal with your problem, rather than passing this information back up stack levels.Code Snippets
function add($left, $right) {
if (!(isset($left, $right) && is_numeric($left) && is_numeric($right)))
{
throw new InvalidArgumentException(
__METHOD__ . ' Left and Right arguments must be numeric.');
}
return $left + $right;
}try
{
print add(1, 2) . "\n";
print add(1, '') . "\n";
}
catch (Exception $e)
{
echo $e->getMessage();
}Context
StackExchange Code Review Q#8391, answer score: 2
Revisions (0)
No revisions yet.