Java约定——将局部变量命名为与字段相同的变量

Java约定——将局部变量命名为与字段相同的变量,java,naming-conventions,local-variables,Java,Naming Conventions,Local Variables,编写解释文本文件中的一行的程序。 想知道我是否应该在方法“parseWordData”中将局部变量命名为类似于scannedWord的名称,因为word已经是一个类字段。 只要我声明了一个新变量而不是重新分配旧变量,一切都会很好…对吗 public class WordData { private String word; private int index; private LinkedList<Integer> list; private boolean pathFound;

编写解释文本文件中的一行的程序。
想知道我是否应该在方法“parseWordData”中将局部变量命名为类似于
scannedWord
的名称,因为
word
已经是一个类字段。
只要我声明了一个新变量而不是重新分配旧变量,一切都会很好…对吗

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)
}
公共类WordData{
私有字符串字;
私有整数索引;
私有链接列表;
找到私有布尔路径;
PublicWordData(字符串字、整数索引、LinkedList列表、布尔路径查找){
这个单词=单词;
这个指数=指数;
this.list=列表;
this.pathfund=pathfund;
}
公共WordData解析WordData(字符串行){
扫描仪扫描=新扫描仪(行);
int index=scan.nextInt();
String word=scan.next();
//预目标和子目标
LinkedList=新建LinkedList();
while(scan.hasNextInt()){
//添加到LinkedList
}
返回新的WordData(单词、索引、列表、false)
}

不用担心逻辑,我只想知道这样命名是否会让人困惑,或者在java中是否是禁忌

  • 建设者
  • setter方法
假设这些方法将字段设置为与参数具有相同的值

this.word = word;
在构造函数或setter方法中

在所有其他情况下,应避免参数名或局部变量名与字段名相同。这只会导致混淆。这是标准做法


因此,在您的示例中,是的,您应该对从输入中扫描的单词使用
scannedWord
或类似的东西。

要添加到这个答案中,请尝试在Java中搜索“实例变量隐藏”。这将解释这种情况。