June 07, 2011

Programming Anti-patterns

TMTOWTDI is often a trait of the problem that one is trying to solve, and not just the programming language being used. Solutions can be simple or complicated, efficient or inefficient and an invisible constraint of solving problems (implementing) is to find a solution that is in the neighborhood of simple and efficient. Internet helps in finding a solution that is popular or common, and not necessarily efficient.

When I started noticing lots of inefficient code and identified a few patterns across them, I embarked on a study of programming anti-patterns. The definition I follow is, "Commonly used inefficient programming practices to which better alternatives are known".

For my study I also need anti-patterns to be easily identifiable so that dummies like yours truly can identify them, for comparisons between anti-patterns and alternatives to be easily made, for static code analyzers to fish them out, and for changes to be relatively easy to implement. Bill Pugh once said (probably in this) that the goal of FindBugs is to find bugs that are one step away from compilers. My goal is similar, only my focus is on efficiency more than correctness. (There are other kinds of anti-patterns, most famously design anti-patterns, but my focus at present is on code efficiency itself.)

The problem of looking for a new anti-pattern (source) is non-trivial. A few guidelines that I am considering are:
1. Accessing memory << Calling a function << Forking a process: There are exceptions to this, but to my understanding it's mostly true. Smaller the operation that needs to be performed, larger the overhead of doing it in round-about methods. It's easier to check the forking of processes as explained earlier. Re-calling functions is apprently not very uncommon, but I'm yet to scratch the surface of calling functions vis-a-vis reusing their return values.
2. Legacy code: In my experience code is more often added to, and old code isn't as much "updated" as is "fixed". Resultantly, "legacy code" to a great extent contains code written ages ago. Languages on the other hand constantly evolve, and the things of interest here are newly introduced, say functions, that can do something better. (The first example that comes to my mind is the rampant presence of += for string concatenation in Java instead of StringBuffer or StringBuilder.)
3. n00bs: Bill Pugh mentioned in the same video that, not surprisingly, people new to a programming language are a great source of learning how not to do something (even though it is not syntactically wrong). I have personally seen this to be true. A trickier subset of this is anti-patterns brought in when one migrates from one programming language to another.

No comments:

Post a Comment