the code structure tends to atrophy. Refactoring is the process of fixing a bad or chaotic design. Strictly speaking, refactoring means reorganizing something but leaving its function in the world unchanged. Anything which depended on that thing to behave a certain way will never be disappointed. The notion of strictness was introduced in order to prevent the addition of bugs. Pure refactoring isn’t always necessary (or desired); if you try to do it, you may have to fend off some the possible improvements you notice. Normally people will aim to improve and change meaning (hopefully for the better). It’s more efficient than doing one and then the other, usually. Sometimes it lands you in trouble, so the extremely cautious will refactor first and then add and then refactor. Refactoring is usually motivated by noticing a code smell. For example the method at hand may be very long, or it may be a near duplicate of another nearby method. Once recognized, such problems can be addressed by refactoring the source code, or transforming it into a new form that behaves the same as before but that no longer “smells”. For a long routine, one or more smaller subroutines can be extracted; or for duplicate routines, the duplication can be removed and replaced with one shared function. Failure to perform refactoring can result in accumulating technical debt. There are two general categories of benefits to the activity of refactoring.
Maintainability: It is easier to fix bugs because the source code is easy to read and the intent of its author is easy to grasp. This might be achieved by reducing large monolithic routines into a set of individually concise, well-named, single-purpose methods. It might be achieved by moving a method to a more appropriate class, or by removing misleading comments.
Extensibility: It is easier to extend the capabilities of the application if it uses recognizable design patterns, and it provides some flexibility where none before may have existed. Before refactoring a section of code, a solid set of automatic unit tests is needed. The tests should demonstrate in a few seconds  that the behavior of the module is correct. The process is then an iterative cycle of making a small program transformation, testing it to ensure correctness, and making another small transformation. If at any point a test fails, the last small change is undone and repeated in a different way. Through many small steps the program moves from where it was to where you want it to be. Proponents of extreme programming and other agile describe this activity as an integral part of the software development cycle. When not to refactor? Sometimes you should throw things out and start again. Sometimes you are too close to a deadline.