Search code examples
javafinal

Duplicate final declaration, should it be avoided?


If we have a private final instance variable to be passed to a private method, do we redeclare it with final modifier in the function when passed as parameter ? eg:

public class GraphAlgo {

  private final source;

  public GraphAlgo(source) {
     this.source = source
  }

  public void runAlgo() {
     runAlgoUsingSource(source);
  } 

  private runAlgoUsingSource(final source) {  // here final is declared on a final field
    //-- whatever.
  } 
}

Dont declare final for a parameter which is already a final. Advantage. prevents duplicate final modifier Disadvantage: Does not provide explicit picture, eg: if GraphAlgo is a 10000 line code then simply looking at the function 'runAlgoUsingSource' he would not have visual access to understand if 'source' was final or not.

Whats the general convention in this case ?


Solution

  • Here, source is already an instance variable. Why pass it to a method? For that matter, here,

    private runAlgoUsingSource(final source) {
    

    source is now another variable, scoped as a local variable, and named the same as your instance variable. (It also needs a type.) Whether this local source is final does not depend on whether this.source (the instance variable) is final.