2dbi

Model a human body with OOP

viaLeetCode

Problem Model a human body with object-oriented design. The body is composed of parts (Head, Arms, Legs, Torso, …) that must integrate into a single Body while enforcing structural constraints such as "at most 2 arms" and "at most 2 legs".

Requirements

  • A part hierarchy: shared behaviour (name, attach/detach, health/state) on a base type; specific parts specialize it.
  • A Body aggregate exposing addPart(part), removePart(part), and queries like getParts(type).
  • Constraint enforcement: attaching a third Arm must fail deterministically (exception or Result), not silently corrupt state.

Core design

  • Abstract BodyPart base class; concrete Arm, Leg, Head, etc. Body holds a Map<PartType, List<BodyPart>> and a Map<PartType, Integer> of maximum cardinalities checked in addPart — composition over inheritance for the body/part relationship.
  • Consider a Builder or factory that assembles a valid default body, so invariants hold from construction.

Discussion points

  • Where the constraint lives (Body vs part vs validator) and why centralizing it in the aggregate is safer.
  • Extensibility: adding new part types without modifying Body (open/closed principle).
  • How composite parts nest (Hand on Arm, Fingers on Hand) — Composite pattern.
  • Thread safety if parts can be attached concurrently.
Add a follow-up question they asked
No follow-ups yet. Be the first to add one.
asked …
LeaderboardSalary
Language
Account