SOLID is a collection of fundamental principles designed to enhance the manageability and scalability of code in Object-Oriented Programming (OOP). It consists of five key principles:
These principles were introduced by Robert C. Martin (also known as Uncle Bob) in the early 2000s and have since become widely adopted in the software development community. By following SOLID principles, developers can create code that is easier to understand, modify, and extend, leading to more robust and maintainable software systems.
Single Responsibility Principle is the first and most fundamental principle in OOP and SOLID. As the name sounds, this principle means “One class should have only one specific responsibility to take care of”.
Suppose we have a class called Invoice , which contains 2 methods generateInvoice() and saveToFiles() .
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } public void saveToFiles() { // code to save invoice as a file. } }
This is not a good practice because the Invoice class has two responsibilities. A better approach would be to separate these functionalities into dedicated classes.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } } public class FileManager { public void saveToFiles(Invoice invoice) { // code to save invoice as a file. } }
Here, we can see we have 2 classes for the use case:
Open-Closed principle is another core principle in SOLID. This principle was introduced by Bertrand Meyer in 1997. The idea behind this principle is “Software artifacts (classes, modules, and functions) should open for extensions, but closed for modifications.”
For example;
Let’s say, we have a class called Shape , we can use this class to calculate the area of the shape.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } public void saveToFiles() { // code to save invoice as a file. } }
In the code above, adding a new shape requires modifying the existing Shape class, which is not considered a good practice.
Below is a code example that demonstrates how to apply the Open-Closed Principle to this scenario.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } } public class FileManager { public void saveToFiles(Invoice invoice) { // code to save invoice as a file. } }
With the application of OCP, we can add many shapes as we want without modifying the current implementation.
NOTE: Using interfaces is not the only way to achieve OCP.
Liskov’s Substitution Principle is another important principle in OOP. It was introduced by Barbara Liskov in 1987 during a conference talk on data abstraction.
The principle states, “Objects of a superclass should be replaceable with objects of its subclasses without altering the correctness of the program”.
For example, if Circle and Rectangle are sub types of Shape, then we should be able to replace Shape object with a Circle or Rectangle object without any issues.
public class Shape { private String shapeType; private double radius; private double length; private double width; public Shape(String shapeType, double radius, double length, double width) { this.shapeType = shapeType; this.radius = radius; this.length = length; this.width = width; } public double area() { if (shapeType.equals("circle")) { return Math.PI * (radius * radius); } else if (shapeType.equals("rectangle")) { return length * width; } else { throw new IllegalArgumentException("Unknown shape type"); } } } // Usage public class Main { public static void main(String[] args) { Shape circle = new Shape("circle", 5, 0, 0); Shape rectangle = new Shape("rectangle", 0, 4, 6); System.out.println(circle.area()); System.out.println(rectangle.area()); } }
As demonstrated in this example, adhering to the Liskov Substitution Principle means we should be able to substitute a superclass instance with a subclass instance seamlessly.
The Interface Segregation Principle is one of the five SOLID principles introduced by Robert C. Martin. It states: “Clients should not be forced to depend on interfaces they do not use”.
In other words, Using many task specific interfaces is better than using one general purpose interface.
Below example shows the usage of general purpose interface.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } public void saveToFiles() { // code to save invoice as a file. } }
Using a general-purpose interface like MultifunctionPrinter forces us to implement unnecessary methods, which is considered bad practice. Let’s explore how we can apply the Interface Segregation Principle to this scenario.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } } public class FileManager { public void saveToFiles(Invoice invoice) { // code to save invoice as a file. } }
public class Shape { private String shapeType; private double radius; private double length; private double width; public Shape(String shapeType, double radius, double length, double width) { this.shapeType = shapeType; this.radius = radius; this.length = length; this.width = width; } public double area() { if (shapeType.equals("circle")) { return Math.PI * (radius * radius); } else if (shapeType.equals("rectangle")) { return length * width; } else { throw new IllegalArgumentException("Unknown shape type"); } } } // Usage public class Main { public static void main(String[] args) { Shape circle = new Shape("circle", 5, 0, 0); Shape rectangle = new Shape("rectangle", 0, 4, 6); System.out.println(circle.area()); System.out.println(rectangle.area()); } }
By applying the ISP , we split it into smaller, role-specific interfaces — like Printer, Scanner, and Fax. This allows each class (e.g. BasicPrinter, AdvancedPrinter, or FaxMachine) to implement only the relevant functionality, promoting modularity and reducing unnecessary dependencies.
Dependency Inversion Principle is the final principle of SOLID. Which was also introduced by Robert C. Martin. This promotes loosely-coupled code.
DIP states few points:
In simple terms, instead of a class directly depending on other specific classes (concrete implementations), it should depend on interfaces or abstract classes. This makes the code more flexible and easier to maintain, as you can swap out implementations without changing the dependent class.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } public void saveToFiles() { // code to save invoice as a file. } }
As shown in the example above, the Computer class directly depends on the Keyboard class.
public class Invoice { private Long InvoiceNo; public void generateInvoice() { // code to generate Invoice. } } public class FileManager { public void saveToFiles(Invoice invoice) { // code to save invoice as a file. } }
Now, Computer depends on the InputDevice interface, not a specific Keyboard. This makes it easy to switch to another input device, like a WirelessKeyboard, without modifying the Computer class.
In conclusion, the SOLID principles: Single Responsibility, Open-Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion provide essential guidelines for writing clean, maintainable, and scalable code in object-oriented programming.
By adhering to these principles, developers can create systems that are easier to understand, modify, and extend, ultimately leading to higher quality software and more efficient development processes.
Thank you for reading this article! I hope you now have a solid understanding of the SOLID principles and how you can apply them to enhance your projects.
Follow me on:
— Sadisha Nimsara
The above is the detailed content of SOLID Principles. For more information, please follow other related articles on the PHP Chinese website!