If you dread or fear refactoring, it’s because your code is a big ugly mess.
If your code is a big ugly mess, it’s because you didn’t refactor soon enough or often enough.
To make your code not be a big ugly mess, you need to refactor it.
So, refactor every time you see the opportunity. Keep the code lean and pretty. Then refactoring stays simple and easy and doesn’t take long or hurt.
I say do this even if you feel mounting deadline pressure. In the long run, the gains in maintainability will far outweigh perceived slowdown of productivity. Working on maintainable code is far more productive than working on unmaintainable code.
Don’t ship messy code. Messy code hides many flaws. Flaws that you’ll need to fix sooner or later anyway. When you fix a mess, it’s a lot more work than fixing something that’s clean.
I’m guilty of not refactoring enough. It’s difficult when you have serious time pressures, but you know that writing that bolt on section of code is the wrong thing to do. Do you have any good recommended reading for refactoring well/appropriately/effectively? I have heard a lot about the book by Martin Fowler, but it’s still in my reading queue.
mgrecar
I don’t have a recommendation for a book specifically on refactoring, but there are a lot of good coding practices mentioned in Code Complete 2nd Edition.
I just wrote this as reminder to myself after spending a couple of days on refactoring Boobie Teeth. For that refactoring, the majority of what I did was to name things consistently and de-duplicate code.
Naming stuff consistently is important so you can keep it all straight and have a useful pattern for how you call stuff so you can do it from memory easily and avoid having to look up stuff. For variables and constants, names should be clear, meaningful, and not too long but not ultra abbreviated. For methods, I try to stick with “object.verbs_noun” or “object.verb”, depending on what the method does. When I’m in a hurry, I get inconsistent with this and it’s helpful to go back and tidy up.
I also did a lot of commenting my scripts so that I can easily remember what the script does and what my intent was when I wrote it.
For de-duplicating, I look for anything I do more than once, and refactor that into a method and then call the method twice instead of having the code in two places.
At times I also realize there is a better way to do something, and will rewrite for simplicity, performance, clarity, or improved safety. I don’t consider it to be refactoring unless I’m doing it for simplicity or clarity. Improving safety is usually pre-emptive debugging rather than refactoring, and improving performance is optimization. Sometimes these can come as consequences of refactoring (clearer code is usually easier to confirm to be safe, for example.)
Chris Sanyk