I added the getCValue
method to reduce the cyclomatic complexity, but the cyclomatic complexity still persists. How can I reduce it? Can I change this code using regular expressions? if I can how?
public final class UnicodeEscapeUtil { public static String unicodeUnescape(String unicodeEscapedMessage) { if (unicodeEscapedMessage == null || "".equals(unicodeEscapedMessage.trim())) { return ""; } char[] inputCharArray = unicodeEscapedMessage.trim().toCharArray(); int lengthOfInput = inputCharArray.length; char[] outputCharArray = new char[lengthOfInput]; int lengthOfOutput = 0; int index = 0; while (index < lengthOfInput) { char c = inputCharArray[index++]; if (c == '\\') { c = inputCharArray[index++]; if (c == 'u') { int value = 0; for (int i = 0; i < 4; i++) { c = inputCharArray[index++]; value = getCValue(value,c); } outputCharArray[lengthOfOutput++] = (char) value; } else { if (c == 't') { c = '\t'; } else if (c == 'r') { c = '\r'; } else if (c == 'n') { c = '\n'; } else if (c == 'f') { c = '\f'; } else { //log } outputCharArray[lengthOfOutput++] = c; } } else { outputCharArray[lengthOfOutput++] = c; } } return new String(outputCharArray, 0, lengthOfOutput); }
After the getCValue function cyclomatic complexity is reduced: 22 to the 15 allows.
private static int getCValue(int value, int c){ switch (c) { case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': case '8': case '9': value = (value << 4) + c - '0'; break; case 'a': case 'b': case 'c': case 'd': case 'e': case 'f': value = (value << 4) + 10 + c - 'a'; break; case 'A': case 'B': case 'C': case 'D': case 'E': case 'F': value = (value << 4) + 10 + c - 'A'; break; default: throw new IllegalArgumentException("Malformed \\uxxxx encoding."); } return value; }