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

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

问题描述

在 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.

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.

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

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