【问题标题】:Java Code clean up for utility if statements [closed]Java代码清理实用程序if语句[关闭]
【发布时间】: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


【解决方案1】:

我不会尝试使其更紧凑,而是将其拆分为清晰的单独步骤:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-09
    • 1970-01-01
    • 2013-11-04
    相关资源
    最近更新 更多