在Java中更改参数是否是一个好习惯

在Java中更改参数是否是一个好习惯

本文介绍了在Java中更改参数是否是一个好习惯的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我正在用Java编写方法 foo(int i).
由于 i 是按值传递的,因此可以安全地在 foo 中进行更改.例如

Suppose I am writing a method foo(int i) in Java.
Since i is passed by value it is safe to change it in foo. For example


void foo(int i) {
   i = i + 1; // change i
   ...
}

在Java中更改方法的参数被认为是好还是不好的做法?

Is it considered good or bad practice to change arguments of methods in Java?

推荐答案

一般认为这是一种不好的做法,尽管有些人却忽略了它,正如您在其他答案中看到的那样.

It's considered bad practice in general, though some people overlook it as you can see in the other answers.

对于诸如按值直接传递的基元之类的参数,覆盖原始变量没有任何好处.在这种情况下,您应该按照@João的建议进行复制.

For parameters like primitives that are directly passed in by value, there is no advantage in overriding the original variable. In this case you should make a copy as suggested by @João.

对于通过值(对象)传递其 reference 的参数,如果修改句柄以指向其他对象,那将造成混乱.更重要的是,修改作为参数传递的对象的内容也会修改原始对象.

For parameters whose reference is passed in by value (objects), if you modify the handle to point to a different object, that is downright confusing. It's all the more important because modifying the contents of an object passed as a parameter will modify the original object too.

如果替换句柄引用的对象,然后修改内容,则不会替换调用者中原始引用所引用的对象,但是阅读代码的人可能会期望就是这样.

If you replace the object referred to by the handle, and then modify its contents, the object referred to by the original reference in the caller will not be replaced, but someone reading the code might expect it to be.

如果您不替换对象并修改内容,则您的方法调用可能不会期望此更改.此类别通常属于与安全相关的不良做法.

Whereas if you don't replace the object, and modify the contents, the method calling your method might not expect this change. This category generally comes under security-related bad practices.

这篇关于在Java中更改参数是否是一个好习惯的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-01 22:19