Methods with the same name but with a number of different parameters

Asked

Viewed 1,140 times

3

In C# or Java in a class I can define methods with the same name but with different variables, like this:

//em C#
public class Classe {
    public String teste(String hello, String world){
        return  hello + world;
    }
    public String teste(String full){
        return full;
    }
    public String teste(){
       return "hello world";
    }
}

I need to know how I could generate methods with that same sense where the method name is the same but depending on the elements I send it will process a block of code or other...

  • From the accepted answer it was clear that the intention of the question is the same as the existing question, so I voted to close as duplicate.

3 answers

9


What is done in javascript in this regard is to create a function and, at the beginning of the implementation of the function, analyze and treat the arguments so that it can be used in a more dynamic way. By setting a function twice javascript overwrites the first implementation of the function, you have no immutability.

A function that would translate the functionality you search, written in javascript, would be the following:

function teste() {
  if(arguments.length === 0)
    return "hello world"

  if(arguments.length === 1 &&
    typeof(arguments[0]) === 'string')
    return arguments[0];

  if(arguments.length === 2 &&
    typeof(arguments[0]) === 'string' &&
    typeof(arguments[1]) === 'string')
    return arguments[0] + arguments[1];
}

// Para casos tratados
teste(); // "hello world"
teste("teste1"); // "teste1"
teste("teste1", "teste2"); // "teste1teste2"

// Para casos não tratados
// Quando uma função não retorna, explicitamente, nenhum valor, você recebe undefined
teste("teste1", "teste2", "teste3"); // undefined
teste(1); // undefined
teste("teste1", 1); // undefined

Within the scope of every function you can access the variable arguments. This variable represents an object whose indices are numbers, starting at zero. I believe this is the key to solving your problem.

Ex.:

// arguments = {length: 0}
teste();

// arguments = {length: 1, 0: "teste1"}
teste("teste1");

// arguments = {length: 2, 0: "teste1", 1: "teste2"}
teste("teste1", "teste2");

// arguments = {length: 3, 0: "teste1", 1: "teste2", 2: "teste3"}
teste("teste1", "teste2", "teste3");

// arguments = {length: 1, 0: 1}
teste(1);

teste("teste1", 1); // arguments = {length: 2, 0: "teste1", 1: 1}
  • Man, I see JS as a very good language for those who work on the web but I miss what you get in typed languages... but thanks partner, very good this logic your

  • @Leandroluk I agree that JS is deficient and that is why I am interested in and study functional languages such as http://www.erlang.org/, http://elm-lang.org and one day learn https://www.haskell.org/

5

It’s called overload of methods. No, this is not possible the way you are wanting to do in Javascript.

However, Javascript does not reject passing a number of parameters other than what is stated in the function signature. If you have a function

function funcaoComAridade2(parametro1, parametro2) {
    console.log("Primeiro: " + parametro1);
    console.log("Segundo: " + parametro2);
}

nothing stops you from calling her that:

funcaoComAridade2(33);

The only problem is parametro2 will receive the value undefined.

You can even find out the amount of parameters passed. Just get the size (length) of the vector-style object arguments inside the function. This object contains the actual parameters received, regardless of how many. You can rely on this to decide, in the body of the method, which way to take.

  • arguments is not a vector, this variable is an object. But the rest of the explanation proceeds, in my opinion

  • 2

    I called it "style-vector object". I didn’t want to explain in depth not to prolong something that is detail.

3

These are actually different parameters, this is called overloading (overload).

In Javascript this is not possible because it has not mentioned the resource, it has to put something in the name to differentiate one from the other. Try to find a suggestive name that indicates the difference, if you cannot specify the difference by specifying the type(s) in the name, but try to make it as intuitive as possible.

In fact this would not even be technically possible since Javascript does not have static types, at least until the current version, which makes the decision difficult.

It is possible to simulate this with checks within the body of the function. That is, you would have only one function accepting several parameters. Inside would have some ifs analysing the amount of parameters actually passed and possibly the type of each one. The decision of which parts of the function (or delegate to others) are to be carried out shall be based on what is decided therein. There are other techniques passing objects or using the technique of default Arguments.

Examples written by John Resig. Behold question on the subject with more examples.

In dynamic languages several mechanisms need to be written by the programmer.

Even Typescript (more information) that has types does not have the ability to decide by types. If you did this would have complications to generate the JS source. She is able to decide only by the amount of parameters.

  • I preferred not to give examples, because it is full of questions in Sopt with examples, in the background, answering I realized until the question is duplicated.

Browser other questions tagged

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