Wednesday, November 19, 2008

Refactoring:Compose Method

Today I applied this refactoring to extreme. Let's learn some theory about it after lots of practice. Below are all quoted from Refactoring to Patterns.

"You can't rapidly understand a method's logic.

Transform the logic into a small number of intention-revealing steps at the same level of detail. "

"A Composed Method is a small, simple method that you can understand in seconds. Do you write a lot of Composed Methods? I like to think I do, but I often find that I don't, at first. So I have to go back and refactor to this pattern. When my code has many Composed Methods, it tends to be easy to use, read, and extend."

For people who worry about performance issue, the book also clarify:

"Once you finish this refactoring, you will likely have numerous small, private methods that are called by your Composed Method. Some may consider such small methods to be a performance problem. They are only a performance problem when a profiler says they are. I rarely find that my worst performance problems relate to Composed Methods; they almost always relate to other coding problems."

Finally,
"
Benefits and Liabilities
+ Efficiently communicates what a method does and how it does what it does.
+ Simplifies a method by breaking it up into well-named chunks of behavior at the same level of detail.
– Can lead to an overabundance of small methods.
– Can make debugging difficult because logic is spread out across many small methods.
"

I think this is a technique we need to use in most of refactorings. Because a typical procedure program/code is usually hard to understand especially when the procedure is horribly long and contains lots of conditional logic.

No comments: