使用“最终”任何适用于Java的修饰符 [英] Using the "final" modifier whenever applicable in Java

查看:96
本文介绍了使用“最终”任何适用于Java的修饰符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java中,有一种做法是声明每个变量(本地或类),如果它们确实是参数final。

In Java, there is a practice of declaring every variable (local or class), parameter final if they really are.

虽然这使得代码更多详细说明,这有助于轻松阅读/掌握代码,并防止错误,因为意图已明确标记。

Though this makes the code a lot more verbose, this helps in easy reading/grasping of the code and also prevents mistakes as the intention is clearly marked.

您对此有何看法,您关注什么?

What are your thoughts on this and what do you follow?

推荐答案

我认为这一切都与良好的编码风格有关。当然,你可以在任何地方编写好的,健壮的程序而不需要使用大量的 final 修饰符,但是当你想到它时......

I think it all has to do with good coding style. Of course you can write good, robust programs without using a lot of final modifiers anywhere, but when you think about it...

不应更改的所有内容添加 final ,只会缩小您(或下一个程序员,为您工作的可能性)的可能性代码)将误解或误用导致您的代码的思维过程。至少它应该响起一些钟声,因为他们现在想要改变你以前不可改变的东西。

Adding final to all things which should not change simply narrows down the possibilities that you (or the next programmer, working on your code) will misinterpret or misuse the thought process which resulted in your code. At least it should ring some bells when they now want to change your previously immutable thing.

首先,看到很多<$ c $看起来很尴尬你的代码中有c> final 关键字,但很快你就会停止注意到这个词本身,并且只会想到,那件事 - 永远不会改变 - 从这一点 - 在(你可以从我这里拿走它; - )

At first, it kind of looks awkward to see a lot of final keywords in your code, but pretty soon you'll stop noticing the word itself and will simply think, that-thing-will-never-change-from-this-point-on (you can take it from me ;-)

我认为这是一个好习惯。我并没有一直使用它,但是当我可以并且标记 final 时,我会这样做。

I think it's good practice. I am not using it all the time, but when I can and it makes sense to label something final I'll do it.

这篇关于使用“最终”任何适用于Java的修饰符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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