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

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

问题描述

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

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.

起初,在您的代码中看到很多 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天全站免登陆