DEV Community

Cover image for How to write clean and reusable code as a developer
Olaniran Olarotimi Ademola
Olaniran Olarotimi Ademola

Posted on • Updated on

How to write clean and reusable code as a developer

In the world of software development, we often hear developers talk about the importance of writing clean and reusable code. This article is here to help you understand the basics of creating code that not only works well but is also well-suited for practical use. Clean code is like creating a beautiful piece of art, a composition that's easy to understand, makes sense, and gives you a sense of satisfaction because of how elegant it is.
Here are some of the tips you should try out to be good at this art

Picking names for entities in your code that clearly show what they are is super important. It's like giving things the right labels. But, strangely, it can also be a big source of confusion for people working on the same code.
here is an example
code A


interface Subscription1{
payment:boolean
}
const subscription: Subscription1 = {
payment: true}
;
Enter fullscreen mode Exit fullscreen mode

code B

interface Subscription1{
payment:string
}
const subscription: Subscription1 = {
payment: "$20,000"}
;
Enter fullscreen mode Exit fullscreen mode

Analyzing code A and code B, in the absence of initially defined types, the data type of the 'payment' property may introduce confusion. It could represent a boolean or a string, and, in certain scenarios, even a date. To lessen this potential ambiguity, consider renaming 'payment' in code A to 'hasPaid' or another descriptive term that inherently implies a true or false response. For code B, renaming 'payment' to 'paymentAmount' can similarly resolve potential data type uncertainties. These renaming strategies enhance code clarity and reduce the risk of misinterpretation when working with these properties.
clean code A

interface Subscription1{
hasPaid:boolean
}
const subscription: Subscription1 = {
hasPaid: true}
;
Enter fullscreen mode Exit fullscreen mode

code B

interface Subscription1{
paymentAmount:string
}
const subscription: Subscription1 = {
paymentAmount: "$20,000"}
;
Enter fullscreen mode Exit fullscreen mode

Steer clear of employing double negations when dealing with negative variables, as it leads to code complexity. Using double negations complicates code comprehension, adding an unnecessary burden for developers. Clean code, in contrast, should prioritize simplicity, making it accessible and modifiable for all.
An example

function isNotEmpty(someArray) {
    if (!!(someArray)) {
        return true;
    } else {
        return false;
    }
}

const myArray = [1, 2, 3];

if (isNotEmpty(myArray)) {
    console.log("The array is not empty.");
} else {
    console.log("The array is empty.");
}

Enter fullscreen mode Exit fullscreen mode

A clean code update

function isNotEmpty(someArray) {
    return someArray;
}

const myArray = [1, 2, 3];

if (isNotEmpty(myArray)) {
    console.log("The array is not empty.");
} else {
    console.log("The array is empty.");
}

Enter fullscreen mode Exit fullscreen mode

In writing codes, and particularly when working with frameworks like React, it's important to declare complex functions before using them in other parts of your code. This practice helps maintain clean and readable code while avoiding potential issues related to variable hoisting and scope.

import React from 'react';

function MyComponent() {
  // Some code...

  const result = complexCalculation(5);

  // Render result and other elements...

  function complexCalculation(input) {
    // Complex logic...
    return input * 2;
  }

  return (
    <div>
      {result}
      {/* Render more components */}
    </div>
  );
}

export default MyComponent;

Enter fullscreen mode Exit fullscreen mode

modified code:

import React from 'react';

function complexCalculation(input) {
  // Complex logic...
  return input * 2;
}

function MyComponent() {
  // Some code...

  const result = complexCalculation(5);

  // Render result and other elements...

  return (
    <div>
      {result}
      {/* Render more components */}
    </div>
  );
}

export default MyComponent;


Enter fullscreen mode Exit fullscreen mode

In React, it's essential to adhere to the Single Responsibility Principle (SRP), which is a fundamental concept in software development. According to SRP, a component should have one primary responsibility or function. If you find that a component is doing more than one thing, it's a sign that you should consider breaking it into smaller, more focused components. Here's why this principle is crucial:

existing code

import React from 'react';

function UserProfile(props) {
  // Fetch user data, perform data formatting, and rendering all in one component.
  const user = fetchUserData(props.userId);
  const formattedUser = formatUserData(user);

  return (
    <div>
      <h1>{formattedUser.name}</h1>
      <p>Email: {formattedUser.email}</p>
      <p>Address: {formattedUser.address}</p>
      {/* Additional UI elements */}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

modified code

import React from 'react';

function UserProfile(props) {
  const user = fetchUserData(props.userId);

  return (
    <UserDisplay user={user} />
  );
}

function UserDisplay(props) {
  const formattedUser = formatUserData(props.user);

  return (
    <div>
      <h1>{formattedUser.name}</h1>
      <p>Email: {formattedUser.email}</p>
      <p>Address: {formattedUser.address}</p>
      {/* Additional UI elements */}
    </div>
  );
}

Enter fullscreen mode Exit fullscreen mode

And lastly, when writing code, it's essential to adopt the mindset that other developers will read and work with your code. This approach encourages the creation of code that is clear, comprehensible, and free from ambiguity, making it easier for your colleagues to collaborate with you. You can achieve this by using code comments, refactoring, documenting your code, and following a consistent coding pattern.

In the world of programming, clean and readable code is not just a virtue but a necessity. It eases collaboration, reduces errors, and ensures that your work stands the test of time. So, remember, the code you write today should be a beacon of clarity for those who come after you. Happy coding!

Top comments (0)