Programming logic best practice - redundant checks
Posted
by
eldblz
on Stack Overflow
See other posts from Stack Overflow
or by eldblz
Published on 2012-12-18T15:26:07Z
Indexed on
2012/12/18
17:03 UTC
Read the original article
Hit count: 184
I'm creating a large PHP project and I've a trivial doubt about how to proceed.
Assume we got a class books
, in this class I've the method ReturnInfo
:
function ReturnInfo($id) {
if( is_numeric($id) ) {
$query = "SELECT * FROM books WHERE id='" . $id . "' LIMIT 1;";
if( $row = $this->DBDrive->ExecuteQuery($query, $FetchResults=TRUE) ) {
return $row;
} else {
return FALSE;
}
} else {
throw new Exception('Books - ReturnInfo - id not valid.');
}
}
Then i have another method PrintInfo
function PrintInfo($id) {
print_r( $this->ReturnInfo($id) );
}
Obviously the code sample are just for example and not actual production code.
In the second method should I check (again) if id is numeric ? Or can I skip it because is already taken care in the first method and if it's not an exception will be thrown?
Till now I always wrote code with redundant checks (no matter if already checked elsewhere i'll check it also here)
Is there a best practice? Is just common sense?
Thank you in advance for your kind replies.
© Stack Overflow or respective owner