Ankur Sharma
Ankur Sharma

Reputation: 538

Java check style : Final Parameter reference variable assignment

I am working on resolving Checkstyle warnings in a Java project.

Suppose this is the method i have:

public SomeObject someObjectBehavior(SomeObject oldSomeObject,
    SomeObject newSomeObject) {

    if(oldSomeObject == null) { 
        oldSomeObject = newSomeObject; 
    } 
}

When I enable the Checkstyle, it notifies

Parameter oldSomeObject should be final

Parameter newSomeObject should be final

When I convert both the parameters like this:

public SomeObject someObjectBehavior(final SomeObject oldSomeObject,
    final SomeObject newSomeObject) {

    if(oldSomeObject == null) {
        oldSomeObject = newSomeObject;  //Assignment operation
    } 
}

So, now assignment operation is not possible, there is a error in Java code

The final local variable oldSomeObject cannot be assigned. It must be blank and not using a compound assignment.

If any one of you have faced this, so please help, as I am trying to resolve all the Checkstyle issues.

Thank You

Regards

Ankur Sharma

Upvotes: 2

Views: 7025

Answers (4)

Andre Piwoni
Andre Piwoni

Reputation: 11

This checkstyle rule is a perfect example of shoot first (gotta be final else it's wrong) and ask questions later (does re-assignment actually takes place).

Upvotes: -3

Keppil
Keppil

Reputation: 46219

The example method you provide

public SomeObject someObjectBehavior(final SomeObject oldSomeObject,final SomeObject newSomeObject) { 
    if(oldSomeObject == null) { 
        oldSomeObject = newSomeObject;  //Assignment operation
    } 
}

is a perfect example of why making your parameters final is a Good Idea. Without making your variables final, you might not realize that your method does nothing, since reassigning a parameter reference doesn't change anything outside of your method.

Upvotes: 4

koljaTM
koljaTM

Reputation: 10262

The main reason for defining the parameters as final is to avoid unintentionally overwriting them later. If you define them final you can always be sure that the parameter is always what was given into the method in the first place.

It is better style to use a new local variable if you want to change the value. In many cases assigning variables only once makes the code much more readable. It's not always possible but often it is.

Try something like

Object realObject;
if (oldSomeObject != null) { 
  realObject = oldSomeObject;
} else {
  realObject = newSomeObject;
}

Upvotes: 3

Blank Chisui
Blank Chisui

Reputation: 1073

It is considered bad style to reassign parameters. You are supposed to create a new local variable.

Upvotes: 6

Related Questions