OOP Principles - SOLID

Sure, SOLID is an acronym coined by Robert C. Martin (Uncle Bob) in the early 2000s and is a popular set of design principles in object-oriented programming (OOP) intended to make software designs more understandable, flexible, and maintainable.

 

SOLID stands for:

  1. Single Responsibility Principle (SRP)

  2. Open/Closed Principle (OCP)

  3. Liskov Substitution Principle (LSP)

  4. Interface Segregation Principle (ISP)

  5. Dependency Inversion Principle (DIP)

A Brief Explanation of each:

  1. Single Responsibility Principle (SRP): A class should have only one reason to change. This means that a class should only have one job or responsibility. For example, a User class should only handle things directly related to users and shouldn't contain methods for handling, say, product details or order handling.

  2. Open/Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification. This means that you should be able to add new functionality to a class without changing its existing code. This can be achieved by using inheritance and/or interfaces.

  3. Liskov Substitution Principle (LSP): Subtypes must be substitutable for their base types. If class B is a subclass of class A, we should be able to replace A with B without disrupting the behavior of our program. For example, if you have a Bird class with a method fly(), and Penguin is a subclass of Bird, it violates the LSP because penguins can't fly.

  4. Interface Segregation Principle (ISP): Clients should not be forced to depend upon interfaces that they do not use. This principle deals with the disadvantages of "fat" interfaces. Classes that have "fat" interfaces are classes whose interfaces are not cohesive. In other words, the interfaces of the class can be broken up into groups of member functions. Each group serves a different set of clients.

  5. Dependency Inversion Principle (DIP): High-level modules should not depend on low-level modules. Both should depend on abstractions. Also, abstractions should not depend upon details. Details should depend upon abstractions. In other words, instead of writing our abstractions around the methods, we should write our methods around the abstractions. This can be done by using a technique like Dependency Injection.

These principles, when used together, make it easier to avoid code smells, easily refactor code, and are also a part of the agile or adaptive software development.

COSC-1437 / ITSE-2457 Computer Science Dept. - Author: Dr. Kevin Roark