Sunday, February 25, 2007

Is Decomposition Readable

Last week I claimed that you could make code more readable by decomposing methods into smaller, well-named methods, which are effectively self-documented. This week I am going to challenge that claim.

On the surface, the technique I showed last week looks good. Each individual method is short enough that you can grasp all of its semantics at once. Its easy to see if each method does what it is supposed to do. With such short well-defined methods bugs should be scarce and easy to find, right?

Unfortunately this isn't true. As I found out last week when I was testing the code, there was a bug in it. The bug was in the original version, so at least I hadn't introduced a new bug. However, when I asked myself honestly which version would be easier to debug, I wasn't sure. The problem with such decomposition is that your code is now scattered about. If you want to trace through code you have to now jump around many methods. While each individual method is short, the algorithm as a whole may now be too large to fit on your screen at once. This makes it harder to debug.

subtle details matterThe problem is that decomposition doesn't actually solve one of the problems of programming - subtle details matter. What happens when you choose the smallest or largest element as your pivot? What happens if your split point is the first or last element in the array? Boundary conditions always matter, but when you decompose a problem, now the subunits have to handle the boundary conditions in a consistent manner. So while decomposition can make some bugs easier to avoid, it can add an insidious subtle new bug of inconsistency.

Note that this problem is not limited to decomposing a single function like I did last week. This problem is endemic to component based software whether your components are methods, objects, or entire software products. Even if every component is bug free, the system will still contain bugs if the components have different assumptions. From experience I can say that some of these bugs can be a doozie.

Despite the objections I have just raised, I still think decomposition is a good thing. However, it is no silver bullet and you have to watch out for its pitfalls.

No comments: