java :Why the Local variable should be declared final [duplicate]

↘锁芯ラ 提交于 2019-12-01 04:27:47
Nick Garvey

Taken from the following article: http://www.javapractices.com/topic/TopicAction.do?Id=23

  • clearly communicates your intent
  • allows the compiler and virtual machine to perform minor optimizations
  • clearly flags items which are simpler in behaviour - final says, "If you are looking for complexity, you won't find it here."

This is also discussed in this question: Can excessive use of final hurt more than do good?

final indicates the local variable won't be changed. My feeling is that methods should be so short you should be able to easily understand them and so making the variable final may be a bit redundant.

I prefer to make fields final because making the whole class so short, is a serious limitation. Also fields can have thread safety issues which local variables do not.

I dont know about performance-benefits by making status final, but PMD is suggesting you this, because probably you are never writing on status after its first initialization.

So what you gain by making it final is just that your code is less error-prone - if you declare it final, you cant overwrite it by mistake...

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!