php - How many variable checks should you do? -


something i've never been sure how many variable checks in php. example take following piece of code. not checking of variables before assign them or pass them function see if contain expect

$carid = '12'; $acar = fetchcar($carid);  $make = $acar['make']; $model = $acar['model']; $yearmade = $acar['year']; $age = calcage($yearmade); 

now if add 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 better bit excessive , bloated? should doing many checks?

if shouldn't doing many checks draw line between should , shouldn't check?

this dilemma of dynamic type language. depends heavily on fetchcar() function doing.

the approach take assume fetchcar returning car array or throwing exception. if combine exception handling logic can end clean , stable code.

for example:

function fetchcar($id) {      $car = querydatabasesomehow();     if (empty($car)) {         throw new exceptionnotfound();     }     //eventually can put type checking here?     if (!isset($car['x']) || !is_string($car['x'])) {         throw new exceptiondb();     } }  echo fetchcar(3)['make']; 

also if super-proper , go oop, car should become class make,model , year members. fetchcar() return car or throw exception. not desirable of course.


Comments