Methods that change a value, and not return anything

匿名 (未验证) 提交于 2019-12-03 08:46:08

问题:

Please what's the term for methods that alter the contents of a variable, while not returning anything.

For instance in Java from the java.util.Arrays class the static method sort sorts an array internally and sets the sorted array to the original arrays 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 that kind of method,

and;

2 - How does this work internally? Does it delete the original variable and assign the sorted values to a fresh one with that same name or??

Thanks!!

回答1:

I'd normally call it a mutator - or just talk about it having side-effects. (Usually a mutator is a method you call on an object which changes that object's state. In this case we're changing the object referred to by the argument/parameter, which is slightly different.)

As for how it works - it's important to understand the difference between a variable, a reference and an object.

This method call:

sort(arr); 

copies the value of the arr variable as the value of the parameter within the sort method. That value is a reference to an object (the array in this case). The method doesn't change the value of arr at all - it's still a reference to the same array. However, the method changes the contents of the array (i.e. which elements have which values).



回答2:

There is a name for that: an anti-pattern ;)

Seriously, I consider overusing them a bad practice: as much as possible, methods should not modify the world outside of them, it's far better (and far more Object-oriented) to put the result in a temp array that you return at the end of your processing. If you don't want to do that, and use methods which mutate other elements, you will run into all kind of problems (breaking of encapsulation, concurrency problems, etc.) that you could avoid much more easily without doing that.

Exception: setters, of course.

As for how it works, Jon Skeet said it in his answer.



回答3:

Methods which return a value are sometimes called "functions" and those which don't return anything "procedures".



回答4:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!