Lately I've been too worried about preventing code errors. However I had this doubt:
Is it better to check (prevent) or remedy (Ensure existence)?
Let's say you have:
$var = array(
'name' => 'Guilherme',
'lastName' => 'Lautert'
);
What is the ideal to check if the index exists or to ensure that it exists?
Check
if(isset($var['name'])){
# code ...
}
Ensure
$default = array(
'name' => null,
'lastName' => null,
);
$var = array(
'name' => 'Guilherme',
);
$var = array_merge($default, $var);
$lastName = $var['lastName'];
Issue
As commented you can be based on opinion, then assuming a situation:
jQuery.ajax({
url: APP + "/"+CONTROLADOR_ATUAL+"/jsonGetResposta",
data: { cd : cd},
dataType: 'json',
async: false,
success: function(msg){
jQuery('#vl_total').val(msg.dados.vlTotal);
jQuery('#nr_total').val(msg.dados.nrTotal);
}
});
What is the best way to ensure that the index exists in PHP, or check if dados
, vlTotal/nrTotal
exists in JS?