Search code examples
c#oopscenegraph

Building a new hierarchy, use an abstract class or an interface?


I'm preparing to build a 2D scene graph for my game, and i would like to know whether i should use at it's root an interface or two or a couple of abstract classes. Here's my requirements:

  • Base node item
    • needs to be able to store a matrix
    • also needs to be able to store a list of child nodes
    • as well as a single parent node
  • Transform node items
    • needs to have a Draw method (implementation is highly probable to be the same)
    • requires that the base node item be implemented/derived from
  • Drawable node item
    • needs to have a Draw method (implementation may be different)
    • requires that the base node item be implemented/derived from and cannot be implemented/derived from alongside the transform node item

What scheme of base classes/interfaces should i use for this?


Solution

  • Jasonh covered the basics -- use the abstract class where you want to share code, otherwise use the interface.

    I wan to add one point -- even if you go the abstract class route, I'd still recommend creating an interface as well. You never know when you'll want to have a subclass that acts like the others, but really needs to inherit another class for some reason. Abstract base classes are great to save implementation code. Interfaces are more flexible though, so unless there's a really good reason (ie. your testing reveals you can't take the performance hit of virtual method calls), use an interface as well as an abstract base class where it makes sense.

    My general rule on this is: use interfaces to define the API, and use abstract base classes to allow implementations of the interface to share code.