3 ms·
His example is bad. class Item def add_to_cart(cart) cart.increase_total(this.price) The fault is really that Item.price isn't defined, so i
by parenthephobia 11y ago
His example is bad.
class Item
def add_to_cart(cart)
cart.increase_total(this.price)
The fault is really that Item.price isn't defined, so it can't be assumed to exist in Item.add_to_cart. When he later adds get_price to all subclasses, he is really just fixing that bug.
In a language like Java, this problem could never have arisen in the first place, since the compiler would know that Item.price didn't exist.
In a language like Ruby, it isn't a problem. Ruby doesn't expose "fields" and methods differently, so the consumer of Book doesn't need to know that the price "field" is now a method that computes the price. That's proper abstraction.
His interface-based solution solves nothing, because exactly the same sequence of events would have unfolded if he'd originally been using an implicitly defined price field. If he then needed to make that a method, he'd then need to define an interface for get_price and then make all the things that should be Priceable implement that interface[1].
[1] And this bypasses one of the principle advantages of Go's interfaces. You don't say that a type implements an interface; types automatically implement an interface simply by having the appropriate methods.