DEV Community

Minh Hang Nguyen
Minh Hang Nguyen

Posted on

Code Refactoring and Rebase

As new features are added to the tool, I realized that the logic is not clear anymore and some parts were duplicated, making it inefficient and hard to maintain. This time, I decided to focus on removing those duplications by moving the statements to the appropriate place and extracting function for reusability. All the refactoring was done through a single commit with the help of git rebase.

Improvements

Firstly, I could see that I was validating the input, output and stylesheet options several times in different modules. I reread the code and found that some of them were unnecessary and I could easily remove them while modifying the arguments passed in function.

Secondly, in the processFile.js, a lot of the logic was similar. I decided to extract a function called getOutputFileName() which will generate the output file name based on the type of input. Since we have different types of input file extensions (.txt and .md), if there's no such function, I'll have to repeat the code several times, especially when the tool is scaled up to support other extensions as well.

Another thing I noticed was that the process of convert .txt and .md have lots of things in common. Therefore, I only kept the different parts inside the if... else... block, and put the shared logic outside of the block.

Problems during refactoring

I had a problem while trying to move all the validations of input, output and stylesheet inside the processInput.js. The program crashed since that placement of the validations requires more checks to be done, which means even longer and harder-to-maintain code. I decided to abort that approach and tried to find another position that wouldn't affect the rest of the code. It turned out that putting the validations in index.js would not only solve the problem but also make the structure of the file more consistent.

git rebase

git rebase was very helpful in condensing git history. Before knowing about this, there were moments when I wish I didn't commit so early because I was having multiple commits to solve the same issue. Having separate commits for these changes are just not necessary. With git rebase, I don't have to worry about accidentally committing before the code is ready since I can always squash the related commits together amend the message with git comment --amend.

Discussion (0)