DEV Community

Cover image for Enhancing JavaScript Code: Using Objects Instead of Switch Statements
Nassbin
Nassbin

Posted on

Enhancing JavaScript Code: Using Objects Instead of Switch Statements

Introduction

This is a short and somewhat unusual topic to write about, but I haven’t encountered it much on the web while working, so here is my contribution. I would love to hear people’s opinions on this method since I use it regularly. I don’t like writing multiple cases inside a switch statement, so I found using an object to be a cleaner alternative. It may not be faster, but the code looks cleaner to me.

Demonstration

I want to handle orders with different payment statuses and apply different treatments depending on whether they are paid or not.

Let's begin with this:

const orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "UnPaid"
}];


const handlePaymentStatus =(order) =>{
  return order.paymentStatus
}

for (const order of orders) {
 handlePaymentStatus(order)
}
Enter fullscreen mode Exit fullscreen mode

We want to apply a specific treatment based on the order.paymentStatus. A simple solution would be to use a switch statement like this:

let orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "Unpaid"
}];


const handlePaymentStatus =(order) =>{
switch (order.paymentStatus) {
  case 'Paid':
    console.log("it's all good");
    break;
  case 'Unpaid':
    console.log("need to be paid");
    break;
  default:
    console.log(`We'll wait`);
}
}

for (const order of orders) {
 handlePaymentStatus(order)
}
Enter fullscreen mode Exit fullscreen mode

It's a simple case since we have two options and a default, but imagine it with multiple payment methods. We’ll keep it like this for the purpose of clarity:

let orders = [{
  "id": 1,
  "product": "shoes",
  "paymentStatus": "Paid"
},{
  "id": 3,
  "product": "tie",
  "paymentStatus": "Unpaid"
},{
  "id": 2,
  "product": "pants",
  "paymentStatus": "Pending"
},];

const paymentStatusHandlers = {
  'Paid': () =>  console.log("it's all good"),
  'Unpaid': () => console.log("needs to be paid"),
}

for (const order of orders) {
 paymentStatusHandlers[order.paymentStatus] 
    ? paymentStatusHandlers[order.paymentStatus]()
    : console.log("We'll wait")
}
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using an object instead of a switch statement can make your code more readable and maintainable, especially when dealing with multiple cases. It’s a matter of personal preference, but it’s worth considering as an alternative approach.

Feel free to let me know if there are any other specific changes or additions you'd like to make!

Image of Docusign

Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more

Top comments (2)

Collapse
 
alexmustiere profile image
Alex Mustiere

Your code reminds me of the "Strategy" pattern. You could have written this:

const orders = [
  {
    id: 1,
    product: 'shoes',
    paymentStatus: 'Paid',
  },
  {
    id: 3,
    product: 'tie',
    paymentStatus: 'Unpaid',
  },
  {
    id: 2,
    product: 'pants',
    paymentStatus: 'Pending',
  },
];

const paymentStrategy = {
  of: (status) => paymentStrategy.statuses[status] ?? paymentStrategy.statuses.default,
  statuses: {
    Paid: {
      handler: () => {
        console.log(`it's all good`);
      },
    },
    Unpaid: {
      handler: () => {
        console.log(`needs to be paid`);
      },
    },
    default: {
      handler: () => {
        console.log(`We'll wait`);
      },
    },
  },
};

for (const order of orders) {
  paymentStrategy.of(order.paymentStatus).handler();
}
Enter fullscreen mode Exit fullscreen mode

It's quite similar but:

  • if you have a new status you juste have to change the code in the strategy
  • if you need to define other action(s) for each status, you just have to add method(s) attached to the different statuses
Collapse
 
nassbin profile image
Nassbin

C'est en effet une très bonne solution et je vais commencer à l'implémenter j'avais pas fait le parallèle en développant mais ça saute aux yeux merci pour votre commentaire

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Explore a sea of insights with this enlightening post, highly esteemed within the nurturing DEV Community. Coders of all stripes are invited to participate and contribute to our shared knowledge.

Expressing gratitude with a simple "thank you" can make a big impact. Leave your thanks in the comments!

On DEV, exchanging ideas smooths our way and strengthens our community bonds. Found this useful? A quick note of thanks to the author can mean a lot.

Okay