Java 约定--将局部变量命名为与字段相同
Java convention--naming a local variable the same as field
正在编写一个程序来解释文本文件中的一行。
想知道我是否应该将方法 'parseWordData' 中的局部变量命名为
scannedWord
与 word
相反,因为 word
已经是 class 字段。
只要我声明一个新变量而不是重新分配旧变量,一切都应该没问题...对吗?
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)
}
不用担心逻辑,我只是想知道这样命名会不会令人困惑或者在java
中是禁忌
在 Java 中,标准做法是将 参数 命名为与
中的字段相同
- 构造函数
- setter 方法
前提是这些方法将字段设置为与参数具有相同的值。在这种情况下,您会看到类似
的行
this.word = word;
在您的构造函数或您的 setter 方法中。
在所有其他情况下您应该避免使用与字段名称相同的参数名称或局部变量名称。这只会导致混乱。这是标准做法。
所以在你的例子中,是的,你应该使用 scannedWord
或类似的东西来表示从输入中扫描的单词。
正在编写一个程序来解释文本文件中的一行。
想知道我是否应该将方法 'parseWordData' 中的局部变量命名为 scannedWord
与 word
相反,因为 word
已经是 class 字段。
只要我声明一个新变量而不是重新分配旧变量,一切都应该没问题...对吗?
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)
}
不用担心逻辑,我只是想知道这样命名会不会令人困惑或者在java
中是禁忌在 Java 中,标准做法是将 参数 命名为与
中的字段相同- 构造函数
- setter 方法
前提是这些方法将字段设置为与参数具有相同的值。在这种情况下,您会看到类似
的行this.word = word;
在您的构造函数或您的 setter 方法中。
在所有其他情况下您应该避免使用与字段名称相同的参数名称或局部变量名称。这只会导致混乱。这是标准做法。
所以在你的例子中,是的,你应该使用 scannedWord
或类似的东西来表示从输入中扫描的单词。