If you mark a method parameter as final
, you can't modify the parameter's value within the scope of the method:
public void xyz(final String parameter) {
parameter = "..." //compiler error!
}
Understand that the value of parameter
is the reference to the object passed to the method, and not the value of the object itself.
By marking the method parameter as final
, the compiler will throw an error upon compilation. This serves as a reminder that you should not modify the value of the parameter within your method.
It's considered a bad practice to modify the original parameter within your method.[1]
If the value of the parameter can change to reference another object, it might not be immediately clear what object is being referenced at any given point within the body of your method.
Consider the following:
public void xyz(String parameter) {
//Complicated logic that might span 20-30 lines.
parameter = "Joe";
//More complicated logic that might span a few lines.
//New logic being added that needs reference to the value of the parameter.
}
In a complicated method, like above, it might be difficult for a programmer to identify what object parameter
references. Furthermore, if the programmer needs a reference to parameter
he no longer has one.
- Is it a good practice to change arguments in Java