DEV Community

Cover image for SOLID
Victor Lis Bronzo
Victor Lis Bronzo

Posted on Edited on

SOLID

WHAT IS SOLID?

If you are a dev and have browsed this network, you've probably seen dozens of posts about this topic...

So, straight to the point, SOLID is a set of 5 principles that help improve the quality, scalability, and maintainability of software projects. And here on this network, I will share my experience with it!


SINGLE RESPONSIBILITY PRINCIPLE

A class should have one, and exclusively one, reason to change.

In other words, we shouldn't have a single class doing everything: receiving data, validating requests, applying business rules, and accessing the database...

This class that “does it all” is the so-called “God Class”, and it is an anti-pattern.

Code Example:

// ❌ Anti-pattern: God Class doing too much
class UserAccount {
  createAccount(user: any) {
    // 1. Validates request
    if (!user.email) throw new Error("Email is required");
    // 2. Applies business rules
    user.status = "active";
    // 3. Accesses the database
    database.save(user);
    // 4. Sends email
    emailService.send("Welcome!");
  }
}

// ✅ SOLID: Separated responsibilities
class UserValidator {
  validate(user: any) { /* validation logic */ }
}
class UserRepository {
  save(user: any) { /* DB logic */ }
}
class EmailSender {
  send(message: string) { /* email logic */ }
}
Enter fullscreen mode Exit fullscreen mode

OPEN - CLOSED PRINCIPLE

The integral parts of a code should be open for extension and closed for modification.

The idea is to avoid relying on conditional checks using if-else and switch. When a new requirement arrives, you add the behavior by creating something new, without modifying the old code.

Code Example:

// ❌ Anti-pattern: Modifying existing code for every new type
class PaymentProcessor {
  process(paymentType: string, amount: number) {
    if (paymentType === "