为什么将局部变量和方法参数标记为“最终”?在Java? [英] Why would one mark local variables and method parameters as "final" in Java?

查看:86
本文介绍了为什么将局部变量和方法参数标记为“最终”?在Java?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,您可以使用final关键字限定局部变量和方法参数。

In Java, you can qualify local variables and method parameters with the final keyword.

public static void foo(final int x) {
  final String qwerty = "bar"; 
}

这样做会导致无法在x和qwerty中重新分配x和qwerty方法。

Doing so results in not being able to reassign x and qwerty in the body of the method.

这种做法使你的代码向不变性方向推动,这通常被认为是一个加分。但是,它也会使代码混乱,最终出现在各处。您对Java中局部变量和方法参数的final关键字有什么看法?

This practice nudges your code in the direction of immutability which is generally considered a plus. But, it also tends to clutter up code with "final" showing up everywhere. What is your opinion of the final keyword for local variables and method parameters in Java?

推荐答案

您应该尝试这样做,每当这是合适的。除了用于在意外尝试修改值时警告您,它还为编译器提供了可以更好地优化类文件的信息。这是Robert Simmons,Jr。书中的Hardcore Java中的一点。事实上,本书花了所有第二章关于使用final来促进优化和防止逻辑错误。出于这个原因,静态分析工具(如PMD和Eclipse的内置SA)标记了这些类型的案例。

You should try to do this, whenever it is appropriate. Besides serving to warn you when you "accidentally" try to modify a value, it provides information to the compiler that can lead to better optimization of the class file. This is one of the points in the book, "Hardcore Java" by Robert Simmons, Jr. In fact, the book spends all of its second chapter on the use of final to promote optimizations and prevent logic errors. Static analysis tools such as PMD and the built-in SA of Eclipse flag these sorts of cases for this reason.

这篇关于为什么将局部变量和方法参数标记为“最终”?在Java?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆