0

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.

Rossiar
  • 157

1 Answers1

7

You seem to be under the misconception that when content is modified inside write, that modification is visible to the caller.

It is not.

It's when you write to properties on it that those changes are visible to the caller, but final does not protect against this in any way.

DeadMG
  • 36,914