On this page20 sections
- Introduction
- The Five SOLID Principles
- 1. Single Responsibility Principle (SRP)
- Bad Example
- Good Example
- 2. Open/Closed Principle (OCP)
- Bad Example
- Good Example
- 3. Liskov Substitution Principle (LSP)
- Bad Example
- Good Example
- 4. Interface Segregation Principle (ISP)
- Bad Example
- Good Example
- 5. Dependency Inversion Principle (DIP)
- Bad Example
- Good Example
- Practical Application: Building a Notification System
- Benefits of Applying SOLID Principles
- Conclusion
Introduction
SOLID is an acronym representing five fundamental principles of object-oriented programming and design. These principles, when applied together, help developers create software that is easier to maintain, understand, and extend.
The SOLID principles were introduced by Robert C. Martin (Uncle Bob) and have become the cornerstone of modern software architecture. Whether you’re building a small utility or a large-scale enterprise application, understanding these principles will dramatically improve your code quality.
The Five SOLID Principles
| Principle | Description |
|---|---|
| S - Single Responsibility | A class should have only one reason to change |
| O - Open/Closed | Open for extension, closed for modification |
| L - Liskov Substitution | Subtypes must be substitutable for their base types |
| I - Interface Segregation | Many specific interfaces are better than one general interface |
| D - Dependency Inversion | Depend on abstractions, not concretions |
1. Single Responsibility Principle (SRP)
“A class should have one, and only one, reason to change.”
The Single Responsibility Principle states that every module, class, or function should have responsibility over a single part of the functionality provided by the software.
Bad Example
// Violates SRP - This class does too many things
class UserService {
private users: User[] = [];
createUser(userData: UserData): User {
// Validation logic
if (!userData.email.includes('@')) {
throw new Error('Invalid email');
}
if (userData.password.length < 8) {
throw new Error('Password too short');
}
// User creation
const user: User = {
id: crypto.randomUUID(),
...userData,
createdAt: new Date(),
};
this.users.push(user);
// Email notification
this.sendWelcomeEmail(user.email);
// Logging
console.log(`User created: ${user.id}`);
this.writeToLogFile(`New user: ${user.email}`);
return user;
}
private sendWelcomeEmail(email: string): void {
// Email sending logic
}
private writeToLogFile(message: string): void {
// File writing logic
}
}Good Example
// Follows SRP - Each class has a single responsibility
// Handles user validation only
class UserValidator {
validate(userData: UserData): ValidationResult {
const errors: string[] = [];
if (!userData.email.includes('@')) {
errors.push('Invalid email format');
}
if (userData.password.length < 8) {
errors.push('Password must be at least 8 characters');
}
return {
isValid: errors.length === 0,
errors,
};
}
}
// Handles user persistence only
class UserRepository {
private users: User[] = [];
save(user: User): User {
this.users.push(user);
return user;
}
findById(id: string): User | undefined {
return this.users.find(user => user.id === id);
}
}
// Handles email notifications only
class EmailService {
sendWelcomeEmail(email: string): void {
// Email sending logic
}
}
// Handles logging only
class Logger {
log(message: string): void {
console.log(`[${new Date().toISOString()}] ${message}`);
}
}
// Orchestrates the user creation process
class UserService {
constructor(
private validator: UserValidator,
private repository: UserRepository,
private emailService: EmailService,
private logger: Logger
) {}
createUser(userData: UserData): User {
const validation = this.validator.validate(userData);
if (!validation.isValid) {
throw new Error(validation.errors.join(', '));
}
const user: User = {
id: crypto.randomUUID(),
...userData,
createdAt: new Date(),
};
this.repository.save(user);
this.emailService.sendWelcomeEmail(user.email);
this.logger.log(`User created: ${user.id}`);
return user;
}
}2. Open/Closed Principle (OCP)
“Software entities should be open for extension, but closed for modification.”
This principle encourages writing code that doesn’t have to be changed every time requirements change. Instead, you extend the existing code.
Bad Example
// Violates OCP - Need to modify this class for every new payment method
class PaymentProcessor {
processPayment(amount: number, method: string): void {
if (method === 'credit_card') {
console.log(`Processing credit card payment: $${amount}`);
// Credit card specific logic
} else if (method === 'paypal') {
console.log(`Processing PayPal payment: $${amount}`);
// PayPal specific logic
} else if (method === 'bank_transfer') {
console.log(`Processing bank transfer: $${amount}`);
// Bank transfer specific logic
}
// Every new payment method requires modifying this class
}
}Good Example
// Follows OCP - Open for extension, closed for modification
// Abstract payment method interface
interface PaymentMethod {
name: string;
process(amount: number): Promise<PaymentResult>;
validate(): boolean;
}
// Concrete implementations - extend without modifying existing code
class CreditCardPayment implements PaymentMethod {
name = 'Credit Card';
constructor(
private cardNumber: string,
private cvv: string,
private expiryDate: string
) {}
async process(amount: number): Promise<PaymentResult> {
// Credit card specific processing
console.log(`Processing credit card payment: $${amount}`);
return { success: true, transactionId: crypto.randomUUID() };
}
validate(): boolean {
return this.cardNumber.length === 16 && this.cvv.length === 3;
}
}
class PayPalPayment implements PaymentMethod {
name = 'PayPal';
constructor(private email: string) {}
async process(amount: number): Promise<PaymentResult> {
console.log(`Processing PayPal payment: $${amount}`);
return { success: true, transactionId: crypto.randomUUID() };
}
validate(): boolean {
return this.email.includes('@');
}
}
class CryptoPayment implements PaymentMethod {
name = 'Cryptocurrency';
constructor(private walletAddress: string, private currency: string) {}
async process(amount: number): Promise<PaymentResult> {
console.log(`Processing ${this.currency} payment: $${amount}`);
return { success: true, transactionId: crypto.randomUUID() };
}
validate(): boolean {
return this.walletAddress.length > 20;
}
}
// Payment processor doesn't need modification for new payment methods
class PaymentProcessor {
async processPayment(
amount: number,
paymentMethod: PaymentMethod
): Promise<PaymentResult> {
if (!paymentMethod.validate()) {
throw new Error(`Invalid ${paymentMethod.name} details`);
}
return paymentMethod.process(amount);
}
}
// Usage - Adding new payment methods doesn't require changing PaymentProcessor
const processor = new PaymentProcessor();
await processor.processPayment(100, new CreditCardPayment('1234...', '123', '12/25'));
await processor.processPayment(50, new CryptoPayment('0x...', 'ETH'));3. Liskov Substitution Principle (LSP)
“Objects of a superclass should be replaceable with objects of its subclasses without breaking the application.”
If class B is a subtype of class A, you should be able to replace A with B without disrupting the behavior of your program.
Bad Example
// Violates LSP - Square changes the behavior of Rectangle
class Rectangle {
constructor(protected width: number, protected height: number) {}
setWidth(width: number): void {
this.width = width;
}
setHeight(height: number): void {
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
class Square extends Rectangle {
constructor(size: number) {
super(size, size);
}
// Violates LSP - changes expected behavior
setWidth(width: number): void {
this.width = width;
this.height = width; // Unexpected side effect!
}
setHeight(height: number): void {
this.width = height; // Unexpected side effect!
this.height = height;
}
}
// This function expects Rectangle behavior
function calculateArea(rectangle: Rectangle): number {
rectangle.setWidth(5);
rectangle.setHeight(10);
// Expected: 50, but with Square: 100!
return rectangle.getArea();
}
const rect = new Rectangle(2, 3);
console.log(calculateArea(rect)); // 50 - correct
const square = new Square(2);
console.log(calculateArea(square)); // 100 - unexpected!Good Example
// Follows LSP - Use composition and proper abstraction
interface Shape {
getArea(): number;
getPerimeter(): number;
}
class Rectangle implements Shape {
constructor(
private readonly width: number,
private readonly height: number
) {}
getArea(): number {
return this.width * this.height;
}
getPerimeter(): number {
return 2 * (this.width + this.height);
}
// Factory method for creating modified rectangles
withWidth(width: number): Rectangle {
return new Rectangle(width, this.height);
}
withHeight(height: number): Rectangle {
return new Rectangle(this.width, height);
}
}
class Square implements Shape {
constructor(private readonly side: number) {}
getArea(): number {
return this.side * this.side;
}
getPerimeter(): number {
return 4 * this.side;
}
withSide(side: number): Square {
return new Square(side);
}
}
// Now both can be used interchangeably where Shape is expected
function printShapeInfo(shape: Shape): void {
console.log(`Area: ${shape.getArea()}`);
console.log(`Perimeter: ${shape.getPerimeter()}`);
}
const rectangle = new Rectangle(5, 10);
const square = new Square(5);
printShapeInfo(rectangle); // Area: 50, Perimeter: 30
printShapeInfo(square); // Area: 25, Perimeter: 204. Interface Segregation Principle (ISP)
“No client should be forced to depend on methods it does not use.”
This principle suggests that many client-specific interfaces are better than one general-purpose interface.
Bad Example
// Violates ISP - Too many methods in one interface
interface Worker {
work(): void;
eat(): void;
sleep(): void;
attendMeeting(): void;
writeReport(): void;
code(): void;
design(): void;
}
// Robot doesn't eat or sleep!
class Robot implements Worker {
work(): void {
console.log('Robot working...');
}
eat(): void {
throw new Error('Robots do not eat!'); // Forced to implement
}
sleep(): void {
throw new Error('Robots do not sleep!'); // Forced to implement
}
attendMeeting(): void {
throw new Error('Robots do not attend meetings!');
}
writeReport(): void {
console.log('Generating report...');
}
code(): void {
console.log('Writing code...');
}
design(): void {
throw new Error('Robots do not design!');
}
}Good Example
// Follows ISP - Segregated interfaces
interface Workable {
work(): void;
}
interface Feedable {
eat(): void;
}
interface Sleepable {
sleep(): void;
}
interface Programmer {
code(): void;
debug(): void;
}
interface Designer {
design(): void;
prototype(): void;
}
interface MeetingAttendee {
attendMeeting(): void;
takeNotes(): void;
}
// Human developer implements relevant interfaces
class Developer implements Workable, Feedable, Sleepable, Programmer, MeetingAttendee {
work(): void {
console.log('Developer working...');
}
eat(): void {
console.log('Having lunch...');
}
sleep(): void {
console.log('Sleeping...');
}
code(): void {
console.log('Writing TypeScript...');
}
debug(): void {
console.log('Debugging code...');
}
attendMeeting(): void {
console.log('In standup meeting...');
}
takeNotes(): void {
console.log('Taking meeting notes...');
}
}
// Robot only implements what it can do
class CodingRobot implements Workable, Programmer {
work(): void {
console.log('Robot processing tasks...');
}
code(): void {
console.log('Generating code...');
}
debug(): void {
console.log('Running automated debugging...');
}
}
// Designer implements their specific interfaces
class UIDesigner implements Workable, Feedable, Sleepable, Designer, MeetingAttendee {
work(): void {
console.log('Designer working...');
}
eat(): void {
console.log('Coffee break...');
}
sleep(): void {
console.log('Resting...');
}
design(): void {
console.log('Creating UI mockups...');
}
prototype(): void {
console.log('Building prototype in Figma...');
}
attendMeeting(): void {
console.log('Design review meeting...');
}
takeNotes(): void {
console.log('Documenting feedback...');
}
}5. Dependency Inversion Principle (DIP)
“High-level modules should not depend on low-level modules. Both should depend on abstractions.”
This principle reduces coupling between modules and makes the system more modular and testable.
Bad Example
// Violates DIP - High-level module depends on low-level modules
class MySQLDatabase {
save(data: string): void {
console.log(`Saving to MySQL: ${data}`);
}
query(sql: string): any[] {
console.log(`Querying MySQL: ${sql}`);
return [];
}
}
class EmailSender {
send(to: string, subject: string, body: string): void {
console.log(`Sending email via SMTP to ${to}`);
}
}
// High-level module directly depends on low-level implementations
class OrderService {
private database: MySQLDatabase;
private emailSender: EmailSender;
constructor() {
// Direct instantiation creates tight coupling
this.database = new MySQLDatabase();
this.emailSender = new EmailSender();
}
createOrder(order: Order): void {
this.database.save(JSON.stringify(order));
this.emailSender.send(
order.customerEmail,
'Order Confirmation',
`Your order ${order.id} has been placed.`
);
}
}Good Example
// Follows DIP - Depend on abstractions
// Abstract interfaces (abstractions)
interface Database {
save(data: string): Promise<void>;
query<T>(query: string): Promise<T[]>;
}
interface NotificationService {
send(recipient: string, subject: string, message: string): Promise<void>;
}
interface Logger {
info(message: string): void;
error(message: string, error?: Error): void;
}
// Low-level implementations
class PostgreSQLDatabase implements Database {
async save(data: string): Promise<void> {
console.log(`Saving to PostgreSQL: ${data}`);
}
async query<T>(query: string): Promise<T[]> {
console.log(`Querying PostgreSQL: ${query}`);
return [];
}
}
class MongoDatabase implements Database {
async save(data: string): Promise<void> {
console.log(`Saving to MongoDB: ${data}`);
}
async query<T>(query: string): Promise<T[]> {
console.log(`Querying MongoDB: ${query}`);
return [];
}
}
class EmailNotification implements NotificationService {
async send(recipient: string, subject: string, message: string): Promise<void> {
console.log(`Email to ${recipient}: ${subject}`);
}
}
class SMSNotification implements NotificationService {
async send(recipient: string, subject: string, message: string): Promise<void> {
console.log(`SMS to ${recipient}: ${message}`);
}
}
class ConsoleLogger implements Logger {
info(message: string): void {
console.log(`[INFO] ${message}`);
}
error(message: string, error?: Error): void {
console.error(`[ERROR] ${message}`, error);
}
}
// High-level module depends on abstractions
class OrderService {
constructor(
private database: Database,
private notification: NotificationService,
private logger: Logger
) {}
async createOrder(order: Order): Promise<void> {
try {
await this.database.save(JSON.stringify(order));
this.logger.info(`Order ${order.id} saved to database`);
await this.notification.send(
order.customerEmail,
'Order Confirmation',
`Your order ${order.id} has been placed.`
);
this.logger.info(`Notification sent for order ${order.id}`);
} catch (error) {
this.logger.error(`Failed to create order ${order.id}`, error as Error);
throw error;
}
}
}
// Dependency injection - easy to swap implementations
const orderService = new OrderService(
new PostgreSQLDatabase(),
new EmailNotification(),
new ConsoleLogger()
);
// For testing, easily swap with mocks
const testOrderService = new OrderService(
new MongoDatabase(), // Different database
new SMSNotification(), // Different notification
new ConsoleLogger()
);Practical Application: Building a Notification System
Let’s apply all SOLID principles to build a real-world notification system:
// ============================================
// SOLID-Compliant Notification System
// ============================================
// --- Interfaces (DIP & ISP) ---
interface NotificationChannel {
readonly channelType: string;
send(notification: Notification): Promise<NotificationResult>;
isAvailable(): Promise<boolean>;
}
interface NotificationFormatter {
format(notification: Notification): FormattedContent;
}
interface NotificationLogger {
logSent(notification: Notification, result: NotificationResult): void;
logError(notification: Notification, error: Error): void;
}
interface NotificationValidator {
validate(notification: Notification): ValidationResult;
}
// --- Types ---
interface Notification {
id: string;
recipient: string;
subject: string;
body: string;
priority: 'low' | 'medium' | 'high';
metadata?: Record<string, unknown>;
}
interface NotificationResult {
success: boolean;
messageId?: string;
error?: string;
timestamp: Date;
}
interface FormattedContent {
subject: string;
body: string;
html?: string;
}
interface ValidationResult {
isValid: boolean;
errors: string[];
}
// --- Implementations (OCP - easily extendable) ---
class EmailChannel implements NotificationChannel {
readonly channelType = 'email';
constructor(private smtpConfig: SMTPConfig) {}
async send(notification: Notification): Promise<NotificationResult> {
// Email-specific sending logic
console.log(`Sending email to ${notification.recipient}`);
return {
success: true,
messageId: crypto.randomUUID(),
timestamp: new Date(),
};
}
async isAvailable(): Promise<boolean> {
// Check SMTP connection
return true;
}
}
class SlackChannel implements NotificationChannel {
readonly channelType = 'slack';
constructor(private webhookUrl: string) {}
async send(notification: Notification): Promise<NotificationResult> {
console.log(`Sending Slack message to ${notification.recipient}`);
return {
success: true,
messageId: crypto.randomUUID(),
timestamp: new Date(),
};
}
async isAvailable(): Promise<boolean> {
return true;
}
}
class PushNotificationChannel implements NotificationChannel {
readonly channelType = 'push';
constructor(private fcmConfig: FCMConfig) {}
async send(notification: Notification): Promise<NotificationResult> {
console.log(`Sending push notification to ${notification.recipient}`);
return {
success: true,
messageId: crypto.randomUUID(),
timestamp: new Date(),
};
}
async isAvailable(): Promise<boolean> {
return true;
}
}
// --- Single Responsibility Classes ---
class HTMLFormatter implements NotificationFormatter {
format(notification: Notification): FormattedContent {
return {
subject: notification.subject,
body: notification.body,
html: `
<div style="font-family: Arial, sans-serif;">
<h1>${notification.subject}</h1>
<p>${notification.body}</p>
</div>
`,
};
}
}
class PlainTextFormatter implements NotificationFormatter {
format(notification: Notification): FormattedContent {
return {
subject: notification.subject,
body: notification.body,
};
}
}
class NotificationValidatorImpl implements NotificationValidator {
validate(notification: Notification): ValidationResult {
const errors: string[] = [];
if (!notification.recipient) {
errors.push('Recipient is required');
}
if (!notification.subject || notification.subject.length < 3) {
errors.push('Subject must be at least 3 characters');
}
if (!notification.body) {
errors.push('Body is required');
}
return {
isValid: errors.length === 0,
errors,
};
}
}
class ConsoleNotificationLogger implements NotificationLogger {
logSent(notification: Notification, result: NotificationResult): void {
console.log(
`[${result.timestamp.toISOString()}] Notification ${notification.id} sent successfully`
);
}
logError(notification: Notification, error: Error): void {
console.error(
`[ERROR] Failed to send notification ${notification.id}: ${error.message}`
);
}
}
// --- Main Service (Orchestrator) ---
class NotificationService {
constructor(
private channels: NotificationChannel[],
private formatter: NotificationFormatter,
private validator: NotificationValidator,
private logger: NotificationLogger
) {}
async send(notification: Notification): Promise<NotificationResult[]> {
// Validate
const validation = this.validator.validate(notification);
if (!validation.isValid) {
throw new Error(`Validation failed: ${validation.errors.join(', ')}`);
}
// Format
const formatted = this.formatter.format(notification);
const formattedNotification = {
...notification,
...formatted,
};
// Send through all available channels
const results: NotificationResult[] = [];
for (const channel of this.channels) {
if (await channel.isAvailable()) {
try {
const result = await channel.send(formattedNotification);
this.logger.logSent(notification, result);
results.push(result);
} catch (error) {
this.logger.logError(notification, error as Error);
results.push({
success: false,
error: (error as Error).message,
timestamp: new Date(),
});
}
}
}
return results;
}
}
// --- Usage ---
const notificationService = new NotificationService(
[
new EmailChannel({ host: 'smtp.example.com', port: 587 }),
new SlackChannel('https://hooks.slack.com/...'),
new PushNotificationChannel({ apiKey: '...' }),
],
new HTMLFormatter(),
new NotificationValidatorImpl(),
new ConsoleNotificationLogger()
);
// Send notification
await notificationService.send({
id: crypto.randomUUID(),
recipient: 'user@example.com',
subject: 'Welcome!',
body: 'Thank you for signing up.',
priority: 'high',
});Benefits of Applying SOLID Principles
| Benefit | Description |
|---|---|
| Maintainability | Code is easier to understand and modify |
| Testability | Components can be tested in isolation |
| Flexibility | Easy to add new features without breaking existing code |
| Reusability | Components can be reused across different parts of the application |
| Scalability | System can grow without becoming unmanageable |
Conclusion
SOLID principles are not just academic concepts - they are practical guidelines that lead to better software design. By applying these principles consistently, you’ll create codebases that are:
- Easier to understand for new team members
- Simpler to test and debug
- More flexible when requirements change
- Less prone to bugs when adding new features
Start by identifying violations of these principles in your existing code, and gradually refactor towards a more SOLID architecture. Remember, perfection isn’t the goal - continuous improvement is.
Further Reading:
- “Clean Architecture” by Robert C. Martin
- “Design Patterns: Elements of Reusable Object-Oriented Software” by Gang of Four
- “Refactoring: Improving the Design of Existing Code” by Martin Fowler