What refactoring is
What is refactoring?
- It is changing the code without altering its behaviour and improving its current structure
- A good programmer is the one that write code that human can understand and it is easy to change
Why refactor is needed?
- Code needs to be easy to modify, to understand and to transmit intention of the feature
- A poorly designed system is hard to change
- Economical benefits are obtained due to features are delivered faster
Drawbacks of refactoring?
- Refactors that make code more understandable may introduce a decay on the performance. After the refactor, you can measure it with profilers.
- Stakeholders want code that works, not one that would please an academic
When to apply refactoring?
- When programming you have to add a new functionality or refactor. You need to choose if it is the moment of applying a refactor. Most of the times it will be.
- Follow the boyscout rule: leave code better than when you found it
- If some code is messy but doesn't affect the current development, it is not mandatory to refactor it
- Sometimes you can't refactor and code needs to be done from scratch
- Refactoring doesn't imply making changes foreseeing the future (Yagni, You Are not Gonna Need It)
How to apply effectively refactoring?
Refactor methodologies need to be applied in small substantial changes. Make a small modification, test it and commit it locally. If some error happens, rollback to previous commit
You need solid self-checking tests in order to make sure your changes do not break anything. Continuous integration is a great companion.
Complicated pieces of code need to be broken down and set a name for each of them
Legacy code without tests is a big drawback, you need tests
Most of IDEs will help you with refactoring
A refactor is needed when you identify a piece of code that may lead to some misunderstanding or improvement. It is also known as Code Smells
