<p>A basic problem I run into quite often, but ever found a clean solution to, is one where you want to code behaviour for interaction between different objects of a common base class or interface. To make it a bit concrete, I'll throw in an example;</p>

<p><em>Bob has been coding on a strategy game which supports "cool geographical effects". These round up to simple constraints such as if troops are walking in water, they are slowed 25%. If they are walking on grass, they are slowed 5%, and if they are walking on pavement they are slowed by 0%.</em></p>

<p><em>Now, management told Bob that they needed new sorts of troops. There would be jeeps, boats and also hovercrafts. Also, they wanted jeeps to take damage if they went drove into water, and hovercrafts would ignore all three of the terrain types. Rumor has it also that they might add another terrain type with even more features than slowing units down and taking damage.</em></p>

<p>A very rough pseudo code example follows:</p>

<pre><code>public interface ITerrain
{
    void AffectUnit(IUnit unit);
}

public class Water : ITerrain
{
    public void AffectUnit(IUnit unit)
    {
        if (unit is HoverCraft)
        {
            // Don't affect it anyhow
        }
        if (unit is FootSoldier)
        {
            unit.SpeedMultiplier = 0.75f;
        }
        if (unit is Jeep)
        {
            unit.SpeedMultiplier = 0.70f;
            unit.Health -= 5.0f;
        }
        if (unit is Boat)
        {
            // Don't affect it anyhow
        }
        /*
         * List grows larger each day...
         */
    }
}
public class Grass : ITerrain
{
    public void AffectUnit(IUnit unit)
    {
        if (unit is HoverCraft)
        {
            // Don't affect it anyhow
        }
        if (unit is FootSoldier)
        {
            unit.SpeedMultiplier = 0.95f;
        }
        if (unit is Jeep)
        {
            unit.SpeedMultiplier = 0.85f;
        }
        if (unit is Boat)
        {
            unit.SpeedMultiplier = 0.0f;
            unit.Health = 0.0f;
            Boat boat = unit as Boat;
            boat.DamagePropeller();
            // Perhaps throw in an explosion aswell?
        }
        /*
         * List grows larger each day...
         */
    }
}
</code></pre>

<p>As you can see, things would have been better if Bob had a solid design document from the beginning. As the number of units and terrain types grow, so does code complexity. Not only does Bob have to worry about figuring out which members might need to be added to the unit interface, but he also has to repeat alot of code. It's very likely that new terrain types require additional information from what can be obtained from the basic IUnit interface. </p>

<p>Each time we add another unit into the game, each terrain must be updated to handle the new unit. Clearly, this makes for a lot of repetition, not to mention the ugly runtime check which determines the type of unit being dealt with. I've opted out calls to the specific subtypes in this example, but those kinds of calls are neccessary to make. <em>An example would be that when a boat hits land, its propeller should be damaged. Not all units have propellers.</em></p>

<p>I am unsure what this kind of problem is called, but it is a many-to-many dependence  which I have a hard time decoupling. I don't fancy having 100's of overloads for each IUnit subclass on ITerrain as I would want to come clean with coupling.</p>

<p>Any light on this problem is highly sought after. Perhaps I'm thinking way out of orbit all together?</p>

[{'answer_id': 68560, 'author': 'Jiaaro', 'author_id': 2908, 'author_profile': 'https://Stackoverflow.com/users/2908', 'pm_score': 0, 'selected': False, 'text': '<p>Old idea:</p>\n\n<blockquote>\n  <p>Make a class iTerrain and another\n  class iUnit which accepts an argument\n  which is the terrain type including a\n  method for affecting each unit type</p>\n  \n  <p>example:</p>\n\n<pre> <code> boat = new\niUnit("watercraft") field = new\niTerrain("grass")\nfield.effects(boat)</code></pre>\n</blockquote>\n\n<p>ok forget all that I have a better idea:</p>\n\n<p>Make the effects of each terrain a property of each unit</p>\n\n<p>Example:</p>\n\n<pre><code>\npublic class hovercraft : unit {\n    #You make a base class for defaults and redefine as necessary\n    speed_multiplier.water = 1\n}\n\npublic class boat : unit {\n    speed_multiplier.land = 0\n}\n</code></pre>\n'}, {'answer_id': 68658, 'author': 'Tim Williscroft', 'author_id': 2789, 'author_profile': 'https://Stackoverflow.com/users/2789', 'pm_score': 1, 'selected': False, 'text': "<p>Terrain has-a Terrain Attribute </p>\n\n<p>Terrain Attributes are multidimensional. </p>\n\n<p>Units has-a Propulsion.</p>\n\n<p>Propulsion is compatible able with Terrain Attributes.</p>\n\n<p>Units move by a Terrain visit with Propulsion as an argument.\nThat gets delegated to the Propulsion.</p>\n\n<p>Units <em>may</em> get affected by terrain as part of the visit.</p>\n\n<p>Unit code knows nothing about propulsion.\nTerrain types can change w/o changing anything except Terrain Attributes and Propulsion.\nPropuslion's constructors protect existing units from new methods of travel.</p>\n"}, {'answer_id': 68888, 'author': 'munificent', 'author_id': 9457, 'author_profile': 'https://Stackoverflow.com/users/9457', 'pm_score': 1, 'selected': False, 'text': '<p>The limitation you\'re running into here is that C#, unlike some other OOP languages, lacks <a href="http://en.wikipedia.org/wiki/Multiple_dispatch" rel="nofollow noreferrer">multiple dispatch</a>.</p>\n\n<p>In other words, given these base classes:</p>\n\n<pre><code>public class Base\n{\n    public virtual void Go() { Console.WriteLine("in Base"); }\n}\n\npublic class Derived : Base\n{\n    public virtual void Go() { Console.WriteLine("in Derived"); }\n}\n</code></pre>\n\n<p>This function:</p>\n\n<pre><code>public void Test()\n{\n    Base obj = new Derived();\n    obj.Go();\n}\n</code></pre>\n\n<p>will correctly output "in Derived" even though the reference "obj" is of type Base. This is because <em>at runtime</em> C# will correctly find the most-derived Go() to call. </p>\n\n<p>However, since C# is a single dispatch language, it only does this for the "first parameter" which is implicitly "this" in an OOP language. The following code does <em>not</em> work like the above:</p>\n\n<pre><code>public class TestClass\n{\n    public void Go(Base b)\n    {\n        Console.WriteLine("Base arg");\n    }\n\n    public void Go(Derived d)\n    {\n        Console.WriteLine("Derived arg");\n    }\n\n    public void Test()\n    {\n        Base obj = new Derived();\n        Go(obj);\n    }\n}\n</code></pre>\n\n<p>This will output "Base arg" because aside from "this" all other parameters are <em>statically</em> dispatched, which means they are bound to the called method at compile time. At compile time, the only thing the compiler knows is the declared type of the argument being passed ("Base obj") and not its actual type, so the method call is bound to the Go(Base b) one.</p>\n\n<p>A solution to your problem then, is to basically hand-author a little method dispatcher:</p>\n\n<pre><code>public class Dispatcher\n{\n    public void Dispatch(IUnit unit, ITerrain terrain)\n    {\n        Type unitType = unit.GetType();\n        Type terrainType = terrain.GetType();\n\n        // go through the list and find the action that corresponds to the\n        // most-derived IUnit and ITerrain types that are in the ancestor\n        // chain for unitType and terrainType.\n        Action&lt;IUnit, ITerrain&gt; action = /* left as exercise for reader ;) */\n\n        action(unit, terrain);\n    }\n\n    // add functions to this\n    public List&lt;Action&lt;IUnit, ITerrain&gt;&gt; Actions = new List&lt;Action&lt;IUnit, ITerrain&gt;&gt;();\n}\n</code></pre>\n\n<p>You can use reflection to inspect the generic parameters of each Action passed in and then choose the most-derived one that matches the unit and terrain given, then call that function. The functions added to Actions can be anywhere, even distributed across multiple assemblies.</p>\n\n<p>Interestingly, I\'ve run into this problem a few times, but never outside of the context of games.</p>\n'}, {'answer_id': 69129, 'author': 'Steven A. Lowe', 'author_id': 9345, 'author_profile': 'https://Stackoverflow.com/users/9345', 'pm_score': 1, 'selected': False, 'text': "<p>decouple the interaction rules from the Unit and Terrain classes; interaction rules are more general than that. For example a hash table might be used with the key being a pair of interacting types and the value being an 'effector' method operating on objects of those types.</p>\n\n<p>when two objects must interact, find ALL of the interaction rules in the hash table and execute them</p>\n\n<p>this eliminates the inter-class dependencies, not to mention the hideous switch statements in your original example</p>\n\n<p>if performance becomes an issue, and the interaction rules do not change during execution, cache the rule-sets for type pairs as they are encountered and emit a new MSIL method to run them all at once</p>\n"}, {'answer_id': 69253, 'author': '17 of 26', 'author_id': 2284, 'author_profile': 'https://Stackoverflow.com/users/2284', 'pm_score': 1, 'selected': False, 'text': "<p>There's definitely three objects in play here:</p>\n\n<blockquote>\n  <p>1) Terrain<br>\n  2) Terrain Effects<br>\n  3) Units</p>\n</blockquote>\n\n<p>I would not suggest creating a map with the <em>pair</em> of terrain/unit as a key to look up the action.  That is going to make it difficult for you to make sure you've got every combination covered as the lists of units and terrains grow.  </p>\n\n<p>In fact, it appears that every terrain-unit combination has a unique terrain effect so it's doubtful that you'd see a benefit from having a common list of terrain effects at all.</p>\n\n<p>Instead, I would have each unit maintain its own map of terrain to terrain effect.  Then, the terrain can just call Unit->AffectUnit(myTerrainType) and the unit can look up the effect that the terrain will have on itself.</p>\n"}]
['https://Stackoverflow.com/questions/68537', 'https://Stackoverflow.com', 'https://Stackoverflow.com/users/2166173/']