On refactoring and code reuse

Categories Development, Java

Strolling through Google Reader, diagonally reading blog posts from the almost 1 hundred blogs that I tend to follow(1000+ unread 😉 ) a phrase jump started my brain.

Not ever line of code can be reused. A lot of web development is about crafting a very specific solution. Localization, error handling, and coding conventions introduce challenges.

This is part of a post from one of the Mozilla blogs that I’m following, namely the blog of Austin King.

Now, this is as straight forward and clear as it is correct, not ever line of code can be reused. Putting it out of its initial context (web development that is) and bringing it into to context of enterprise applications it becomes pure evil, used as an excuse to re-invent a perfectly good wheel.

Puzzle
Photo by tcp909

Some advice:

  • Reuse as much as you can, extracting recurring pieces of code as methods
  • If common code spawns between projects, always extract it in a common library
  • Run a copy-paste detector such as CPD. Extract the code to methods.
  • Try to keep your methods under a fixed number of lines, let’s say 20. Doing this will force you to extract consistent pieces of code in separate methods, making them more re-usable
  • Try to maintain low cyclomatic complexity. Use a metrics package such as PMD or Panopticode. Refactor complex methods to smaller, less complex chunks of reusable code.
  • If you have the feeling that it’s the second time you’ve written a piece of code, search for the first one, because it’s usually true.

Now go and read a good book about this kind of stuff. I recommend The Productive Programmer by Neal Ford. It’s an excellent book for beginners but don’t fear – it’s superb even if you’re an experienced developer, I caught some nice Groovy tips that made the reading worth while, maybe you’ll find something interesting too.

Leave a Reply

Your email address will not be published. Required fields are marked *