12

Warning: this question uses an analogy to RPG as an example.

Let's say I'm making this RPG I've been dreaming of, using C#. When the player enters battle, there is some kind of battlefield appearing, that holds references to every elements relevant to the battle, like the various opponents and items available on the battlefield.

Now all those elements have one but several roles: for instance, an Ally (which is a Fighter through direct inheritance) is able to move on the battlefield, to issue commands or to be targeted by ennemies.

Now that mighty sword in the stone has also a few roles in battle. Obviously it can't move nor issue commands, but it can still be targeted, and it can (hopefully) be lifted or used.

All these behaviors are represented by interfaces in my code, so that all objects with the same behaviors can be used regardless of the object that implements it.

Code example:

public class Ally : Fighter, IMovable, IActor, ITarget
{
    // IMovable implementation
    public void Move(...) { ... }

    // IActor implementation
    public bool HasInitiative { get { ... } }

    public ICommand IssueCommand(...) { ... }

    // ITarget implementation
    public void OnTarget(...) { ... }

    // other code ...
}

public class MightySword : ITarget, ILiftable, IUsable
{
    // ITarget implementation
    public void OnTarget(...) { ... }

    // ... other interface implementation

    // other code ...
}

Now my question is the following: How should my Battlefield class holds its references to all these objects? I came up with two possible solutions, but at this point it's not clear which one is the best, and whether better solutions are to be found.

Solution A:

Reference several time, access directly: Using this solution, each object is referenced once per interface it implements, so my battlefield class would look like below:

public class Battlefield : ...
{
   IList<IMovable> movables;
   IList<ITarget> targets;
   IList<IActor> actors;
   // ... and so on
}

and the Battlefield.Update method could look this way:

Update(...) 
{
  // Say every actor needs to target somebody else
  // it has nothing to do in the Update method,
  // but this is an example
  foreach (IActor actor in actors) 
  {
    if (actor.HasInitiative) 
    {
      ITarget target = targets[actor.TargetIndex];
      target.OnTarget(actor.IssueCommand(...));
    }
  }
}

This solution allows us to have a direct access to the objects' various behavior, but it introduces redundancy, as an Ally would have to be referenced into movables, targets and actors . This redundancy means a bigger memory footprint and will make adding and removing an object to the battlefield a lot more complicated (each type should now from which collections it has to be added/removed).

Also, adding a new interface means adding a new collection to hold the item and manage the corresponding code.

Solution B:

Reference once, filter access: Using this solution, all objects derive from a single class or interface (something akin to IBattleElement), and are stored in one single collection. When using the elements, they are filtered according to their types:

Update(...)
{
    IList<IActor> actors = elements.OfType<Actor>();
    foreach (IActor actor in actors) 
    {
     ITarget target = elements.OfType<Target>()[actor.TargetIndex];
     target.OnTarget(actor.IssueCommand(...));
    }
}

There. No more redundancy, but I dislike using a "typeof" construct and I generally try to avoid it. Obviously this is worse regarding runtime performance.

I implemented solution A in my toy project, but there is nothing performance critical in this project. The answer should consider not only performance (both memory wise and CPU wise), but also what offers the best design for the operations me or my designers might have to perform, such as adding new classes of BattleElement or new interfaces for new behaviors, adding and removing instances of objects from a Battlefield, and more generally use them in the game logic.

I apologize for the general silliness of my examples, I hope my English is good enough, and that my question carries at least a little bit of interest and doesn't indicate an overall silliness in the design itself.

3
  • 2
    English is good. Well asked question. +1
    – spender
    Sep 24, 2013 at 18:49
  • spender: thanks! I wish I'd found a better title, though.
    – dureuill
    Sep 24, 2013 at 18:55
  • 2
    Solution B looks much less error-prone. And since you're doing a linear scan through a list anyway, Solution A has the same asymptotic performance. The performance difference might not really matter. One of these might have better locality of reference but it really depends on what the access pattern to the different types of objects is. You can also get rid of the .OfType() method by using a visitor pattern but in this case it seems to me more like patternwank than something useful. (For one all your battlefield entities would have to have a bunch of empty methods.)
    – millimoose
    Sep 24, 2013 at 19:07

3 Answers 3

4

Solution A, but don't discount querying the entire list of instances at once if there is a reason to do so.

In general (big generalization, but with significant precedent), you will achieve the greatest flexibility by working with the least derived type possible, that is, just the interface you care about. You will likely get the best performance from working with and grouping instances ahead of time rather than splitting them out after the fact.

Whether or not that performance gain matters is a different question. Since you are probably talking about 10s or 100s of objects (not millions), performance wouldn't be my first concern.

I would shy away from anything which requires real-time type interrogation from a design standpoint (but that's a matter of opinion).

As with performance, profile memory before designing around it. If you are using Visual Studio, you have great tools available to you for doing so. And presumably you aren't copying these instances, so the overhead is minimal anyhow.

A hybrid approach could also make sense.

  • Add/remove from a single collection.
  • Expose both the collection and filtered, read-only collections of a specific type.
  • Only (re)build those filtered collections when needed.

public class Battlefield
{
    private readonly IList<IBattleElement> _all = new List<IBattleElement>();
    private IReadOnlyList<IActor> _actors;
    private bool _isDirty;

    /// <summary>
    ///     Gets a list of all elements.
    /// </summary>
    public IReadOnlyList<IBattleElement> All
    {
        get { return _all; }
    }

    /// <summary>
    ///     Gets a filtered list of elements that are <c>IActor</c>.
    /// </summary>
    public IReadOnlyList<IActor> Actors
    {
        get
        {
            if( _isDirty || _actors == null )
            {
                _actors = All.OfType<IActor>().ToList();
            }

            return _actors;
        }
    }

    /// <summary>
    ///     The one and only way to add new elements. This could be made thread-safe if needed.
    /// </summary>
    /// <param name="element"></param>
    public void AddElement( IBattleElement element )
    {
        _all.Add( element );
        _isDirty = true;
    }
}

...and that my question carries at least a little bit of interest and doesn't indicate an overall silliness in the design itself.

Not silly at all.

3
  • Indeed we are speaking tens or hundreds of objects at most, but I'm interested in the more general performance implications. The big problem with solution A is adding or removing elements from the various collections. Is there anything I could do to make this process less error-prone?
    – dureuill
    Sep 24, 2013 at 19:23
  • Good question. One way is to abstract the classification into a helper/manager that knows how to manipulate the various collections. So you could have an AddToBattlefield() method which properly classifies the object based on the interface(s) it implements. This still requires type interrogation, but it only happens once and against one instance.
    – Tim M.
    Sep 24, 2013 at 19:29
  • I added an additional approach which avoids having to add instances to multiple collections.
    – Tim M.
    Sep 24, 2013 at 19:43
2

I would go with Solution A; the extra memory footprint is effectively having multiple pointers to the same instance of an object, and the code is much easier to maintain for future extensibility.

BTW ... a question like this is more opinion based, so I don't think there is a right or wrong answer. For example, I could tweak Solution A to implement IDictionary instead of IList and you don't need to worry about index maintenance!

1
  • Yes, I originally put a ICollection there, then used the index thing in an example. Currently, the implemented example does use List, though, as I'm trying to avoid string that makes people in the C++ part of the engine angry. Then, I could use a IDictionary without indexing it with a string...
    – dureuill
    Sep 24, 2013 at 18:59
1

I would create one last interface. IBattleFieldObject, for all of them to be common. Then put them all in a list via constructor for Dependency Injection. Then in your Update method, I'd use a lambda to extract all IActor's via linq. Then perform my actions relevant to IActor. Also, in Update, you could handle any other Interfaces you'd need to use to simulate a battlefield.

var IActors = (from list in battlefieldobjects where list is IActor select list).ToList();

Or you could make an extension :

public static List<IActor> GetActors(this List<IBattleFieldObject> list)
{
    return list.Where(t => t is IActor).ToList();
}

Usage : battlefieldobjects.GetActors();

It would eliminate the difficulty of removing objects in your various collections. When an object needs to be removed..just remove it from your List collection.

Also, should your game add any new features or behaviors.. you'll be able to just add the IBattleFieldObject interface onto that new "thing".. and then throw in the code for handling that new "thing" in your update method.

2
  • So your solution would be akin to my solution B, but using lambdas and extensions instead of my limited TypeOf attempt. What would be the cost of the GetActors method, though? Also, isn't the Where(t => t is IActor) involving runtime type check?
    – dureuill
    Sep 24, 2013 at 19:19
  • Any attempt at speculation would be evil. I'd say that since games are usually massive do while loops.. the cleaner and simpler and shorter your code is.. the happier anyone involved will be. As long as the code isn't arcane.. keeping your code as lean as possible is a service in itself whether on a team, or solo.
    – Slack Shot
    Sep 24, 2013 at 19:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.