views:

336

answers:

3

What are the advantages/disadvantages of Option 2 over 1 in this example?

Option 1 (Inheritance):

public class SalesList : List<Sales>
{
    //methods that add extra behavior List<Sales>
}

Option 2 (Composition):

public class SalesList 
{
    private List<Sales> _list;
    //methods that add extra behavior to List<Sales>
}
+1  A: 

The advantage of option 2 is agility. Using composition, you can choose which parts of the list interface you expose.

Imagine that later on you decide no longer to extend from another class. By now, some of the users of your library will have used methods provided by List, so you need to implement all of the list methods yourself: add/addAll/contains/retainAll. That's a whole lot of methods to implement for a simple sales list.

Basically, this comes down to "when in doubt, leave it out" which Joshua Bloch talks about in Bumper-Sticker API Design. Every facet of an API should be as small as possible, but no smaller. You can always add things later, but you can't take them away.

Frederik
+1  A: 

Option 1
- Advantages - all advantages of inheritance & re-use
- Disadvantages - the code is now signalling to the consumers that it is dervied from List. If this needs to change at a later date, then all the related consumers will be affected.

Option 2
- Advantages - the implementation detail about the storage of the sales data is abstracted aways from the consumer. So, if the implementation needs to change (say a dictionary, for example), the consumer of the class will be immune from these changes.
- Disadvantages - the SalesList class will now need to expose additional methods to get and/or set to the inner _list object. this is additional code which need to be maintained. Also, if the inner implementation changes, you need to take care to still support the previous behaviour...

Just a few thoughts that come to mind.

HTH.

Sunny
+1  A: 

The main disadvantage of Composition is that you need to wrap (duplicate) all the public methods of the private List if you need to present the same interface, in Inheritance you have all of them already available, but you can't override any of them that was made not overridable (in C# it means the method should be marked 'virtual', in Java it can't be marked as 'final').

In C# 3 and up, you can use Extension Methods, which give the appearance of inheritance without truly messing up the hierarchy tree.

Monoman