Prevent or remedy?

5

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?

    
asked by anonymous 03.02.2016 / 12:10

1 answer

1

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? Then they need to be properly evaluated.

Do you want to treat them as optional values? So, use the default values.

existing implementations

Regarding this way of using this default values (default values), use of it usually occurs when an argument or a value is optional.

In these cases, we might remember the optional parameters given for some functions. A callable value, for example, that can have the value null by default.

I've seen some frameworks, such as CakePHP 2 , that use this "default values" to treat a array as if it were a argumento nomeado . I'll show you a classic example in cases where you would need to, for example, save data from a model, where the creation date is entered automatically if it is not passed.

Example:

function saveData(array $data)
{
     $data += ['created_at' => new DateTime;];

}

These examples allow you to do:

saveData(['name' => 'Wallace', 'created_at' => new DateTime('-1 day')]

or

saveData(['name' => 'Wallace']);

Still talking about argumentos nomeados , we can still "mix" "prevent" with "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 will have to "prevent" (validate), and others that you will want to "remedy" (make optional).

    
03.02.2016 / 13:04