24

I don't know if it's just with me, but when I start refactoring some code I waste a lot time doing that and it never ends.

Every time I read the code again, I find something that can be improved, code refactoring is like my brain into a infinite loop and the end conditional is reached randomly with no satisfaction.

So, how much time should I dedicate to refactoring my code?

1

1 Answer 1

24

If you treat refactoring as its own thing, rather than as part of the process of development, then it can become never ending.

If you follow the test driven development approach of red, green, refactor, then you typically won't have to spend a lot of time refactoring for two reasons:

  1. You'll be refactoring as you go, so it shouldn't become a mammoth task, just another small step in the TDD cycle.

  2. The internal "pressure" to get the next test written will keep your refactoring efforts to a sensible level.

If you are working with legacy code, then follow Uncle Bob's "Boy scout rule." Timebox yourself to a short time period (say, 30 minutes) and make your goal to check in the code in a cleaner state than it was before. Each time you have to touch the code, you will leave it slightly better. Over time, the most modified code will be the most readable and well factored in your codebase.

1
  • 1
    "If you treat refactoring as its own thing, rather than as part of the process of development, then it can become never ending" ... Otoh, "It seems that perfection is attained, not when there is nothing more to add, but when there is nothing more to take away" - Antoine de Saint Exupéry ;-)
    – Mawg
    Apr 28, 2015 at 12:25

Not the answer you're looking for? Browse other questions tagged or ask your own question.