将变量声明为“最终"变量是否是一种好习惯?在任何可能的地方? [英] Is it a good practice to declare variables "final" wherever possible?

查看:52
本文介绍了将变量声明为“最终"变量是否是一种好习惯?在任何可能的地方?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能重复:
何时应该使用final?

除非必要,我倾向于将所有变量声明为 final .我认为这是一个好习惯,因为它允许编译器检查标识符是否按我的期望使用(例如,它没有突变).另一方面,它会使代码混乱,也许这不是"Java方式".

I tend to declare all variables final unless necessary. I consider this to be a good practice because it allows the compiler to check that the identifier is used as I expect (e.g. it is not mutated). On the other hand it clutters up the code, and perhaps this is not "the Java way".

我想知道是否存在关于非必需使用最终变量的普遍公认的最佳实践,以及在此讨论中是否应该考虑其他折衷或方面.

I am wondering if there is a generally accepted best practice regarding the non-required use of final variables, and if there are other tradeoffs or aspects to this discussion that should be made aware of.

推荐答案

"Java方式"本质上是混乱的.

The "Java way" is inherently, intrinsically cluttery.

我说这是一个好习惯,但我没有遵循.

I say it's a good practice, but not one I follow.

测试通常可以确保我按照自己的意愿去做,而且对我的审美而言,这太混乱了.

Tests generally ensure I'm doing what I intend, and it's too cluttery for my aesthetics.

这篇关于将变量声明为“最终"变量是否是一种好习惯?在任何可能的地方?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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