Search code examples
javacode-cleanup

Java Code clean up for utility if statements


the code below is an extract of a function which loads my config file into setting objects. In the beginning there are two if statements which first check if the config file object is null (handled beforehand) and if so prints an error message in the log and returns the function, and the second one does the same but checks if the file actually has some content. I would like to know if there is a cleaner way to do those two if statements, in terms of code length and readability.

@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());
    }
}

Solution

  • I would not try to make it more compact, but split it into clear separate steps:

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