Search This Blog

Loading...

Sunday, August 5, 2012

IntelliJ: Final parameters and variables


Different teams require different coding styles and source code metrics. We have for example a rule which states that all method parameters should be final. Without going to discuss this rule (since your mileage may vary) I will show how IntelliJ can be used to enforce this rule.

There are two use cases here:
  1. Adding the final keyword to all methods generated with IntelliJ.
  2. Add the final keyword to existing methods.

To add the final keyword to parameters of generated methods do the following:
  1. Open up the Project Settings dialog and navigate to Code Style -> Java.
  2. Click the Code Generation tab.
  3. In here you will find the Final modifier section.
  4. Check the "Make generated parameters final" option.

If you now generate methods, IntelliJ will insert the final keyword before every parameter.

Besides adding the final keyword to every parameter in generated methods you can also add the final keyword to parameters in existing methods. To do this, do the following:
  1. Open up the settings dialog and click Inspections (in Project settings)
  2. Click copy to copy the Project default inspections and name the profile anything you want.
  3. Click the Rest to Empty button to disable all inspections. Disabling all inspections is a quick way to only focus on a specific inspection if you want to apply just that specific inspection.
  4. Enter 'final' in the search box
  5. Under the "Code style issues" check the following rule: "Local variable or parameter can be final".
  6. On the left make sure the option "Report method parameters" and/or "Report Local Variables".
  7. Click OK.
  8. Click Analyse -> Inspect code in the menu.
  9. Make sure you select the Whole project and select the profile created in step 2.
  10. Click OK.
  11. In the inspection dialog you see all methods where the parameter could be final.
  12. Right click the inspection and click "Apply fix 'Accept suggested final modifier'" to add the final modifier to all method parameters where it can be final.

Please note that the inspection does not add the final keyword to parameters which are reassigned since this gives compile errors. You could argue if this should be included in the inspection as well. I personally feel this can be handy to add final to all parameters regardless if they are changed or not. You can then afterwards fix all compile time issues you may have.
Post a Comment