C
C#3mo ago
Zeke

Composition over Inheritance

My architecture is currently as follows: Unit C# object Behaviours (Attack, Health, Targeting, Movement, etc) component based so I add and remove as needed. However, the way I currently use composition is I have an AssassinAttackComponent, MageAttackComponent, DefaultAttackComponent, etc. I feel like there are some logic that I reuse between all 3 of these (and more to come), but I don't want to inherit from these as that would break the push for composition over inheritance right? At that point my class attack components would be inheriting from DefaultAttackComponent, all of them. Advice?
3 Replies
mtreit
mtreit3mo ago
If inheritance cleanly solves the problem and allows you to avoid duplicate code, use inheritance.
Zeke
Zeke3mo ago
Even if I'm using inheritance with composition side by side?
mtreit
mtreit3mo ago
It's not a black and white proposition. The terms aren't even that well defined, there are lots of fuzzy grey areas. A lot of people consider using interfaces instead of base classes is composition, I've seen other people argue that's not right. It's all semantics. Do what lets you solve your specific programming problem.