Tuesday, June 1, 2010

Anti-Patterns

While most good software development teams have knowledge of software patterns, I still don't hear teams frequently talking about anti-patterns. I'm not really sure why that is. It seems logical to me that if patterns are a way of communicating common ways of doing things, anti-patterns should be in a programmer's language to communicate how not to do things, and to identify problematic areas of code. Anti-patterns do also extend beyond code into management, organization, etc, but I will just focus on coding anti-patterns.

One that I see so frequently is copy-paste-mutate. That is, when a developer copies a block of code, pastes it somewhere else, and changes it slightly. Most of it is duplicated and now mistakes are duplicates and testing must be duplicated (if you are testing). If you find yourself copying and pasting, stop. Should the functionality be in an abstract class? Should it be in a utility class? Regardless of where it needs to go, it shouldn't be copied and pasted.

Another recurring anti-pattern is see deals with poor exception handling. It's way too common to see e.printStackTrace() or LOGGER.error(e) (or even worse, an empty catch block) as a solution to error handling. If you can "handle" the exception by just printing it out, maybe it shouldn't be an exception at all. Exceptions should indicate errors (i.e. exceptional cases) and your program generally shouldn't be able to continue to operate normally when one occurs without proper handling.

Wikipedia has a large list of anti-patterns here http://en.wikipedia.org/wiki/Anti-pattern#Software_design_anti-patterns. Take a look and see which of these traps you're falling into.