How should I handle the input validation of a method?
Of these two, which one is the more correct way? or there is a better way
This method is called by the constructor and $prodID can be user input or come from the db.
private function fill_data1($prodID)
{
//Way 1
filter_var($prodID, FILTER_VALIDATE_INT, array('options'=>array('min_range'=>1, 'max_range'=>1000000)));
if (is_null($prodID)) {
return FALSE;
} elseif ($prodID === FALSE) {
return FALSE;
}
$prod = getArtData($prodID);
$this->set_id($prod['artID']);
$this->set_name($prod['artName']);
$this->set_price($prod['precio']);
}
private function fill_data(2$prodID)
{
//Way 2
filter_var($prodID, FILTER_VALIDATE_INT, array('options'=>array('min_range'=>1, 'max_range'=>1000000)));
if (is_null($prodID) || $prodID === FALSE)
{
die('invalid input for prodID (' . $prodID . '). It has to be an integer > 0');
}
$prod = getArtData($prodID);
$this->set_id($prod['artID']);
$this->set_name($prod['artName']);
$this->set_price($prod['precio']);
}
Option 3: Use exceptions and put the ID validation as close to the data as possible.
The problem with returning
falseis that you must check for the return value to handle and skip it. If where you handle it (the presentation layer) is several function calls removed from where it’s validated (the data layer), you have to check forfalseat each level. An exception will propagate up to the first function that catches it, bypassing the remaining code in each function along the way.Calling
die()causes its own difficulties. It is harder to unit test and it forces you to put the error-display code at the point of failure. What happens when you want to use your code from a web-service?