【发布时间】:2020-01-16 19:40:13
【问题描述】:
我有一个 LogAnalyzer 类,它查看 Web 服务器日志、创建 LogEntry 对象并将这些对象放入 HashMap 中进行分析。
我的 LogAnalyzer 类有以下字段:
private int totalVisits;
private int uniqueVisits;
private ArrayList<LogEntry> records;
private HashMap<String, ArrayList<LogEntry>> uniqueIPs; //<address, log entries>
private HashMap<String, ArrayList<LogEntry>> dailyRecords; // <date, log entries>
我的构造函数如下所示:
public LogAnalyzer() {
records = new ArrayList<>();
dailyRecords = new HashMap<>();
uniqueIPs = new HashMap<>();
}
然后我就有了这个方法:
public void initializeRecords(String path){
readFile(path); //reads the web log file and fills out the records and dailyRecords fields
getUniqueIPs(); //fills out the uniqueIPs HashMap field.
uniqueVisits = uniqueIPs.size(); //fills out the uniqueVisits field
totalVisits = records.size(); //fills out the totalVisits field
}
所以我的问题:
我已经读过(但不太明白)在构造函数中调用方法是“不好的”。然而,这里的构造函数似乎毫无意义,因为它实际上是 initializeRecords 完成了“创建”对象的所有有意义的工作。
我没有 Java 或编程背景,无法理解迄今为止找到的解释。有很多关于压倒一切的讨论,我认为这就是我不清楚的地方。我想知道为什么我要把我的构造函数和这个方法分开,用初学者可以理解的简单术语。
**编辑:** 这是 readFile() 的代码:
public void readFile(String filename) {
FileResource fr = new FileResource(filename);
for (String line : fr.lines()){
LogEntry le = WebLogParser.parseEntry(line);
String date = le.getAccessTime().toString().substring(4, 10);
if (dailyRecords.keySet().contains(date)){
dailyRecords.get(date).add(le);
}
else{
ArrayList<LogEntry> entries = new ArrayList<>();
entries.add(le);
dailyRecords.put(date, entries);
}
records.add(le);
}
【问题讨论】:
-
你从哪里读到在构造函数中调用方法不好?
-
请提供此结论的参考。
-
能否提供readFile方法的代码?
-
@mapeters stackoverflow.com/questions/5230565/…, stackoverflow.com/questions/51592673/…, stackoverflow.com/questions/18348797/… 是几个例子......显然这个问题之前已经问过,但我不明白答案。
-
您并没有调用任何实例方法,而是在初始化实例变量,其中之一稍后会被覆盖。你提到的最后一个问题是最好的,回复:可覆盖的方法和泄漏
this——这最终是你要问的。 稍后初始化你使用的变量是否有意义是一个观点和使用的问题。