Inheritance best practice

inheritancepatterns-and-practices

I'm fairly new to object oriented programming and have a question I've stumbled upon regarding inheritance best practice.

I'm building a system for weapons in a game. I have a base class called Weapon and two subclasses – Melee and Projectile (such as knives and guns) – inheriting from Weapon.

All weapons have stats (like Attack Point) and parts (like Grip, Magazine and Blade). Booth guns and knives have Attack Point and Grip. But only guns have Magazines and only knives have Blade.

My question here is how to think when inheriting from Weapon:

  1. Thematically a weapon consist of parts so it would make sense to have the classes Melee and Projectile be in charge of all the parts that weapon consist of, so Melee have a Grip and a Blade, and Projectile have a Grip and a Magazine. But then I would duplicate the Grip field.

  2. Since both weapon types have Grip, should Grip be a part of the base class Weapon? It feels weird to break out Grip and put it by itself in another class.

  3. Weapon hold all parts, even if the subclasses don't use all of them? But the it feels like I will bloat the Weapon class.

Is there some sort of best practice? Thank you!

Best Answer

Inheritance (driven to the extreme) is not an efficient approach in modeling something like weapons or enemies in a game. It's quite common to see people thinking about having Enemy, FlyingEnemy, GroundEnemy, then wanting to add more behaviour and realize that they'd end up with InvisibleFlyingEnemy and so on.

You're trying to decompose your weapon into their sub-parts, then trying to avoid duplication. One could ask you why you have different classes for the weapons, but your Grip class is shared by both (i.e. why not BladeGrip and ProjectileGrip). This can easily result in weird inheritance trees, and in the end none of them really makes you comfortable.

Since that doesn't work very well, generally in game development you avoid inheritance and use the Entity-Component-System architecture.

I'm not saying that you shouldn't have any inheritance, but there's no advantage in trying to get a 1-to-1 mapping between classes and what you see in the game. Disadvantages include serious inflexibility when you try to add new things and wasting time working on the invisible inheritance hierarchy instead of the visible game.

Related Topic