Jake
Jake

Reputation: 26117

Refactor switch statement to reduce code complexity

I have the following code and I would like to refactor it by using a dictionary or something like that, to reduce the code complexity. It is possible there can be any number of case statements.

switch (this.errorType) {
      case ErrorType.NoApps:
        this.title = 'No Apps Found';
        this.subtitle = 'Contact applications team';
        this.message = 'no apps message';
        this.contact = 'John';
        break;
      case ErrorType.NoAccounts:
        this.title = 'No Accounts Found';
        this.subtitle = 'Contact Support Team';
        this.message = 'no accounts message';
        this.contact = 'Jake';
        break;
      case ErrorType.NoUsers:
        this.title = 'No users Found';
        this.subtitle = 'Contact customer service';
        this.message = 'no accounts message';
        this.contact = 'Wiley';
        break;
}

Upvotes: 2

Views: 566

Answers (1)

Lars Flieger
Lars Flieger

Reputation: 2564

I had once a quite similar problem. This is my modular and typesafe solution for it:

  1. First define your enum and a type how an error should look like:
enum ErrorType {
    NoApps,
    NoAccounts,
    NoUsers
}

type ErrorDetails = {
    title: string
    subtitle: string
    message: string
    contact: string
}
  1. Create an model object which holds the different data:
const errorTypes: { [key in ErrorType]: ErrorDetails } = {
    [ErrorType.NoApps]: {
        title: "No Apps Found",
        subtitle: "Contact applications team",
        message: "no apps message",
        contact: "John"
    },
    [ErrorType.NoAccounts]: {
        title: "No Accounts Found",
        subtitle: "Contact Support Team",
        message: "no accounts message",
        contact: "Jake"
    },
    [ErrorType.NoUsers]: {
        title: "No users Found",
        subtitle: "Contact customer service",
        message: "no accounts message",
        contact: "Wiley"
    }
}
  • [key in ErrorType] makes it typesafe. If you add something to the enum it will throw an error till you implement the details for it.
  1. You can now use the object to get your details:
class Example {
    errorType = ErrorType.NoAccounts
    error: ErrorDetails | null = null

    constructor() {
        if (this.errorType)
            this.error = errorTypes[this.errorType]

        console.log(this.error)
    }
}

new Example()
  • If you get the this.errorType from an API (or it's a string or number) you can use this.errorType as ErrorType

Runnable snippet on codesandbox.

Upvotes: 4

Related Questions