Skip to content

Date archive for: October 2012

Fake Multiple Inheritance

Leveraging code reuse in a world without mixins First, we need our interface. All the other objects conform to this interface, so they are all polymorphic.

The DiscountCart is the most primitive of the Discount types. It gives the customer a 15% discount on their entire cart. Inheritance.

The VolumeDiscount inherits from the DiscountCart, and overrides with its own discount based on the volume of each product in the cart. Inheritance with a method override.

There is another discount which adds free shipping. Inheritance with a property override.

Now, there is a very special customer type: the Frequent Customer. We give them a Volume discount AND they get free shipping all the time. If we had mixins, we could just “mix in” the free shipping, but since this is php (or C# for that matter) I do it this way:

This lets the FreeShippingDiscountCart be compatible with any IDiscountCart polymorphism and leverage inherited traits from its private objects. That way, if Free Shipping gets complicated (ex: drop-shipped or sale items are not eligible) I don’t have to re-implement the exceptions.