# The Krubner Law Of Ugly Code

(written by lawrence krubner, however indented passages are often quotes). You can contact lawrence at: lawrence@krubner.com, or follow me on Twitter.

The Krubner Law Of Ugly Code states that any computer programming language that has a “return” keyword will tend to be ugly. “Tend” means the tendency is there, though of course, as I’m sure hundreds will rush to remind me, you can write beautiful code in any language.

Here is a simple example from a well-respected project. Here the return is used in a guard clause. This is good code, for the Java language, in that it puts the guard clauses at the top of the function, so they are obvious. That is best practice. Still the code is ugly. If I was writing this in Clojure, or any language that supported pattern matching, the if statements would become part of the function signature. (If you are about to say “Clojure does not support pattern matching” please note I’m thinking of defun.)

   public static void unescapeJava(Writer out, String str) throws IOException {
if (out == null) {
throw new IllegalArgumentException("The Writer must not be null");
}
if (str == null) {
return;
}
int sz = str.length();
StringBuffer unicode = new StringBuffer(4);
boolean inUnicode = false;
for (int i = 0; i < sz; i++) {
char ch = str.charAt(i);
if (inUnicode) {
// if in unicode, then we're reading unicode
// values in somehow
unicode.append(ch);
if (unicode.length() == 4) {
// unicode now contains the four hex digits
// which represents our unicode character
try {
int value = Integer.parseInt(unicode.toString(), 16);
out.write((char) value);
unicode.setLength(0);
inUnicode = false;
} catch (NumberFormatException nfe) {
throw new NestableRuntimeException("Unable to parse unicode value: " + unicode, nfe);
}
}
continue;
}
// handle an escaped value
switch (ch) {
case '\\':
out.write('\\');
break;
case '\'':
out.write('\'');
break;
case '\"':
out.write('"');
break;
case 'r':
out.write('\r');
break;
case 'f':
out.write('\f');
break;
case 't':
out.write('\t');
break;
case 'n':
out.write('\n');
break;
case 'b':
out.write('\b');
break;
case 'u':
{
// uh-oh, we're in unicode country....
inUnicode = true;
break;
}
default :
out.write(ch);
break;
}
continue;
} else if (ch == '\\') {
continue;
}
out.write(ch);
}
// then we're in the weird case of a \ at the end of the
// string, let's output it anyway.
out.write('\\');
}
}


I've seen much worse than this, especially when dealing with PHP code. I've seen PHP functions with 35 return statements.

I invite you to post examples in the comments.

### Post external references

1. 1
http://grepcode.com/file_/repo1.maven.org/maven2/commons-lang/commons-lang/2.1/org/apache/commons/lang/StringEscapeUtils.java/?v=source
2. 2
https://github.com/killme2008/defun
Source