在java中何时返回值或在类中使用getter
我有一个类可以将文件读入我想要的格式:在java中何时返回值或在类中使用getter,java,return-value,getter,Java,Return Value,Getter,我有一个类可以将文件读入我想要的格式: public class ProgramReader { public List<String> readFromFile(String path){ List<String> commands = null; try { commands = Files.lines(Paths.get(getClass().getResource(path).toURI()))
public class ProgramReader {
public List<String> readFromFile(String path){
List<String> commands = null;
try {
commands = Files.lines(Paths.get(getClass().getResource(path).toURI()))
.map(line -> line.split("\\s+")).flatMap(Arrays::stream)
.collect(Collectors.toList());
} catch (IOException e) {
System.err.println(e.getMessage());;
} catch (URISyntaxException e) {
e.printStackTrace();
}
return commands;
}
}
公共类程序读取器{
公共列表readFromFile(字符串路径){
List命令=null;
试一试{
commands=Files.lines(path.get(getClass().getResource(path.toURI()))
.map(行->行.split(\\s+)).flatMap(数组::流)
.collect(Collectors.toList());
}捕获(IOE异常){
System.err.println(e.getMessage());;
}捕获(URISyntaxException e){
e、 printStackTrace();
}
返回命令;
}
}
我将路径作为参数传递(而不是通过构造函数传递),因为我不想每次更改路径时都进行实例化。但我对返回结果感到困惑?我应该将其存储到类成员中,然后使用getter方法访问结果吗?或者这个类有效吗?根据您提供的代码示例,如果您不必多次访问同一个值,那么返回值而不保存它应该没有问题。如果必须多次访问相同的值,那么保存结果确实是个好主意 基本上,我可以看到三种方式:
地图
在这里,每次调用
readFromFile
时,实际上都会读取文件
另一个选项是保留结果,以便在多次调用该方法时不再读取该文件:
public class ProgramReader {
private String path;
private List<String> words = null;
public ProgramReader(String path) {
super();
this.path = path;
}
public List<String> getWords() {
if(words == null) {
words = readFromFile();
}
return words;
}
private List<String> readFromFile() {
// ...
}
}
公共类程序读取器{
私有字符串路径;
私有列表字=null;
公共程序读取器(字符串路径){
超级();
this.path=path;
}
公共列表getWords(){
if(words==null){
words=readFromFile();
}
返回单词;
}
私有列表readFromFile(){
// ...
}
}
视情况而定。你想实现什么?我看不出有任何问题,除了方法似乎与实例无关(这更多是个人的不喜欢,而不是实际的缺陷)。至于将其存储在字段变量中,这取决于你的应用程序需要什么,我想知道这是否真的适用于OO概念。这里我只是封装了一个函数。但这可以吗?我必须通过构造函数传递路径吗。那么,每次路径改变时,我不必实例化一个新对象吗?是的,你必须这样做。这些词与特定路径相关。非常感谢。这是有道理的。