SOLID principles

SOLID is a bundle of five object-oriented design principles that help you write code that’s easier to understand, change, and not hate six months later
Here’s the rundown, with a practical lens.


S — Single Responsibility Principle (SRP)

A class should have one reason to change.

In practice:
If a class does too many things, changes ripple everywhere.

Bad smell

UserService:
- validates users
- saves users to DB
- sends welcome emails

Better

  • UserValidator

  • UserRepository

  • EmailService

💡 Most-used in real life. Even outside OOP, this principle saves you constantly.


O — Open/Closed Principle (OCP)

Open for extension, closed for modification.

In practice:
You should be able to add new behavior without editing existing, tested code.

Example

  • Use interfaces / abstract classes

  • Use strategy patterns instead of if/else explosions

PaymentProcessor
  ├── CreditCardPayment
  ├── PaypalPayment
  └── CryptoPayment

Add a new payment type → no need to touch old code.

💡 Used a lot in frameworks, plugins, and business rules.


L — Liskov Substitution Principle (LSP)

Subtypes must be usable anywhere their base type is expected.

In practice:
If subclassing breaks expectations, you’re in trouble.

Classic red flag:

Square extends Rectangle

Because changing width breaks height assumptions.

💡 You mostly notice LSP when it’s violated—bugs appear in “perfectly valid” polymorphism.


I — Interface Segregation Principle (ISP)

Clients shouldn’t depend on methods they don’t use.

In practice:
Prefer small, focused interfaces over giant god-interfaces.

Bad

Machine:
- print()
- scan()
- fax()

Better

  • Printable

  • Scannable

  • Faxable

💡 Super common in APIs and microservices—especially when contracts evolve.


D — Dependency Inversion Principle (DIP)

Depend on abstractions, not concrete implementations.

In practice:
High-level code shouldn’t care how things are done.

OrderService → PaymentGateway (interface)
                   ↑
        StripeGateway / PaypalGateway

This enables:

  • Testing with mocks

  • Swapping implementations

  • Cleaner architecture

💡 Heavily used with dependency injection frameworks.


Which SOLID principles get used the most in practice?

If we’re being honest:

  1. Single Responsibility (SRP) — constantly, everywhere

  2. Dependency Inversion (DIP) — especially in testable systems

  3. Interface Segregation (ISP) — once systems grow

  4. Open/Closed (OCP) — when extensibility matters

  5. Liskov (LSP) — more of a guardrail than a daily tool

Or said differently:

  • SRP & DIP → daily habits

  • OCP & ISP → design decisions

  • LSP → “don’t mess this up”


Nenhum comentário:

Postar um comentário

HashMap in Java

Let’s break down how   HashMap   works internally (Java 8+ implementation). What Is a HashMap? HashMap<K, V>  is a  hash table–based  ...