vendredi 1 mai 2020

Is implementing IEnumerable the middle ground between composition and inheritance?

Say you had a fridge that could only contain bacon slices (The dream?!), would you code it like this :

class Fridge : Collection<BaconSlice>
{
    public int Capacity;

    //logic of bacon storage
}

Or would you code it like that :

class Fridge
{
    public int Capacity;

    private List<BaconSlice> Content;

    //logic of bacon storage
}

Now, we clearly see this would be a hard choice between Composition and Inheritance, but then, what if you want to code it like so :

class Fridge : IEnumerable<BaconSlice>
{
    public int Capacity;

    //implementation of IEnumerable<BaconSlice>

    //logic of bacon storage
}

Then it would not be inheritance per se - although I suppose you would get, in the end, pretty much all of the benefits of inheriting a Collection<BaconSlice> - and it would definitely not be composition; How would that kind of practice be called then?

Now, for the record, I suppose that the best business choice here would be composition, since a Fridge is nowhere near being a list, and to implement IEnumerable<BaconSlice> is way too much work just for enjoying Bacon, but as you may have read it is not the object of this thread.

Aucun commentaire:

Enregistrer un commentaire