Home > Web Front-end > JS Tutorial > Don&#t Just Copy and Paste Code, Make It Reusable

Don&#t Just Copy and Paste Code, Make It Reusable

Susan Sarandon
Release: 2024-12-04 04:37:13
Original
358 people have browsed it

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.

Don

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;
}
Copy after login
Copy after login

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);
Copy after login
Copy after login

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(' ');
Copy after login

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");
Copy after login

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 calculateAreaRectangle(width: number, height: number): number {
    return width * height;
}

function calculateAreaTriangle(base: number, height: number): number {
    return 0.5 * base * height;
}
Copy after login
Copy after login

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

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);
Copy after login
Copy after login

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.

The above is the detailed content of Don&#t Just Copy and Paste Code, Make It Reusable. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template