What does it mean to refactor code?
Essentially, re-write it while making it functionally equal.
refactoring implies making a series of small, controlled changes to your code without changing any of the functionality. the aim of refactoring is to improve the design, readability and maintainability of your code.
You can re-write it for a myriad reasons, but re-factoring is done to make it more object oriented, more readable, more modular, more testable, etc. etc.!!
Re-factoring has an implied meaning of making improvements to meet the kinds of goals mentioned above. Re-write is a crude term and does not imply any goal in mind.
ideally, you should be able to prove that each step in a series of refactoring steps are non-function changing. e.g. if you perform a rename of a class using an IDE where non of the code uses reflection, then that is a proven safe refactoring step.
So if I looked at my code and noticed me copy-and-pasting stuff, and decide to simply encapsulate crucial stuff into a function and simply reuse that function instead, would that be code refactoring?
Yes. It is.
yes - as long as you make that change in a series of small safe steps.
asnaseer - sorry, re-factoring does not have to be done in small and safe steps. It is prudent to do so, but the term does not imply such approach.
I think it's nice to replace paragraphs of code with one simple function call
I beg to differ @GT
a lot of people mis-use the term refactoring
People who re-factor code also try to bring it into a test framework to ensure functional preservation and also make the code testable during future changes. So, re-factoring and unit test framework go hand-in-hand most of the times.
if you follow the TDD/BDD principals (i.e. Test Driven Development or Behaviour Driven Development), then your tests are always written first. the tests basically "drive" the design of your code.
the typical cycle is: - write tests that fail - implement until tests pass - refactor to remove code smells - repeat
but that's an infinite loop :(
:-) - you would exit the loop as soon as you get to a point where you feel there is no more refactoring that you can do.
if you are interested here are a couple of very good books on the subject: 1. Refactoring: improving the design of existing code by Martin Fowler and Kent Beck 2. Growing Object-Oriented Software, Guided by Tests by Steve Freeman and Nat Pryce
Or, much sooner when it is good enough and the point of diminishing returns kicks in. Time cost and opportunity cost of that time to build new functionality need to be weighed in at some point.
Join our real-time social learning platform and learn together with your friends!