Is sending parameters to another function using object or hash a good practice?

Asked

Viewed 282 times

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 good practice, and if it has a good use for parameter crossings using hash or other Javascript objects.

It seems strange that I receive two parameters or more and then send them to another function for any particular treatment.

1 answer

6


Once again I begin the answer by saying that good practice is doing 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 multiple parameters must be a consequence of the good organization of the data structure.

Some say that knowing how to put together the data structure is more important than knowing how to organize the algorithms well, I am one of them.

Creating a weird, meaningless, unrelated object just to avoid passing multiple parameters makes no sense.

Trying to avoid a large number of parameters in the function without a plausible reason also makes no sense. There are cases that need several parameters even.

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

Note that in fact there is only harm. It is more work without any gain. And it will probably slightly affect performance, if any, also without readability. On the contrary, it is possible to argue that it is even less readable.

Do not create artificial objects without need unless required for some reason. Create objects when they characterize themselves as a group cohesive of information.

Be sure to pass objects when you already have them. The recommendation is only to not create artificial objects, only to pass as a single parameter. There’s nothing wrong with passing objects.

Looking the other way, if you have many parameters is an indicative that maybe should have an object if they are related and in the background are part of something larger. If the API you are using expects objects or has facilities if passing objects, do so. My recommendation is just not to make this a rule. In many cases the use of an object is normal, only it should not force the situation to use an object when it is not necessary.

Browser other questions tagged

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