HanJohn
HanJohn

Reputation: 1

Javascript - lots of standalone functions are bad ??? (node.js)

I am refactoring my code now..and I have to refactor my lots of if..else statements, so I am now creating many functions by each conditions.

Code:

class Strategy {
    constructor(state) {
        this.state = state;

        if(this.state === 1){
          return first();
        }else if (val === 2){
          return second();
        }else if (val === 3){
          return third();
        }
    }

}

function first(){
  //do something
}

function second(){
  //do something
}

function third(){
  //do something
}

let firstClass = new Strategy(1);

Is it OK to declare all each functions by condition??? Or, Is it better to declare each functions in prototype method?/?

Upvotes: 0

Views: 150

Answers (1)

mindriven
mindriven

Reputation: 143

you could also use plain JS object as a strategy map, like this:

const strategies = {
    1: () => {},  //do something
    2: () => {},   //do something
    3: () => {}   //do something
}

and the you can use it like this:

strategies[state]();

Hope this helps.

Upvotes: 1

Related Questions