Question:
Lately I've been worrying too much about preventing errors in the code. However, I have this doubt:
Is it better to check (prevent) or remedy (ensure existence)?
Let's say you have:
$var = array(
'name' => 'Guilherme',
'lastName' => 'Lautert'
);
Which is ideal to check if the index exists or ensure that it exists?
To 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'];
Edition
As commented, you can be based on opinion, so 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);
}
});
Which is better, ensuring that the index exists in PHP, or checking if dados
, vlTotal/nrTotal
, exists in JS?
Answer:
The question can be interpreted as based on opinions, because, as a friend of mine would say: It all depends.
Do you necessarily need the data to exist? So it is necessary that they are properly evaluated.
Do you want to treat them as optional values? Then use the default values.
existing implementations
Regarding this way of using this default values
, its use is usually when an argument or a value is optional.
In such cases, we could remember the optional parameters given to some functions. A callable
value for example that can default to null
.
I've seen some frameworks, like CakePHP 2
, that use these "default values" to treat an array
as if it were a argumento nomeado
. I will show a classic example in cases where I would need to save data from a model, for example, where the creation date is automatically inserted if it is not passed.
Example:
function saveData(array $data)
{
$data += ['created_at' => new DateTime;];
}
These examples allow you to:
saveData(['name' => 'Wallace', 'created_at' => new DateTime('-1 day')]
Where
saveData(['name' => 'Wallace']);
Still talking about the argumentos nomeados
, we can still "mix" the "prevent" with the "remedy".
For example:
saveData(array $data)
{
$data += ['data' => new DateTime];
if (! isset($data['name']) {
throw new BadCallMethodException('É necessário passar "name"');
}
}
So, there are cases where you'll have to "prevent" (validate), and others you'll want to "remedy" (make optional).