It’s usually impossible to get things right first time. The solution needs refactoring. Refactoring is the action of improving the design of existing code without changing its behavior.
Refactoring does not fix bugs, but it may help find bugs by scrutinizing code. It may also reduce further bugs occurrence by cleaning-up code. Refactoring does not add new functionality to the system, but it will ease the further adding of new functionality.
why should you refactor?
- Refactoring helps to improve code readability and comprehensibility and makes it easier to add new code.
- It helps to simplify code structure, improve design quality
- It improves the maintainability of code.
When to refactor?
It is a good idea to refactor before modification or adding a new feature. Refactor when you are fixing a bug or doing a code review.
- If you have similar code in related sub-classes.
- Move common subset of code to super-class as a method.
- Subclass specific code can be implemented as overridden methods.
- A section of code with an explanatory comment can often be replaced by suitably named method.
- If code for a method is too long to understand easily, extract subparts as separate methods.
- Any section of code that needs commenting should be replaced by a method with a meaningful identifier.
- When a method uses data mostly from a different class, refactor it by moving method to the class responsible for most of the data.