JavaScript and TypeScript course ยท Module 9: Design Patterns and Architecture
SOLID Principles in JavaScript/TypeScript
In this lesson7
Welcome back to Jurassic Park! Picture a control room where a single class runs the fences, sells tickets and sends emails. A fix at the ticket desk could then cut the power to the T-Rex paddock. The cure is SOLID: an acronym for five object-oriented design principles popularized by Robert C. Martin. Although they were born for object-oriented languages, they work great in JavaScript and TypeScript.
S - Single Responsibility Principle
Every class or module should have only one reason to change, that is, one responsibility. The DNA lab does not sell tickets, and the ticket desk does not clone dinosaurs.
Bad approach - violating SRP
Here is a jack of all trades. How many reasons to change does UserManager have?
// UserManager class does too many things
class UserManager {
constructor() {
this.users = [];
}
// User management
addUser(userData) {
this.users.push(userData);
}
removeUser(userId) {
this.users = this.users.filter(user => user.id !== userId);
}
// Validation - different responsibility
validateEmail(email) {
return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}
validatePassword(password) {
return password.length >= 8 && /[A-Z]/.test(password);
}
// Logging - another responsibility
logUserAction(action, userId) {
console.log(`[${new Date().toISOString()}] User ${userId}: ${action}`);
}
// Sending emails - yet another responsibility
sendWelcomeEmail(userEmail) {
console.log(`Sending welcome email to ${userEmail}`);
}
// Data formatting - another responsibility
formatUserData(user) {
return `${user.firstName} ${user.lastName} (${user.email})`;
}
}Five: storage, validation, logging, emails and formatting. Changing the log format forces you to edit a class that also guards passwords.
Good approach - compliant with SRP
Now every responsibility gets its own class, and UserService coordinates them:
// Each class has one responsibility
// User management
interface User {
id: string;
firstName: string;
lastName: string;
email: string;
password: string;
}
class UserRepository {
private users: User[] = [];
add(user: User): void {
this.users.push(user);
}
remove(userId: string): boolean {
const initialLength = this.users.length;
this.users = this.users.filter(user => user.id !== userId);
return this.users.length < initialLength;
}
findById(userId: string): User | null {
return this.users.find(user => user.id === userId) || null;
}
findByEmail(email: string): User | null {
return this.users.find(user => user.email === email) || null;
}
getAll(): User[] {
return [...this.users];
}
}
// Validation
class UserValidator {
validateEmail(email: string): boolean {
const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
return emailRegex.test(email);
}
validatePassword(password: string): boolean {
return password.length >= 8 &&
/[A-Z]/.test(password) &&
/[a-z]/.test(password) &&
/[0-9]/.test(password);
}
validateUser(userData: Partial<User>): string[] {
const errors: string[] = [];
if (!userData.firstName || userData.firstName.length < 2) {
errors.push('First name must be at least 2 characters');
}
if (!userData.lastName || userData.lastName.length < 2) {
errors.push('Last name must be at least 2 characters');
}
if (!userData.email || !this.validateEmail(userData.email)) {
errors.push('Invalid email format');
}
if (!userData.password || !this.validatePassword(userData.password)) {
errors.push('Password must have at least 8 characters, an uppercase letter, a lowercase letter, and a digit');
}
return errors;
}
}
// Logging
class UserLogger {
private logs: string[] = [];
logAction(action: string, userId: string): void {
const logEntry = `[${new Date().toISOString()}] User ${userId}: ${action}`;
this.logs.push(logEntry);
console.log(logEntry);
}
getLogs(): string[] {
return [...this.logs];
}
clearLogs(): void {
this.logs = [];
}
}
// Sending emails
class EmailService {
sendWelcomeEmail(userEmail: string, userName: string): Promise<boolean> {
// Simulating email sending
console.log(`Sending welcome email to ${userEmail}`);
return new Promise(resolve => {
setTimeout(() => {
console.log(`Welcome email sent to ${userName}`);
resolve(true);
}, 1000);
});
}
sendPasswordResetEmail(userEmail: string): Promise<boolean> {
console.log(`Sending password reset email to ${userEmail}`);
return Promise.resolve(true);
}
}
// Data formatting
class UserFormatter {
formatFullName(user: User): string {
return `${user.firstName} ${user.lastName}`;
}
formatUserDisplay(user: User): string {
return `${this.formatFullName(user)} (${user.email})`;
}
formatUserSummary(user: User): object {
return {
id: user.id,
fullName: this.formatFullName(user),
email: user.email
};
}
}
// Service layer - coordinates different components
class UserService {
constructor(
private userRepository: UserRepository,
private userValidator: UserValidator,
private userLogger: UserLogger,
private emailService: EmailService,
private userFormatter: UserFormatter
) {}
async createUser(userData: Omit<User, 'id'>): Promise<User | null> {
// Validation
const validationErrors = this.userValidator.validateUser(userData);
if (validationErrors.length > 0) {
throw new Error(`Validation errors: ${validationErrors.join(', ')}`);
}
// Check if email is taken
if (this.userRepository.findByEmail(userData.email)) {
throw new Error('A user with this email already exists');
}
// Create user
const user: User = {
id: 'user_' + Math.random().toString(36).slice(2, 11),
...userData
};
this.userRepository.add(user);
// Logging
this.userLogger.logAction('USER_CREATED', user.id);
// Send welcome email
await this.emailService.sendWelcomeEmail(
user.email,
this.userFormatter.formatFullName(user)
);
return user;
}
deleteUser(userId: string): boolean {
const user = this.userRepository.findById(userId);
if (!user) {
return false;
}
const deleted = this.userRepository.remove(userId);
if (deleted) {
this.userLogger.logAction('USER_DELETED', userId);
}
return deleted;
}
}
// Usage
const userRepository = new UserRepository();
const userValidator = new UserValidator();
const userLogger = new UserLogger();
const emailService = new EmailService();
const userFormatter = new UserFormatter();
const userService = new UserService(
userRepository,
userValidator,
userLogger,
emailService,
userFormatter
);
// Test
userService.createUser({
firstName: 'Jan',
lastName: 'Kowalski',
email: 'jan@example.com',
password: 'SecurePass123'
}).then(user => {
if (user) {
console.log('User created:', userFormatter.formatUserDisplay(user));
}
});The application behaves exactly as before, but you can test and replace each part separately. UserService receives its helpers in the constructor, which the letter D will expand on.
O - Open/Closed Principle
Classes should be open for extension but closed for modification. A new species means a new paddock, not tearing down fences that already work.
Example with a payment system
First the problem: this function needs editing for every new payment method.
// OCP violation - every new payment type means changing this function
function processPayment(type: string, amount: number): void {
if (type === 'credit-card') {
console.log(`Card: ${amount} PLN`);
} else if (type === 'paypal') {
console.log(`PayPal: ${amount} PLN`);
}
// cryptocurrency? Another else if in code that was already tested
}The OCP-compliant version is built on the PaymentProcessor interface, and PaymentService keeps the processors in a map:
// Good approach - compliant with OCP
interface PaymentProcessor {
processPayment(amount: number, details: any): Promise<PaymentResult>;
validatePayment(details: any): boolean;
}
interface PaymentResult {
success: boolean;
transactionId?: string;
error?: string;
}
// Basic implementation for credit cards
class CreditCardProcessor implements PaymentProcessor {
async processPayment(amount: number, details: CreditCardDetails): Promise<PaymentResult> {
if (!this.validatePayment(details)) {
return { success: false, error: 'Invalid card data' };
}
// Simulating card payment processing
console.log(`Processing card payment: ${amount} USD`);
return {
success: true,
transactionId: 'cc_' + Math.random().toString(36).slice(2, 11)
};
}
validatePayment(details: CreditCardDetails): boolean {
return !!(details.cardNumber &&
details.expiryDate &&
details.cvv &&
details.cardNumber.length === 16);
}
}
interface CreditCardDetails {
cardNumber: string;
expiryDate: string;
cvv: string;
holderName: string;
}
// Extension - new processor without modifying existing code
class PayPalProcessor implements PaymentProcessor {
async processPayment(amount: number, details: PayPalDetails): Promise<PaymentResult> {
if (!this.validatePayment(details)) {
return { success: false, error: 'Invalid PayPal data' };
}
console.log(`Processing PayPal payment: ${amount} USD`);
return {
success: true,
transactionId: 'pp_' + Math.random().toString(36).slice(2, 11)
};
}
validatePayment(details: PayPalDetails): boolean {
return !!(details.email && details.password);
}
}
interface PayPalDetails {
email: string;
password: string;
}
// Another extension
class BankTransferProcessor implements PaymentProcessor {
async processPayment(amount: number, details: BankTransferDetails): Promise<PaymentResult> {
if (!this.validatePayment(details)) {
return { success: false, error: 'Invalid transfer data' };
}
console.log(`Processing bank transfer: ${amount} USD`);
return {
success: true,
transactionId: 'bt_' + Math.random().toString(36).slice(2, 11)
};
}
validatePayment(details: BankTransferDetails): boolean {
return !!(details.accountNumber &&
details.bankCode &&
details.accountNumber.length >= 20);
}
}
interface BankTransferDetails {
accountNumber: string;
bankCode: string;
recipientName: string;
}
// New processor for cryptocurrencies - without modifying existing code
class CryptocurrencyProcessor implements PaymentProcessor {
async processPayment(amount: number, details: CryptoDetails): Promise<PaymentResult> {
if (!this.validatePayment(details)) {
return { success: false, error: 'Invalid wallet address' };
}
console.log(`Processing ${details.currency} payment: ${amount} USD`);
return {
success: true,
transactionId: 'crypto_' + Math.random().toString(36).slice(2, 11)
};
}
validatePayment(details: CryptoDetails): boolean {
return !!(details.walletAddress &&
details.currency &&
details.walletAddress.length >= 26);
}
}
interface CryptoDetails {
walletAddress: string;
currency: 'BTC' | 'ETH' | 'LTC';
}
// Context using processors - does not need to be modified
class PaymentService {
private processors = new Map<string, PaymentProcessor>();
registerProcessor(type: string, processor: PaymentProcessor): void {
this.processors.set(type, processor);
}
async processPayment(type: string, amount: number, details: any): Promise<PaymentResult> {
const processor = this.processors.get(type);
if (!processor) {
return { success: false, error: `Unsupported payment type: ${type}` };
}
return processor.processPayment(amount, details);
}
getSupportedPaymentTypes(): string[] {
return Array.from(this.processors.keys());
}
}
// Usage - easy to add new payment types
const paymentService = new PaymentService();
paymentService.registerProcessor('credit-card', new CreditCardProcessor());
paymentService.registerProcessor('paypal', new PayPalProcessor());
paymentService.registerProcessor('bank-transfer', new BankTransferProcessor());
paymentService.registerProcessor('crypto', new CryptocurrencyProcessor());
// Testing different payment types
async function testPayments() {
// Card payment
const creditCardResult = await paymentService.processPayment('credit-card', 100, {
cardNumber: '1234567890123456',
expiryDate: '12/25',
cvv: '123',
holderName: 'Jan Kowalski'
});
// PayPal payment
const paypalResult = await paymentService.processPayment('paypal', 50, {
email: 'user@example.com',
password: 'password123'
});
// Cryptocurrency payment
const cryptoResult = await paymentService.processPayment('crypto', 200, {
walletAddress: '1A1zP1eP5QGefi2DMPTfTL5SLmv7DivfNa',
currency: 'BTC'
});
console.log('Payment results:', {
creditCard: creditCardResult,
paypal: paypalResult,
crypto: cryptoResult
});
}
testPayments();Cryptocurrency did not change a single line in PaymentService: it was enough to add a class and call registerProcessor.
L - Liskov Substitution Principle
Objects of derived classes should be able to replace objects of the base class without affecting the correctness of the program. The principle was formulated by Barbara Liskov, and the example is about birds, the living descendants of dinosaurs.
Example with birds - violating LSP
The Bird class promises that every bird flies. What happens when a penguin joins?
// Violating LSP
abstract class Bird {
abstract fly(): void;
abstract makeSound(): void;
}
class Sparrow extends Bird {
fly(): void {
console.log('Sparrow is flying!');
}
makeSound(): void {
console.log('Chirp chirp!');
}
}
class Eagle extends Bird {
fly(): void {
console.log('Eagle is soaring!');
}
makeSound(): void {
console.log('Screech!');
}
}
// Problem: a penguin cannot fly!
class Penguin extends Bird {
fly(): void {
throw new Error('Penguins cannot fly!'); // LSP violation
}
makeSound(): void {
console.log('Quack quack!');
}
}
// Function expecting every bird can fly
function makeBirdFly(bird: Bird): void {
bird.fly(); // May throw an error for a penguin!
}TypeScript stays silent, but makeBirdFly(new Penguin()) throws an exception at runtime. The subclass broke the promise made by the base class.
Corrected approach compliant with LSP
Abilities move into separate interfaces, Flyable, Swimmable and Walkable, and the base class promises only what every bird can do:
// Compliant with LSP - better hierarchy modeling
interface Animal {
makeSound(): void;
move(): void;
}
interface Flyable {
fly(): void;
}
interface Swimmable {
swim(): void;
}
interface Walkable {
walk(): void;
}
// Base class for birds
abstract class Bird implements Animal {
abstract makeSound(): void;
abstract move(): void;
eat(): void {
console.log('Bird is eating');
}
sleep(): void {
console.log('Bird is sleeping');
}
}
// Flying birds
class FlyingBird extends Bird implements Flyable {
makeSound(): void {
console.log('Bird makes a sound');
}
move(): void {
this.fly();
}
fly(): void {
console.log('Bird is flying');
}
}
// Swimming birds
class SwimmingBird extends Bird implements Swimmable {
makeSound(): void {
console.log('Bird makes a sound');
}
move(): void {
this.swim();
}
swim(): void {
console.log('Bird is swimming');
}
}
// Concrete implementations
class Sparrow extends FlyingBird {
makeSound(): void {
console.log('Chirp chirp!');
}
fly(): void {
console.log('Sparrow flies fast');
}
}
class Eagle extends FlyingBird {
makeSound(): void {
console.log('Screech!');
}
fly(): void {
console.log('Eagle soars majestically');
}
}
class Penguin extends SwimmingBird implements Walkable {
makeSound(): void {
console.log('Quack quack!');
}
swim(): void {
console.log('Penguin swims gracefully');
}
walk(): void {
console.log('Penguin walks on ice');
}
move(): void {
// Penguin can move in different ways
if (Math.random() > 0.5) {
this.swim();
} else {
this.walk();
}
}
}
// Functions respecting LSP
function makeAnimalMove(animal: Animal): void {
animal.move(); // Will always work correctly
}
function makeFlyableObjectFly(flyable: Flyable): void {
flyable.fly(); // Only for objects that can actually fly
}
function makeSwimmableObjectSwim(swimmable: Swimmable): void {
swimmable.swim(); // Only for objects that can actually swim
}
// Testing
const birds: Bird[] = [
new Sparrow(),
new Eagle(),
new Penguin()
];
birds.forEach(bird => {
bird.makeSound();
makeAnimalMove(bird); // Each bird can move in its own way
});
// Testing flight ability only for flying birds
const flyingBirds: Flyable[] = [
new Sparrow(),
new Eagle()
// Penguin is not added because it doesn't implement Flyable
];
flyingBirds.forEach(bird => {
makeFlyableObjectFly(bird);
});Now makeAnimalMove works for every bird, and you cannot add the penguin to a Flyable array, because the compiler reports an error.
I - Interface Segregation Principle
Classes should not be forced to implement interfaces they do not use. A paddock ranger does not need to know how to fly a helicopter.
Violating ISP
One huge interface forces a simple printer to pretend it can do everything:
// Violating ISP - interface too large
interface MultiFunctionDevice {
print(document: string): void;
scan(document: string): string;
fax(document: string, number: string): void;
copy(document: string): string;
email(document: string, address: string): void;
}
// Problem: a simple printer must implement all methods
class SimplePrinter implements MultiFunctionDevice {
print(document: string): void {
console.log(`Printing: ${document}`);
}
// Forced to implement unused methods
scan(document: string): string {
throw new Error('Printer does not support scanning');
}
fax(document: string, number: string): void {
throw new Error('Printer does not support faxing');
}
copy(document: string): string {
throw new Error('Printer does not support copying');
}
email(document: string, address: string): void {
throw new Error('Printer does not support emailing');
}
}Four out of five methods throw an exception, which only comes to light at runtime.
Compliant with ISP
We split the interface into small parts, and every class implements only what it needs:
// Compliant with ISP - segregated interfaces
interface Printer {
print(document: string): void;
}
interface Scanner {
scan(document: string): string;
}
interface FaxMachine {
fax(document: string, number: string): void;
}
interface Copier {
copy(document: string): string;
}
interface EmailSender {
email(document: string, address: string): void;
}
// Simple printer implements only what it needs
class SimplePrinter implements Printer {
print(document: string): void {
console.log(`Printing: ${document}`);
}
}
// Scanner implements only scanning
class SimpleScanner implements Scanner {
scan(document: string): string {
console.log(`Scanning: ${document}`);
return `Scanned: ${document}`;
}
}
// Multi-function device implements needed interfaces
class MultiFunctionPrinter implements Printer, Scanner, Copier {
print(document: string): void {
console.log(`[MFP] Printing: ${document}`);
}
scan(document: string): string {
console.log(`[MFP] Scanning: ${document}`);
return `Scanned: ${document}`;
}
copy(document: string): string {
console.log(`[MFP] Copying: ${document}`);
const scanned = this.scan(document);
this.print(scanned);
return scanned;
}
}
// Professional office machine
class OfficeMachine implements Printer, Scanner, FaxMachine, Copier, EmailSender {
print(document: string): void {
console.log(`[Office] Printing: ${document}`);
}
scan(document: string): string {
console.log(`[Office] Scanning: ${document}`);
return `Scanned: ${document}`;
}
fax(document: string, number: string): void {
console.log(`[Office] Sending fax ${document} to number ${number}`);
}
copy(document: string): string {
console.log(`[Office] Copying: ${document}`);
return this.scan(document);
}
email(document: string, address: string): void {
console.log(`[Office] Sending email ${document} to address ${address}`);
}
}
// Functions using only needed interfaces
class DocumentProcessor {
static printDocument(printer: Printer, document: string): void {
printer.print(document);
}
static scanDocument(scanner: Scanner, document: string): string {
return scanner.scan(document);
}
static copyDocument(copier: Copier, document: string): string {
return copier.copy(document);
}
}
// Usage
const simplePrinter = new SimplePrinter();
const simpleScanner = new SimpleScanner();
const mfp = new MultiFunctionPrinter();
const officeMachine = new OfficeMachine();
// Each device uses only its capabilities
DocumentProcessor.printDocument(simplePrinter, 'Document 1');
DocumentProcessor.scanDocument(simpleScanner, 'Document 2');
DocumentProcessor.copyDocument(mfp, 'Document 3');
DocumentProcessor.printDocument(officeMachine, 'Document 4');DocumentProcessor asks for exactly what it uses, and OfficeMachine shows that a class can implement several interfaces at once.
D - Dependency Inversion Principle
High-level modules should not depend on low-level modules. Both should depend on abstractions. The control room uses a power socket, not one specific generator.
Violating DIP
Here UserService creates a specific MySQL database and a specific email service by itself:
// Violating DIP - depending on concrete implementations
class MySQLDatabase {
save(data: any): void {
console.log('Saving to MySQL:', data);
}
find(id: string): any {
console.log('Searching in MySQL:', id);
return { id, data: 'mysql_data' };
}
}
class EmailNotification {
send(message: string, recipient: string): void {
console.log(`Sending email to ${recipient}: ${message}`);
}
}
// Problem: UserService depends on concrete implementations
class UserService {
private database: MySQLDatabase; // Concrete dependency
private notification: EmailNotification; // Concrete dependency
constructor() {
this.database = new MySQLDatabase(); // Creating dependencies inside the class
this.notification = new EmailNotification();
}
createUser(userData: any): void {
this.database.save(userData);
this.notification.send('Welcome!', userData.email);
}
getUser(id: string): any {
return this.database.find(id);
}
}Switching the database means editing the service, and in tests you cannot swap it for a fake.
Compliant with DIP
Now the service knows only the Database, NotificationService and Logger interfaces, and receives concrete classes from outside, for example from a simple DI container:
// Compliant with DIP - depending on abstractions
// Abstractions (interfaces)
interface Database {
save(data: any): void;
find(id: string): any;
update(id: string, data: any): void;
delete(id: string): boolean;
}
interface NotificationService {
send(message: string, recipient: string): Promise<boolean>;
}
interface Logger {
log(level: 'info' | 'warn' | 'error', message: string): void;
}
// Concrete implementations - low level
class MySQLDatabase implements Database {
save(data: any): void {
console.log('Saving to MySQL:', data);
}
find(id: string): any {
console.log('Searching in MySQL:', id);
return { id, data: 'mysql_data' };
}
update(id: string, data: any): void {
console.log(`Updating in MySQL ${id}:`, data);
}
delete(id: string): boolean {
console.log('Deleting from MySQL:', id);
return true;
}
}
class PostgreSQLDatabase implements Database {
save(data: any): void {
console.log('Saving to PostgreSQL:', data);
}
find(id: string): any {
console.log('Searching in PostgreSQL:', id);
return { id, data: 'postgres_data' };
}
update(id: string, data: any): void {
console.log(`Updating in PostgreSQL ${id}:`, data);
}
delete(id: string): boolean {
console.log('Deleting from PostgreSQL:', id);
return true;
}
}
class MongoDatabase implements Database {
save(data: any): void {
console.log('Saving to MongoDB:', data);
}
find(id: string): any {
console.log('Searching in MongoDB:', id);
return { id, data: 'mongo_data' };
}
update(id: string, data: any): void {
console.log(`Updating in MongoDB ${id}:`, data);
}
delete(id: string): boolean {
console.log('Deleting from MongoDB:', id);
return true;
}
}
class EmailNotificationService implements NotificationService {
async send(message: string, recipient: string): Promise<boolean> {
console.log(`Sending email to ${recipient}: ${message}`);
return true;
}
}
class SMSNotificationService implements NotificationService {
async send(message: string, recipient: string): Promise<boolean> {
console.log(`Sending SMS to ${recipient}: ${message}`);
return true;
}
}
class SlackNotificationService implements NotificationService {
async send(message: string, recipient: string): Promise<boolean> {
console.log(`Sending Slack message to ${recipient}: ${message}`);
return true;
}
}
class ConsoleLogger implements Logger {
log(level: 'info' | 'warn' | 'error', message: string): void {
console.log(`[${level.toUpperCase()}] ${message}`);
}
}
class FileLogger implements Logger {
log(level: 'info' | 'warn' | 'error', message: string): void {
console.log(`Writing to file [${level.toUpperCase()}]: ${message}`);
}
}
// High-level module - depends only on abstractions
class UserService {
constructor(
private database: Database,
private notificationService: NotificationService,
private logger: Logger
) {}
async createUser(userData: any): Promise<void> {
try {
this.logger.log('info', `Creating user: ${userData.email}`);
this.database.save(userData);
await this.notificationService.send(
'Welcome to our application!',
userData.email
);
this.logger.log('info', `User ${userData.email} has been created`);
} catch (error) {
this.logger.log('error', `Error creating user: ${error}`);
throw error;
}
}
getUser(id: string): any {
this.logger.log('info', `Fetching user: ${id}`);
return this.database.find(id);
}
async updateUser(id: string, userData: any): Promise<void> {
try {
this.logger.log('info', `Updating user: ${id}`);
this.database.update(id, userData);
await this.notificationService.send(
'Your data has been updated',
userData.email
);
this.logger.log('info', `User ${id} has been updated`);
} catch (error) {
this.logger.log('error', `Error updating user: ${error}`);
throw error;
}
}
deleteUser(id: string): boolean {
this.logger.log('info', `Deleting user: ${id}`);
return this.database.delete(id);
}
}
// Dependency Injection Container (simplified)
class DIContainer {
private services = new Map<string, any>();
register<T>(name: string, instance: T): void {
this.services.set(name, instance);
}
get<T>(name: string): T {
const service = this.services.get(name);
if (!service) {
throw new Error(`Service ${name} not found`);
}
return service;
}
}
// Dependency configuration
const container = new DIContainer();
// Registering different implementations
container.register<Database>('database', new PostgreSQLDatabase());
container.register<NotificationService>('notification', new EmailNotificationService());
container.register<Logger>('logger', new ConsoleLogger());
// Creating the service with injected dependencies
const userService = new UserService(
container.get<Database>('database'),
container.get<NotificationService>('notification'),
container.get<Logger>('logger')
);
// Testing
userService.createUser({
id: '1',
name: 'Jan Kowalski',
email: 'jan@example.com'
});
// Easy to switch implementations
const mobileUserService = new UserService(
new MongoDatabase(), // Different database
new SMSNotificationService(), // Different notifications
new FileLogger() // Different logging
);
mobileUserService.createUser({
id: '2',
name: 'Anna Nowak',
email: '+48123456789'
});The code of UserService did not change by a single character, yet it runs once with PostgreSQL and email, and once with MongoDB and SMS. I recommend constructor injection as your default style: in tests you simply pass in fakes.
Event Bus
An Event Bus is a shared event channel through which modules communicate without direct dependencies, like rangers talking over the park radio. The sender calls publish, and whoever is interested listens with subscribe:
class EventBus {
constructor() {
this.listeners = new Map(); // event name -> array of callbacks
}
subscribe(event, callback) {
if (!this.listeners.has(event)) this.listeners.set(event, []);
this.listeners.get(event).push(callback);
}
unsubscribe(event, callback) {
const callbacks = this.listeners.get(event) || [];
this.listeners.set(event, callbacks.filter(cb => cb !== callback));
}
publish(event, data) {
(this.listeners.get(event) || []).forEach(cb => cb(data));
}
}
const bus = new EventBus();
bus.subscribe('fence:breach', data => console.log('Alarm in sector', data.sector));
bus.publish('fence:breach', { sector: 'B6' });The fence module does not know who will receive the alarm, and the alarm system does not import it: both know only the event bus, which is the abstraction.
Singleton and module registry
A Singleton guarantees a single instance, like a single control room: it stores that instance in a static field, and every later new returns exactly that one:
class ParkCore {
constructor() {
if (ParkCore.instance) return ParkCore.instance;
ParkCore.instance = this;
this.modules = new Map();
}
registerModule(name, module) {
this.modules.set(name, module);
}
getModule(name) {
return this.modules.get(name);
}
init() {
this.modules.forEach(module => module.init?.());
}
}
console.log(new ParkCore() === new ParkCore()); // trueYou register a new module without touching the core (the open/closed principle). A singleton is still a hidden global variable, though, so prefer passing it through the constructor. Protect your modules with the Module pattern: it gives you encapsulation and does not pollute the global scope.
Practical example - SOLID-compliant e-commerce system
Finally, all five principles in one ordering system, and the comments with the letters S, O, L, I and D show where each one is at work:
// Comprehensive example applying all SOLID principles
// Abstractions
interface Product {
id: string;
name: string;
price: number;
category: string;
inStock: boolean;
}
interface ProductRepository {
findById(id: string): Promise<Product | null>;
findByCategory(category: string): Promise<Product[]>;
save(product: Product): Promise<void>;
update(id: string, updates: Partial<Product>): Promise<void>;
delete(id: string): Promise<boolean>;
}
interface PricingStrategy {
calculatePrice(product: Product, quantity: number): number;
}
interface DiscountCalculator {
calculateDiscount(product: Product, quantity: number): number;
}
interface InventoryService {
checkAvailability(productId: string, quantity: number): Promise<boolean>;
reserveItems(productId: string, quantity: number): Promise<boolean>;
releaseReservation(productId: string, quantity: number): Promise<void>;
}
interface OrderRepository {
save(order: Order): Promise<void>;
findById(orderId: string): Promise<Order | null>;
}
interface NotificationService {
sendOrderConfirmation(order: Order): Promise<void>;
sendInventoryAlert(productId: string): Promise<void>;
}
// S - Single Responsibility
class RegularPricingStrategy implements PricingStrategy {
calculatePrice(product: Product, quantity: number): number {
return product.price * quantity;
}
}
class BulkDiscountStrategy implements PricingStrategy {
constructor(private discountCalculator: DiscountCalculator) {}
calculatePrice(product: Product, quantity: number): number {
const basePrice = product.price * quantity;
const discount = this.discountCalculator.calculateDiscount(product, quantity);
return basePrice - discount;
}
}
class QuantityDiscountCalculator implements DiscountCalculator {
calculateDiscount(product: Product, quantity: number): number {
if (quantity >= 10) return product.price * quantity * 0.1;
if (quantity >= 5) return product.price * quantity * 0.05;
return 0;
}
}
class CategoryDiscountCalculator implements DiscountCalculator {
private discountRates = new Map([
['electronics', 0.15],
['books', 0.1],
['clothing', 0.2]
]);
calculateDiscount(product: Product, quantity: number): number {
const rate = this.discountRates.get(product.category) || 0;
return product.price * quantity * rate;
}
}
// O - Open/Closed - easy to add new strategies
class SeasonalPricingStrategy implements PricingStrategy {
constructor(
private basePricingStrategy: PricingStrategy,
private seasonalMultiplier: number
) {}
calculatePrice(product: Product, quantity: number): number {
const basePrice = this.basePricingStrategy.calculatePrice(product, quantity);
return basePrice * this.seasonalMultiplier;
}
}
// L - Liskov Substitution - all strategies are interchangeable
class PremiumPricingStrategy implements PricingStrategy {
calculatePrice(product: Product, quantity: number): number {
return product.price * quantity * 1.2; // 20% premium
}
}
// I - Interface Segregation - small, dedicated interfaces
interface OrderItem {
productId: string;
quantity: number;
unitPrice: number;
totalPrice: number;
}
interface Order {
id: string;
customerId: string;
items: OrderItem[];
totalAmount: number;
status: 'pending' | 'confirmed' | 'shipped' | 'delivered';
createdAt: Date;
}
// D - Dependency Inversion
class OrderService {
constructor(
private productRepository: ProductRepository,
private orderRepository: OrderRepository,
private inventoryService: InventoryService,
private pricingStrategy: PricingStrategy,
private notificationService: NotificationService
) {}
async createOrder(customerId: string, items: Array<{productId: string, quantity: number}>): Promise<Order> {
const orderItems: OrderItem[] = [];
let totalAmount = 0;
// Check availability and calculate prices
for (const item of items) {
const product = await this.productRepository.findById(item.productId);
if (!product) {
throw new Error(`Product ${item.productId} not found`);
}
const isAvailable = await this.inventoryService.checkAvailability(item.productId, item.quantity);
if (!isAvailable) {
throw new Error(`Insufficient quantity of product ${product.name}`);
}
const totalPrice = this.pricingStrategy.calculatePrice(product, item.quantity);
orderItems.push({
productId: item.productId,
quantity: item.quantity,
unitPrice: product.price,
totalPrice
});
totalAmount += totalPrice;
}
// Reserve products
for (const item of orderItems) {
await this.inventoryService.reserveItems(item.productId, item.quantity);
}
// Create order
const order: Order = {
id: 'order_' + Math.random().toString(36).slice(2, 11),
customerId,
items: orderItems,
totalAmount,
status: 'pending',
createdAt: new Date()
};
await this.orderRepository.save(order);
await this.notificationService.sendOrderConfirmation(order);
return order;
}
async confirmOrder(orderId: string): Promise<void> {
const order = await this.orderRepository.findById(orderId);
if (!order) {
throw new Error('Order not found');
}
order.status = 'confirmed';
await this.orderRepository.save(order);
}
}
// Example usage with different pricing strategies
function createOrderServiceWithRegularPricing(): OrderService {
return new OrderService(
new InMemoryProductRepository(),
new InMemoryOrderRepository(),
new SimpleInventoryService(),
new RegularPricingStrategy(),
new EmailNotificationService()
);
}
function createOrderServiceWithBulkDiscount(): OrderService {
return new OrderService(
new InMemoryProductRepository(),
new InMemoryOrderRepository(),
new SimpleInventoryService(),
new BulkDiscountStrategy(new QuantityDiscountCalculator()),
new EmailNotificationService()
);
}
function createOrderServiceWithSeasonalPricing(): OrderService {
const basePricing = new BulkDiscountStrategy(new CategoryDiscountCalculator());
const seasonalPricing = new SeasonalPricingStrategy(basePricing, 0.8); // 20% discount
return new OrderService(
new InMemoryProductRepository(),
new InMemoryOrderRepository(),
new SimpleInventoryService(),
seasonalPricing,
new SlackNotificationService()
);
}
// Helper implementations (simplified)
class InMemoryProductRepository implements ProductRepository {
private products = new Map<string, Product>();
async findById(id: string): Promise<Product | null> {
return this.products.get(id) || null;
}
async findByCategory(category: string): Promise<Product[]> {
return Array.from(this.products.values()).filter(p => p.category === category);
}
async save(product: Product): Promise<void> {
this.products.set(product.id, product);
}
async update(id: string, updates: Partial<Product>): Promise<void> {
const product = this.products.get(id);
if (product) {
this.products.set(id, { ...product, ...updates });
}
}
async delete(id: string): Promise<boolean> {
return this.products.delete(id);
}
}
class InMemoryOrderRepository implements OrderRepository {
private orders = new Map<string, Order>();
async save(order: Order): Promise<void> {
this.orders.set(order.id, order);
}
async findById(orderId: string): Promise<Order | null> {
return this.orders.get(orderId) || null;
}
}
class SimpleInventoryService implements InventoryService {
private inventory = new Map<string, number>();
async checkAvailability(productId: string, quantity: number): Promise<boolean> {
const available = this.inventory.get(productId) || 0;
return available >= quantity;
}
async reserveItems(productId: string, quantity: number): Promise<boolean> {
const available = this.inventory.get(productId) || 0;
if (available >= quantity) {
this.inventory.set(productId, available - quantity);
return true;
}
return false;
}
async releaseReservation(productId: string, quantity: number): Promise<void> {
const current = this.inventory.get(productId) || 0;
this.inventory.set(productId, current + quantity);
}
}
class EmailNotificationService implements NotificationService {
async sendOrderConfirmation(order: Order): Promise<void> {
console.log(`Email: Order confirmation ${order.id} sent`);
}
async sendInventoryAlert(productId: string): Promise<void> {
console.log(`Email: Low inventory alert for ${productId}`);
}
}
class SlackNotificationService implements NotificationService {
async sendOrderConfirmation(order: Order): Promise<void> {
console.log(`Slack: Order confirmation ${order.id} sent`);
}
async sendInventoryAlert(productId: string): Promise<void> {
console.log(`Slack: Low inventory alert for ${productId}`);
}
}OrderService does not know whether it calculates regular, bulk or seasonal prices, because it receives the strategy from outside, and its own code stays untouched.
Summary of SOLID principles
- Single Responsibility - one class, one responsibility
- Open/Closed - open for extension, closed for modification
- Liskov Substitution - derived objects can replace base objects
- Interface Segregation - small, dedicated interfaces
- Dependency Inversion - depend on abstractions, not implementations
Code that follows SOLID is easier to maintain, testable, scalable and readable. Do not force the principles, though: three lines of code do not need five interfaces. In the editor below you will complete your own EventBus, and in the next lesson functional programming will reach similar goals with pure functions.
Remember: a good park is many small, specialized systems connected through abstractions, not one giant control panel.
Code for this lesson: index.js
// Observer pattern - Event Bus
// Exercise: Create an event system for the Park
class EventBus {
constructor() {
this.listeners = {};
}
// Implement the methods:
// subscribe(event, callback) - subscription
// unsubscribe(event, callback) - unsubscription
// publish(event, data) - publish an event
subscribe(event, callback) {
// Your code here
}
publish(event, data) {
// Your code here
}
}
const bus = new EventBus();
bus.subscribe("alert", (data) => console.log("Alert:", data));
bus.publish("alert", { level: "HIGH", message: "Fence damaged!" });Docs entries used in this lesson
Spotted a mistake in this lesson?
Check yourself
Answer the questions from this lesson. Pick an answer to see right away whether it is correct.
1. What is the purpose of an Event Bus in application architecture?
2. What does the Module pattern provide in JavaScript?
Hands-on tasks in the game
- Code editor
The index.js file has a ParkCore class that keeps the park modules in a Map (this.modules). Fill in the blanks with Map methods: ___BLANK1___ checks whether a module name is already taken (then registerModule returns false and does not overwrite the module), ___BLANK2___ returns the module stored under a name, and ___BLANK3___ goes through all modules so that init() calls init() of every module that has it and returns the number of initialized modules.
- Click in order
Arrange the elements of a Singleton pattern implementation.
- Code editor
The index.js file has the EventBus class from the SOLID lesson. Fill in the blanks: ___BLANK1___ is the array method that adds the callback at the end of the event list, ___BLANK2___ is the array method that returns a new array without the removed callback, and ___BLANK3___ is the call of the callback cb with the event data. publish should pass the data to every subscriber of the event, and after unsubscribe the removed callback must not receive anything.