将java方法参数作为最终参数

时间:2022-08-07 18:20:15

What difference that final makes between the code below. Is there any advantage in declaring the arguments as final.

下面的代码有什么区别呢?将论点声明为最终论点有什么好处吗?

public String changeTimezone( Timestamp stamp, Timezone fTz, Timezone toTz){  
    return ....
}

public String changeTimezone(final Timestamp stamp, final Timezone fTz, 
        final Timezone toTz){
    return ....
}

9 个解决方案

#1


84  

As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.

由于形式方法参数是局部变量,只有在声明为final的情况下,才能从内部匿名类访问它们。

This saves you from declaring another local final variable in the method body:

这样可以避免在方法主体中声明另一个本地最终变量:

 void m(final int param) {
        new Thread(new Runnable() {
            public void run() {
                System.err.println(param);
            }
        }).start();
    }

#2


22  

Extract from The final word on the final keyword

从final关键字的最后一个单词中提取

Final Parameters

最后一个参数

The following sample declares final parameters:

以下示例声明最终参数:

public void doSomething(final int i, final int j)
{
  // cannot change the value of i or j here...
  // any change would be visible only inside the method...
}

final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style.

这里使用final是为了确保方法不会意外地重置i和j两个索引。这是防止错误地更改参数值的潜在bug的一种简便方法。一般来说,简短的方法是一种更好的方法来避免这类错误,但是最终的参数对于您的编码风格来说是一个有用的补充。

Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.

注意,最终参数不被视为方法签名的一部分,并且在解析方法调用时被编译器忽略。参数可以被声明为final(或not),不影响该方法的overriden。

#3


16  

The final prevents you from assining a new value to the variable, and this can be helpful in catching typos. Stylistically you might like to keep the parameters received unchanged and assign only to local variables, so final would help to enforce that style.

最后一种方法可以防止您将一个新值赋值给变量,这有助于捕获输入错误。在风格上,您可能希望保持接收到的参数不变,并只分配给局部变量,因此final将有助于加强这种风格。

Must admit I rarely remember to use final for parameters, maybe I should.

必须承认我很少记得用final作为参数,也许我应该用。

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}

#4


11  

It doesn't make a lot of difference. It just means that you can't write:

这没什么区别。它只是意味着你不能写:

stamp = null;
fTz = new ...;

but you can still write:

但你仍然可以这样写:

stamp.setXXX(...);
fTz.setXXX(...);

It's mainly a hint to the maintenance programmer that follows you that you aren't going to assign a new value to the parameter somewhere in the middle of your method where it isn't obvious and might therefore cause confusion.

这主要是对跟随您的维护程序员的一个提示,即您不会将一个新值赋给方法中间的某个地方的参数,在那里它并不明显,因此可能会引起混乱。

#5


2  

The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment. It's considered sometimes a good coding practice.

在Java中用于参数/变量的final关键字将引用标记为final。如果将对象传递给另一个方法,系统将创建引用变量的副本并将其传递给该方法。通过标记新的引用最终,您可以保护它们不被重新赋值。它有时被认为是一种很好的编码实践。

#6


1  

For the body of this method the final keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that using final in general whenever possible will speed things up but that's not the case in recent JVMs.

对于这个方法的主体来说,final关键字将防止不小心重新分配参数引用,从而在这些情况下产生编译错误(大多数ide将直接抱怨)。有些人可能会认为尽可能地使用final会加快速度,但在最近的jvm中并非如此。

#7


0  

Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil

它只是Java中的一个构造,用来帮助您定义契约并坚持它。这里有一个类似的讨论:http://c2.com/cgi/wiki?

BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.

顺便说一句(正如twiki所说),如果您遵循良好的编程原则,并且hance重新分配/重新定义传入的参数引用,那么将args标记为final通常是多余的。

In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.

在最坏的情况下,如果重新定义args引用,它不会影响传递给函数的实际值——因为只传递了一个引用。

#8


0  

I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).

我说的是一般意义上的标记变量和字段——不仅仅适用于方法参数。(给方法/类打分是完全不同的事情)。

It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.

这对您的代码的读者/未来维护者是一种恩惠。加上合理的变量的名称,这是有帮助的,让您的代码的读者看到/理解问题中的变量表示,让读者,每当你看到相同的变量范围,意思保持不变,所以(s)他没有抓他的头总是找出一个变量在每个上下文意味着什么。我们已经看到太多的“重用”变量的滥用,这使得即使是一个简短的代码片段也很难理解。

#9


-3  

The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example

final关键字阻止您为参数分配新值。我想用一个简单的例子来解释这个问题

Suppose we have a method

假设我们有一个方法

method1(){

method1(){

Date dateOfBirth =new Date("1/1/2009");

日期dateOfBirth = new日期(“1/1/2009”);

method2(dateOfBirth);

method2(dateOfBirth);

method3(dateOfBirth); }

method3(dateOfBirth);}

public mehod2(Date dateOfBirth) {
....
....
....
}

公共mehod2(日期dateOfBirth){ .... .... ....}

public mehod2(Date dateOfBirth) {
....
....
....
}

公共mehod2(日期dateOfBirth){ .... .... ....}

In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.

在上面的例子中,如果“dateOfBirth”在method2中被分配了新的值,那么这会导致method3输出错误。因为传递给method3的值与传递给method2之前的值不同。为了避免最后的关键字被用于参数。

And this is also one of the Java Coding Best Practices.

这也是Java编码的最佳实践之一。

#1


84  

As a formal method parameter is a local variable, you can access them from inner anonymous classes only if they are declared as final.

由于形式方法参数是局部变量,只有在声明为final的情况下,才能从内部匿名类访问它们。

This saves you from declaring another local final variable in the method body:

这样可以避免在方法主体中声明另一个本地最终变量:

 void m(final int param) {
        new Thread(new Runnable() {
            public void run() {
                System.err.println(param);
            }
        }).start();
    }

#2


22  

Extract from The final word on the final keyword

从final关键字的最后一个单词中提取

Final Parameters

最后一个参数

The following sample declares final parameters:

以下示例声明最终参数:

public void doSomething(final int i, final int j)
{
  // cannot change the value of i or j here...
  // any change would be visible only inside the method...
}

final is used here to ensure the two indexes i and j won't accidentally be reset by the method. It's a handy way to protect against an insidious bug that erroneously changes the value of your parameters. Generally speaking, short methods are a better way to protect from this class of errors, but final parameters can be a useful addition to your coding style.

这里使用final是为了确保方法不会意外地重置i和j两个索引。这是防止错误地更改参数值的潜在bug的一种简便方法。一般来说,简短的方法是一种更好的方法来避免这类错误,但是最终的参数对于您的编码风格来说是一个有用的补充。

Note that final parameters are not considered part of the method signature, and are ignored by the compiler when resolving method calls. Parameters can be declared final (or not) with no influence on how the method is overriden.

注意,最终参数不被视为方法签名的一部分,并且在解析方法调用时被编译器忽略。参数可以被声明为final(或not),不影响该方法的overriden。

#3


16  

The final prevents you from assining a new value to the variable, and this can be helpful in catching typos. Stylistically you might like to keep the parameters received unchanged and assign only to local variables, so final would help to enforce that style.

最后一种方法可以防止您将一个新值赋值给变量,这有助于捕获输入错误。在风格上,您可能希望保持接收到的参数不变,并只分配给局部变量,因此final将有助于加强这种风格。

Must admit I rarely remember to use final for parameters, maybe I should.

必须承认我很少记得用final作为参数,也许我应该用。

public int example(final int basicRate){
    int discountRate;

    discountRate = basicRate - 10;
    // ... lots of code here 
    if ( isGoldCustomer ) {
        basicRate--;  // typo, we intended to say discountRate--, final catches this
    }
    // ... more code here

    return discountRate;
}

#4


11  

It doesn't make a lot of difference. It just means that you can't write:

这没什么区别。它只是意味着你不能写:

stamp = null;
fTz = new ...;

but you can still write:

但你仍然可以这样写:

stamp.setXXX(...);
fTz.setXXX(...);

It's mainly a hint to the maintenance programmer that follows you that you aren't going to assign a new value to the parameter somewhere in the middle of your method where it isn't obvious and might therefore cause confusion.

这主要是对跟随您的维护程序员的一个提示,即您不会将一个新值赋给方法中间的某个地方的参数,在那里它并不明显,因此可能会引起混乱。

#5


2  

The final keyword when used for parameters/variables in Java marks the reference as final. In case of passing an object to another method, the system creates a copy of the reference variable and passes it to the method. By marking the new references final, you protect them from reassignment. It's considered sometimes a good coding practice.

在Java中用于参数/变量的final关键字将引用标记为final。如果将对象传递给另一个方法,系统将创建引用变量的副本并将其传递给该方法。通过标记新的引用最终,您可以保护它们不被重新赋值。它有时被认为是一种很好的编码实践。

#6


1  

For the body of this method the final keyword will prevent the argument references to be accidentally reassigned giving a compile error on those cases (most IDEs will complain straight away). Some may argue that using final in general whenever possible will speed things up but that's not the case in recent JVMs.

对于这个方法的主体来说,final关键字将防止不小心重新分配参数引用,从而在这些情况下产生编译错误(大多数ide将直接抱怨)。有些人可能会认为尽可能地使用final会加快速度,但在最近的jvm中并非如此。

#7


0  

Its just a construct in Java to help you define a contract and stick to it. A similar discussion here : http://c2.com/cgi/wiki?JavaFinalConsideredEvil

它只是Java中的一个构造,用来帮助您定义契约并坚持它。这里有一个类似的讨论:http://c2.com/cgi/wiki?

BTW - (as the twiki says), marking args as final is generally redundant if you are following good programming principles and hance done reassign / redefine the incoming argument reference.

顺便说一句(正如twiki所说),如果您遵循良好的编程原则,并且hance重新分配/重新定义传入的参数引用,那么将args标记为final通常是多余的。

In the worst case, if you do redefine the args reference, its not going to affect the actual value passed to the function - since only a reference was passed.

在最坏的情况下,如果重新定义args引用,它不会影响传递给函数的实际值——因为只传递了一个引用。

#8


0  

I'm speaking of marking variables and fields final in general - doesn't just apply to method arguments. (Marking methods/classes final is a whole different thing).

我说的是一般意义上的标记变量和字段——不仅仅适用于方法参数。(给方法/类打分是完全不同的事情)。

It's a favor to the readers/future maintainers of your code. Together with a sensible name of the variable, it's helpful and reassuring to the reader of your code to see/understand what the variables in question represent - and it's reassuring to the reader that whenever you see the variable in the same scope, the meaning stays the same, so (s)he doesn't have to scratch his head to always figure out what a variable means in every context. We've seen too many abuses of "re-use" of variables, that makes even a short code snippet hard to understand.

这对您的代码的读者/未来维护者是一种恩惠。加上合理的变量的名称,这是有帮助的,让您的代码的读者看到/理解问题中的变量表示,让读者,每当你看到相同的变量范围,意思保持不变,所以(s)他没有抓他的头总是找出一个变量在每个上下文意味着什么。我们已经看到太多的“重用”变量的滥用,这使得即使是一个简短的代码片段也很难理解。

#9


-3  

The final keyword prevents you from assigning a new value to the parameter. I would like to explain this with a simple example

final关键字阻止您为参数分配新值。我想用一个简单的例子来解释这个问题

Suppose we have a method

假设我们有一个方法

method1(){

method1(){

Date dateOfBirth =new Date("1/1/2009");

日期dateOfBirth = new日期(“1/1/2009”);

method2(dateOfBirth);

method2(dateOfBirth);

method3(dateOfBirth); }

method3(dateOfBirth);}

public mehod2(Date dateOfBirth) {
....
....
....
}

公共mehod2(日期dateOfBirth){ .... .... ....}

public mehod2(Date dateOfBirth) {
....
....
....
}

公共mehod2(日期dateOfBirth){ .... .... ....}

In the above case if the "dateOfBirth" is assigned new value in method2 than this would result in the wrong output from method3. As the value that is being passed to method3 is not what it was before being passed to method2. So to avoid this final keyword is used for parameters.

在上面的例子中,如果“dateOfBirth”在method2中被分配了新的值,那么这会导致method3输出错误。因为传递给method3的值与传递给method2之前的值不同。为了避免最后的关键字被用于参数。

And this is also one of the Java Coding Best Practices.

这也是Java编码的最佳实践之一。