java 传递参数与从函数返回参数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10403766/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Passing a parameter versus returning it from function
提问by instanceOfObject
As it might be clear from the title which approach should we prefer?
从标题中可以清楚地看出我们应该更喜欢哪种方法?
Intention is to pass a few method parameters and get something as output. We can pass another parameter and method will update it and method need not to return anything now, method will just update output variable and it will be reflected to the caller.
意图是传递一些方法参数并获得一些东西作为输出。我们可以传递另一个参数,方法会更新它,方法现在不需要返回任何东西,方法只会更新输出变量并将其反映给调用者。
I am just trying to frame the question 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
}
versus
相对
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 passes the reference and another doesn't.
我知道一个通过参考,另一个没有。
Which one should we prefer (in different situations) and why?
我们应该更喜欢哪一个(在不同的情况下),为什么?
Update: Consider it only for mutable objects.
更新:仅针对可变对象考虑它。
回答by Jeff Storey
Returning a value from the function is generally a cleaner way of writing code. Passing a value and modifying it is more C/C++ style due to the nature of creating and destroying pointers.
从函数返回一个值通常是一种更简洁的代码编写方式。由于创建和销毁指针的性质,传递和修改值更像是 C/C++ 风格。
Developers generally don't expect that their values will be modified by passing it through a function, unless the function explicitly states it modifies the value (and we often skim documentation anyway).
开发人员通常不希望通过将其传递给函数来修改他们的值,除非该函数明确声明它修改了值(无论如何我们经常浏览文档)。
There are exceptions though.
不过也有例外。
Consider the example of Collections.sort
, which does actually do an in place sort of a list. Imagine a list of 1 million items and you are sorting that. Maybe you don't want to create a second list that has another 1 million entries (even though these entries are pointing back to the original).
考虑 的例子Collections.sort
,它实际上做了一个就地排序的列表。想象一个包含 100 万个项目的列表,您正在对其进行排序。也许您不想创建包含另外 100 万个条目的第二个列表(即使这些条目指向原始条目)。
It is also good practice to favor having immutable objects. Immutable objects cause far fewer problems in most aspects of development (such as threading). So by returning a new object, you are not forcing the parameter to be mutable.
支持不可变对象也是一种很好的做法。不可变对象在开发的大多数方面(例如线程)引起的问题要少得多。因此,通过返回一个新对象,您不会强制参数可变。
The important part is to be clear about your intentions in the methods. My recommendation is to avoid modifying the parameter when possible since it not the most typical behavior in Java.
重要的部分是要清楚你在方法中的意图。我的建议是尽可能避免修改参数,因为它不是 Java 中最典型的行为。
回答by SpacePrez
You should return it.The second example you provided is the way to go.
你应该退货。您提供的第二个示例是要走的路。
First of all, its more clear.When other people read your code, there's no gotcha that they might not notice that the parameter is being modified as output. You can try to name the variables, but when it comes to code readability, its preferable.
首先,它更清晰。当其他人阅读您的代码时,他们可能没有注意到参数被修改为输出。您可以尝试命名变量,但在代码可读性方面,它更可取。
The BIG reasonwhy you should return it rather than pass it, is with immutable objects.Your example, the List, is mutable, so it works okay. But if you were to try to use a String that way, it would not work.
很大的原因,为什么你应该回到它,而不是通过它,是不可变对象。您的示例 List 是可变的,因此它可以正常工作。但是,如果您尝试以这种方式使用 String,它将不起作用。
As strings are immutable, if you pass a string in as a parameter, and then the function were to say:
由于字符串是不可变的,如果您将字符串作为参数传入,则该函数会说:
public void fun(String result){
result = "new string";
}
The value of result that you passed in would notbe altered. Instead, the local scope variable 'result' now points to a new string inside of fun, but the result in your calling method still points to the original string.
您传入的结果值不会改变。相反,局部范围变量“result”现在指向 fun 中的一个新字符串,但调用方法中的结果仍指向原始字符串。
If you called:
如果你打电话:
String test = "test";
fun(test);
System.out.println(test);
It will print: "test", not "new string"!
它将打印:“测试”,而不是“新字符串”!
So definitely, it is superior to return. :)
所以肯定的是,返回是优越的。:)
回答by Charles
The reason I don't think we understand is that those are two totally different types of actions. Passing a variable to a function is a means of giving a function data. Returning it from the function is a way of passing data out of a function.
我认为我们不明白的原因是那是两种完全不同的行为。将变量传递给函数是为函数提供数据的一种方式。从函数中返回它是一种将数据传出函数的方式。
If you mean the difference between these two actions:
如果您的意思是这两个操作之间的区别:
public void doStuff(int change) {
change = change * 2;
}
and
和
public void doStuff() {
int change = changeStorage.acquireChange();
change = change * 2;
}
Then the second is generally cleaner, however there are several reasons (security, function visibilty, etc) that can prevent you from passing data this way.
然后第二个通常更干净,但是有几个原因(安全性、功能可见性等)可以阻止您以这种方式传递数据。
It's also preferable because it makes reusing code easier, as well as making it more modular.
它也更可取,因为它使重用代码更容易,并使其更加模块化。
回答by AmirHossein Abdolmotallebi
according to guys recommendation and java code convention and also syntax limitation this is a bad idea and makes code harder to understand BUT you can do it by implementing a reference holder class
根据伙计们的建议和 Java 代码约定以及语法限制,这是一个坏主意,使代码更难理解,但您可以通过实现引用持有者类来做到这一点
public class ReferenceHolder<T>{
public T value;
}
and pass an object of ReferenceHolder into method parameter to be filled or modified by method. on the other side that method must assign its return into Reference value instead of returning it. here is the code for getting result of an average method by a ReferenceHolder instead of function return.
并将 ReferenceHolder 的对象传递给方法参数,以供方法填充或修改。另一方面,该方法必须将其返回值分配给 Reference 值,而不是返回它。这是通过 ReferenceHolder 而不是函数返回获取平均方法结果的代码。
public class ReferenceHolderTest {
public static void main(String[] args) {
ReferenceHolder<Double> out = new ReferenceHolder<>();
average(new int[]{1,2,3,4,5,6,7,8},out);
System.out.println(out.value);
}
public static void average(int[] x, ReferenceHolder<Double> out ) {
int sum=0;
for (int a : x) {
sum+=a;
}
out.value=sum/(double)x.length;
}
}
回答by pcalcao
Returning it will keep your code cleaner and cause less coupling between methods/classes.
返回它将使您的代码更清晰,并减少方法/类之间的耦合。
回答by EstebanSmits
This is more about best practices and your own method to program. I would say if you know this is going to be a one value return type function like:
这更多是关于最佳实践和您自己的编程方法。我会说,如果您知道这将是一个单值返回类型函数,例如:
function IsThisNumberAPrimeNumber{ }
函数 IsThisNumberAPrimeNumber{ }
Then you know that this is only going to ever return a boolean. I usually use functions as helper programs and not as large sub procedures. I also apply naming conventions that help dictate what I expect the sub\function will return. Examples:
然后你知道这只会返回一个布尔值。我通常将函数用作辅助程序而不是大型子程序。我还应用了一些命名约定来帮助确定我期望 sub\function 将返回的内容。例子:
GetUserDetailsRecords GetUsersEmailAddress IsEmailRegistered
GetUserDetailsRecords GetUsersEmailAddress IsEmailRegistered
If you look at those 3 names, you can tell the first is going to give you some list or class of multiple user detail records, the second will give you a string value of a email and the third will likely give you a boolean value. If you change the name, you change the meaning, so I would say consider this in addition.
如果您查看这 3 个名称,您可以看出第一个将为您提供多个用户详细记录的列表或类,第二个将为您提供电子邮件的字符串值,而第三个可能会给您一个布尔值。如果您更改名称,则会更改含义,因此我会说另外考虑这一点。