实用程序if语句的Java代码清理
下面的代码是一个函数的摘录,该函数将我的配置文件加载到设置对象中。在开头有两个if语句,它们首先检查config file对象是否为null(预先处理),如果为null,则在日志中打印一条错误消息并返回函数,第二个if语句执行相同的操作,但检查文件是否确实包含某些内容。我想知道,在代码长度和可读性方面,是否有更干净的方法来执行这两个if语句实用程序if语句的Java代码清理,java,code-cleanup,Java,Code Cleanup,下面的代码是一个函数的摘录,该函数将我的配置文件加载到设置对象中。在开头有两个if语句,它们首先检查config file对象是否为null(预先处理),如果为null,则在日志中打印一条错误消息并返回函数,第二个if语句执行相同的操作,但检查文件是否确实包含某些内容。我想知道,在代码长度和可读性方面,是否有更干净的方法来执行这两个if语句 @Override public void load() { if(file == null) { Log.error("
@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());
}
}
我不会试图使其更紧凑,而是将其分为明确的单独步骤:
public void load() {
if (!isValid(file)) {
return;
}
try {
read(file);
} catch (Exception e) {
// you usually log once with the complete exception and the message
Log.error("Error while loading the config file.", e);
}
}
private boolean isValid(MyFile file) {
if(file == null) {
Log.error("Object of config file is null!");
return false;
}
if(file.length() == 0) {
Log.error("Config file that exists is empty!");
return false;
}
return true;
}
private void read(MyFile file) {
// If you are using Java 8 or up, try-with-resources can auto close Closeables
try (FileReader reader = file.getFileReader(true)) {
while (reader.nextLine() != null) {
String key = reader.getNextString(), value = reader.getNextString();
// Do not omit the curly braces or a puppy will die
for (Setting setting : SettingsManager.instance.getSettings()) {
if (setting.getKey().equalsIgnoreCase(key)) {
setting.setValue(value);
}
}
}
}
Log.info("Config file was loaded successfully!");
}
如果(file==null | | file.length()==0){//Error code},则
如何?代码读取器中存在资源泄漏-在发生异常时不会关闭对象。考虑使用finally块。另外,整个try/catch{}可以写入if((file!=null)&&file.exists()&&file.length()>0){…}中。如果这样做有效,那么它应该处于启用状态