我在重构这部分代码时遇到问题。如何降低此代码的认知复杂度

if (fieldseparator != null && !fieldseparator.isEmpty()) {
        if (fieldseparator.equals("\\t")) {
            delim = '\t';
        } else {
            // handling unicode separator
            Integer i = Ints.tryParse(fieldseparator);
            if (i != null) {
                fieldseparator = String.valueOf(Character.toChars(i));
                delim = fieldseparator.charAt(0);
            } else {
                delim = fieldseparator.charAt(0);
            }
        }
    }

最佳答案

public static Character getDelim(String fieldseparator, Character defaultDelim) {
    if (isNotEmpty(fieldseparator)) {
        return fieldseparator.equals("\\t") ? '\t' : getFromUnicode(fieldseparator);
    }
    return defaultDelim;
}

private static Character getFromUnicode(String fieldseparator) {
    Integer i = Ints.tryParse(fieldseparator);
    return i != null ? String.valueOf(Character.toChars(i)).charAt(0) : fieldseparator.charAt(0);
}

private static boolean isNotEmpty(String fieldseparator) {
    return fieldseparator != null && !fieldseparator.isEmpty();
}

10-06 06:05