jeudi 27 avril 2017

Creating element inside IEnumerable instead of adding existing element to it

It is good to use such approach to add new item to custom collection? Not to add existing element, but create new element inside the collection? The method name "Add" is suitable for this case? (The purpose is hiding repositories.) Thanks.

public class MyObject
{
    public int ID { get; }
    public Value1 { get; }
    public Value2 { get; }
}

public interface ICustomCollection : IEnumerable<MyObject>
{
    MyObject Add(value1, value2);
}

public class CustomCollection : ICustomCollection
{
    MyObjectFactory factory;
    MyObjectRepository repository;

    public IEnumerator<MyObject> GetEnumerator()
    {
        return repository.GetAllObjects();
    }

    public MyObject Add(value1, value2)
    {
        var newItem = factory.Create(value1, value2);
        repository.AddObject(newItem);
        return newItem;
    }

    //...
}

Aucun commentaire:

Enregistrer un commentaire