Question

Let's say i have a method being called by passing an object.

public String retrieveXyz(Criteria criteria){

//get some info out of criteria and do something.

}

Is it a good practice to make the criteria final so that this handler cannot be used to target some other object other than the passed one or its an overhead as this doesn't protect the object state from getting changed.

public String retrieveXyz(final Criteria criteria){

//get some info out of criteria and do something.

}
Was it helpful?

Solution

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.


  1. Is it a good practice to change arguments in Java

OTHER TIPS

final in method parameter has no difference in most situations, you still won't be able to change its address inside the method but its attributes can be changed.

You might need to use final sometimes when you have something like below, run method won't be compile unless a is final, though you can assign it to other final object etc, but why bother that.

public void foo(final String a) {
    SwingUtilities.invokeLater(new Runnable() {
        public void run() {
            System.out.print(a);
        }
    }); 
}

PMD would advise you to do this: http://pmd.sourceforge.net/pmd-4.3/rules/optimizations.html

This allows for useful optimisations, and warns when you might do something undesirable in your code. IDEs like Eclipse and Intellij have options to do this automatically, and it is sensible to do so.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top