tags:

views:

31

answers:

2

In my project I use quite complicated (and nested) collection:

List<Pair<List<Pair<double>>, double>> myCollection

As I use it in whe same way in several places in my project, I would like to convert it to new class. But I have some doubts...

What is the best way to handle this sort of collections, create an inner field and pass as public only selected items:

public class MyComplicatedCollection
{
    private List<Pair<List<Pair<double>>, double>> myInnerCollection = null;

    // Here come some constructors, data accessors etc... only to those elements which I would like to pass as public.
}

Or maybe in other way, by deriving the original collection:

public class MyComplicatedCollection : List<Pair<List<Pair<double>>, double>>
{

    // Here come some constructors, 
    // Most of the data accessors are given "out of the box"
}

Second way seems to be easier, but not as safe as the first way. The other thing is performance - these collections are really big and I need quite fast access to it - it is crucial.

And the second question: if the second way is better... For List there is a constructor when you can populate your collection by passing any ICollection. Is there any easy way of creating such constructor for my class, or do I need to populate my collection element by element (or using AddRange method)?

+1  A: 

When in doubt use composition. Inheritance is hard to do right and you should only use it if you must have a IS-A relationship between your new type and the base/composed type. In this case I think that composition (i.e. your first example) is the best solution.

Composition gives you the flexibility to build your type with whatever public interface you desire. Inheritance dictates that interface to you and also creates a tight coupling between your new type and its base type which can make future modifications difficult.

Andrew Hare
Well, in fact I have already created few methods/classes, where I use this collections. Using inheritance I wouldn't have to refactor it and I will have the backward compatibility provided... But it seems that this solution might be better. Just a little more of work to do...
Gacek
It sounds like you have a good case for creating an `IS-A` relationship here but perhaps refactoring the other areas would save you maintenance headaches in the future.
Andrew Hare
+1  A: 

Wrapping the collection will give you better control, and therefore less chance to introduce bugs, than the inherited version. It will also allow you to hide or disguise the complexity of the collection. You can create your own accessors and properties for example.

Performance-wise you're not hurting yourself much by wrapping the collection. The wrapping class is really a very thin layer over the collection data and should not affect performance.

Paul Sasik