-1

Writing a program that interprets a line from a text file.
Wondering if I should be naming the local variables in method 'parseWordData' something like
scannedWord as oppposed to word, because word is already a class field.
as long as I am declaring a new variable instead of reassigning the old one, everything should be fine...right?

public class WordData {

private String word;
private int index;
private LinkedList<Integer> list;
private boolean pathFound;

public WordData(String word, int index, LinkedList<Integer> list, boolean pathFound) {
    this.word = word;
    this.index = index;
    this.list = list;
    this.pathFound = pathFound;
}

public WordData parseWordData(String line){
    Scanner scan = new Scanner(line);
    int index = scan.nextInt();
    String word = scan.next();
    //precond and subGoal
    LinkedList<Integer> list = new LinkedList<Integer>();
    while(scan.hasNextInt()){
        //add to LinkedList
    }
    return new WordData(word, index, list, false)
}

dont worry about the logic, i just want to know if naming things like this will be confusing or is taboo in java

1 Answers1

6

In Java, it's standard practice to name parameters the same as fields in

  • constructors
  • setter methods

provided that these methods set the fields to have the same values as the parameters. In this case, you see lines like

this.word = word;

in your constructor or your setter method.

In all other cases you should avoid having parameter names or local variable names that are the same as field names. It only leads to confusion. This is standard practice.

So in your example, YES, you should use scannedWord or something similar for the word that's scanned from the input.

Dawood ibn Kareem
  • 77,785
  • 15
  • 98
  • 110
  • To add to this answer, try searching for 'instance variable hiding' in Java. That will explain this case if yours. – Tharun Nov 14 '17 at 18:58