使用getter一類我有讀取一個文件轉換成格式的類我想:當返回一個值或Java中
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;
}
}
我傳遞的路徑作爲參數(而不是通過構造函數),因爲,我不想實例化每次我改變路徑。但是我對於返回結果感到困惑?我是否應該將其存儲到類成員中,然後使用getter方法來訪問結果?或者這個班級是否高效?
這要看情況。你試圖達到什麼目的? – Arlind
我沒有看到任何問題,除了這個方法似乎並不涉及實例(這更多的是個人厭惡而不是實際的缺陷)。至於存儲在一個字段var,這取決於你的應用程序需要什麼 –
我想知道這實際上是否適用於面向對象的概念。這裏我只是封裝了一個函數。但是,那好嗎? –