Sitemap
Better Programming

Advice for programmers.

Keeping Your Code DRY

Refactoring essentials

5 min readFeb 29, 2020

--

Press enter or click to view image in full size
Photo by Franck V. on Unsplash

Background

This past week, the majority of my time was spent on working on a coding challenge. It was definitely tough, from understanding the user stories to wireframing out the application to implementing the code to debugging.

There was a lot of going back and forth between my components. I was slowly starting to realize that when I changed one part of my code, I would need to change all the other parts of the code that was dependent on it.

By having a downstream effect of manual changes from changing one part of my code, this was violating the DRY (Don’t Repeat Yourself) principle.

When you initially write out your code, this may happen a lot more than you think. Keeping your code DRY is part of the refactoring process, so if you don’t catch it right away, that’s not a problem.

Keeping Your Code DRY Within a Component

The first time I realized I wasn’t keeping my code DRY was when I had to make a log-in form. The gist below shows the code for my log-in form.

Login Form Non-DRY

This is a generic form where you need to input your email and password. handleChange is the callback function that makes the form a controlled component.

If you are unfamiliar with a controlled component, it is essentially where the values from the React component are the same as what is shown on the DOM, adhering to the single source of truth principle.

Can you find where the code may not be DRY?

Hint: Take a look at the input attributes.

If you take a look at the input attributes and the switch/case statements, the strings “email” and “password” are repeated.

If you accidentally deleted a letter from those strings, the code will still compile, but now that would make debugging a nightmare when you need to send the email and password values to the back end.

Also, what if I decided to change my log-in form such that instead of using email as a credential, I wanted to use a username instead?

Now, I need to find all the places where “email” appears and change it to “username”. You might be thinking: “Wait, my text editor can find all instances of “name” and I can replace it all with “username” and call it a day.”

And I would say you are correct, but it doesn’t address the issue of any accidental errors mentioned in the previous paragraph.

So, how can this log-in form be DRY? You can save the repeated strings to a constant.

const EMAIL = "email"
const PASSWORD = "password"

This funnels all instances of those strings into a single source of truth, a constant. Please note that the constants are capitalized based on convention.

So now, if you replace all of the “email” and “password” strings with their respective constants, the code will look like the gist below.

Log-in Form DRY

How does this adjudicate the issue of accidental errors? If you make an error with the constant name (e.g., EMAIL to EMAL), JavaScript will have a compilation error as the incorrect named constant is not defined.

If you make an error on the string, or the value of the constant, you can exactly pinpoint where the error is because there is only one line where that value is declared. This saves time and effort looking thoroughly through your code for potential minor errors.

Keeping Your Code DRY Across Components

So far, we talked about being DRY within a component. But what if the same values are used throughout multiple components?

Get Samuel Guo’s stories in your inbox

Join Medium for free to get updates from this writer.

Let’s bring in another component for demonstration purposes. We will be re-using the log-in form as well since we’re familiar with it at this point.

Log-in Form with a fetch request
Friends component with a fetch request

In the log-in form, the only thing I added was the first half of the fetch request that includes the URL. The rest of the fetch request will not be applicable to this topic.

In the Friends component, it makes a fetch request to the back end when the component is mounted to retrieve all of the friends associated with the user that has an ID of 1.

Notice how our code isn’t DRY as soon as I introduced the Friends component. But how?

If you look at the fetch request in both components, the URL uses the same domain: http://localhost:3001. Typically, domain names never change, which is a perfect application of pulling out the domain portion of the URL and saving it as a constant, just like what we did before!

But wait, this is across components, not within the same component. Assigning the domain portion of the URL to a variable and using it once within the same component is redundant.

So, how can we save the domain URL and use it across multiple components? In the same way as we do with libraries, we can import them! But instead of having a library of variables, we can create a file that holds all of the constants, and import them as needed.

So, first, let’s create the constants file and put the domain URL in it.

Next, we import the DOMAIN constant in the files we need it in and then replace all instances of using http://localhost:3001 with DOMAIN.

Log-in form with the imported DOMAIN constant implemented
Friends component with the imported DOMAIN constant implemented

It was that easy keeping the code DRY across multiple components!

Leveraging Constants.js

At this point in the code, we made a separate file, Constants.js, to store constants that are used across multiple components.

The next question is this: “Do we want to use Constants.js to store constants that are only local to the component (e.g., the log-in form component) at this point in time?”

And the answer is…I don’t know. I can easily make the argument for both cases.

1. Storing all constants in Constants.js

By storing all constants in Constants.js, the file has only one responsibility. This also makes it easier to debug as the single source of truth for all constant values are in that file.

Scaleability will play a huge factor as well because if you were to create new components that use the same constants, we can directly import them and not have to worry about refactoring the component where the constants were first used at a local component level.

2. Storing only constants in Constants.js that are used across multiple components

This implies that the constants used in the local component level will only be used for that component. This narrows the scope of where the constants are used.

If you see the same constant in a different component, that can indicate the constant is being used incorrectly or the component may not need the constant to begin with.

In both cases, I believe a design decision will need to be made before implementing code.

If you change your mind mid-implementation, you will need to parse through all your components and determine whether the constants should be at a local level or within the constants file.

Conclusion

Keeping your code DRY avoids code smells. It maintains clean and concise code with minimal effort when it comes to debugging and minimizes repetition.

Keep in mind that you do not have to apply the DRY principle in the way I did. I’m sure that there are other ways to go about keeping code DRY so, as long as you’re not repeating yourself, you’re on the right track!

--

Samuel Guo
Samuel Guo

Written by Samuel Guo

Full stack software developer with experience in Javascript, React, Redux, and Ruby on Rails and a background in Mechanical Engineering.