From Concrete to Abstract
Eat the pizza
function eatPizza() {
globalPizza.slices.forEach(slice => slice.remove())
}
Eat a pizza
function eatPizza(pizza) {
pizza.slices.forEach(slice => slice.remove())
}
Get the pizza eaten
const Pizza = {
slices: [ /* ... */ ],
eat() {
this.slices.forEach(slice => slice.remove())
}
}
Pizza.eat()
Eat a food, called pizza
class Food {
constructor({ bites }) {
this.bites = bites
}
eat() {
this.bites.forEach(bite => bite.remove())
}
}
const pizza = new Food({
bites: [ /* ... same as slices ... */ ]
})
pizza.eat()
Get an eater, called human, to eat an eatable food, called pizza
OR: Get an eatable food, called pizza, to be eaten by an eater, called human
class Eatable {
constructor({ bites }) {
this.bites = bites
}
eat() {
this.bites.forEach(bite => bite.remove())
}
}
class Food extends Eatable {
constructor({ bites }) {
super({ bites })
}
}
class Eater {
eat(eatable) {
if (!(eatable instanceof Eatable)) {
throw new Error("I won't eat that shit")
}
eatable.eat()
}
}
const human = new Eater()
const pizza = new Food({
bites: [ /* ... same as slices ... */ ]
})
human.eat(pizza)