平衡抽象层次

public String evaluate() {
        String result = templateText;
        for (Entry<String, String> entry : variables.entrySet()) {
            String regex = "\\$\\{" + entry.getKey() + "\\}";
            result = result.replaceAll(regex, entry.getValue());
        }
        checkForMissingValue(result);
        return result;
    }

    private void checkForMissingValue(String result) {
        if (result.matches(".*\\$\\{.+\\}.*")) {
            throw new MissValueException();
        }
    }
方法evaluate做了两件事情,替换变量和检查缺失的变量值,两件事的抽象层次完全不一样,为了平衡方法抽象层次,我会将代码调整为:
public String evaluate() {
        String result = replaceVariables();
        checkForMissingValue(result);
        return result;
    }

    private String replaceVariables() {
        String result = templateText;
        for (Entry<String, String> entry : variables.entrySet()) {
            String regex = "\\$\\{" + entry.getKey() + "\\}";
            result = result.replaceAll(regex, entry.getValue());
        }
        return result;
    }

    private void checkForMissingValue(String result) {
        if (result.matches(".*\\$\\{.+\\}.*")) {
            throw new MissValueException();
        }
    }

你可能感兴趣的:(平衡抽象层次)