Java – pass an argument instead of returning it from a function
It is clear from the title which method should we adopt?
The intent is to pass some method parameters and get the output We can pass another parameter. The method will update it. Now the method does not need to return anything. The method will only update the output variable, which will be reflected to the caller
I just want to construct the problem through this example
List<String> result = new ArrayList<String>(); for (int i = 0; i < SOME_NUMBER_N; i++) { fun(SOME_COLLECTION.get(i),result); } // in some other class public void fun(String s,List<String> result) { // populates result }
And
List<String> result = new ArrayList<String>(); for (int i = 0; i < SOME_NUMBER_N; i++) { List<String> subResult = fun(SOME_COLLECTION.get(i)); // merges subResult into result mergeLists(result,subResult); } // in some other class public List<String> fun(String s) { List<String> res = new ArrayList<String>(); // some processing to populate res return res; }
I understand that one person has passed the reference and the other has not
Which one should we choose (in different cases) and why?
Update: only variable objects are considered
Solution
Returning a value from a function is usually a simpler way to write code Because of the nature of creating and destroying pointers, passing values and modifying them are more C / C + + styles
Developers usually don't want to change their values by passing functions unless the function explicitly states that it changes the value (we often browse the documentation)
But there are exceptions
Consider collections In the example of sort, it actually does sort a list Imagine a list of 1 million items that you are sorting Maybe you don't want to create a second list of another million entries (even if they point to the original entry)
It is also a good habit to support the use of immutable objects Immutable objects cause far fewer problems in most aspects of development, such as threads Therefore, by returning a new object, you do not force the parameter to be mutable
It is important to clarify your intention in the method My advice is to avoid modifying parameters as much as possible because it is not the most typical behavior in Java