What do you do when you realize you've written unmaintainable code?
Refactor. Basically, you sit down with the code and improve it. But you don't try to improve it by adding new functionality, or making it faster; you do it by making the code more maintainable. Usually this involves making it simpler, smaller, less redundant, more modular, and so on.

The fact that you recognize good code from bad means you can accomplish it. What you need is a systematic approach: prepare tests first, then decide what you're going to try to attack. After each substantial change, re-test it to make sure you didn't break anything. Where you stop is a matter of judgement: how big it is, how much time you have, and similar considerations.

Refactoring can be a very educational experience. It forces you to consider alternate ways of doing things. And after a few rounds, you'll get in the habit of using the more maintainable solutions in the first place. Plus, it matures you to admit, "Yes, I wrote really nasty code." ;-)

I can recommend a good book about refactoring by Martin Fowler. The examples are in Java, but the principles in the first part of the book apply to most languages.


In reply to Re: What to do when you realize you've written bad code by VSarkiss
in thread What to do when you realize you've written bad code by l2kashe

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.