07 February 2006

Hack of the day

Well, this hasn't happened in a while. I had an idea, wrote it up in vi, then compiled and ran it, and it compiled cleanly and worked the first time! Obviously it's a trivial example, but it's kind of neat, so I thought I'd share.

Background: On my current project, we have some boilerplate logging code that has to go into every method. It looks something like this:
logEvent("Module", ErrorConstants.EVENT_START, "Method name");
I got a comment on a code review that I should be defining string constants for my module and method names, since string constants should never be directly used in code (yes, that's the kind of shop we have here...)

The idea: I had had another idea regarding allocation tracing, and I remember that (since Java 1.4) you could get access to the call stack via a Throwable. A quick glance at the JavaDocs showed that you can get both the class and method names from the stack trace. This led to the quick&dirty code shown here:


private String getMethodName() {
Throwable t = new Throwable();
StackTraceElement[] ste = t.getStackTrace();

String methodName = ste[1].getMethodName();

return methodName;
}

private String getModuleName() {
Throwable t = new Throwable();
StackTraceElement[] ste = t.getStackTrace();

String moduleName = ste[1].getClassName();

return moduleName;
}


Quick & dirty == no JavaDoc or comments. Could be worse, I could have written it all on one line!

Denoumont: "Warning: may contain code which is too intense for young programmers". Turns our my solution (replacing all hard-coded strings with dynamic code to obtain the module and method names) was too...something for my team. They never really said what, just that they didn't think it was a good idea. This is a CMM Level 5 crew, and they don't really accept outside ideas well. Oh well, it'll go into my bag of tricks, and I'm sure I'll find a use for it on another project.

No comments: