Question

I have an object that acts as nothing more complicated than a data store for a collection of items. I do this because it lets me bind the data to a single object, which I can store in the Unity (game engine) editor and assign to a bunch of other objects so they all operate on the same list of data.

I'm not really sure what to call the class though:

class NameNeeded<T> : // Unity stuff
{
    public List<T> items { get; }
}

I can't inherit this object from anything but a special Unity object, so I can't mask it and pretend that it's a collection itself. There's some other bookkeeping methods, but it's basically a collection container.

If I treat it like a regular collection, I end up with this...

class Lobby
{
    NameNeeded<User> users;

    void DoSomething()
    {
        users.items.Whatever();
    }
}

... which I find unattractive from the double plural implying users is a collection itself.

Was it helpful?

Solution

Given, your class is basically a collection container and the mentioned bookkeeping methods do not violate the single responsibility principle, you could benefit from the decorator pattern.

With this approach you can:

  • Inherit from the unmentioned Unity parent class
  • Bind this class (assuming your unknown code is using abstractions and takes IList<T>, ICollection<T> or IEnumerable<T>
  • Add some other bookkeeping methods.

Given your naming question, something like UnityList, CustomList etc is all valid. You can even inherit, i.e. class UserList : UnityList<User>.

public class Lobby
{
    private UnityList<User> _users;

    void DoSomething()
    {
        // Using LINQ on IList<T>
        var firstUser = _users.First();

         // Invoking one of your bookkeeping methods
        _users.ExtraMethod1(); 
    }

}

public class UnityList<T> : UnmentionedUnityClass, IList<T>
{
    private IList<T> _innerList = new List<T>();

    // Use this to just create empty list
    public UnityList<T>() { }

    // Use this to decorate your existing list i.e. from domain model
    public UnityList<T>(IList<T> innerList)
    {
        _innerList = innerList;
    }

    public void ExtraMethod1() {  }
    public void ExtraMethod2() {  }

    public IEnumerator<T> GetEnumerator()
    {
        return _innerList.GetEnumerator();
    }


    public void Add(T item)
    {
        _innerList.Add(item);
    }

    public void Clear()
    {
        _innerList.Clear();
    }

    // Removed other calls to _innerList for readability.
    // However, using ReSharper, the IList<T> implementation can be generated and directly delegated to _innerList.        
}

OTHER TIPS

I'd suggest using a name that a lot of JavaScript frameworks use nowadays. Store. Its a store for objects of type T. To go with your example an userStore sounds about right. You could then write userStore.items.Whatever(), which I think makes perfect sense.

Licensed under: CC-BY-SA with attribution
scroll top