Thursday, January 8, 2009

Essential Software Refactorings: Compose Method

Joshua Kerievsky introduced a refactoring in his (great) book Refactoring to Patterns, which involves a practice I believe strongly in. The refactoring is called Compose Method. (Spoiler: It is really all about using short and descriptive methods.)

The technique is to transform complex logic into a number of self-explanatory methods. The whole point is to increase understandability, and by that also maintainability.

Here's a simple example taken from the industrial logic catalog page for this refactoring. You have a complex method. To increase clarity, you refactor out the individual parts into smaller methods, making the logic easier to understand (I don't fully agree with the coding standard though):

The main advantage with this approach is that core logic will be more readable and maintainable. A disadvantage is that classes will be very fragmented, which can be annoying. It can also affect debugging, since logic is so decentralized.

In terms of length of methods, Joshua defines composed methods as usually being about five lines long, rarely over ten.

Long methods have many undesirable properties, like being harder to understand, harder to refactor and containing duplicated logic.

No comments: