Home > Blogs > Refactoring and Performance

Refactoring and Performance

Refactoring is a book I've wanted to read for a long time, but never got around to until recently. I thought that I probably already knew the gist of everything I would read, thus it was not a priority. However, it did not take long for the text to surprise me and make me re-think some things that I have taken for granted.

The book's "First Example" show some typical code that needs to be refactored. The code calculates the bill for people renting videos. It's kind of funny to think about people renting videos, showing the age of the book, but it is the code that is important. One of the refactorings that Fowler makes is to replace a single loop that calculates charges and renter points with a couple of methods. From an OOP perspective, it is a sound move -- he moves those calculations to the class where they belong. However the net effect -- as Fowler points out -- is to perform a loop three times instead of one time.

Fowler states that a lot of people would not even consider this refactoring because of this obvious performance issue. I have to admit that I am one of those people. However, as Fowler points out, it is still a good refactoring. I like to say make your code work first, and make it fast second. Fowler's point is that if you make your code good, then making it fast is a lot easier. For example, if those loops prove to costly, then obviously you could store some of the calculations in the class as a private attribute. This makes sense inside the appropriate class and is not too hard to do.

So how would I have handled this refactoring? I probably would have created a single, not-so-obvious method with a name like "calculate" and private fields for total charges and total renter points, in the Customer class. The calculate method would set those fields in one loop. Now if you did performance tuning on top of Fowler's code, I think you might wind up with something similar. But it is harder refactoring, and it may not really be necessary. That is an important lesson. Make it work. Make it good. Make it fast.

Become an InformIT Member

Take advantage of special member promotions, everyday discounts, quick access to saved content, and more! Join Today.