Saturday, October 23, 2010

"Refactoring: Improving the Design of Existing Code" by Martin Fowler

So I started reading THE refactoring book. Admittedly I should have picked it up a long time ago, but now that I'm writing this blog, I have no excuse.

I'm on Chapter 1, and so far the book has met my expectations. It has confirmed the value of most of the techniques I've acquired through experience, and the principles behind them.

Here are some of the highlights in the very illustrative example that Fowler uses in Chapter 1.

  • Move code into a separate function
    • And make sure that the signature has the correct types
  • Rename variables to what makes sense
  • Functions that no longer reference the class that they're in, are good to move to another class
  • Function signatures can typically be reduced when we moved functions to the classes that are more relevant to them
  • After the function has been moved, we can either forward all calls to it from the original class, or replace all references to the original class's function to the new class's function
  • Getting rid of temporary variables
    • This is something I don't do as much because typically temp variables are easier to debug than function calls. 
    • Fowler uses the example: result += "\t" + ... + each.getCharge() + "\n"
    • I would very rarely want to place a direct function call inside a string concatenation like this for 3 reasons
      • It's easier to debug the value if it's on a separate line
      • The return value of the function might be needed again
      • The string concatenation code becomes shorter easier to read, if it's not infested with multiple function calls (and god forbid those functions also have side effects, but that's another story altogether)
  • Replacing switch / case statements with polymorphism
    • I have done this before, but I find the overhead to be prohibitive most of the time
    • This may be worth while if the switch / case statement has large chunks of code of 10+ lines for each major case, but if it's a 2 liner for each case, then both readability and performance might be better off with the switch / case, and the overhead of going to the polymorphic solution is not worth your while. 
Fowler also makes good use of UML class and sequence diagrams to illustrate the effect of each step of his refactoring. So far so good. 

No comments:

Post a Comment