DEV Community

Cover image for Code Custodian: A lesson in refactoring.
Andre Willomitzer
Andre Willomitzer

Posted on

Code Custodian: A lesson in refactoring.

The Story So Far...

When the OSD600 course began, we were asked to create a Static Site Generator tool to create HTML documents from txt files. Then, we were asked to add extra options to allow for customizing the HTML files such as stylesheet. As the weeks progress we added more and more features to the project. I noticed my code was following the same pattern for each of the operations, with minor tweaks in the HTML template based on the options passed in.

Improvements

The focus of my refactoring for this lab was making a module for my Yargs configuration options, and refactoring my repeated code into functions that can be called instead of retyping all the HTML template strings like so:
generatepara

Previously, instead of calling generatePara(), I would have had the split/map/join and regexp repeated inside each of the txt "if" statements checking file type. Furthermore, you may notice

let styles = argv.s ? `\n<link rel="stylesheet" href="${argv.s}">` : "";
Enter fullscreen mode Exit fullscreen mode

which previously was a statement checking

if(argv.s){render the whole html template + link tag}
Enter fullscreen mode Exit fullscreen mode

By doing it this improved way, I can simply add "styles" variable to my HTML template, and if it doesn't exist a blank string is added which produces nothing in the HTML. This allowed me to eliminate 2-3 repeated if statements and make the code much more readable.

I did the same thing in the Markdown sections and made a separate function to handle h1, h2, and p tags. I removed the repeated template code, added a function, and changed the styles tag as I did with txt.

yargsConfig.js

In terms of the Yargs code, I made a module and required it in my main file in order to get access to "argv" value. This helped me make my main textToHTML.js file much cleaner because the setup code for Yargs was put into it's own file and textToHTML.js just handles the file logic.

Squash... and not the vegetable.

Butternut Squash

At the end I had a total of 4 commits and used git rebase -i main to squash the changes into 1 commit. Overall the command was very intuitive and allowed me to pick my 1st commit and squash the others into it. I then went to rename the commit message so that they would all be under a single name of "Refactored textToHTML.js for modularity". A link to the final commit can be found here.

Thanks for reading!

Top comments (0)