Eclipse Tips: Auto generate ‘final’ on your variable, field, and parameter

If you are reading a lot of blogs about Java lately, you’ll find more and more people suggesting to use ‘final’ everywhere. The main argument is by using ‘final’ we will have a code with less bug. This post will not argue with the up/down side of the suggestion, if you eager to do that, just do that somewhere else (here for example).

However, if you are convince with such argumentation, probably the first thing on your mind is: should I now change all my code? How much time do I need to develop this instinct until all of my code is using ‘final’ everywhere?

Fortunately for Eclipse user, there is a functionality in Eclipse to help we develop this instinct. And it even will fixes our mistakes and we will get a consistent look of our code.

Let’s look at a code example:

2009-08-13_1139

There are some places where ‘final’ could be used. Now… open the Preferences dialog (under Window on Windows and Linux, under Eclipse on Mac). Navigate to Java->Editor->Save Actions.

2009-08-13_1142

Tick the ‘Perform the selected actions on save’ checkbox and ‘Additional actions’ checkbox. After that, click the ‘Configure…’ button.
2009-08-13_1146

What we’re interested in is in tab ‘Code Style’. Tick all ‘Private fields’, ‘Parameters field’, and ‘Local variables’. Click ‘OK’

Now you can go back to your source code and do small change, revert it back (Eclipse prevents saving if there is no change in the source code), and save it. Tarammm…. you get ‘final’ everywhere.

2009-08-13_1151

Note that this doesn’t put final on your method and class, you still have to do that manually.

Now you can enforce your team to use ‘final’ everywhere if you like!

Leave a Reply

Your email address will not be published. Required fields are marked *