TurnKey Linux Virtual Appliance Library

My code refactoring algorithm

You're looking at a block of Python code. It's not immediately obvious what it does. It's sort of a mess and you realize it needs to be refactored. But how? What mental algorithm do you use?

Here's a trick I just figured out how to put into words. You first add comments to your code to make it easier to explain what it's doing in each part. Then you restructure the code until those comments are no longer necessary, using the comments as a guide to creating high level constructs that not only tuck complexity neatly away, they also explain the purpose of the surface.

What tricks do you use? 

You can get future posts delivered by email or good old-fashioned RSS.
TurnKey also has a presence on Google+, Twitter and Facebook.

Comments

Umh, I don't get what you

Umh, I don't get what you mean. If you always chose the right names for indentifiers and care about the common guidelines (not to much identation levels, useful sparse comments, etc) you don't need to refactor code because "readability" problems.

Liraz Siri's picture

Those are good rules of thumb

Implementing the "common guidelines" will bring you a long way, but I find that often isn't enough. The point I was trying to make is that truly readable code shouldn't need any explanation / comments. If it does, I take that as a signal that something is wrong.

Finally somone actually put

Finally somone actually put that in words :)

version control thinking helps

I find it useful to code when you know it is under version control. And you know you will eventually need to read patches and stuff. This makes you write shorter lines, break your expressions into more lines. This improves readability a lot.

Liraz Siri's picture

Version control essential

I started using version control about a decade ago (RCS integrated with Emacs) and found it immediately improved my productivity. By a lot. Suddenly it was much easier to spot exactly what I had changed since the last revision. Nowadays I try to make all my commits self-contained and self-documenting. Thankfully I don't use RCS any more. Git is much nicer.

Post new comment

The content of this field is kept private and will not be shown publicly. If you have a Gravatar account, used to display your avatar.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Allowed HTML tags: <a> <p> <span> <div> <h1> <h2> <h3> <h4> <h5> <h6> <img> <map> <area> <hr> <br> <br /> <ul> <ol> <li> <dl> <dt> <dd> <table> <tr> <td> <em> <b> <u> <i> <strong> <font> <del> <ins> <sub> <sup> <quote> <blockquote> <pre> <address> <code> <cite> <strike> <caption>

More information about formatting options

Leave this field empty. It's part of a security mechanism.
(Dear spammers: moderators are notified of all new posts. Spam is deleted immediately)