Don't Just Copy and Paste Code, Make It Reusable

estotriramdani

Esto Triramdani N

Posted on November 25, 2024

Don't Just Copy and Paste Code, Make It Reusable

Background

It’s perfectly normal to copy and paste code from the internet. In fact, most coding issues we face—whether bugs, styling challenges, or the need for a sleek page loader in plain CSS—often have solutions available online. We search for answers, and the internet offers a wealth of code snippets and guides. Of course, it’s essential to filter and verify these solutions to ensure they’re a good fit for our needs.

https://dev-to-uploads.s3.amazonaws.com/uploads/articles/ymjjuowk3hriep6l1x8z.png

When writing code, it’s easy to get swept up in the convenience of copying and pasting code. Over time, though, we may start to notice that our code has become messy and hard to maintain. The pattern often goes like this:

  1. We encounter a problem.
  2. Search for a solution online.
  3. Copy the code we find.
  4. Paste it into our codebase.
  5. Move on.

As mentioned earlier, there's a good chance we’ll eventually face the same issues again. This cycle repeats, and we end up revisiting and re-copying solutions without truly integrating or understanding them (the challenges others faced have now become our own 🤣). So, we return to Step 1: Encounter a problem—and the cycle continues.

Solution

To avoid this hell circle, DRY principle might be the solution. The DRY principle, which stands for "Don't Repeat Yourself", is a software development principle that aims to reduce code duplication and repetitive patterns. Applying DRY principle to your code will replace repetitive code and logic with modular and referenceable code. Or in this article, to avoid you back again from step 5 to step 1 for the same problem.

Let’s take a look these examples:

Using Functions to Avoid Repetition

Function come to solve repetitive code. It is defintely wrong if you write a function but you still left repetitive code in your codebase.

If you find similar blocks of logic being repeated, refactor them into a reusable function.

// Before

function calculateAreaRectangle(width: number, height: number): number {
    return width * height;
}

function calculateAreaTriangle(base: number, height: number): number {
    return 0.5 * base * height;
}
Enter fullscreen mode Exit fullscreen mode

Create a general-purpose function for area calculation.

// after

function calculateArea(shape: "rectangle" | "triangle", dimension1: number, dimension2: number): number {
    if (shape === "rectangle") return dimension1 * dimension2;
    if (shape === "triangle") return 0.5 * dimension1 * dimension2;
    throw new Error("Invalid shape");
}

// Usage
const rectangleArea = calculateArea("rectangle", 5, 10);
const triangleArea = calculateArea("triangle", 5, 10);
Enter fullscreen mode Exit fullscreen mode

Creating Utility Functions

I am still talking about function: creating an utility function is one of the way to achieve clean code. Example, if multiple parts of your code convert a string to title case, extract that into a utility function.

// before

let title1 = "hello world".split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
let title2 = "good morning".split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
Enter fullscreen mode Exit fullscreen mode

Consider to create a function to handle this problem.

// after
function toTitleCase(input: string): string {
    return input.split(' ').map(word => word[0].toUpperCase() + word.slice(1)).join(' ');
}

let title1 = toTitleCase("hello world");
let title2 = toTitleCase("good morning");
Enter fullscreen mode Exit fullscreen mode

Constants for Common Values

How many times you call an API which has the same endpoint? I believe, it is more than once.

If certain values like URLs or configuration options are used across your app, define them once as constants.

// before 

function getApiEndpoint() {
    return "https://api.example.com";
}

function fetchData() {
    return fetch("https://api.example.com/data");
}
Enter fullscreen mode Exit fullscreen mode

What if the backend changed the URL? If you are still write this code like the example above, you will change all the codes which contains the URL. It is a wise if you move the endpoint to a constant that you can change it once and all the API call still works because they follow the constant you have made.

// after

const API_ENDPOINT = "https://api.example.com";

function getApiEndpoint() {
    return API_ENDPOINT;
}

function fetchData() {
    return fetch(`${API_ENDPOINT}/data`);
}
Enter fullscreen mode Exit fullscreen mode

Got another idea?

Those examples are just a little to describe how important to keep our code to point and not keeping the repetitive code over and over again. Feel free to share in the comment box below your thought.

Summary

The DRY (Don't Repeat Yourself) principle is a fundamental coding practice that encourages developers to avoid redundancy by reusing code wherever possible. Applying DRY principles can significantly enhance maintainability, readability, and efficiency across a codebase, as it minimizes the number of places where changes need to be made when updates are required. The DRY principle is about creating reusable, maintainable code. By leveraging TypeScript's capabilities—like functions, generics, interfaces, and enums—you can keep your codebase clean and reduce redundancy.

💖 💪 🙅 🚩
estotriramdani
Esto Triramdani N

Posted on November 25, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related