Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How many variable checks should you do? [closed]

Tags:

variables

php

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?

like image 839
Pattle Avatar asked Oct 04 '22 14:10

Pattle


1 Answers

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.

like image 171
fsw Avatar answered Oct 12 '22 07:10

fsw