Final keyword is not used enough

Mostly when I see the final keyword, it is for defining a constant reference, whereas this is not the main use of “final”.

Remember that the final keyword is applied to references but not to objects. That means objects are mutable but we can’t reaffect an instance to the reference.
This behavior is the same if I use final on variables or parameters.

Now check this code :

void m(String p) {
    // Here my code
}

No problem, I’ve “p” parameter of type String and I can use it, but I can reaffect “p” :

void m(String p) {
    p = "new value";
    // Here my code
}

What’s the problem ? There is no problem, this code compiles and runs fine, but the question is why should I do that ?
Because reaffectation is like creating a new variable, I probably have other choices that reaffect the “p” reference.
This reaffectation can be difficult to see and It’s always a good idea to have immutable references when you can to avoid side effects.

We can talk about final members. If there is no reason to change a reference, make it final as in the following code :

public class C {
    private final List<String> data = new ArrayList<String>();

    public void m(final String p) {
        // Code here
    }
}

.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s