The SOLID principles are five design principles in Object-Oriented Programming (OOP) that help developers write clean, scalable, and maintainable code.
Each principle ensures that software is easy to modify, extend, test, and understand. Letβs break them down with real-life examples and code snippets in Java.
πΉ What is it?
A class should have only one reason to change, meaning it should have only one job.
π Real-Life Example:
Imagine a Restaurant. The Chef cooks food, and the Cashier handles payments.
π Bad Code (Violating SRP)
class Restaurant {
void cookFood() {
System.out.println("Cooking food...");
}
void processPayment() {
System.out.println("Processing payment...");
}
}
π΄ Problem:
Restaurant class does two things: cooking and handling payments.π Good Code (Following SRP)
class Chef {
void cookFood() {
System.out.println("Cooking food...");
}
}
class Cashier {
void processPayment() {
System.out.println("Processing payment...");
}
}
β Now:
Chef class handles cooking.