Wednesday, June 10, 2009

Here's a particularly egregious example of code that was much more complicated than it needed to be.

I'll also note that it duplicated a bunch of code from a factory class that had been first added a month before this code was first checked in, and that the factory class had been last updated two weeks before this code was checked in. I replaced the code after I noticed it a week and a half later. I reimplemented the guts of the factory class using the Spring Framework about 5 months later.

The code went something like this:

Class<Interface> clazz = (Class<Interface>) Class.forName(implementationClassName);
Constructor<Interface> constructor = clazz.getConstructor(...);
Object implementation = constructor.newInstance(...); // yes, it was declared as Object and not Interface
Method method = clazz.getMethod("knownMethodName", new Class[] { ... });
result = (cast) method.invoke(implementation, new Object[] { ... });

I've elided multiple try-catch blocks and comments such as "get the constructor from the handler class" and "get the [something or other] method". It was totally ridiculous.

I replaced it with something like:

result = InterfaceFactory.newInstance(implementationClassName, ...).knownMethodName(...);

No comments:

Post a Comment