I think the most common way of adding something to a collection is to use some k
ID: 645896 • Letter: I
Question
I think the most common way of adding something to a collection is to use some kind of Add method that a collection provides:
class Item {}
var items = new List<Item>();
items.Add(new Item());
and there is actually nothing unusual about that.
I wonder however why don't we do it this way:
var item = new Item();
item.AddTo(items);
it seems to be somehow more natural then the first method. This would have the andvantange that when the Item class has a property like Parent:
class Item
{
public object Parent { get; private set; }
}
you can make the setter private. In this case of course you cannot use an extension method.
But perhaps I'm wrong and I've just never seen this pattern before because it's so uncommon? Do you know whether there is any such pattern?
In C# an extension method would be useful for that
public static T AddTo(this T item, IList<T> list)
{
list.Add(item);
return item;
}
How about other languages? I guess in most of them the Item class had to provide a let's call it ICollectionItem interface.
Explanation / Answer
No, item.AddTo(items) it is not more natural. I think you mix this up with the following:
t3chb0t.Add(item).To(items)
You are right in that items.Add(item) is not very near to the natural english language. But you also don't hear item.AddTo(items) in natural english language, do you? Normally there is someone who supposed to add the item to the list. Be it when working at a supermarket or while cooking and adding ingredients.
In the case of programming languages, we made it so that a list does both: storing its items and being responsible for adding them to itself.
The problem with your approach is that an item has to be aware that a list exists. But an item could exist even if there were no lists at all, right? This shows that it should not be aware of lists. Lists should not occur in its code in any way at all.
Lists however don't exist without items (at least they would be useless). Therefore its fine if they know about their items - at least in a generic form.