title: Effective communication in a component-based system
body: <p>Yes, this is another question about my game engine, which is <a href="http://www.youtube.com/watch?v=XdJ6aqSx2dc" rel="nofollow noreferrer">coming along very nicely</a>, with much thanks to you guys.</p>
  
  <p>So, if you watched the video (or didn't), the objects in the game are composed of various components for things like position, sprites, movement, collision, sounds, health, etc. I have several message types defined for "tell" type communication between entities and components, but this only goes so far. There are plenty of times when I just need to ask for something, for example an entity's position.</p>
  
  <p>There are dozens of lines in my code that look like this:</p>
  
  <pre><code>SomeComponent comp = (SomeComponent)entity.GetComponent(typeof(SomeComponent));
  if (comp != null) comp.GetSomething();
  </code></pre>
  
  <p>I know this is very ugly, and I know that casting smells of improper OO design. But as complex as things are, there doesn't seem to be a better way. I could of course "hard-code" my component types and just have</p>
  
  <pre><code>SomeComponent comp = entity.GetSomeComponent();
  </code></pre>
  
  <p>but that seems like a cop-out, and a bad one.</p>
  
  <p>I literally JUST REALIZED, while writing this, after having my code this way for months with no solution, that a generic will help me.</p>
  
  <pre><code>SomeComponent comp = entity.GetComponent&lt;SomeComponent&gt;();
  </code></pre>
  
  <p>Amazing how that works. Anyway, this is still only a semantic improvement. My questions remain.</p>
  
  <ol>
  <li>Is this actually that bad?</li>
  <li>What's a better alternative?</li>
  </ol>