Appearance
SOLID
Single Responsibility Principle (SRP)
A class should have only one reason to change.
java
class UserManager {
public void saveUser(User user) {
// Save user to database
db.save(user);
}
public void emailUser(User user) {
// Send email
emailService.send(user.getEmail(), "Welcome!", "Welcome to our platform!");
}
public void generateUserReport(User user) {
// Generate PDF report
PDFGenerator.create(user.getData());
}
}Open/Closed Principle (OCP)
Software entities should be open for extension but closed for modification.
java
class PaymentProcessor {
public void processPayment(String type, double amount) {
if (type.equals("credit")) {
// Process credit payment
} else if (type.equals("debit")) {
// Process debit payment
}
// Adding new payment type requires modifying this class
}
}Liskov Substitution Principle (LSP)
Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.
java
class Bird {
public void fly() {
// Flying implementation
}
}
class Penguin extends Bird {
@Override
public void fly() {
throw new UnsupportedOperationException("Penguins can't fly!");
}
}Interface Segregation Principle (ISP)
Clients should not be forced to depend on interfaces they do not use.
java
interface Worker {
void work();
void eat();
void sleep();
}
class Robot implements Worker {
public void work() { /* */ }
public void eat() { throw new UnsupportedOperationException(); }
public void sleep() { throw new UnsupportedOperationException(); }
}Dependency Inversion Principle (DIP)
High-level modules should not depend on low-level modules. Both should depend on abstractions.
java
class EmailService {
private MySQLDatabase database;
public EmailService() {
this.database = new MySQLDatabase();
}
public void sendEmail(String message) {
database.save(message);
// Send email
}
}