Sent parameters to another function using object or hash is a good practice?

4
Exemplo:

    function atualizar(dados, events) {
      //faz qualquer tratamento dos valores

         var hash = {
           novoValor: dados,
           outroValor: event
         };

      // primeira opção
      return customize(dados, event);

     // segunda opção
     return custom(hash);
    }

  function customize(dados, event) {
     //faça algo
  }

  function custom(hash) {
     //faça algo
  }

I want to know if it is a good practice, and whether it has good use for parameter passing using hash or other JavaScript objects.

It seems strange that I get two or more parameters and then send them to another function for some special treatment.

    
asked by anonymous 29.01.2015 / 17:04

1 answer

5

Once again, I begin by saying that good practice is right for the specific situation.

In general it is common to work with objects when it makes sense to group various information into an object. Passing the object instead of several parameters should be a consequence of the good organization of the data structure.

Some people say that building a data structure is more important than organizing the algorithms well.

Creating a weird, meaningless, unrelated object just to avoid passing multiple parameters does not make sense.

Trying to avoid a large number of parameters in the function without a plausible reason also does not make sense. There are cases that need several same parameters.

In the specific case you are presenting, it seems to be a case of grouping two unrelated things just to have the "benefit" of passing only one parameter. This is pretty bad.

Note that there is actually only evil. It gives more work without gain. And it will probably slightly affect the performance also without readability gain. On the contrary, it is possible to argue that it is even less readable.

Do not artificially create unnecessary objects unless you have to do it for some reason. Create objects when they are characterized as a cohesive group of information.

Make sure you pass objects when you already have them. The recommendation is only for those who do not create artificial objects, only to pass as a single parameter. There is nothing wrong with passing objects.

On the other hand, if you have many parameters it is a code that maybe should have an object if they are related and in the background are part of something bigger. If the API you are using expects objects or has facilities if you pass objects, do so. My recommendation is just not to make this a rule. Many cases the use of an object is normal, you should not just force the situation to use an object when it is not needed.

    
29.01.2015 / 17:25