DEV Community

CDPhu
CDPhu

Posted on

Refactoring Code

This is the 6th week of OSD600, and this week we have Lab 5 to complete. This lab is different from the previous labs we had, this week we are going to modify our code of SSG program and make it looks better. It's about refactoring our code.

Note: Due to the new features added to the program, the complexity of the code grew with it. We added new features and we created new code paths, functions, variables. It would be harder to control due to the new additions

Procedure

Step 1: Create a refactoring branch

Essentially, you have your cloned code, and within the terminal you type git checkout -b refactor in order to create a branch called refactor. to check type in git status.

Step 2: Go through the code

I went through my code, and looking through it, what I saw was a lot of of duplication. So I decided it would be a better idea converting the entire code as multiple functions that call on each other.

Step 3: Create Functions

  1. I created a function called "mdFileConverter" to store the code that adding a new feature to my SSG so that all --- in a Markdown file would get converted to an <hr> tag.
  2. I found that the way I try to convert a txt file to a html file is very similar the way I covert a md file to a html file. Therefore, I put then into a new function named htmlGen.
  3. I have duplicated logic and code for my program to convert a folder and a single file. In order to make my program with less duplication. I created a new function named htmlConverter to store the converting logic and code.
  4. instead of being just a global if statement, I changed the conversion into a function called convert() which would be called by the config file checker from Lab 4.

Step 4: Improving Variables

Since I updated my code with some new functions, it became more tidy. So, I changed fname to a more specific name fileName. It's way more clear than with the name fname.Also, I changed the variable stats to filePath so that it became easier to understand.

Step 5: Get rid of global variables

Finally, I removed all the global variables I had in my code. Instead of having global variables, I put those variables to each specific function that I will use them.

Step 6: Combine my commits

After updating my code, I use this command git rebase master -i to start an interactive rebase, and opening the editor. And then I overwrite the pick keyword to squash so that I can combine all the commits I had into 1 commit. Then I use the command git commit --amend to rename some of my commit descriptions. Last but not least, I merged my refactor branch to my main branch.

Final Thoughts

It was an interesting but good experience. All in all a good way to improve coding structure as well as making the code itself much easier to understand via converting it into separate functions.

Top comments (0)