jeudi 29 janvier 2015

How can I consolidate code for checking true/false, retrieving an error message, and returning a JSON response?

Consider the class below (assume it has a simple constructor not shown here):



class Poll{

public $id = 0;
public $errorMessage = "";

public function vote($age = 0){
if($age <= 18){
// do something here
}
else{
$this->errorMessage = "You are not old enough to vote.";
return false;
}

try{
// do something here
}
catch (\Exception $e){
$this->errorMessage = "Voting failed!";
return false;
}

// do some more things here

return true;
}
}


Now consider using it like this:



// Setup an initial object we'll use in a JSON response
$response = new \stdClass;
$response->error = "";
$response->message = "";

// Let's vote
$myPoll = new Poll($input['id']);
if(!$myPoll->vote($input['age'])){
// Opps something went wrong
$response->error = "Error: ".$myPoll->errorMessage;
return json_encode($response);
}

// Voting finished, return success message
$response->message = "Voted Successfully!";
return json_encode($response);


I'm going to be doing this a lot throughout the application. I'm checking a method for true/false and then asking the object for an error message to give out in some fashion. The classes that produce errors may not necessarily be used for JSON responses, but it will be quite often. Also notice the two techniques used in the class for producing an error. How should I alter/add classes like the one shown here (or what design pattern would help here) to consolidate this approach and take more advantage of the power of OOP?


Aucun commentaire:

Enregistrer un commentaire