Refactoring Tip

by Anthony Panozzo

When you have something like

// connect to database
code
code
code

This might be an indicator that you can extract the code under the comment into a separate method to make things clearer and more modular.

For example:

public Connection connectToDatabase(necessary parameters) {
    code
    code
    code
}

This is nice because it is just as readable, and it’s harder for the description of the code block to get out of sync with what the code actually does.

Between when I thought of this and when I actually published it, I read a similar blog post that confirmed this thought pattern. Fowler also talks about this in Refactoring.

previous post: Open Source for Retired People
next post: Help Me Figure Out What I Should Write About

Published on June 2nd, 2010 in category Coding

2 Comments
  1. I like to call this refactoring: “extract method from inline comment”. It’s a really useful one and is pretty harmless if you make sure to account for local variables.

  2. Anthony Panozzo permalink

    Thanks for the term to use Eric! I still see this in code that I look at, and it’s handy. I think the comment implies a semantic division, which is generally helpful to split out.

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS