【发布时间】:2021-04-06 15:48:51
【问题描述】:
下面的代码是一个函数的摘录,它将我的配置文件加载到设置对象中。一开始有两个 if 语句,首先检查配置文件对象是否为空(预先处理),如果是则在日志中打印错误消息并返回函数,第二个执行相同但检查文件是否实际有一些内容。我想知道在代码长度和可读性方面是否有更简洁的方法来执行这两个 if 语句。
@Override
public void load() {
if(file == null) {
Log.error("Object of config file is null!");
return;
}
if(file.length() == 0) {
Log.error("Config file that exists is empty!");
return;
}
try {
FileReader reader = file.getFileReader(true);
while (reader.nextLine() != null) {
String key = reader.getNextString(), value = reader.getNextString();
for (Setting setting : SettingsManager.instance.getSettings())
if (setting.getKey().equalsIgnoreCase(key)) setting.setValue(value);
}
reader.close();
Log.info("Config file was loaded successfully!");
} catch (Exception ex) {
Log.error("Error while loading the config file.");
Log.error(ex.getMessage());
}
}
【问题讨论】:
-
if(file == null || file.length() == 0) { //Error code }怎么样? -
您的代码阅读器对象中存在资源泄漏,在发生异常时不会关闭。考虑使用 finally 块。整个 try/catch{} 也可以写在 if ( (file != null) && file.exists() && file.length() > 0) { ... }
-
如果这行得通,那么它应该在codereview.stackexchange.com
标签: java code-cleanup