开发者

What is the BCL equivalent of GetValueElseAdd in PowerCollections

In Wintellect's PowerC开发者_运维问答ollections, there's a GetValueElseAdd which works like this:

if ( collection.GetValueElseAdd( key, ref value))
{
    // just added, value unmodified
}

Or

// factory method only gets called if the key is not present.
if ( collection.GetValueElseAdd( key, out value, () => thingFactory.CreateNew()))
{
    // just added; value contains factory result
}

In both cases, there's only one walk through the hashes to isolate where the value is going to sit. (See What happens to C# Dictionary<int, int> lookup if the key does not exist? for more discussion of the tradeoffs)

The question is, why has functionality like this not made it into the BCL, especially given that pretty much all of the rest of PowerCollections got sucked in via 3.5/LINQ and the new collections added in 4.0?

Is it because the general usage pattern is that one only does an Add once whereas you're generally only hitting the equivalent of the TryGetValue path with a single hashtable lookup the bulk of the time?

Is it because this is much more valuable in a tree than in a hashtable (could only find this implementation on the net but I think it was on more than just an OrderedList collection)

EDIT: See also the post linked in the comment's on Fredrik's response which discusses multithreading considerations for Sychronized variants of a collection.

Or is there another idiom I'm missing? If only Peter Golde was here!


The only rationale that I can come up with that could potentially argue against a GetValueElseAdd is the Single Responsibility Principle. The method name indicates that the method has two responsibilities: it tries to get an item and, if it fails, adds the item (I never worked with the PowerCollections, but I will assume that value gets assigned with the created object in the case when the key is not found).

If I was designing the API this, together with the fact that the behavior is simple to create and encapsulate, would probably be enough to keep me from implementing it.

I usually try to take a step back as soon as method names start having words like And, Or, Else and such, as these for me are indicators that the method might have too many responsibilities.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜