DEV Community

TianZhen
TianZhen

Posted on • Originally published at youth2009.org on

How to understand Program to an interface not an implementation

Yesterday my colleagues and I talk about JS for loop and const. I found this post, it refers a quote "Program to an interface not an implementation", I read this several years ago, and have no feeling about this, just think it's a cool quote or rule.

Now, after several years working experience, I got some understanding about that.

For instance I use a simple JS example,

var counter = function() {
    var count = 0;
    return {
        incr: function(){count++;},
        decr: function(){count--;},
        disp: function(){console.log(count)}
    }
}
Enter fullscreen mode Exit fullscreen mode

I exposed three functions: incr, decr, disp, they operate private count variable, on the outer side, callee don't know count, callee can call incr, decr, disp, three functions are interfaces of counter.

Another implementation of counter is expose count, callee increase count, decrease count, display count by operate count variable directly.

When incr, decr logic is changed, e.g. increase count by 2, not 1. Interfaces are same as before, callee don't need change any codes.

Top comments (0)