The code of a living project tends always to chaos. The more features I add, the more complex it becomes. From time to time it’s necessary to refactor some parts.
Refactoring the code means review the existing code, extract duplicated code and remove unused features. This operation is never accepted by product owners, as it doesn’t produce any new feature. But refactoring the code base allows the developers to add more features faster. As there is less complexity, it’s easier to add more features and to understand the existing code.
In the following post, I’m listing 3 metrics that must trigger a refactoring operation.
It’s Hard To Read
I spend more time reading code than writing code. So, when a code is hard to read, it means that something must change.
Maybe I only need to rename variables and methods. Or clarify concepts.
This also applies when my code is hard to read for other people. I can easily read my code. I’ve been working on it several hours. But if the code reviews are hard to read, or the code is hard to understand when I explain it to somebody else, it’s time to refactor.
It’s Hard To Test
TDD (Test-Driven Development) is when I write tests before writing my code. But most of the time, I write my unit tests after writing my code.
There is no problem with that. The case is that I need to write some unit tests.
The problem comes when it’s hard to write the unit tests. It needs too many mocks, or to initialize too many objects in the database.
When I write unit tests, I clearly separate each test into the given-when-then blocks.
When I have too many mocks in the given block, or the assertions in the then block are complicated, it’s time to refactor.
How?
TDD is not the solution for everything. But it allows to write code and tests very clearly.
Using TDD, I perfectly see what I need as input and what I expect as output. But even if I don’t use TDD, that must be how I write unit tests.
When I refactor my code due to the complexity of my unit tests, I always start by identifying the inputs and outputs. And extract all the possible outside my method to test.
It Has No Boundaries
All the methods or processes have a similar structure:
- they fetch the data;
- they work the data;
- and they prepare the data to be returned.
When there is no more boundary between the pre-processing, processing and post-processing, it’s time to re-order the code.
Sometimes it’s a matter of extracting some lines in separated methods. And sometimes it’s a matter of move some lines up and down to clearly identify those steps.
Conclusion
When I work in Agile projects, I always book some time for refactoring. It doesn’t need to be too much, maybe a 10% of the time. But it should be done regularly.



Leave a comment