José F. Romaniello

Las aventuras y desventuras de un codificador.

How many times have you seen something like this?

public class Album : Entity, IAlbum
{
    public virtual Artist Artist { get;  set; }
    public virtual string Title { get; set; }

    public virtual IEnumerable<Track> Tracks { get; private set; }
    public virtual void AddTrack(Track track)
    {
        track.Album = this;
        Tracks.Add(track);
    }
    public virtual void AddTracks(IEnumerable<Track> tracks)
    {
        tracks.ForEach(AddTrack);
        
    }
    public Album()
    {
        Tracks = new List<Track>();
    }
}

The question is why is better than this:

public class Album : Entity, IAlbum
{
    public virtual Artist Artist { get;  set; }
    public virtual string Title { get; set; }

    public virtual ICollection<Track> Tracks { get; private set; }

    public Album()
    {
        Tracks = new EditableCollection<Track>();
        Tracks.CollectionChanged += (sender, args) =>
              {
                  if (args.Action == NotifyCollectionChangedAction.Add)
                      args.NewItems.ForEach(track => track.Album = this);
              };
    }
}

Then you can call album.Tracks.Add( .. ) normally. EditableCollection is from my previous post. You can do the same for the remove method.

| More

1 comentarios:

Well, what happens if your album next time instead of using a collection will use some Xml object, or something which is not an IEnumerable at all?
In your second solution you are forced to a big refactoring...
May be i didn't get it, but i think you lose encapsulation, the user of your class now knows how you internally manages things and your class won't be able to change easily without breaking contracts...

Publicar un comentario en la entrada