Inheritance vs Composition in Programming

Aug 9, 2024

Inheritance vs. Composition in Programming

Key Concepts

  • Inheritance and Composition are methods used in programming to reuse code effectively.
  • Inheritance is widespread, but Composition can be more suitable in certain situations.

Example Setup

  • Entities:
    • Player: Can attack, has health, hitbox, and accepts user input.
    • Enemy: Similar attributes to Player but includes AI.

Inheritance Approach

  • Create an Entity class for shared attributes (attack, health, hitbox).
    • Player and Enemy extend from Entity.
    • Changes in Entity reflect in both Player and Enemy.

Limitations of Inheritance

  • Adding another object (e.g., Tree) that also takes damage complicates the hierarchy:
    • Tree doesn’t need an attack ability, but inheriting from Entity gives it one.
    • Godot doesn’t support multiple class inheritance, causing issues with class types (e.g., CharacterBody2D).

Composition Approach

  • Instead of a single superclass, create multiple components:
    • Attack Component
    • Health Component
    • Hitbox Component
  • Player and Enemy maintain their lists of needed components.
  • Tree can also use Health and Hitbox components without inheriting unwanted abilities.

Advantages of Composition

  • Greater flexibility since components can be attached to any node.
  • For other objects (e.g., Bullets):
    • Can have only an attack component and a hitbox, without health.

Godot Implementation Steps

  1. Set Up Components:
    • Create Health Component and Hitbox Component nodes in Godot.
    • Implement scripts to manage health and damage.
  2. Attach Components:
    • For Enemy: Add Health Component and Hitbox Component.
    • For Tree: Only attach Health and Hitbox Components.
  3. Collision Handling:
    • Use a Collision Shape as a child of Hitbox Component for unique hitbox shapes.
    • Ensure correct logic for damage and interactions.
  4. Script Functionality:
    • Ensure that components communicate properly: e.g., Hitbox checks for damage functionalities in colliding objects.

Final Thoughts

  • Composition simplifies the hierarchy and allows for more versatile object behaviors.
  • Sometimes, inheritance may be better suited, depending on the scenario.
  • Understanding the appropriate context for using each method is crucial in game development.