I have been used to do some refactorings by introducing compilation errors. For example, if I want to remove a field from my class and make it a parameter to some methods, I usually remove the field first, which causes a compilation error for the class. Then I would introduce the parameter to my methods, which would break callers. And so on. This usually gave me a sense of security. I haven't actually read any books (yet) about refactoring, but I used to think this is a relatively safe way of doing it. But I wonder, is it really safe? Or is it a bad way of doing things?
One should not start refactoring unless he has a clear purpose in mind. Once the purpose has been accomplished, one is done. There is probably not an explicit 10 point check list to tell you when you are done, but most people can determine if they are being productive or just playing.
The most common cause of refactoring problems is not in the code -- it's a lack of proper tools. Refactoring nearly always includes renaming variables and methods, changing method signatures, and moving things around. Trying to make all these changes by hand can easily lead to disaster.
Fixing any bugs that you find along the way is not refactoring. Optimization is not refactoring. Tightening up error handling and adding defensive code is not refactoring. Making the code more testable is not refactoring – although this may happen as the result of refactoring.
The best time for refactoring is before adding new features or updates to existing code. Doing so can help improve the product's quality. By cleaning the code base before adding new features or updates, it helps to make the product more robust and easier to use in the future.
I never rely on simple compilation when refactoring, the code can compile but bugs might have been introduced.
I think that only writing some unit tests for the methods or classes that you want to refactor will be the best, then by running the test after the refactoring you'll be sure that no bugs were introduced.
I'm not saying go to Test Driven Development, just write the unit tests to get the necessary confidence that you need to refactor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With