3

One important and essential rule I have learnt as a C++ programmer is the preference of Composition over Inheritance (http://en.wikipedia.org/wiki/Composition_over_inheritance).

I totally agree with this rule which mostly makes things much more simple than It would be if we used Inheritance.

I have a problem which should be solved using Composition but I'm really struggling to do so.

Suppose you have a Vendor Machine, and you have two types of products:

  1. Discrete product - like a snack.
  2. Fluid product - like a drink.

These two types of products will need to be represented in a class called VendorCell which contains the cell content.

These two products share some identical attributes(dm) as Price, Quantity and so on...BUT also contain some different attributes.

Therefore using Composition here might lead for the following result:

class VendorCell {
private : // default access modifier
    int price;
    int quantity;

    // int firstProductAttributeOnly
    // char secondProductAttributeOnly
};

As you can see the commented lines show that for a single VendorCell depending on the product it containing, only one of these two commented lines will be significant and useable (the other one is only relevant for the other type - fluid for example).

Therefore I might have a VendorCell with a snack inside and its secondProductAttributeOnly is not needed.

Is composition (for the VendorCell) is the right solution? is It seems proper to you guys that someone will determine the VendorCell type via a constructor and one DM (the DM dedicated for the other type) will not be used at all (mark it as -1 for example) ?>

Thanks you all!

TemplateRex
  • 69,038
  • 19
  • 164
  • 304
SyndicatorBBB
  • 1,757
  • 2
  • 26
  • 44
  • 2
    huh?... again, huh? why not just have a VendorObject, and then have VendorSnack and VendorDrink inherited from VendorObject. – thang Jan 28 '13 at 09:12
  • 3
    don't use rules or patterns just for the sake of using rules or patterns. use what is the most appropriate; don't bend things to force them into unnaturla molds – Marius Bancila Jan 28 '13 at 09:14
  • Yes I was so persistent to avoid inheritance and therefore my mistake. Thanks. – SyndicatorBBB Jan 28 '13 at 09:15
  • 3
    I think a `vendorcell` has-a `product` and `snack` is-a `product`. you get it? – Marius Bancila Jan 28 '13 at 09:15
  • Yes totally clear, I was just confused trying to combine rules of patterns while avoiding inheritance. Thanks! – SyndicatorBBB Jan 28 '13 at 09:17
  • @Marius Bancila - What also confused me, which seems like a bad rule now, is the following tip I got: Use inheritance only if the inherited classes act differently. Stack and Drink both act the same just having different data memeber... That is why I was trying to avoid inhertiance. – SyndicatorBBB Jan 28 '13 at 09:20
  • 1
    so you think inheritance should only be used only when 'functions' behave differently? I think that's wrong. polymorphism is not just about functions. is also about data. – Marius Bancila Jan 28 '13 at 09:53
  • 1
    @Marius Bancilla: "is also about data" <- Example? – Frank Osterfeld Jan 28 '13 at 09:57

2 Answers2

4

Your general rule of favoring composition over inheritance is right. The problem here is that you want a container of polymorphic objects, not a giant aggregate class that can hold all possible products. However, because of the slicing problem, you can't hold polymorphic objects directly, but you need to hold them by (preferably smart) pointer. You can hold them directly by (smart) pointer such as

class AbstractProduct { /* price, quauntity interface */ };
class AbstractSnack: public AbstractProduct { /* extended interface */ };
class AbstractDrink: public AbstractProduct { /* extended interface */ };
typedef std::unique_ptr<AbstractProduct> VendorCell;
typedef std::vector< VendorCell > VendorMachine;

You simply define your snacks/drinks by deriving from AbstractSnack/AbstractDrink

class SnickersBar: public AbstractSnack { /* your implementation */ };
class CocaColaBottle: public AbstractDrink { /* your implementation */ };

and then you can insert or extract products like this:

// fill the machine
VendorMachine my_machine;
my_machine.emplace_back(new SnickersBar());
my_machine.emplace_back(new CocaColaBottle());

my_snack = my_machine[0]; // get a Snickers bar
my_drink = my_machine[1]; // get a Coca Cola bottle;

There are also other solutions such as Boost.Any that uses a wrapper class that internally holds a pointer to a polymorphic object. You could also refactor this code by replacing the typedef with a separate class VendorMachine that holds a std::vector< VendorCell >, so that you can get a nicer interface (with money exchange functionality e.g.)

Community
  • 1
  • 1
TemplateRex
  • 69,038
  • 19
  • 164
  • 304
  • I can use this technique also for the Vendor Machine mode? Holding a pointer as a data member of the class BaseMode which will be inherited by two other modes (MaintenanceMode, SellMode) - each one has virtual functions defined inside. – SyndicatorBBB Jan 28 '13 at 10:08
  • @SyndicatorBBB If you want to implement state dependent behavior, you might want to study design patterns like State: http://sourcemaking.com/design_patterns/state I believe that link has a vending machine example :-) – TemplateRex Jan 28 '13 at 10:21
  • Thanks for this detalied explanation. helped me alot! – SyndicatorBBB Jan 28 '13 at 10:26
  • I can use this principle for so much things !! much more than just states. I can hold a pointer of another system to update a report which needs to be update both in the current system and the report system. It's really strong tool! thanks! – SyndicatorBBB Jan 28 '13 at 10:40
0

You inherit in order to be re-used.

You compose in order to re-use.

If you have different attributes then you probably want to inherit, otherwise compose.

Some variation:

class ProductVariety {
public:
    virtual void display(Screen& screen) = 0;
};

An implementation:

class Liquid : public ProductVariety {
public:
    virtual void display(Screen& screen) {
        //...
    }
}

Composing variation:

class Product
{
    int price;
    int quantity;

    unique_ptr<ProductVariety> variety;
}
Peter Wood
  • 23,859
  • 5
  • 60
  • 99