Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Methods that change a value, and not return anything

Tags:

java

arrays

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!!

like image 640
Mob Avatar asked Oct 28 '11 15:10

Mob


2 Answers

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).

like image 143
Jon Skeet Avatar answered Sep 28 '22 07:09

Jon Skeet


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.

like image 26
Guillaume Avatar answered Sep 28 '22 07:09

Guillaume