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:
- Adding the final keyword to all methods generated with IntelliJ.
- Add the final keyword to existing methods.
To add the final keyword to parameters of generated methods do the following:
- Open up the Project Settings dialog and navigate to Code Style -> Java.
- Click the Code Generation tab.
- In here you will find the Final modifier section.
- 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:
- Open up the settings dialog and click Inspections (in Project settings)
- Click copy to copy the Project default inspections and name the profile anything you want.
- 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.
- Enter 'final' in the search box
- Under the "Code style issues" check the following rule: "Local variable or parameter can be final".
- On the left make sure the option "Report method parameters" and/or "Report Local Variables".
- Click OK.
- Click Analyse -> Inspect code in the menu.
- Make sure you select the Whole project and select the profile created in step 2.
- Click OK.
- In the inspection dialog you see all methods where the parameter could be final.
- 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.