This week, I worked on my project to refactor the codes for better maintainability in this commit. No new feature was added this week, but simply refactoring the codes made me feel good, by making the codes cleaner and more organized.
My refactoring process consists of mainly three parts,
- Extract code blocks into functions
- Refactor functions into classes
- Split the classes/functions into a separate file
I have repeated these steps for the argument parser, file content writer, and utility functions, now the codes are more readable. Extracting code blocks into functions improves the readability through abstraction, by hiding the details in codes, to allow us to focus on the overall logic flow of the main program. While refactoring functions into classes and splitting classes/functions into separate file allow me or future reviewers to focus only on the concerned parts by simply checking the relevant files, without having to read irrelevant details from other modules.
It was also noted that refactoring is not simply copy and pasting codes into separate files, syntax and the structure of codes may need slight adjustmenta. For example, when extracting code blocks to functions, the order of codes and condition checking may need to change, due to the use of return value instead of direct value assignment in code block. We should also be mindful of the exception handling, to ensure that throwing of exception is not missing. When functions are refactored to a class, a class object needs to be instantiated first before the class functions can be called. When splitting classes/functions into different files, the modules used should also be moved.
I have learnt to use git rebase
to squash multiple relevant commits into one, and git commit --amend
to edit the commit message. This can be a good way to organize the commit history, such that relevant commits having the same purpose can be grouped together, which can save time reading redundant commit history in future maintenance work.
Top comments (0)