DEV Community

vive
vive

Posted on

SOLID principles in OOP for beginners

SOLID principles are sets of best practices aimed to solve the common problems that developers face in object-oriented programming.

While design patterns provide concrete solutions to common design problems, the SOLID principles are way more abstract. They are intended to help in organizing and structuring the code, making it easier to manage and extend over time.

There are five SOLID principles in total:

Single Responsibility Principle (SRP)

Each entity (like a class, function, or method) should have only one responsibility or job.

Advantages:

  • Easier maintenance and updates
  • Clear purpose for each class
  • Simplified testing
  • Enhanced reusability

single responsibility principle code example

Open/Closed Principle (OCP)

Entities (like classes, methods, or functions) should be open for extension but closed for modification. This means you can add new functionality without changing existing code.

Advantages:

  • Lower risk of introducing bugs
  • Faster development of new features since existing code remains unchanged
  • Enhanced reusability

open closed principle code example

Liskov Substitution Principle (LSP)

Subtypes must be substitutable for their base types. In other words, wherever Parent is used, it could be replaced by Child without affecting the functionality of the program (without altering the existing code).

Advantages:

  • New classes can be added without breaking existing functionality
  • Enables creating substitutional parts of complex systems
  • Enhanced reusability

liskov substitution principle code example

Interface Segregation Principle (ISP)

No client should be forced to depend on methods it does not use. In other words, instead of adding new methods to an existing interface, create a new interface.

Advantages:

  • Smaller, more understandable interfaces
  • Changes in one interface do not impact unrelated classes
  • Enhanced reusability

Interface Segregation Principle code example 1

Interface Segregation Principle code example 2

Dependency inversion principle (DIP)

High-level modules should not depend on low-level modules.
Both should depend on abstractions.
Abstractions should not depend on details.
Details should depend on abstractions.

High-level modules - business logic, use cases
Low-level modules - writing to DB, handling HTTP requests

Abstractions - interfaces, abstract classes
Details - concrete classes

Advantages:

  • Promotes flexible and reusable code
  • Reduces coupling between different parts of the codebase
  • Enhanced reusability

Dependency inversion principle code example

Top comments (0)