3 ms·
You're hand-waving a lot away with "some collection of stuffs implementing price()". That stuff was the actual problem the article was about. The question of ho
by parenthephobia 11y ago
You're hand-waving a lot away with "some collection of stuffs implementing price()". That stuff was the actual problem the article was about. The question of how it gets in the cart and how and when the total is calculated is irrelevant.
The actual problem of the article was that if the stuff you put in a cart simply derives from a single base class, then any new stuff-based behaviour (potentially) requires changing all subclasses. For example, if you wanted to to add shelf life to perishable items and have the cart maintain the minimum shelf life, then you have to add shelf life to the item class and potentially override it on all subclasses.
An alternative implementation would be to define a Perishable interface with a ShelfLife method and only implement that for perishable items.
class Cart
def minimumShelfLife
items.ofType<Perishable>().minimum(item -> item.shelfLife, ifEmpty: infinity)
This avoids cluttering up the base class with loads of methods which won't be meaningful for most of the types, and which may cause problems when extending things later.
I'm not convinced, but I believe that's the essence of the argument the article intends to make.
- wvenable 11y agoBut that's not true as it's not a binary choice. The idea of adding a Perishable interface works just as well whether or not items extend a single base class. Sometimes cluttering the base class is a better solution if there is a meaningful default. For example, if you start with all non-taxable items and the requirements change for taxable items -- it makes sense to implement in the base class as a Tax property that defaults to zero. Then you don't need conditionals and interface checks whenever you want to display or do tax calculations.
- mediaobelia 11y ago> This avoids cluttering up the base class with loads of methods which won't be meaningful for most of the types I'd argue that shelfLife is meaningful for all Items, and it's unnecessarily presumptuous to assume only Carts will want to know about shelfLife. Plus it's less code to simply add a shelfLife method in Item to return infinity. Later, when you realize expirationDate is what you really want to know you'll have less code to modify to get the logic correct. In most cases you'll have fewer problems doing things the traditional OO way and sending the expirationDate message directly to the item.