1. Write:
function add (a, b) { return a + b; }
2. Refactor to object: class AccumulatingIntegerWidget {
constructor (...numbers) {
this.accumulation = 0;
this.accumulate(...numbers);
}
accumulate (...numbers) {
for (const n of numbers) {
this.accumulation = this.accumulation + n;
}
}
getAccumulation () {
return this.accumulation;
}
}
Presto! It’s stateful and object-oriented and handles future cases like adding three numbers, even though WeArentGonnaNeedIt!If this does not satisfy, I progress to making my classes observe each other and update themselves automatically. “We’re doing two-way binding!” I exclaim proudly, while leaving debugging as an exercise for my colleagues.