Courtesy Implmentation
I have a great deal of respect and admiration of Martin Fowler. I read his blog and try to absorb as many of his talks as possible.
While reading his blog one day, I found his post on the Courtesy Implementation. The first time through, my mind went wonky on me. After a brief mental tussle over over who is smarter, me or Martin Fowler, I considered that I should give it another look. It started to make more sense, but I knew I wasn't going to completely click until I coded it up.
I think part of my confusion is that Martin did his implementation in Ruby - which I don't have any experience with. I implemented it in Javascript and everything just clicked.
'use strict';
// box
class box {
constructor () {
this.children = [];
}
addChild (child) {
this.children.push (child);
console.log('added ' + child.name);
}
num_elephants () {
var result = 0;
for (var value of this.children) {
console.log (value);
result += value.num_elephants();
}
return result;
}
}
// elephant
class elephant {
constructor (name) {
this.name = name;
}
num_elephants () {
return 1;
}
}
ALL GLORY TO THE COURTESY IMPLEMENTATION!!!

Comments
Post a Comment