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

∥☆過路亽.° 提交于 2019-12-30 08:55:01

问题


Possible Duplicate:
Is there any performance reason to declare method parameters final in Java?
Why would one mark local variables and method parameters as “final” in Java?

I am using PMD to see the code violations.

Inside a webService Method, I have this below code

public ServiceRequest getData()
{
Status status = new Status();
// code
}

What PMD is suggesting me is that, this local variable status could be declared as final.

My question is, making it final would result in any performance improvements or if not what benefits the code could get?


回答1:


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?




回答2:


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.




回答3:


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...



来源:https://stackoverflow.com/questions/9195752/java-why-the-local-variable-should-be-declared-final

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