DEV Community

Parsa Frahani
Parsa Frahani

Posted on

Clean Code Is Not Quick Code!πŸ’»

Good code Manners!
Most of us when we come back to our code after a 15m break, we can barely understand what is going on. or maybe if you change just one line the projects will stop working & you even don't know where you should fix. as Uncle Bob say's clean code is not quick code, it's smart code. so let me explain what I mean by smart.

Image description

What Is Smart Code

Have you ever rushed into writing code & feel lost when you come back to it later? It happens to the best of us. Deciphering your own quick code can be like solving a puzzle. But what if there were seven simple things you could do to make your code easy to understand at a glance?

Imagine looking at your code for just a moment and being able to continue where you left off. Picture your team feeling at ease while working on what you've created. In this blog, we'll explore these seven practices for smart & cleaner coding tips. Let's jump into the details:

1- Variable Naming:

Consider the importance of naming variables, especially in larger projects. Let's dive into an example. Imagine you have a variable that you want to pass as a parameter to a function and then log it. Here's the initial code:

const bb = "this is text";

const hrb = function (bbr) {
  console.log(bbr);
};

hrb(bb);
Enter fullscreen mode Exit fullscreen mode

In this snippet, the variable names (like bb and hrb) lack clear meaning. Now, picture having tons of code like this – it becomes a puzzle to figure out which function does what and which variable it's working with. now let's make this code better:

const text = "this is text";

const textHandler = function (data) {
  console.log(data);
};

textHandler(text);
Enter fullscreen mode Exit fullscreen mode

See? now we'll understand what is our function doing.

2- Small Refactors Are Way Better

So you are just coding without think about what the h*ll am I coding or will my team or even myself understand that last week what I worked on. new features will add to the project & it is getting bigger & bigger. then you realize what a mess! I can't figure out what is this code doing & it also got so much complicated. so now you do even a worse mistake. you plane to refactor all the project.
Think about it just for few seconds. wasn't it better to do small refactors as you go on with new features? you do a little coding then a little refactor and so on. so instead of ignoring your messy code, clean it as you go on!

3- Do Commenting Not Documenting

They are so different from each other & still some people mix these two things up.
You have to comment a little explonation about maybe a complicated functionality for your team or even yourself. not to explain the whole code! for example:

const text = "this is text";

// log what ever it gets
const textHandler = function (data) {
  console.log(data);
};

textHandler(text);
Enter fullscreen mode Exit fullscreen mode

This is commenting. now look at this:

const text = "this is text";

// This function will get the data that we pass to it and log it in the console.
const textHandler = function (data) {
  console.log(data);
};

textHandler(text);
Enter fullscreen mode Exit fullscreen mode

You are just overexplaining when you can simply just explain it with several words. this documenting will waste your team members & your time! try to explain the functionality a little bit & only do this if you think it will be confusing in the future.

4- Make Smart Functionalities For Your Project

Ever seen code with too many functions doing single tasks, making it unnecessarily complicated? That's what we call "beginner mode" coding – doubling the code length without a good reason. I'm not saying we shouldn't break down code (we'll talk about that in a bit), but let's avoid making things needlessly complex.
Imagine we're fetching data from an API, and for different button clicks, we want to show different things. Initially, our code looks like this:

import React, { useState } from "react";

function ShowActivity() {
   const [data, setData] = useState("");
  const [key, setKey] = useState();

  async function ShowActivity() {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const activity = await response.json();
    console.log(activity);
    setData(activity);
  }

  const ShowKey = function () {
    setKey(data.key);
  };

  return (
    <div className="parent">
      <h1>{data.activity}</h1>
      <h1>{key}</h1>
      <button onClick={() => ShowActivity()}>Show Activity</button>
      <button onClick={() => ShowKey()}>Show Status</button>
    </div>
  );
}

export default ShowActivity;
Enter fullscreen mode Exit fullscreen mode

in this React example we get a random activity and show it when we click the Show Activity button. this also will happen when we click the Key button too. it will show the activity key. It works, but we've created two separate functions for each button click, which is a bit repetitive. Now, let's make it simpler using one function:

import React, { useState } from "react";

function ShowActivity() {
  const [data, setData] = useState("");
  const [key, setKey] = useState();

  async function Checker(type) {
    const response = await fetch("https://www.boredapi.com/api/activity");
    const jsonData = await response.json();
    console.log(jsonData);

    if (type === "Activity") {
      return setData(jsonData.activity);
    } else if (type === "Key") {
      return setKey(jsonData.key);
    }
  }

  return (
    <div className="parent">
      <h1>{data}</h1>
      <h1>{key}</h1>
      <button onClick={() => Checker("Activity")}>Show Activity</button>
      <button onClick={() => Checker("Key")}>Show Key</button>
    </div>
  );
}

export default ShowActivity;
Enter fullscreen mode Exit fullscreen mode

As I said that not always put all the functionalities in one function is good! sometimes it can be so difficult to understand what is going on, so you have to devide the code to different functions & components. you might also don't see a lot of change in these two codes but the second code can be a way better & cleaner style than the first one, because I use a single function except two different functions for each event & if you want to use another parameter from API you just have to give it a type and check if the type is true rather than writing another function for just that one parameter.

5- Devide Responsibilities

As I said sometimes you have to devide your code to smaller pieces. this division can help your team & also yourself to understand each function is doing what & you can edit or add new features to your project way easier. but you have to name your functions in a way that by reading it's name, you understand what this function is doing. for example look at this code:

import React, { useState } from "react";

function App() {
  const [value, setValue] = useState("");
  const [data, setData] = useState([
    {
      activity: "Take a shower",
      description: "6AM in the morning",
      id: Math.random(),
      done: false,
      editable: false,
    },
  ]);

  const DoneHandler = function (todoId) {
    console.log(todoId);
  };

  const formHandler = function (e) {
    e.preventDefault();
    console.log(value);
    setData([
      {
        activity: value,
        description: "6AM in the morning",
        id: Math.random(),
        done: false,
        editable: false,
      },
      ...data,
    ]);

    setValue("");
  };

  return (
    <div className="main-container">
      <form className="conatiner" onSubmit={formHandler}>
        <input
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          className="container-input"
        />
        <button>Add</button>
      </form>
      <div>
        {data.map((i) => (
          <div className="todo" key={i.id} onClick={() => DoneHandler(i.id)}>
            <h1>{i.activity}</h1>
            <p>{i.description}</p>
            <label>{i.key}</label>
          </div>
        ))}
      </div>
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

It's so hard to figure out what exactly this code is doing. but as soon as I start to folder my code & components right (that I talk about in next one), reading the code get so much simpler. like this:

Image description
and devide code to small piece's. I do the functionalities here:

import React from "react";
import { useState } from "react";

function TMain(props) {
  const [value, setValue] = useState("");
  const [data, setData] = useState([
    {
      activity: "Take a shower",
      id: Math.random(),
      done: false,
      editable: false,
    },
  ]);

  const formHandler = function (e) {
    e.preventDefault();
    setData([
      {
        activity: value,
        description: "6AM in the morning",
        id: Math.random(),
        done: false,
        editable: false,
      },
      ...data,
    ]);

    setValue("");
  };

  return (
    <div className="main-container">
      <form className="conatiner" onSubmit={formHandler}>
        <input
          type="text"
          value={value}
          onChange={(e) => setValue(e.target.value)}
          className="container-input"
        />
        <button>Add</button>
      </form>
      <div>
        {data.map((i) => (
          <div
            className="todo"
            key={i.id}
            onClick={() => props.DoneHandler(i.id)}
          >
            <h1>{i.activity}</h1>
            <label>{i.key}</label>
          </div>
        ))}
      </div>
    </div>
  );
}

export default TMain;

Enter fullscreen mode Exit fullscreen mode

Then if anything click I log that It has been done here:

import React, { useState } from "react";
import TMain from "../Todo-Main/TMain";

function TFunc() {
  const DoneHandler = function (todoId) {
    console.log(`${todoId} Has been done`);
  };

  return (
    <div>
      <TMain DoneHandler={DoneHandler} />
    </div>
  );
}

export default TFunc;

Enter fullscreen mode Exit fullscreen mode

& finally I use it in my App.jsx:

import React from "react";
import TFunc from "./Components/Todo-Functionality/TFunc";

function App() {
  return (
    <div>
      <TFunc />
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

In the store.js you can save your data in browser cache using Redux or Jotai or any library that you like.
This is an small example but in bigger projects it can really life saver!

6- Be Better At Foldering Your Components

Foldering is so important to find your code. for example think I foldered my components like this:

Image description
I really don't know each component is responsible for what task so I have to put a lot of time to read the code in each file & see if that is what I'm looking for. but I can manage it in a better way:

Image description
Now by just reading the folder's name I'll understand what each file is doing.

7- Do You Know How To Handle Errors?

So lot's of beginners just code without thinking about handling errors. but a pro coder think about this one too.
If our app runs to an error, the whole project will stops & you will see a blank page. this is so awful for user experience. you have to manage error somehow that the user still use the website. you can use try/catch functionality or error boundaries or use the react error boundaries package or any way that you are comfortable with.

Conclusion

What I tried to talk in this blog was all about experiences that most of programmers as well as me had all the time, also the most popular way that all of the programmers do to keep they code creative & clean is SOLID Principles. so it have 5 stages that help you write better code. if you are interested you can read about it here.
**

Was this blog helpful?
Or can it be better?
Let me know in the commentsπŸ™.
**

Top comments (0)