« Back to Index

Strategy pattern to remove the need for conditionals. If you find yourself writing conditionals then that’s really just an object waiting to be made. Yes there are more lines of code, but this enforces the ‘open/closed principle’ which means the code is open for extension but closed for modification and means our code can scale a lot more easily than the conditional style.

View original Gist on GitHub

1. bad.js

function test(condition){
    if (condition === 'a') {
        console.log('test a here');
    } else if (condition === 'b') {
        console.log('test b here');
    } else if (condition === 'c') {
        console.log('test c here');
    }
}

test('a');
test('b');
test('c');

2. good.js

function betterExample(obj) {
    obj.log();
}

var a = {
    log: function(){
        console.log('better a here');
    }
};

var b = {
    log: function(){
        console.log('better b here');
    }
};

var c = {
    log: function(){
        console.log('better c here');
    }
};

betterExample(a);
betterExample(b);
betterExample(c);