Say I have a method that writes a string to a file:
public void write(String content, File out) {
// writes content to out
}
If I want to protect the parameters and ensure that they are not re-assigned a new value within this write
method, I can use the final
keyword to prevent this:
public void write(final String content, final File out) {
// writes content to out
}
From what I know of best practice (and this handy question here), this is a good thing - as it is not clear behaviour if a method modifies what it has been given. However, I do still understand that sometimes we will need to do this and so the functionality should be built in to Java to allow this.
My question is, why do I have to explicitly state that a parameter is final
and not the other way around? Why can't all method parameters (or even all parameters?) be implicitly final
- and I have to use a new Java keyword (for instanceunstable
) to explicitly be able to modify a parameter.
public String write(unstable String content, File out) {
// writes content to out
...
// then for some mad reason, this happens
content = "Done";
return content;
}
This could be passed along into the Javadoc so that a caller could explicitly know that a variable they are providing is not safe and will be modified.