DEV Community

Alexander Samaniego
Alexander Samaniego

Posted on

DPS909 Blog - Lab 5: Refactoring & Rewriting Git History

This week in my Open-Source course (DPS909), we were introduced to the concept of code refactoring and git history rewriting via git rebase. The purpose of this lab was to help us to practice refactoring existing code to make it easier to read, maintain, and more modular. Using git rebase showed us how to rewrite git history to simplify commits.

GitHub Repo: https://github.com/alexsam29/ssg-cli-tool
Refactoring commit: https://github.com/alexsam29/ssg-cli-tool/commit/cb9bb6e4278680df99c9202ca17288703cebe885

Refactoring Process

To start refactoring my code, I first went through my code and used the 'Prettier' Visual Studio extension to format the code and adjust any lines to make it more readable. This included things like wrapping code where necessary, adding spaces between lines, adding indents, etc.

Next, I focused on extracting functions from my existing code. I had functions within main() that made the code look a bit messy, so I took them out of main() and created new files that contained functions for similar tasks. create.js is where I house the functions to create HTML files and the index page. While ssgStart.js is where command-line arguments are parsed and read. I also created a file called utils.js that contains miscellaneous functions for verifying files types and file paths.

I tried to reduce code duplication by creating new functions whenever I see lines of code repeated more than once. Originally I had similar lines of code for reading one file and reading more than one file in a directory. I created the readFromFile() function in ssgStat.js to reduce redundant code.

Lastly, I went through all my variable names and renamed some for more clarity. I tried to use similar variable names in functions where data is passed through, in order to be consistent. I also removed some unused packages so that unnecessary files are not installed when running the program.

While refactoring, I did encounter some bugs that I didn't find before. Instead of fixing it in the same branch, I created a new branch based off of main and fixed it there. I then merged it into the main branch before I was done with refactoring.

Rewriting Git History

Once I was done refactoring, I used git rebase to squash all of the refactoring commits into a single commit. I then amended the commit message using git commit --amend to include a summarized title and the changes I made in point form.

I didn't have much issues doing this, the only issue I encountered was a merge conflict. This was because of the bug I fixed earlier in a different branch, so I had to resolve the conflict before continuing the rebase and squash. Once resolved, all my changes were in a single commit and was able to be merged into main problem-free.

Top comments (0)