In another part of the code for JSDoc that I had made a change several years back, I noticed a case of duplicate code. The code snippet below shows what was added/edited from the source file, and it is this snippet that we will walk through the improvements.

Here the duplicated code is used to make the name plural based on the last letter of the supplied name. The logic is simple; if the name ends in s then append “es” otherwise append “s.”

The new method created pluralize replaced the instances of duplicate code, and we now gain a clearer insight as to what is intended. Next, there is this ugly bit of code
name.charAt(0).toUpperCase() + name.slice(1) that capitalizes the name, but it is by no means readable for a person to understand that is what it is doing. So we extract that to a new method and update the code.

Now I want to address the if statement clause. The code is checking to see if the name exists in the array of already defined container names; if it doesn’t, we want to add the title to the navigation. To help make this more readable, we will extract this out to a helper function with a clear name to describe the intent.

Finally, I extract the code into another descriptive method addContainerToNavto help with understanding what this loop is performing. This extraction is debatable on whether it is needed or not, but I felt that I wanted the code to be more reader friendly so that any updates can be applied more quickly. Along with that extraction, I reduced the statements in the loops to single lines removing the name variable.

With the refactoring complete, and despite the heavy usage of global variables in this area of code, we have gained a clearer insight as to the intent. Stay tuned for next week’s split code, and see what intent we can learn from the source that gets its makeover.

If you have a snippet of code that you would like refactored on split code leave a comment below with the code snippet or link to where to obtain it.