🚨 Stop Making This Huge Coding Mistake: Centralize Your Code for Cleaner Projects Like a Pro! 🚨

Irfan Ali
Irfan Ali
Published inPro Tips & Tricks
Sep 23, 2024
2
1
🚨 Stop Making This Huge Coding Mistake: Centralize Your Code for Cleaner Projects Like a Pro! 🚨

I’ve seen this mistake far too often, developers (yes, even experienced ones) scatter libraries, API calls, constants, and configs all over their code without centralizing them. This seemingly small oversight is a basic etiquette of clean coding that has big consequences for the consistency and maintainability of your project. If you're guilty of this, it’s time for a wake-up call! 😬

🔴 The Problem:

  • Redefining libraries like Axios or Fetch in multiple places.
  • Hardcoding constants like URLs, API keys, and version numbers in different files.
  • Configs scattered throughout the codebase, leading to confusion.
  • Duplicating logic instead of centralizing it in helpers or utils.

This isn’t just a small slip-up—it’s a huge mistake that creates a maintenance nightmare as your project grows. You're sacrificing consistency and making your life harder with each new feature or bug fix. 🚫

Bad Code Example (Scattered and Unorganized):

1
2// app/page.tsx
3import axios from "axios";
4
5export async function generateMetadata() {
6  const response = await axios.get(
7    `https://jsonplaceholder.typicode.com/users/1`
8  );
9  return {
10    title: `${response.data.name} | Home Page`,
11    description: "Home Page Description",
12  };
13}
14
15export default async function Home() {
16  const response = await axios.get(
17    `https://jsonplaceholder.typicode.com/users/1`
18  );
19  const userData = response.data;
20
21  const today = new Date();
22  const formattedDate = `${today.getDate()}-${
23    today.getMonth() + 1
24  }-${today.getFullYear()}`;
25
26  return (
27    <div>
28      User {userData.name} Data Fetched on {formattedDate}
29    </div>
30  );
31}
32
33// app/todos/page.tsx
34import axios from "axios";
35
36export async function generateMetadata() {
37  const response = await axios.get(
38    `https://jsonplaceholder.typicode.com/users/1`
39  );
40  return {
41    title: `${response.data.name} | Todos Page`,
42    description: "Todos Page Description",
43  };
44}
45
46export default async function Todos() {
47  const response = await axios.get(
48    `https://jsonplaceholder.typicode.com/users/1`
49  );
50  const todosResponse = await axios.get(
51    `https://jsonplaceholder.typicode.com/todos`
52  );
53
54  const userData = response.data;
55
56  const today = new Date();
57  const formattedDate = `${today.getDate()}-${
58    today.getMonth() + 1
59  }-${today.getFullYear()}`;
60
61  return (
62    <div>
63      {todosResponse.data.length} Todos fetched by {userData.name} on{" "}
64      {formattedDate}
65    </div>
66  );
67}

What’s Wrong With This Code?

  • Redundant API Calls: We're fetching user data multiple times across different files.
  • Hardcoded API URLs: URLs are scattered across the app, making updates error-prone.
  • Duplicated Logic: Date formatting is repeated in both components.
  • No Reusability: There's no clear separation of concerns or centralization of logic.

🟢 The Solution: Centralize Everything for Consistency, Maintainability, and Less Code! 💡

Here's what you should be doing instead: centralize your libraries, API calls, constants, and even commonly used logic. This approach will:

  • Ensure consistency across your entire project. 🧩
  • Make maintenance easier—update it once, and it’s reflected everywhere! ⚙️
  • Keep your code cleaner and more organized, especially as your codebase scales. 📈
  • Reduce redundancy—write less code and avoid repetitive tasks. ✨

Good Code Example (Centralized and Organized):

1. Centralize Configuration:

In `config/index.ts`, centralize your base URLs and app-wide constants:

config/index.ts
1// Centralize all the configuration/envs here
2
3export const API_BASE_URL = process.env.API_BASE_URL; 
4export const APP_VERSION = '1.0.0';
5

2. Create a Centralized Axios Instance:

In `libs/axios.ts`, create a shared Axios instance:

libs/axios/index.ts
1import axios from 'axios';
2import { API_BASE_URL } from '@/config';
3
4export const apiAxios = axios.create({
5  baseURL: API_BASE_URL, // Centralized base URL from environment/configs
6});

3. Centralize User and Todo API Calls:

In `apis/users-api.ts` and `apis/todos-api.ts`, centralize API logic for users and todos:

1// apis/users-api.ts
2import { apiAxios } from "@/libs/axios";
3
4// Centralized all user related apis using the shared Axios instance
5export const getUser = async (userId: string) => {
6    try {
7        const response = await apiAxios.get(`/users/${userId}`);
8        return { success: true, data: response.data };
9    } catch (error) {
10        return { success: false, error };
11    }
12};
13
14// apis/todos-api.ts
15import { apiAxios } from "@/libs/axios";
16
17// Centralized all todos related apis using the shared Axios instance
18export const getTodos = async () => {
19    try {
20        const response = await apiAxios.get(`/todos`);
21        return { success: true, data: response.data };
22    } catch (error) {
23        return { success: false, error };
24    }
25};

4. Create Reusable Utility Functions:

In `utils/date-util.ts`, create a utility for formatting dates:

utils/date-util.ts
1export const formattedDate = (date = new Date()) => {
2    return new Intl.DateTimeFormat('en-US').format(date);
3};

5. Refactor Your Components:

Now, your `Home` and `Todos` components will look much cleaner:

1// app/page.tsx
2import { getUser } from "@/apis/users-api";
3import { formattedDate } from "@/utils/date-util";
4
5export async function generateMetadata() {
6  const userResponse = await getUser("1");
7
8  return {
9    title: `${
10      userResponse.success ? userResponse.data?.name : "Awesome App"
11    } | Home Page`,
12    description: "Home Page Description",
13  };
14}
15
16export default async function Home() {
17  const userResponse = await getUser("1");
18  const date = formattedDate();
19
20  return (
21    <div>
22      User {userResponse.data?.name} Data Fetched on {date}{" "}
23    </div>
24  );
25}
26
27// app/todos/page.tsx
28import { apiAxios } from "@/libs/axios";
29
30// Centralized all todos related apis using the shared Axios instance
31export const getTodos = async () => {
32    try {
33        const response = await apiAxios.get(`/todos`);
34        return { success: true, data: response.data };
35    } catch (error) {
36        return { success: false, error };
37    }
38};

Benefits of the Refactored Code:

  • Consistency: You now have a single source of truth for your API base URL and commonly used utilities.
  • Maintainability: If your API URL changes, you only need to update it in one place.
  • Cleaner Code: The components are now focused on rendering UI, with logic abstracted away.
  • Less Code: No more repeated Axios calls or duplicated logic. Your code is leaner and easier to manage.

⚠️ Reminder: Failing to centralize is a basic, yet critical mistake that makes your code messier and harder to manage. It’s time to level up your coding game and fix this today! 🚀

Centralize it once, and enjoy better organization, easier updates and a project that’s a breeze to manage. Your future self will thank you. 😉

Comments (1)


S

Safiullah

3 months ago

Very Helpfull!