Bird
Raised Fist0
LLDsystem_design~7 mins

Room type hierarchy in LLD - System Design Guide

Choose your learning style10 modes available

Start learning this pattern below

Jump into concepts and practice - no test required

or
Recommended
Test this pattern10 questions across easy, medium, and hard to know if this pattern is strong
Problem Statement
When managing different types of rooms in a system, treating each room type as a separate unrelated entity leads to duplicated code and inconsistent behavior. This makes it hard to add new room types or change common features without breaking existing code.
Solution
Use a hierarchy where a base room class defines common properties and behaviors, and specialized room types inherit and extend this base. This allows code reuse, easier maintenance, and consistent handling of all room types while enabling specific customizations.
Architecture
Room (Base)
- name
Conference
Room

This diagram shows a base Room class with common attributes and methods, and three specialized room types inheriting from it, each adding their own unique features.

Trade-offs
✓ Pros
Reduces code duplication by sharing common features in the base class.
Makes it easier to add new room types by extending the base class.
Ensures consistent behavior across all room types through inheritance.
✗ Cons
Tight coupling between base and derived classes can make changes risky.
Deep hierarchies can become complex and hard to understand.
Inheritance can limit flexibility if room types need to change behavior dynamically.
Use when multiple room types share common features but also have unique behaviors, especially if the number of room types is moderate and mostly static.
Avoid when room types have very different behaviors with little shared code, or when you need to change room behaviors dynamically at runtime.
Real World Examples
Airbnb
Airbnb models different room types like entire homes, private rooms, and shared rooms using a hierarchy to manage shared booking logic and specific features.
HotelTonight
HotelTonight uses room type hierarchies to handle various hotel room categories with shared booking and pricing logic but different amenities.
Code Example
The before code repeats name, capacity, and book method in each room type. The after code moves common parts to a base Room class, reducing duplication and making it easier to add new room types.
LLD
### Before (No hierarchy, duplicated code)
class ConferenceRoom:
    def __init__(self, name, capacity, projector):
        self.name = name
        self.capacity = capacity
        self.projector = projector
    def book(self):
        print(f"Booking conference room {self.name}")

class Bedroom:
    def __init__(self, name, capacity, bed_type):
        self.name = name
        self.capacity = capacity
        self.bed_type = bed_type
    def book(self):
        print(f"Booking bedroom {self.name}")

### After (Using inheritance)
class Room:
    def __init__(self, name, capacity):
        self.name = name
        self.capacity = capacity
    def book(self):
        print(f"Booking room {self.name}")

class ConferenceRoom(Room):
    def __init__(self, name, capacity, projector):
        super().__init__(name, capacity)
        self.projector = projector

class Bedroom(Room):
    def __init__(self, name, capacity, bed_type):
        super().__init__(name, capacity)
        self.bed_type = bed_type

# Usage
conf = ConferenceRoom("Conf A", 50, True)
conf.book()  # Booking room Conf A
bed = Bedroom("Bed 1", 2, "King")
bed.book()   # Booking room Bed 1
OutputSuccess
Alternatives
Composition over Inheritance
Instead of inheriting from a base room, room types contain components that define behavior, allowing more flexible combinations.
Use when: Choose when room behaviors need to change dynamically or when multiple behaviors must be combined without deep hierarchies.
Flat Structure with Type Field
Use a single room class with a type attribute and conditional logic for behavior instead of inheritance.
Use when: Choose when the number of room types is small and behaviors are simple, avoiding complexity of inheritance.
Summary
Room type hierarchy organizes room classes by shared and unique features using inheritance.
It reduces code duplication and eases maintenance by centralizing common logic.
Use it when room types share behavior but need specific customizations.

Practice

(1/5)
1. What is the main purpose of using a Room type hierarchy in system design?
easy
A. To randomly assign room types without any structure
B. To organize rooms by shared and unique features for easier maintenance
C. To store all room data in a single flat list without categories
D. To duplicate room properties in every class separately

Solution

  1. Step 1: Understand the concept of hierarchy

    A hierarchy groups items by common traits, making management simpler.
  2. Step 2: Apply to room types

    Using a base class for shared features and subclasses for specifics avoids duplication and eases updates.
  3. Final Answer:

    To organize rooms by shared and unique features for easier maintenance -> Option B
  4. Quick Check:

    Hierarchy = Organize by features [OK]
Hint: Think: shared features go in base, unique in subclasses [OK]
Common Mistakes:
  • Confusing hierarchy with flat lists
  • Duplicating properties in every room class
  • Ignoring shared features in base class
2. Which of the following is the correct way to define a base class Room with a subclass ConferenceRoom in a typical object-oriented design?
easy
A. class Room {}; class ConferenceRoom extends Room {}
B. class Room; class ConferenceRoom inherits Room
C. class Room() {}; class ConferenceRoom() inherits Room()
D. class Room {}; class ConferenceRoom inherits Room {}

Solution

  1. Step 1: Identify correct syntax for inheritance

    In many modern languages, extends is used to inherit from a base class.
  2. Step 2: Check each option

    class Room {}; class ConferenceRoom extends Room {} uses correct syntax: class ConferenceRoom extends Room {}. Others use incorrect or incomplete syntax.
  3. Final Answer:

    class Room {}; class ConferenceRoom extends Room {} -> Option A
  4. Quick Check:

    Inheritance syntax = extends [OK]
Hint: Remember: subclass extends base class in OOP [OK]
Common Mistakes:
  • Using 'inherits' instead of 'extends'
  • Missing curly braces for class body
  • Incorrect parentheses in class declaration
3. Given this Python-like pseudocode for room types:
class Room:
    def __init__(self, name):
        self.name = name

class Bedroom(Room):
    def __init__(self, name, bed_size):
        super().__init__(name)
        self.bed_size = bed_size

room = Bedroom('Master', 'King')
print(room.name, room.bed_size)

What will be the output?
medium
A. Error: missing argument
B. Bedroom King
C. Master None
D. Master King

Solution

  1. Step 1: Trace object creation

    Creating Bedroom('Master', 'King') calls Bedroom's constructor, which calls Room's constructor with 'Master'.
  2. Step 2: Check printed attributes

    room.name is 'Master' from Room; room.bed_size is 'King' from Bedroom.
  3. Final Answer:

    Master King -> Option D
  4. Quick Check:

    Subclass calls base, attributes set correctly [OK]
Hint: Remember: super() sets base class attributes [OK]
Common Mistakes:
  • Assuming subclass overwrites base attributes
  • Forgetting to call super().__init__
  • Confusing attribute names
4. Consider this code snippet for a room hierarchy:
class Room:
    def __init__(self, name):
        self.name = name

class MeetingRoom(Room):
    def __init__(self, name, capacity):
        self.capacity = capacity

room = MeetingRoom('Boardroom', 20)
print(room.name, room.capacity)

What is the issue here?
medium
A. capacity attribute is not set correctly
B. Syntax error in class definition
C. Missing call to base class constructor causes room.name to be undefined
D. No issue; code runs fine

Solution

  1. Step 1: Check constructor chaining

    MeetingRoom's constructor sets capacity but does not call super().__init__(name), so name is not set.
  2. Step 2: Understand effect on attributes

    Without base constructor call, room.name is missing, causing error or undefined behavior.
  3. Final Answer:

    Missing call to base class constructor causes room.name to be undefined -> Option C
  4. Quick Check:

    Always call base __init__ in subclass [OK]
Hint: Call super().__init__ to set base attributes [OK]
Common Mistakes:
  • Assuming base constructor runs automatically
  • Ignoring missing attributes in subclass
  • Confusing syntax errors with logic errors
5. You need to design a room type hierarchy for a hotel system that includes Room, Bedroom, ConferenceRoom, and Suite. Suites can have multiple bedrooms and a living area. Which design approach best models this?
hard
A. Make Suite inherit from Room and include a list of Bedroom objects plus living area
B. Make Suite inherit from Bedroom and add living area attributes
C. Make Suite a separate class unrelated to Room hierarchy
D. Make Bedroom inherit from Suite to reuse features

Solution

  1. Step 1: Analyze relationships

    Suite is a special Room that contains multiple Bedrooms and a living area, so it should inherit from Room.
  2. Step 2: Model composition

    Suite should have a list of Bedroom objects (composition) to represent multiple bedrooms, plus its own living area attributes.
  3. Final Answer:

    Make Suite inherit from Room and include a list of Bedroom objects plus living area -> Option A
  4. Quick Check:

    Use inheritance + composition for complex types [OK]
Hint: Use composition for multiple rooms inside Suite [OK]
Common Mistakes:
  • Using inheritance to model 'has-many' relationships
  • Ignoring composition for complex room types
  • Making unrelated classes inherit incorrectly