开发者

Complicated collection changed to class - best way of handling it

开发者 https://www.devze.com 2022-12-23 10:54 出处:网络
In my project I use quite complicated (and nested) collection: List<Pair<List<Pair<double>>, double>> myCollection

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 co开发者_高级运维me 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)?


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.


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号