Can excessive use of final hurt more than do good?

2019-04-06 04:21发布

Why are people so emphatic about making every variable within a class "final"? I don't believe that there is any true benefit to adding final to private local variables, or really to use final for anything other than constants and passing variables into anonymous inner classes.

I'm not looking to start any sort of flame war, I just honestly want to know why this is so important to some people. Am I missing something?

8条回答
SAY GOODBYE
2楼-- · 2019-04-06 05:00

It marks that I'm not expecting that value to change, which is free documentation. The practice is because it clearly communicates the intent of that variable and forces the compiler to verify that. Beyond that, it allows the compiler to make optimizations.

查看更多
【Aperson】
3楼-- · 2019-04-06 05:04

One benefit for concurrent programming which hasn't been mentioned yet:

Final fields are guaranteed to be initialized when the execution of the constructor is completed.

查看更多
登录 后发表回答