重构此方法以降低其认知复杂性

时间:2018-05-28 08:25:48

标签: java

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

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

1 个答案:

答案 0 :(得分:2)

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