发布于 2026-01-06 1 阅读
0

🚫 请停止使用SWITCH 🙏

🚫 请停止使用SWITCH 🙏

如果你是一名软件开发人员,那么你很可能在某个时候会用到switchswitch 语句。这个运算符允许你计算表达式的值,并根据表达式的值执行不同的代码块。虽然 switch 语句很有用,但过度使用会导致代码难以维护和修改。本文将解释为什么你应该考虑减少使用 switch 语句,并提供一些替代方案来提高代码的可读性和可维护性。

问题

在这个例子中,通知函数接受一个类型为 `<input>` 的通知参数Notification,该参数是一个枚举类型,代表不同的通知。该函数使用 switch 语句根据Notification参数的值来确定要发送的通知。我们来看一个例子:

您可以点击此处查看为什么不建议使用枚举类型。

const enum Notification {
  verifySignUp,
  resendVerifySignup,
  emailConfirmed
}

export function notifier (notification: Notification) {
  switch (notification) {
    case Notification.verifySignUp: 
      // Execute something...
    return;

    case Notification.resendVerifySignup: 
      // Execute something...
    return;

    case Notification.emailConfirmed: 
      // Execute something...
    return 
  }
}
Enter fullscreen mode Exit fullscreen mode

随着 switch 语句中 case 数量的增加,代码的可读性会降低。此外,如果枚举类型中添加了新的水果,则必须更新函数以处理新情况,如果忘记更新,则可能导致错误。

在这种情况下,有更具可扩展性和可维护性的替代方案,例如使用包含水果颜色的对象。随着水果种类的增加,这种方法还能使代码更易读、更易于扩展。

我在其他项目中发现的另一种可能的替代方案是使用 if 语句。

export function notifier(notification: Notification) {
  if (notification === Notification.verifySignUp) {
    // Execute something...
    return;
  }

  if (notification === Notification.resendVerifySignup) {
    // Execute something...
    return;
  }

  if (notification === Notification.emailConfirmed) {
    // Execute something...
    return;
  }
}
Enter fullscreen mode Exit fullscreen mode

但正如你所看到的,两者存在同样的缺点。既然我们已经正面解决了这个问题,那么我们该如何改进呢?

解决方案

任何软件解决方案都有不同的问题解决方法。这里我们只讨论两种,一种是使用…… objects,另一种是通过……mapping functions

使用对象

const notificationDirectory = {
  verifySignup: () => {
    // Execute something...
  },

  resendVerifySignup: () => {
    // Execute something...
  },

  emailConfirmed: () => {
    // Execute something...
  }
}

type NotificationTypes = keyof typeof notificationDirectory

function notifier (notification: NotificationTypes) {
  const handler = notificationDirectory[notification]

  if (!handler) throw new Error("Your method does not exist");

  if (!(typeof handler === 'function')) throw new Error("Your method must be a function");

  // Execute your method
  handler()
}

// send email for the user to confirm his email.
notifier('verifySignup')

// send email notifying that your email was verified
notifier('emailConfirmed')
Enter fullscreen mode Exit fullscreen mode

使用映射函数

const notificationMap = new Map<string, () => void>()

notificationMap.set('verifySignup', () => {
  // ...
})

notificationMap.set('resendVerifySignup', () => {
  // ...
})

notificationMap.set('emailConfirmed', () => {
  // ...
})

function notifier (notification: string) {
  const handler = notificationMap.get(notification)

  if (!handler) throw new Error("Your method does not exist");

  handler()
}
Enter fullscreen mode Exit fullscreen mode

以下详细介绍了使用这些技术而非开关的优势:

  • 更易于维护:随着新通知的添加,无需在 switch 语句中添加更多实例,只需向notificationDirectory对象添加新函数即可。

  • 更灵活:您可以随时添加或删除通知,而无需担心更新相应的 switch 语句。

  • 更安全:通过使用NotificationTypes类型,您可以确保只有有效值才会传递给通知器方法。如果尝试传递的值不是notificationDirectory对象的有效键之一,则会抛出运行时错误。这有助于尽早发现错误。

  • 更具可扩展性:这种方法不是编写一个处理多种不同情况的长函数,而是为每种情况定义一个单独的函数,从而使您的代码更加模块化,更易于阅读和维护。

  • 更高效:在某些情况下,使用 Map 代替 switch 语句可以提高执行速度。这是因为 Map 是一种键值对数据结构,与 switch 语句中的顺序查找相比,它可以更高效地查找和检索值。

结论

总之,虽然 switch 语句是软件开发中一个有用的工具,但过度使用会导致代码难以维护和修改。随着 switch 语句中 case 数量的增加,代码的可读性会下降,而且如果忘记更新所有使用 switch 语句的地方,添加新的 case 可能会导致错误。此外,还有更具可扩展性和可维护性的替代方案,例如 ` using objectsif` 或 `if` mapping functions,它们可以提高代码的可读性和可维护性。因此,在软件开发中,合理使用 switch 语句并评估其他替代方案以提高代码质量至关重要。

跟我来

文章来源:https://dev.to/ivanzm123/stop-using-switch-please-2hif