Pulling an example out of thin air, shorter total code:
var counter = 0;
function foo() {
log("Incremented");
counter++;
}
function bar() {
log("Incremented");
counter++;
}
Code with an abstraction which makes foo and bar shorter: var counter = 0;
function increment() {
log("Incremented");
counter++;
}
function foo() {
increment();
}
function bar() {
increment();
}
Even longer code, but which encapsulates the counter variable, possibly making it easier to reason about: var Counter = (function ()
{
var counter = 0;
return {
increment : function() {
log("Incremented");
counter++;
},
current : function() {
return counter;
}
};
});
function foo() {
Counter.increment();
}
function bar() {
Counter.increment();
}There are a surprisingly large number of programmers who learn "Oh yay, I can use abstractions to simplify this bit of code" and then turn that into "I think I'll make abstractions out of every bit of code". I was once one of them. In the process, they turn something that could've been a simple program, one that you could fit into your head, into an Enterprise Behemoth that you can't modify without implementing a half dozen interfaces and touching 30 files.
There's a cost to abstraction - it's (usually) extra code, it makes it harder to follow the logic of the program, and it makes your program less flexible in directions other than the intended use. So don't do it unless it actually gains you something in simpler code. Programs can become spaghetti-like through IFactoryFactories just as easily as they can become spaghetti-like through switch statements.
Also on Hacker News at the moment and fairly relevant:
http://coderoom.wordpress.com/2010/03/19/5-stages-of-program...