Something I've never been sure about is how many variable checks to do in PHP. For example take the following piece of code. I am not checking any of the variables before I assign them or pass them to a function to see if they contain what I expect
$carId = '12';
$aCar = fetchCar($carId);
$make = $aCar['make'];
$model = $aCar['model'];
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
Now if I add some checks
$carId = '12';
if(is_numeric($carId))
{
$aCar = fetchCar($carId);
if(isset($aCar['make']) && is_string($aCar['make']))
{
$make = $aCar['make'];
}
else
{
//Report error
}
if(isset($aCar['model']) && is_string($aCar['model']))
{
$model = $aCar['model'];
}
else
{
//Report error
}
if(isset($aCar['year']) && is_numeric($aCar['year']))
{
$yearMade = $aCar['year'];
$age = calcAge($yearMade);
}
else
{
//Report error
}
}
else
{
//Report errors
}
The code is now better but is it a bit too excessive and bloated? Should I be doing this many checks?
If I shouldn't be doing this many checks where do you draw the line between what you should and shouldn't check?
This is the dilemma of a dynamic type language. It depends heavily on what fetchCar() function is doing.
The approach i would take is assume fetchCar is returning a car array or throwing exception. If you combine this with good exception handling logic you can end up with clean and stable code.
For example:
function fetchCar($id) {
$car = queryDatabaseSomehow();
if (empty($car)) {
throw new ExceptionNotFound();
}
//eventually you can put your type checking here?
if (!isset($car['x']) || !is_string($car['x'])) {
throw new ExceptionDb();
}
}
echo fetchCar(3)['make'];
Also if you would like to do this super-proper and go fully OOP, Car should become a class with make,model and year as its members. fetchCar() would return Car or throw Exception. But this is not always desirable of course.
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