什么时候应该对方法参数和局部变量使用 final? [英] When should one use final for method parameters and local variables?

查看:24
本文介绍了什么时候应该对方法参数和局部变量使用 final?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我找到了一些参考资料(例如)建议尽可能多地使用 final ,我想知道这有多重要.这主要是在方法参数和局部变量的上下文中,而不是在最终方法或类中.对于常量,这显然是有意义的.

I've found a couple of references (for example) that suggest using final as much as possible and I'm wondering how important that is. This is mainly in the the context of method parameters and local variables, not final methods or classes. For constants, it makes obvious sense.

一方面,编译器可以做一些优化,让程序员的意图更加清晰.另一方面,它增加了冗长并且优化可能是微不足道的.

On one hand, the compiler can make some optimizations and it makes the programmer's intent clearer. On the other hand, it adds verbosity and the optimizations may be trivial.

这是我应该努力记住的事情吗?

Is it something I should make an effort to remember?

推荐答案

痴迷于:

  • Final 字段 - 将字段标记为 final 强制它们在构造结束时设置,使该字段引用不可变.这允许安全地发布字段,并且可以避免在以后读取时进行同步的需要.(请注意,对于对象引用,只有字段引用是不可变的 - 对象引用所引用的内容仍然可以更改并影响不可变性.)
  • 最终静态字段 - 尽管我现在在许多过去使用静态最终字段的情况下使用枚举.

考虑但要明智地使用:

  • 最终类 - 框架/API 设计是我唯一考虑的情况.
  • Final 方法 - 与 final 类基本相同.如果您正在使用诸如 crazy 和将内容标记为 final 之类的模板方法模式,那么您可能过于依赖继承而对委托的依赖还不够.

忽略除非感觉肛门:

  • 方法参数和局部变量 - 我很少这样做,主要是因为我很懒,而且我发现它使代码混乱.我完全承认标记参数和局部变量我不打算修改是正确的".我希望它是默认的.但事实并非如此,而且我发现代码更难理解为 finals.如果我在别人的代码中,我不会把它们拉出来,但如果我在写新代码,我不会把它们放进去.一个例外是你必须标记一些最终的东西,这样你才能访问它来自匿名内部类.

  • Method parameters and local variables - I RARELY do this largely because I'm lazy and I find it clutters the code. I will fully admit that marking parameters and local variables that I'm not going to modify is "righter". I wish it was the default. But it isn't and I find the code more difficult to understand with finals all over. If I'm in someone else's code, I'm not going to pull them out but if I'm writing new code I won't put them in. One exception is the case where you have to mark something final so you can access it from within an anonymous inner class.

请注意一个用例,其中最终局部变量实际上非常有用,正如 @adam-gent 是将值分配给 if/else 分支中的 var 时.

note that one use case where final local variables are actually very useful as mentioned by @adam-gent is when value gets assigned to the var in the if/else branches.

这篇关于什么时候应该对方法参数和局部变量使用 final?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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