What is SOLID Principles of Object-oriented Programming?
The SOLID principles are a set of guidelines that were introduced by software engineer Robert C. Martin to help developers design maintainable and scalable object-oriented software. The SOLID principles are as follows:
Single Responsibility Principle (SRP): A class should have only one reason to change. This means that a class should have a single, well-defined responsibility, and that responsibility should be encapsulated by the class.
Here is an example of Single Responsibility Principle:
class Employee {
constructor(name, address, salary) {
this.name = name;
this.address = address;
this.salary = salary;
}
getPay() {
// Calculate and return the employee's pay
}
}
class PayStubSender {
constructor(employee) {
this.employee = employee;
}
sendPayStub() {
// Send the employee their pay stub
}
}
const employee = new Employee('John Smith', '123 Main St', 50000);
const payStubSender = new PayStubSender(employee);
payStubSender.sendPayStub();
In this example, the Employee
class has a single responsibility: storing information about an employee and calculating their pay. The PayStubSender
class has a separate responsibility: sending the employee their pay stub. This ensures that the Employee
class is only concerned with its own responsibilities and is not cluttered with unrelated code.
Open-Closed Principle (OCP): Software entities (classes, modules, functions, etc.) should be open…