Prevent or remedy it?

Asked

Viewed 84 times

5

Lately I’ve been too preoccupied with preventing code errors. Yet I was left with that doubt:

It is better to check (prevent) or remedy (Ensure existence)?

Let’s say you did :

$var = array(
    'name' => 'Guilherme',
    'lastName' => 'Lautert'
);

What is ideal to check if the index exists or ensure that it exists?

Verify

if(isset($var['name'])){
    # code ...
}

Ensure

$default = array(
    'name' => null,
    'lastName' => null,
);

$var = array(
    'name' => 'Guilherme',
);

$var = array_merge($default, $var);

$lastName = $var['lastName'];

Editing

As commented may 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);
    }
});

Ideally, ensure that the index exists in PHP, or check whether dados, vlTotal/nrTotal, exists in the JS?

  • 1

    It depends on the case. The two codes are not equivalent, so it is difficult to compare them.

  • 1

    I voted to close because I think it’s based on opinions. There’s already an answer that starts with "particularly prefer...."

  • 1

    Sorry for, particularly, I say this because following the usability standards should if whenever possible return a feedback to the user, but I do not know where you intend to employ the code. I think you should evaluate better before judging a question. Thank you.

  • $var += ['nome' => 'Wallace de Souza']

  • @bigown depending on the case, he can wear both.

1 answer

1


The question can be interpreted as based on opinions, because, as a friend of mine would say: Everything depends.

Do you necessarily need the data to exist? Then it is necessary that they are properly evaluated.

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

existing implementations

How to use this default values(default values), the use of it usually occurs when an argument or value is optional.

In these cases, it is possible to remember the optional parameters given for some functions. A value callable for example that can have the value null by default.

I’ve seen some frameworks, like the CakePHP 2, using that "default values" to treat a array as if it were a argumento nomeado. I will show a classic example in cases where you would need to save data from a model, for example, 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 to do:

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

or

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

Still talking about the argumentos nomeados, we can also "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 will have to "prevent" (validate), and others who will want to "remedy" (make it optional).

Browser other questions tagged

You are not signed in. Login or sign up in order to post.