I'm writing a simple game and a lot of the game objects share attributes. I have two potential implementations for this.
The first is using inheritance as specified in the following image:
The bolded classes are the abstract classes, as you might expect. The branches are the derived classes which are actually used. It's important to note that these classes hold data about the objects, there is no functionality associated with them.
Troop and Vehicle, for example, have a common interface that they both use to do things like attack() and move(). The class hierarchy outlined above is just the raw stats. Furthermore, they are all true ISA relationships.
The second implementation uses composition. Instead of the class hierarchy above, each of the abstract classes are instead 'modules' that hold certain data members. So SpecialAbility has a data member called PointsValueObject (although I changed the names of the abstract (though they are no longer abstract) classes to reflect their modular/attribute nature). And Troop has data members: PointsValueObject, PhysicalObject, PhysicalAttackObject, and BattleOBject, each of them being modules that house data about the troop. Again, no functionality exists in these modules, they are used to store data only. Behavior and functionality are still implemented through Interface classes.
My question is this: people generally prefer composition over inheritance, but in this case, I'm inclined to stick with inheritance, since the ISA relationships hold and the hierarchy does not contain behaviors, only data. Is this hierarchy good OOD or is building the classes using the attribute 'modules' better?
If there is no code being reused, what advantage do you see in using inheritance? Inheritance is useful for DRY (Don't Repeat Yourself) when behavior is the same, but without behavior all you are doing is potentially limiting yourself -- if you later decide you have a sub hierarchy that needs less data, there's not a good solution for doing that.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With