I frequently refactor my code and legacy code. Why should I be scared of refactoring ?

I see refactoring as analogous to balancing my budget. Inevitably expenses are added, so I'm always looking for strategies to make it leaner. If I don't refactor code, I'll likely go "overbudget" - the code will be cost-prohibitive to maintain.

The time I find best to start the refactoring process is the day after I get the code passing all tests; I still understand all the nuances of the problem-space, and I still remember the reasons I used particular flows and structures. At that point I comment the code with data-flow and reentrancy assertions and write tests to reflect those assertions, then fiddle until the code passes the existing unit tests and the new assertions.

1 week after that, I go in as if I'd never seen the code. I do speed and memory profiling. I try to imagine various new scenarios for use of the code (in whole or in part).

If the code needs refactoring for efficiency, I do it as a matter of policy - by that point I've already done most of what's necessary to make such a refactoring successful.

If the code could be refactored to make it more flexible for re-use, I examine my schedule to see whether the refactoring is likely to take up more time than I have available in the short term. If I don't have time, I'll re-evaluate again in 1 week. Otherwise... refactor!.

I hope this exposition has not been overly boring.

-David


In reply to Re: On the fear of re-factoring code by erroneousBollock
in thread On the fear of re-factoring code by deorth

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.