In the POO when to use Re-turn?

Asked

Viewed 446 times

5

I have a question related to POO, when should I use the return in a method?!

Since when I pass an object to the method and modifications are made to it, I do not need to Return, example below:

Method call:

this.ordenaArquivo(this.arquivos);

private void ordenaArquivo(List<Video> arquivos ) {     
    VideoComparatorUtil comparatorUtil = new VideoComparatorUtil(VideoComparatorUtil.ORDERBY_TAMANHO);

    Collections.sort(arquivos, comparatorUtil);
}

Or should I do it:

Method call:

this.arquivos = this.ordenaArquivo(this.arquivo);

private List<Video> ordenaArquivo(List<Video> arquivos ) {      
    VideoComparatorUtil comparatorUtil = new VideoComparatorUtil(VideoComparatorUtil.ORDERBY_TAMANHO);

    Collections.sort(arquivos, comparatorUtil);

    return arquivos;
}
  • 1

    You can perform a test, pass as parameter of your method a String and within your method, try to change this String. something like that: public void changeStringValue(String value) { value = "Ohh!!"; }. and see that if you try to print the value of your String after calling this method, the printed value will be the same as before calling the method. String myStr = "initialValue" ; System.out.printLn(myStr); //initialValue changeStringValue(myStr);&#xA; System.out.println(myStr); //initialValue` for this reason, pass the parameters, and return the result if necessary.

2 answers

3


In fact the return it is not a specific concept of object orientation. It is part of the syntax of Java and many other languages and is a keyword used to return to the code where the method was originally called.

A method of any type returns when it finds the return followed by their type;
A method of the kind void returns when you find the return; or when it comes to the end of it.

But your doubt can best be explained by Java data types and passing arguments by value or reference.

Passing argument by value

When you pass to a method only arguments of primitive types (int, float, double, long, short, char or byte), they are passed por valor. That is, a cópia of that variable is made within the scope of the method and even if you change it, nothing will happen with the original variable that you had passed as argument first.

public static int metodoSomaDois(int argumento) {
    //Uma cópia do seu argumento recebe ele mesmo + 2
    //Sendo assim vc precisa retornar ele caso 
    //queira atribuir o seu valor alterado à uma outra variável externa
    argumento += 2; 
    return argumento;
}

Example:

 int original = 5;
 metodoSomaDois(original); //Nada vai acontecer já que vc não atribuiu o retorno do método a nenhuma outra variável e a original permanece 5.
 original = metodoSomaDois(original); //Agora a variável original vai receber o valor retornado do método


Passing argument by reference (your case)

Arguments of nonprimitive types (arrays, objects, etc.) are passed by referência. This means that the object itself is passed (more precisely a pointer to that object) and not a copy. That is, any change made to that object within the scope of the method will also change the object that was originally passed as argument.

public static void metodoAlteraValores(int listaPorArgumento[]) {
    //Como esta sendo passado por referência
    //os valores da lista original vão ser alterados também sem a necessidade de atribuir o retorno
    for (int i = 0; i < 3; i++)
        listaPorArgumento[i] = 10;
}

Example:

int lista[] = {5, 5, 5};

    for (int i : lista)
        System.out.print(i + ", "); //Exibe 5, 5, 5,

    metodoAlteraValores(lista); //Altera os valores pra 10 sem precisar de atribuir a nenhuma outra variável

    for (int i : lista)
        System.out.print(i + ", "); //Exibe 10, 10, 10, (o que mostra que a lista original foi alterada)


Completion

This shows that your first example is the most correct and why.
In summary, the return will be used when you need to return a value that has to be assigned to some variable, and will not be necessary when directly changing an object that is passed by reference.

It is worth remembering that it is possible to return a primitive type object, which can be assigned to a variable of the same type. Usually this happens when you, for example, want to change an array without changing the original.
Therefore, ideally, for your case, would be to create an object of the same type within the method and make a clone of the original that can be changed and later returned.

  • Perfect, had not stopped to think that primitive type of variables were not changed when passed to a method, great response, thank you.

  • I do not agree with the framework of the problem. The problem is not only about passing arguments by reference vs by value, but about immutable types (primitive or not) vs mutable types (not primitive). For example, string is passed by reference - however, any "changes" must be returned, viewed string be an immutable guy.

  • I believe the answer lacks information. The question was when to use Return. I answered and even extrapolated a little explaining and exemplifying passage by reference using array, which is very close to the example he used in the question. I could explain directly about immutability too, but before what has already been written, it is up to him to go for more information since all this is connected.

1

In java every object is passed as a reference. Therefore, if Voce wants to change an object in a method, it is sufficient to pass it as a parameter and without return. In your case, the first option looks better (Lists are objects).

If you still want to return an object, note that using Return on a Voce object does not return a copy of it, it returns only the reference to this object. So, Return in the list does not return a complete copy of the list, it returns only a reference to your list.

Return is used only for primitive types (int, float ...) that in Java are passed by value;

Browser other questions tagged

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