One effective technique for writing good code is chuck out code that's not working out too well. This is probablly one of the harder techniques to get to grips with. It's pretty easy to understand the idea, however, when your actually writing code and have created a bit of a mess it is easy to convince yourself to keep tinkering to get it right. Or, alternatively, you figure you can refactor your way to good code. Usually there's something in your head that tells you that the approach your taking sucks but you know you can hack it to make it work.
Don't. Cut your losses and kill the code.
The fact you realise that it sucks means you probablly understand the problem a lot better than when you first started. Thats the key thing, that's actually the hard part, writing code when you know exactly what it has to do is often reasonably trvial once your confident in a particular language.
You might salvage the unit tests, but sometimes its better to biff those out also. This gives you the chance to rethink your approach afresh.
For starters you might just comment out your code "just in case". This is especially true if the code you have generated is quite complex. Your not quite sure if you can recreate it. However this is often a big stinky code smell and most often you will find a simpler soloution when you do it again. So once you get used to backing out of code then you'll just delete it.