Understanding Composition over Inheritance in Game Development
Asked by
CuriousCoder92
I'm curious about the concept of "Composition over Inheritance" when it comes to game development. For example, if you have an Entity that implements processes like Collision and Render, how does that work without having unique implementations for each process? I imagine different types of Entities, such as an octopus and a spaceship, would need very distinct implementations for the same processes. Doesn't that complicate the idea that composition is supposed to be easier and more modular?
Answers
Great question! The general rule is that composition is about "it has a..." while inheritance is for "it is a...". Collision and Render are behaviors of an Entity, so it makes sense to lean towards inheritance here. Both an octopus and a spaceship are still entities, and you want your code to treat them as such without getting too specialized. That said, if certain entities share similar collision behaviors, that's a perfect opportunity to use composition!
Reply to this answer
Add your answer
Answers are reviewed before publication.
GamerDevAndy: How would you implement a mix of these concepts in code? For instance, if you only have an Entity class, could you use composition for broad behaviors like rendering and then create a superclass for more specialized behaviors, like an octopus's unique movement?