Archive for the ‘Refactoring’ Category.

Excruciatingly Obvious Ruminations About Extract Method

Last week I had the opportunity to use the Extract Method refactoring. I’m generally a proponent of this refactoring – I think it’s a worthy goal to have more numerous, shorter methods, if that means that any given method is more quickly understood at a glance.

The code I had, after I had made some further complicating modifications, looked something like this.

I didn’t like the nearly-duplicate logic duplicated in the if-else block. I felt there was an extract method in there somewhere. However, it took me three times before I came up with a solution I liked, which is basically this:

I won’t bore you with the first two tries, but I’ll just say that for some reason the use of the third defaultTo arg didn’t occur to me right away, but was just what I needed to make the method calls nice and clean.

After I looked at the finished product, I was reminded that another benefit of Extract Method is that differing levels of abstraction are separated. In this case, the determination of whether WebLogic or Tomcat is in use, and what delimiter and default to use to determine the web app name, is a sort of mid-level policy. The nuts and bolts of parsing that app name out of a String instance is the lowest level of abstraction and, in my opinion, is better off not inlined into the policy code. In a similar vein, we would not want to see the implementation of String.substring() inlined into every single invocation of that method.

I don’t think my finished product is perfect. I think maybe there’s a better method name that could be used, which communicates the intent better, because it’s not perfectly obvious at a glance why the delimiter and default need to be passed to the method and what happens. But then again that’s part of the point, we don’t want to know the details. Meanwhile, on the plus side, we see that the same method is invoked in both cases, and only the arguments differ, so it’s obvious that there’s a pattern there which wasn’t necessarily obvious before.