DEV Community

Discussion on: Reverse switch?

Collapse
 
tqbit profile image
tq-bit • Edited

I personally don't use (or like) switch, it makes code hard to read. And I believe there are cases in which if - else is the only viable option, but given the choice, I'd always favor single if() - clauses that return a value if the expression is met. It's like using switch, with the default statement at the bottom of the function bound to no other if-clause. When I get back to the code after a few weeks, I'm usually glad I did it this way.

Very simple pseudocode sample for simple http - server

try {
  const { clientId } = req.params;

  const found = await Client.findOne({ clientId });
  const hasAccess = await Auth.findOne({clientId});

  if (!found) {
    return res.status(404).send(itemNotFound);
  }

  if(!hasAccess) {
    return res.status(401).send(userNotAuthorized);
  }

  await Client.deleteOne({ clientId });
  res.status(200).send(deleted);
} catch (e) {
  res.status(500).send(internalError);
}
Enter fullscreen mode Exit fullscreen mode