the blog for developers

All variables in Java must be final

I haven’t been using the final keyword in Java for 10 years, but more and more I think it’s an excellent keyword in Java. All local variables should be declared final. Today one of the developers of my team made every local variable in a method final and I was wondering how strange that looked. But of course it was the right thing to do. Declaring all variables final will lead to less bugs (logic and typos e.g.).

public void doSomething(final input) {
   final result = calc(input);

If you reassign a variable you most probably do something wrong. I’ll bet if you reassign a variable your method does at least two different things though every method should only do one thing. As should a class. Final also goes for method parameters, all should be final. Others think so too even for methods.

How do you deal with final attributes? When making most attributes final, just initialize them in the constructor. Immutable objects also play nicely with Tell, don’t ask.

All these final keywords around your code create noise though. It would be best to have all variables automatically be final and have a new transient keyword for reassignable variables. Or at least for my IDE – Intellij IDEA – to hide the final keyword and write the variable in a different color. Hear me IDEA developers!

Update: After some more work with Scala, var and val are a good solution.

About the author

stephan Stephan Schmidt has been working with internet technologies for the last 20 years. He was head of development, consultant and CTO and is a speaker, author and blog writer. He specializes in organizing and optimizing software development helping companies by increasing productivity with lean software development and agile methodologies. Want to know more? All views are only his own. You can find him on Google +

Discuss on Hacker News Vote on HN