Bird
Raised Fist0
LLDsystem_design~7 mins

Enum usage (VehicleType, SpotType) 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 using plain strings or integers to represent categories like vehicle types or parking spot types, the code becomes error-prone and hard to maintain. Typos or inconsistent values can cause bugs that are difficult to trace, and adding new types requires changes scattered across the codebase.
Solution
Enums provide a fixed set of named constants that represent categories such as vehicle types or spot types. By using enums, the code gains clarity, type safety, and easier maintenance because only predefined values are allowed, preventing invalid inputs and simplifying updates.
Architecture
VehicleType
┌───────────┐
ParkingSpot Class
- spot_type: SpotType
Vehicle Class
- vehicle_type: VehicleType

This diagram shows enums VehicleType and SpotType defining fixed categories. These enums are used as types in Vehicle and ParkingSpot classes to ensure only valid types are assigned.

Trade-offs
✓ Pros
Prevents invalid or inconsistent category values by restricting to predefined constants.
Improves code readability by giving meaningful names to category values.
Simplifies maintenance when adding or changing categories in one place.
Enables type checking and better IDE support for autocompletion and error detection.
✗ Cons
Adds slight verbosity compared to using plain strings or integers.
Requires understanding of enum syntax and usage, which may be new to beginners.
May require conversion when interacting with external systems expecting strings or numbers.
Use enums when your system has fixed sets of categories like vehicle types or spot types that rarely change and must be validated consistently across the codebase.
Avoid enums if the category values are highly dynamic, user-defined, or frequently changing at runtime, as enums are static and require code changes to update.
Real World Examples
Uber
Uber uses enums to represent vehicle types such as 'Sedan', 'SUV', and 'Bike' to ensure consistent categorization across their ride matching and pricing systems.
Airbnb
Airbnb uses enums for property types like 'Apartment', 'House', and 'Bed & Breakfast' to validate listing categories and simplify filtering logic.
LinkedIn
LinkedIn uses enums for job types such as 'Full-time', 'Part-time', and 'Contract' to standardize job posting categories and improve search accuracy.
Code Example
Before using enums, vehicle types are plain strings prone to typos and inconsistent values. After applying enums, only predefined VehicleType values are allowed, preventing errors and improving code clarity.
LLD
### Before: Using plain strings (error-prone)
class Vehicle:
    def __init__(self, vehicle_type):
        self.vehicle_type = vehicle_type  # No validation

car = Vehicle('car')
motorcycle = Vehicle('motorcycle')  # Typo fixed here


### After: Using enums (safe and clear)
from enum import Enum

class VehicleType(Enum):
    CAR = 'car'
    MOTORCYCLE = 'motorcycle'
    TRUCK = 'truck'

class Vehicle:
    def __init__(self, vehicle_type: VehicleType):
        self.vehicle_type = vehicle_type

car = Vehicle(VehicleType.CAR)
motorcycle = Vehicle(VehicleType.MOTORCYCLE)  # No typo possible

# Trying to create with invalid type raises error
# invalid_vehicle = Vehicle('motocycle')  # ValueError: 'motocycle' is not a valid VehicleType
OutputSuccess
Alternatives
String constants
Uses plain strings instead of fixed enum types, allowing any string value.
Use when: Choose when categories are very dynamic or user-generated and cannot be fixed in code.
Database lookup tables
Stores category types in a database table rather than code enums, allowing runtime updates.
Use when: Choose when categories need to be managed by non-developers or updated frequently without code deployments.
Summary
Using enums prevents bugs caused by invalid or inconsistent category values.
Enums improve code clarity and maintainability by defining fixed sets of named constants.
They are best used when categories are stable and rarely change at runtime.

Practice

(1/5)
1. What is the main purpose of using enum types like VehicleType and SpotType in system design?
easy
A. To group related constant values and prevent invalid inputs
B. To store large amounts of data efficiently
C. To perform complex mathematical calculations
D. To create user interface elements dynamically

Solution

  1. Step 1: Understand enum purpose

    Enums group related constant values, making code clearer and safer.
  2. Step 2: Identify benefits in system design

    They prevent invalid values by restricting inputs to predefined options.
  3. Final Answer:

    To group related constant values and prevent invalid inputs -> Option A
  4. Quick Check:

    Enums = group constants + prevent errors [OK]
Hint: Enums group fixed options to avoid mistakes [OK]
Common Mistakes:
  • Thinking enums store large data
  • Confusing enums with data structures
  • Using enums for UI elements
2. Which of the following is the correct syntax to define an enum VehicleType with values CAR, BIKE, and TRUCK?
easy
A. enum VehicleType = [CAR, BIKE, TRUCK]
B. enum VehicleType { CAR, BIKE, TRUCK }
C. VehicleType = enum(CAR, BIKE, TRUCK)
D. enum VehicleType: CAR, BIKE, TRUCK

Solution

  1. Step 1: Recall enum declaration syntax

    Standard enum syntax uses curly braces with comma-separated values.
  2. Step 2: Match syntax to options

    enum VehicleType { CAR, BIKE, TRUCK } matches the correct syntax: enum VehicleType { CAR, BIKE, TRUCK }.
  3. Final Answer:

    enum VehicleType { CAR, BIKE, TRUCK } -> Option B
  4. Quick Check:

    Enum syntax = curly braces + commas [OK]
Hint: Enums use braces and commas for values [OK]
Common Mistakes:
  • Using equal sign instead of braces
  • Using square brackets for enums
  • Missing commas between values
3. Given the enum SpotType { COMPACT, LARGE, HANDICAPPED } and a function that assigns spots based on vehicle type, what will be the output of this code snippet?
VehicleType vehicle = VehicleType.CAR;
SpotType spot;
switch(vehicle) {
  case VehicleType.CAR:
    spot = SpotType.COMPACT;
    break;
  case VehicleType.BIKE:
    spot = SpotType.HANDICAPPED;
    break;
  default:
    spot = SpotType.LARGE;
}
print(spot);
medium
A. Error: VehicleType not handled
B. HANDICAPPED
C. COMPACT
D. LARGE

Solution

  1. Step 1: Identify vehicle type value

    VehicleType is set to CAR.
  2. Step 2: Follow switch-case logic

    For CAR, spot is assigned COMPACT.
  3. Final Answer:

    COMPACT -> Option C
  4. Quick Check:

    CAR maps to COMPACT spot [OK]
Hint: Match enum cases carefully in switch [OK]
Common Mistakes:
  • Confusing BIKE case with CAR
  • Assuming default runs for CAR
  • Ignoring break statements
4. Consider this enum usage snippet:
enum VehicleType { CAR, BIKE, TRUCK }

void assignSpot(VehicleType v) {
  if (v == VehicleType.CAR) {
    print("Compact Spot");
  } else if (v == VehicleType.BIKE) {
    print("Bike Spot");
  }
}

What is the problem if assignSpot(VehicleType.TRUCK) is called?
medium
A. Prints "Bike Spot" incorrectly
B. Syntax error due to missing TRUCK case
C. Runtime error because TRUCK is invalid
D. No output because TRUCK case is not handled

Solution

  1. Step 1: Analyze if-else conditions

    Only CAR and BIKE cases are handled explicitly.
  2. Step 2: Consider TRUCK input

    TRUCK does not match any condition, so no print occurs.
  3. Final Answer:

    No output because TRUCK case is not handled -> Option D
  4. Quick Check:

    Unhandled enum value = no output [OK]
Hint: Always handle all enum values or add default [OK]
Common Mistakes:
  • Expecting syntax or runtime error
  • Assuming default print happens
  • Confusing enum invalidity
5. In a parking system, you have enums VehicleType { CAR, BIKE, TRUCK } and SpotType { COMPACT, LARGE, HANDICAPPED }. You want to assign spots such that:
- Cars use COMPACT spots
- Bikes use HANDICAPPED spots
- Trucks use LARGE spots

Which design approach best ensures no invalid spot assignment happens?
hard
A. Use a mapping dictionary from VehicleType to SpotType and validate assignments
B. Use separate if-else blocks without enums for flexibility
C. Assign spots randomly and check later if valid
D. Use strings instead of enums for vehicle and spot types

Solution

  1. Step 1: Understand enum benefits for mapping

    Enums provide fixed sets, so mapping ensures clear, valid assignments.
  2. Step 2: Evaluate design options

    Mapping dictionary with enums enforces rules and prevents invalid spots.
  3. Final Answer:

    Use a mapping dictionary from VehicleType to SpotType and validate assignments -> Option A
  4. Quick Check:

    Mapping enums = safe, clear assignments [OK]
Hint: Map enums directly to enforce valid pairs [OK]
Common Mistakes:
  • Using strings loses type safety
  • Random assignment causes errors
  • If-else without enums is error-prone