> ## Documentation Index
> Fetch the complete documentation index at: https://resources.devweekends.com/llms.txt
> Use this file to discover all available pages before exploring further.

# SOLID Introduction

> Five magic rules that make your code super clean and easy to change!

<Info>
  **Time to Master**: \~30 minutes | **Difficulty**: Beginner-friendly | **Prerequisite**: Basic OOP understanding
</Info>

## 🏗️ What are SOLID Principles?

Imagine building with LEGO blocks:

* **Good LEGO sets**: Pieces fit together nicely, easy to change, fun to build
* **Bad LEGO sets**: Pieces stuck together with glue, can't change anything without breaking

SOLID principles are **five rules** that help you write code like good LEGO sets - modular, flexible, and maintainable!

<CardGroup cols={5}>
  <Card title="S" icon="1">
    Single Responsibility
  </Card>

  <Card title="O" icon="2">
    Open/Closed
  </Card>

  <Card title="L" icon="3">
    Liskov Substitution
  </Card>

  <Card title="I" icon="4">
    Interface Segregation
  </Card>

  <Card title="D" icon="5">
    Dependency Inversion
  </Card>
</CardGroup>

***

## 🎯 Why Learn SOLID?

<CardGroup cols={2}>
  <Card title="🔧 Easy to Change" icon="wrench">
    Modify one thing without breaking everything else
  </Card>

  <Card title="🐛 Fewer Bugs" icon="bug-slash">
    Simpler classes = fewer places for bugs to hide
  </Card>

  <Card title="🧪 Easy to Test" icon="flask">
    Small, focused classes are easy to test
  </Card>

  <Card title="👥 Team Friendly" icon="users">
    Others can understand and work with your code
  </Card>
</CardGroup>

<Warning>
  **Interview Alert**: SOLID principles are asked in almost every LLD interview! "Does your design follow SOLID?" is a common follow-up question.
</Warning>

**Think of SOLID like building codes for construction.** A building inspector does not care whether your house is Victorian or modern -- they care that the foundation is sound, the wiring is safe, and the plumbing does not cross-contaminate. SOLID principles are the building codes of software design. They do not prescribe a specific architecture, but they ensure that whatever you build can be maintained, extended, and debugged by the next person who opens the codebase.

***

## 📚 The Five Principles at a Glance

### S - Single Responsibility Principle (SRP)

> **"Do ONE thing, and do it well!"**

Like how a chef COOKS, a waiter SERVES, and a cashier handles PAYMENT - each has one job.

```python theme={null}
# ❌ BAD: UserManager does EVERYTHING
class UserManager:
    def create_user(self): pass
    def send_email(self): pass      # Email is a different job!
    def generate_report(self): pass  # Reporting is different too!

# ✅ GOOD: Each class has ONE job
class UserService:
    def create_user(self): pass

class EmailService:
    def send_email(self): pass

class ReportService:
    def generate_report(self): pass
```

***

### O - Open/Closed Principle (OCP)

> **"Open for extension, closed for modification!"**

Like adding new apps to your phone without rewriting the operating system.

```python theme={null}
# ❌ BAD: Must modify when adding new shapes
class AreaCalculator:
    def calculate(self, shape):
        if shape.type == "circle":
            return 3.14 * shape.radius ** 2
        elif shape.type == "rectangle":  # Must keep adding elif!
            return shape.width * shape.height

# ✅ GOOD: Add new shapes without changing existing code
class Shape:
    def area(self): pass

class Circle(Shape):
    def area(self):
        return 3.14 * self.radius ** 2

class Rectangle(Shape):
    def area(self):
        return self.width * self.height

# Adding Triangle? Just create new class, don't touch existing!
```

***

### L - Liskov Substitution Principle (LSP)

> **"Children should be able to replace their parents!"**

If you expect an Animal, a Dog should work perfectly - without surprises.

```python theme={null}
# ❌ BAD: Penguin breaks the Bird contract
class Bird:
    def fly(self): pass

class Penguin(Bird):  # But penguins can't fly! 🐧
    def fly(self):
        raise Exception("I can't fly!")  # Surprise!

# ✅ GOOD: Separate flying and non-flying birds
class Bird:
    def eat(self): pass

class FlyingBird(Bird):
    def fly(self): pass

class Penguin(Bird):  # No fly() method to break
    def swim(self): pass
```

***

### I - Interface Segregation Principle (ISP)

> **"Don't force me to implement things I don't need!"**

Like a printer that only prints - it shouldn't need a fax feature if you don't use fax.

```python theme={null}
# ❌ BAD: Forces all workers to implement every method
class Worker:
    def work(self): pass
    def eat(self): pass
    def sleep(self): pass

class Robot(Worker):  # Robots don't eat or sleep!
    def eat(self): raise Exception("I don't eat!")
    def sleep(self): raise Exception("I don't sleep!")

# ✅ GOOD: Separate interfaces
class Workable:
    def work(self): pass

class Eatable:
    def eat(self): pass

class Robot(Workable):  # Only implements what it needs
    def work(self): pass
```

***

### D - Dependency Inversion Principle (DIP)

> **"Depend on abstractions, not concrete things!"**

Like a phone charger - you plug into the WALL SOCKET (abstraction), not directly into power lines!

```python theme={null}
# ❌ BAD: High-level depends on low-level details
class PaymentProcessor:
    def __init__(self):
        self.stripe = StripeAPI()  # Directly tied to Stripe!
    
    def pay(self, amount):
        self.stripe.charge(amount)  # What if we switch to PayPal?

# ✅ GOOD: Depend on abstraction
class PaymentGateway:  # Abstract
    def charge(self, amount): pass

class PaymentProcessor:
    def __init__(self, gateway: PaymentGateway):  # Accept ANY gateway
        self.gateway = gateway
    
    def pay(self, amount):
        self.gateway.charge(amount)  # Works with Stripe, PayPal, anything!
```

***

## 🎮 Interactive Memory Aid

Remember SOLID with this story:

<Steps>
  <Step title="S is for Single Chef 👨‍🍳">
    The chef only COOKS - doesn't clean, serve, or manage money
  </Step>

  <Step title="O is for Open Restaurant 🏪">
    Add new dishes to the menu WITHOUT rewriting the kitchen
  </Step>

  <Step title="L is for Like Parent, Like Child 👨‍👧">
    If menu says "pasta", any pasta type should work the same
  </Step>

  <Step title="I is for I Only Take Orders 📝">
    Waiter takes orders - doesn't need to know cooking
  </Step>

  <Step title="D is for Depend on Rules 📋">
    Kitchen depends on RECIPE standards, not specific ingredients
  </Step>
</Steps>

***

## 🧪 Quick Self-Test

<Accordion title="Test Your Understanding" icon="brain">
  **Q1: Which principle does this violate?**

  ```python theme={null}
  class Report:
      def generate_data(self): pass
      def format_as_pdf(self): pass
      def send_email(self): pass
  ```

  <details>
    <summary>Answer</summary>
    **Single Responsibility Principle (S)** - The Report class is doing THREE things: generating data, formatting, and sending email!
  </details>

  ***

  **Q2: Which principle does this violate?**

  ```python theme={null}
  class Calculator:
      def calculate(self, operation, a, b):
          if operation == "add": return a + b
          elif operation == "subtract": return a - b
          # Must modify here for each new operation!
  ```

  <details>
    <summary>Answer</summary>
    **Open/Closed Principle (O)** - You have to MODIFY the class every time you add a new operation. Use polymorphism instead!
  </details>

  ***

  **Q3: Which principle does this violate?**

  ```python theme={null}
  class Machine:
      def print_doc(self): pass
      def scan_doc(self): pass
      def fax_doc(self): pass
      def copy_doc(self): pass

  class SimplePrinter(Machine):  # Only prints!
      def scan_doc(self): raise NotImplementedError
      def fax_doc(self): raise NotImplementedError
      def copy_doc(self): raise NotImplementedError
  ```

  <details>
    <summary>Answer</summary>
    **Interface Segregation Principle (I)** - SimplePrinter is forced to implement methods it doesn't need. Split into smaller interfaces!
  </details>
</Accordion>

***

## 📚 The SOLID Journey

Now let's dive deep into each principle with fun examples and exercises!

<CardGroup cols={2}>
  <Card title="S - Single Responsibility" icon="1" href="/lld/solid/srp">
    One class, one job - like workers in a factory
  </Card>

  <Card title="O - Open/Closed" icon="2" href="/lld/solid/ocp">
    Add features without changing code - like plugins
  </Card>

  <Card title="L - Liskov Substitution" icon="3" href="/lld/solid/lsp">
    Children behave like parents - no surprises
  </Card>

  <Card title="I - Interface Segregation" icon="4" href="/lld/solid/isp">
    Many specific interfaces - not one giant one
  </Card>

  <Card title="D - Dependency Inversion" icon="5" href="/lld/solid/dip">
    Depend on contracts - not implementations
  </Card>
</CardGroup>

***

## Interview Insight

<Info>
  **How SOLID shows up in interviews:** Interviewers rarely ask "explain the Liskov Substitution Principle" in isolation. Instead, they give you a design problem and watch whether your design *naturally follows* SOLID. For example, when you separate UserRepository from EmailService (SRP), use a PaymentGateway interface instead of if/elif chains (OCP), ensure all subclasses honor parent contracts (LSP), define small focused interfaces (ISP), and inject dependencies rather than hardcoding them (DIP) -- you are demonstrating SOLID without naming it. The highest-signal move is to name the principle when you make a design choice: "I am splitting this into two classes because I want each to have a single reason to change -- that is the Single Responsibility Principle." This shows you are not just designing intuitively but reasoning deliberately.
</Info>

***

## 🏃 Start Your Journey!

<Card title="Begin with Single Responsibility Principle →" icon="arrow-right" href="/lld/solid/srp">
  Learn the first and most important SOLID principle - keeping your classes focused!
</Card>
