Java 实用程序 if 语句的代码清理

Java Code clean up for utility if statements

下面的代码是一个函数的摘录,它将我的配置文件加载到设置对象中。一开始有两个 if 语句,首先检查配置文件对象是否为空(事先处理),如果是,则在日志和 returns 函数中打印一条错误消息,第二个做同样的事情,但检查如果文件实际上有一些内容。我想知道在代码长度和可读性方面是否有更简洁的方法来执行这两个 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());
    }
}

我不会试图让它更紧凑,而是将它分成明确的独立步骤:

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!");
}