Methods that change value and return nothing

Please, what is the term for methods that change the contents of a variable so far does not return anything.

For example, in Java from the java.util.Arrays class, the static sort method sorts the array internally and sets the sorted array to the original array variable (not sure).

 import static java.util.Arrays.sort; public class bs { public static void main(String [] args){ int[] arr = {3,2,4,8,2,5,33,12,19,15,20}; sort(arr); // doing this stuff <<<< and not int [] arr1 = sort(arr); } } 

1 . Is there a specific term for such a method,

and

2 . How does it work domestically? Does the original variable delete and assign the sorted values ​​fresh with the same name or?

Thanks!!

+6
source share
4 answers

I usually call it a mutator or just talk about it with side effects. (Usually, a mutator is a method called by an object that changes this state of the object. In this case, we change the object referenced by the parameter / parameter, which is slightly different.)

How it works - it is important to understand the difference between a variable, a link, and an object.

This method call:

 sort(arr); 

copies the value of the arr variable as the parameter value in the sort method. This value is a reference to an object (an array in this case). The method does not change the value of arr all - it is still a reference to the same array. However, the method modifies the contents of the array (i.e. which elements have values).

+8
source

There is a name for this: anti-pattern;)

Seriously, I find it excessive to use their bad practice: as much as possible, methods should not change the world beyond, it is much better (and much more object-oriented) to cast the result to the temp array that you return at the end of your processing. If you do not want to do this and use methods that mutate other elements, you will encounter all problems (breaking encapsulation, problems with w390, etc.), which you could have avoided much easier without doing this.

Exception: setters, of course.

Regarding how this works, John Skeet said this in his answer.

+2
source

Methods that return a value are sometimes called "functions" and those that do not return any "procedures".

+1
source

Methods and the method header ( Public static void main string or something like that) is the method header. The main method is the usual starting point for all standalone java applications. The word "static" is a modifier of a method. "Void" means that this method does not return a value when called.

0
source

Source: https://habr.com/ru/post/900296/


All Articles