Javascript Code Smell Series: Redundant switch statement

Following code extracted from a production system built with Vue 2
// Assumption: this.protocolStatus, statusConfigurationProtocol, and STATUS_CODE_PROTOCOL are defined outside the function and accessible within the function

Bad:
protocolStatusStyles() {
  let protocolStatusStyles = {
    icon: '',
    class: ''
  }

  switch (this.protocolStatus) {
    case STATUS_CODE_PROTOCOL.INACTIVE:
      protocolStatusStyles = statusConfigurationProtocol[STATUS_CODE_PROTOCOL.INACTIVE]
      break
    case STATUS_CODE_PROTOCOL.ACTIVE:
      protocolStatusStyles = statusConfigurationProtocol[STATUS_CODE_PROTOCOL.ACTIVE]
      break
    case STATUS_CODE_PROTOCOL.COMPLETE:
      protocolStatusStyles = statusConfigurationProtocol[STATUS_CODE_PROTOCOL.COMPLETE]
      break
    case STATUS_CODE_PROTOCOL.UNCOMPLETABLE:
      protocolStatusStyles = statusConfigurationProtocol[STATUS_CODE_PROTOCOL.UNCOMPLETABLE]
      break
    case STATUS_CODE_PROTOCOL.FAILED:
      protocolStatusStyles = statusConfigurationProtocol[STATUS_CODE_PROTOCOL.FAILED]
  }

  return protocolStatusStyles
},

Good:
protocolStatusStyles() {
  if (![
    STATUS_CODE_PROTOCOL.INACTIVE,
    STATUS_CODE_PROTOCOL.ACTIVE,
    STATUS_CODE_PROTOCOL.COMPLETE,
    STATUS_CODE_PROTOCOL.UNCOMPLETABLE,
    STATUS_CODE_PROTOCOL.FAILED,
  ].includes(this.protocolStatus)) {
    return {
      icon: '',
      class: '',
    }
  }

  return statusConfigurationProtocol[this.protocolStatus]
},

Better: (if not necessary to limit STATUS_CODE_PROTOCOL codes)
protocolStatusStyles() {
  const default = {
    icon: '',
    class: '',
  }

  return statusConfigurationProtocol[this.protocolStatus] || default
}
Share: