SOLID Principles in JavaScript: Practical Guide with TypeScript and React
How SOLID principles apply to modern JavaScript: practical examples with TypeScript, React hooks, and functional patterns, plus when they're overkill.
SOLID principles were formulated for object-oriented programming, but modern JavaScript development looks different: functional patterns, React hooks, dynamic typing. They still hold, with one adaptation. Anchor each principle to a composition boundary (a function, a module, a hook, a component’s prop list) instead of a class hierarchy, and all five survive the move.
Those five are Single Responsibility, Open/Closed, Liskov Substitution, Interface Segregation, and Dependency Inversion. What changes in JavaScript is the unit they constrain, not the guarantee they buy. Most of the pain people blame on SOLID comes from importing its Java-shaped ceremony (factories, deep hierarchies, stacked interfaces) into a language that already gets those guarantees from closures and structural types.
What JavaScript Changes#
The principles were written for statically-typed, class-based languages like Java and C#. JavaScript brings different characteristics:
- Dynamic typing - No compile-time type checking without TypeScript
- Functional patterns - Functions as first-class citizens
- Composition focus - Less emphasis on inheritance
- Duck typing - Code calls whatever methods an object has; no runtime check against a declared interface
- React patterns - Hooks and components have different constraints
Single Responsibility Principle (SRP)#
Definition: “A module should be responsible to one, and only one, actor.” That is Robert C. Martin’s wording in Clean Architecture. The older form, “one reason to change”, is often read as an order to make every module do one small thing. Martin’s own gloss points elsewhere: “This principle is about people.” An actor is a group of users or stakeholders that asks for changes, and a function can do one small thing while still answering to two such groups.
This translates most directly to JavaScript. Whether you’re writing classes, functions, or React components, group code by who requests its changes.
React Component Example#
A common violation lets two actors edit the same component:
// BAD: Violates SRP: API contract changes and design changes both land here
function UserProfile({ userId }: { userId: string }) {
const [user, setUser] = useState(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState(null);
useEffect(() => {
setLoading(true);
fetch(`/api/users/${userId}`)
.then(res => res.json())
.then(data => {
setUser(data);
setLoading(false);
})
.catch(err => {
setError(err);
setLoading(false);
});
}, [userId]);
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!user) return null;
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
<img src={user.avatar} alt={user.name} />
</div>
);
}
Two groups request changes to this component. The team that owns /api/users changes the URL, the response shape, and the error codes. The design team changes the layout, the avatar, and the loading screen. The fetch call and the loading flag belong together, because both follow the API contract. Splitting them apart would turn one API change into two edits. The line to draw runs between the API contract and the markup:
interface User {
id: string;
name: string;
email: string;
avatar: string;
}
// Follows SRP: answers to the API contract (URL, response shape, error codes)
function useUser(userId: string) {
const [user, setUser] = useState<User | null>(null);
const [loading, setLoading] = useState(false);
const [error, setError] = useState<Error | null>(null);
useEffect(() => {
const controller = new AbortController();
setLoading(true);
setError(null);
setUser(null);
fetch(`/api/users/${userId}`, { signal: controller.signal })
.then(res => {
// fetch() resolves on 404 and 500 too, so check the status
if (!res.ok) throw new Error(`Request failed with status ${res.status}`);
return res.json() as Promise<User>;
})
.then(data => {
if (!controller.signal.aborted) setUser(data);
})
.catch(err => {
if (!controller.signal.aborted) {
setError(err instanceof Error ? err : new Error(String(err)));
}
})
.finally(() => {
if (!controller.signal.aborted) setLoading(false);
});
// Cancels the stale request when userId changes or the component unmounts
return () => controller.abort();
}, [userId]);
return { user, loading, error };
}
// Design side: picks which screen to show
function UserProfile({ userId }: { userId: string }) {
const { user, loading, error } = useUser(userId);
if (loading) return <Spinner />;
if (error) return <ErrorMessage error={error} />;
if (!user) return null;
return <UserCard user={user} />;
}
// Follows SRP: answers to the design (layout, typography, avatar)
function UserCard({ user }: { user: User }) {
return (
<div>
<h1>{user.name}</h1>
<p>{user.email}</p>
<img src={user.avatar} alt={user.name} />
</div>
);
}
Now each piece answers to one group. A new field or a new error code from the API touches only useUser. UserProfile only picks between Spinner, ErrorMessage and UserCard, so it sits on the design side too. A redesign touches only UserCard and the screen choices in UserProfile. UserCard renders user data without knowing where it came from. The hook can be tested on its own and reused in other components.
The hook also fixes three bugs that the first version shares with most hand-written fetch effects. Without cancellation, a fast change of userId lets the older response arrive last and overwrite the newer user; the React docs call this a race condition and solve it with a cleanup function. fetch() does not reject on HTTP error statuses such as 404 or 500, so without the res.ok check a JSON error body from a 404 lands in user state. And an error that is never reset keeps the error screen visible after the next request succeeds. That is a lot of code for one GET. The React docs recommend a framework’s built-in data fetching or, without a framework, a client-side cache such as TanStack Query, and the SRP split stays the same with either: the library call simply replaces the body of useUser.
Common SRP Anti-pattern: God Objects#
// BAD: Module with unrelated concerns
// utils/user.js
export function validateEmail(email) { /* ... */ }
export function formatCurrency(amount) { /* ... */ }
export function fetchWeatherData(city) { /* ... */ }
export function compressImage(file) { /* ... */ }
These functions have nothing in common. Split them into focused modules:
// Cohesive modules
// utils/validation.js
export function validateEmail(email) { /* ... */ }
export function validatePassword(password) { /* ... */ }
// utils/formatting.js
export function formatCurrency(amount) { /* ... */ }
export function formatDate(date) { /* ... */ }
// services/weather.js
export function fetchWeatherData(city) { /* ... */ }
Open/Closed Principle (OCP)#
Definition: Software entities should be open for extension, closed for modification.
In JavaScript, this means adding new functionality without changing existing code. The strategy pattern works well here.
Payment Processing Example#
The violation shows up as a dispatcher that grows a branch per payment method:
// BAD: Violates OCP: Must modify function for each new payment method
function processPayment(amount: number, method: string) {
if (method === 'credit-card') {
validateCreditCard();
chargeCreditCard(amount);
} else if (method === 'paypal') {
validatePayPalAccount();
chargePayPal(amount);
} else if (method === 'crypto') {
validateWallet();
transferCrypto(amount);
}
// Adding new method requires modifying this function
}
The functional approach using strategy pattern:
// Follows OCP: Extend without modification
type PaymentProcessor = {
validate: () => Promise<boolean>;
charge: (amount: number) => Promise<PaymentResult>;
};
const createCreditCardProcessor = (cardDetails: CardDetails): PaymentProcessor => ({
validate: () => validateCreditCard(cardDetails),
charge: (amount) => chargeCreditCard(cardDetails, amount),
});
const createPayPalProcessor = (email: string): PaymentProcessor => ({
validate: () => validatePayPalAccount(email),
charge: (amount) => chargePayPal(email, amount),
});
const processPayment = async (
processor: PaymentProcessor,
amount: number
): Promise<PaymentResult> => {
const isValid = await processor.validate();
if (!isValid) throw new Error('Payment validation failed');
return processor.charge(amount);
};
// Usage - adding new processor requires no changes to processPayment
await processPayment(createCreditCardProcessor(cardDetails), 100);
await processPayment(createPayPalProcessor('user@email.com'), 100);
// Add crypto without modifying existing code
const createCryptoProcessor = (wallet: string): PaymentProcessor => ({
validate: () => validateWallet(wallet),
charge: (amount) => transferCrypto(wallet, amount),
});
await processPayment(createCryptoProcessor(walletAddress), 100);
This works with TypeScript’s structural typing. New processors only need to match the shape; JavaScript requires no explicit interface declaration, and TypeScript adds compile-time safety on top of it.
Where the Dispatcher Went#
The checkout form still sends a method name such as 'paypal'. Something has to turn that string into a processor, and that code is the old if/else chain in a new place. Make it a lookup table:
// What each method needs from the checkout form
interface PaymentInputs {
'credit-card': CardDetails;
paypal: { email: string };
crypto: { wallet: string };
}
type PaymentMethod = keyof PaymentInputs;
// The one table that maps a method name to its strategy
const processorFactories: {
[M in PaymentMethod]: (input: PaymentInputs[M]) => PaymentProcessor;
} = {
'credit-card': createCreditCardProcessor,
paypal: ({ email }) => createPayPalProcessor(email),
crypto: ({ wallet }) => createCryptoProcessor(wallet),
};
function checkout<M extends PaymentMethod>(
method: M,
input: PaymentInputs[M],
amount: number
): Promise<PaymentResult> {
return processPayment(processorFactories[method](input), amount);
}
await checkout('paypal', { email: 'user@email.com' }, 100);
// Guard for the raw string that arrives from the request
function isPaymentMethod(value: string): value is PaymentMethod {
return Object.hasOwn(processorFactories, value);
}
A new method now costs one line in PaymentInputs and one entry in the table. If the entry is missing, the table stops compiling. processPayment and checkout stay closed.
The table is not free, and the discriminated union in the TypeScript section further down makes the opposite choice. Strategies make a new case cheap: a new payment method touches no existing function. A new operation (a refund on every processor) is the expensive change, because every factory has to grow it. With a union and a switch, a new function over Shape touches nothing that exists, while a new shape forces an edit in every switch over it. Philip Wadler named this tension the expression problem. Pick strategies when the set of cases grows and the operations stay fixed (payment methods, plugins, storage drivers). Pick a union when the cases are fixed and the operations grow (UI states, AST nodes, event types). In both shapes the compiler points at the code that has to change: a missing table entry or a switch that no longer covers every case, provided the function declares its return type or ends with a never check.
OCP with Higher-Order Functions#
// OCP through composition: each step keeps the value's type
const pipe =
<T>(...fns: Array<(value: T) => T>) =>
(value: T): T =>
fns.reduce((result, fn) => fn(result), value);
// Base transformations
const toLowerCase = (str: string) => str.toLowerCase();
const trim = (str: string) => str.trim();
const removeSpaces = (str: string) => str.replace(/\s/g, '');
// Extend by composing - no modification needed
const normalizeEmail = pipe(trim, toLowerCase);
const normalizeUsername = pipe(trim, toLowerCase, removeSpaces);
// Add new transformation
const removeDashes = (str: string) => str.replace(/-/g, '');
const normalizePhoneNumber = pipe(trim, removeSpaces, removeDashes);
// Compile error: parseCount returns a number, the next step expects a string
const parseCount = (str: string) => Number.parseInt(str, 10);
// const broken = pipe(trim, parseCount, toLowerCase);
The generic T is what makes the composition safe. A version typed as (data: any) => any compiles the broken line above and fails only at runtime, when toLowerCase receives a number.
Liskov Substitution Principle (LSP)#
Definition: Objects should be replaceable with their subtypes without breaking the program.
LSP violations are common with inheritance. The classic example:
// BAD: Violates LSP: Square breaks Rectangle's contract
class Rectangle {
constructor(
protected width: number,
protected height: number
) {}
setWidth(width: number) {
this.width = width;
}
setHeight(height: number) {
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
class Square extends Rectangle {
setWidth(width: number) {
this.width = width;
this.height = width; // Unexpected behavior
}
setHeight(height: number) {
this.width = height;
this.height = height; // Unexpected behavior
}
}
// This breaks with Square
function resizeRectangle(rectangle: Rectangle) {
rectangle.setWidth(10);
rectangle.setHeight(5);
console.assert(rectangle.getArea() === 50); // Fails with Square (area = 25)
}
The solution is composition over inheritance:
// Follows LSP: Use composition instead
interface Shape {
getArea(): number;
}
class Rectangle implements Shape {
constructor(
private width: number,
private height: number
) {}
setWidth(width: number) {
this.width = width;
}
setHeight(height: number) {
this.height = height;
}
getArea(): number {
return this.width * this.height;
}
}
class Square implements Shape {
constructor(private size: number) {}
setSize(size: number) {
this.size = size;
}
getArea(): number {
return this.size * this.size;
}
}
// Functions work with Shape interface - no substitution issues
function printArea(shape: Shape) {
console.log(`Area: ${shape.getArea()}`);
}
printArea(new Rectangle(10, 5)); // Works
printArea(new Square(5)); // Works
LSP in React Components#
Substitution happens in React when a parent accepts a component as a prop. The parent relies on the props contract, and every component passed in has to keep it:
interface ButtonProps {
label: string;
onClick: () => void;
disabled?: boolean;
}
function Button({ label, onClick, disabled }: ButtonProps) {
return <button onClick={onClick} disabled={disabled}>{label}</button>;
}
// The parent accepts any component that honors ButtonProps
function SaveBar({ SaveButton, isSaving, onSave }: {
SaveButton: ComponentType<ButtonProps>;
isSaving: boolean;
onSave: () => void;
}) {
return <SaveButton label="Save" onClick={onSave} disabled={isSaving} />;
}
// BAD: Violates LSP: same props type, but `disabled` is silently ignored
function LinkButton({ label, onClick }: ButtonProps) {
return (
<a href="#" onClick={(event) => { event.preventDefault(); onClick(); }}>
{label}
</a>
);
}
// Compiles, yet a second click while saving calls onSave again
<SaveBar SaveButton={LinkButton} isSaving={isSaving} onSave={save} />;
// Follows LSP: adds an optional prop and keeps every promise ButtonProps makes
function IconButton({ label, onClick, disabled, icon }: ButtonProps & { icon?: string }) {
return (
<button onClick={onClick} disabled={disabled}>
{icon && <Icon name={icon} />}
{label}
</button>
);
}
<SaveBar SaveButton={IconButton} isSaving={isSaving} onSave={save} />;
LinkButton type-checks because its props match. What it breaks is the behavior the parent relies on: while saving, the button should not fire. That behavioral contract is what LSP protects, and TypeScript cannot see it. The opposite mistake, a component that requires an extra prop such as icon: string, is caught at the call site: ComponentType<ButtonProps> rejects it, because SaveBar never passes icon.
Interface Segregation Principle (ISP)#
Definition: Clients shouldn’t depend on interfaces they don’t use.
JavaScript’s duck typing naturally supports this, but TypeScript interfaces and React props benefit from explicit segregation.
The Fat Interface Problem#
In a JavaScript codebase, the fat interface usually shows up first in a test. A function needs one method from a data-access object, but its parameter names the whole object:
// BAD: Violates ISP: the function receives the whole store but calls one method
interface UserStore {
findById(id: string): Promise<User | null>;
findByEmail(email: string): Promise<User | null>;
save(user: User): Promise<void>;
delete(id: string): Promise<void>;
listAll(): Promise<User[]>;
}
interface Mailer {
sendResetLink(to: string): Promise<void>;
}
async function sendPasswordReset(users: UserStore, mailer: Mailer, email: string) {
const user = await users.findByEmail(email);
if (user) await mailer.sendResetLink(user.email);
}
// The test fake has to stub four methods the function never calls
const fakeStore: UserStore = {
findByEmail: async () => testUser,
findById: () => { throw new Error('not used'); },
save: () => { throw new Error('not used'); },
delete: () => { throw new Error('not used'); },
listAll: () => { throw new Error('not used'); },
};
Name only the capability the function uses:
// Follows ISP: the parameter asks for one method
interface FindUserByEmail {
findByEmail(email: string): Promise<User | null>;
}
async function sendPasswordReset(users: FindUserByEmail, mailer: Mailer, email: string) {
const user = await users.findByEmail(email);
if (user) await mailer.sendResetLink(user.email);
}
// Production: the full store still fits, through structural typing
await sendPasswordReset(postgresUserStore, smtpMailer, 'ada@example.com');
// Test: the fakes implement only what the function calls
const sent: string[] = [];
await sendPasswordReset(
{ findByEmail: async () => testUser },
{ sendResetLink: async (to) => { sent.push(to); } },
'ada@example.com'
);
The store keeps all five methods; nothing about it had to change. The signature of sendPasswordReset now documents what the function touches, and a test can call it with a one-method object in place of a stub full of throw lines.
ISP in React Components#
// BAD: Violates ISP: Component depends on entire User type
interface User {
id: string;
name: string;
email: string;
address: Address;
phoneNumber: string;
preferences: UserPreferences;
billingInfo: BillingInfo;
// ... 20+ more properties
}
function UserGreeting({ user }: { user: User }) {
return <h1>Hello, {user.name}!</h1>; // Only uses name
}
// Follows ISP: Component depends only on what it uses
interface UserGreetingProps {
name: string;
}
function UserGreeting({ name }: UserGreetingProps) {
return <h1>Hello, {name}!</h1>;
}
// Usage: Pass only needed data
function App() {
const user: User = fetchUser();
return <UserGreeting name={user.name} />;
}
TypeScript Utility Types for ISP#
// Large interface
interface User {
id: string;
email: string;
password: string;
firstName: string;
lastName: string;
address: Address;
phoneNumber: string;
createdAt: Date;
}
// Create focused types using utility types
type UserCredentials = Pick<User, 'email' | 'password'>;
type UserProfile = Pick<User, 'id' | 'firstName' | 'lastName' | 'email'>;
type UserContactInfo = Pick<User, 'email' | 'phoneNumber' | 'address'>;
type PublicUser = Omit<User, 'password'>;
// Components receive only needed properties
function UserContactForm({ email, phoneNumber, address }: UserContactInfo) {
// Component logic
}
Dependency Inversion Principle (DIP)#
Definition: High-level modules shouldn’t depend on low-level modules. Both should depend on abstractions.
This is critical for testability and flexibility.
The Problem: Direct Dependencies#
// BAD: Violates DIP: UserService directly depends on concrete implementations
class MySQLDatabase {
connect() { /* ... */ }
query(sql: string) { /* ... */ }
}
class EmailService {
sendEmail(to: string, subject: string, body: string) {
// Uses Gmail SMTP directly
}
}
class UserService {
private db = new MySQLDatabase(); // BAD: Tight coupling
private emailService = new EmailService(); // BAD: Tight coupling
async createUser(userData: UserData) {
await this.db.connect();
const user = await this.db.query('INSERT INTO users...');
await this.emailService.sendEmail(user.email, 'Welcome', 'Welcome!');
return user;
}
}
// Cannot test without real MySQL and email service
// Cannot switch implementations
Use constructor injection with abstractions:
// Follows DIP: Depend on abstractions
interface Database {
connect(): Promise<void>;
query<T>(sql: string, params?: any[]): Promise<T>;
}
interface EmailProvider {
send(to: string, subject: string, body: string): Promise<void>;
}
// Concrete implementations
class MySQLDatabase implements Database {
async connect() { /* MySQL connection */ }
async query<T>(sql: string, params?: any[]): Promise<T> {
/* MySQL query */
return {} as T;
}
}
class PostgreSQLDatabase implements Database {
async connect() { /* PostgreSQL connection */ }
async query<T>(sql: string, params?: any[]): Promise<T> {
/* PostgreSQL query */
return {} as T;
}
}
// High-level module depends on abstractions
class UserService {
constructor(
private db: Database,
private emailProvider: EmailProvider
) {}
async createUser(userData: UserData) {
await this.db.connect();
const user = await this.db.query<User>('INSERT INTO users...', [userData]);
await this.emailProvider.send(user.email, 'Welcome', 'Welcome!');
return user;
}
}
// Production: Inject real implementations
const userService = new UserService(
new MySQLDatabase(),
new GmailEmailProvider()
);
// Testing: Inject mocks
const testUserService = new UserService(
new MockDatabase(),
new MockEmailProvider()
);
// Easy to switch implementations
const productionUserService = new UserService(
new PostgreSQLDatabase(),
new SendGridEmailProvider()
);
DIP in React with Context API#
// Dependency injection via React Context
interface ApiClient {
get<T>(url: string): Promise<T>;
post<T>(url: string, data: any): Promise<T>;
}
interface Logger {
log(message: string): void;
error(message: string, error: Error): void;
}
// Create contexts
const ApiClientContext = React.createContext<ApiClient | null>(null);
const LoggerContext = React.createContext<Logger | null>(null);
// Custom hooks for dependencies
function useApiClient() {
const client = useContext(ApiClientContext);
if (!client) throw new Error('ApiClient not provided');
return client;
}
function useLogger() {
const logger = useContext(LoggerContext);
if (!logger) throw new Error('Logger not provided');
return logger;
}
// Component depends on abstractions
function UserList() {
const apiClient = useApiClient();
const logger = useLogger();
const [users, setUsers] = useState<User[]>([]);
useEffect(() => {
apiClient.get<User[]>('/users')
.then(setUsers)
.catch(error => logger.error('Failed to fetch users', error));
}, [apiClient, logger]);
return (
<ul>
{users.map(user => <li key={user.id}>{user.name}</li>)}
</ul>
);
}
// Provide dependencies at root
function App() {
const apiClient = useMemo(() => new FetchApiClient(), []);
const logger = useMemo(() => new ConsoleLogger(), []);
return (
<ApiClientContext.Provider value={apiClient}>
<LoggerContext.Provider value={logger}>
<UserList />
</LoggerContext.Provider>
</ApiClientContext.Provider>
);
}
// Testing: Provide mocks
function TestApp() {
const mockApiClient = useMemo(() => new MockApiClient(), []);
const mockLogger = useMemo(() => new MockLogger(), []);
return (
<ApiClientContext.Provider value={mockApiClient}>
<LoggerContext.Provider value={mockLogger}>
<UserList />
</LoggerContext.Provider>
</ApiClientContext.Provider>
);
}
When SOLID Becomes Overkill#
Not all code benefits from strict SOLID adherence. Premature abstraction creates unnecessary complexity.
Overkill Example: Simple String Formatting#
// BAD: Overkill for simple utility
interface StringFormatter {
format(input: string): string;
}
class UpperCaseFormatter implements StringFormatter {
format(input: string): string {
return input.toUpperCase();
}
}
class FormatterFactory {
static create(type: string): StringFormatter {
switch (type) {
case 'uppercase':
return new UpperCaseFormatter();
default:
throw new Error('Unknown formatter');
}
}
}
// Simple function is sufficient
const toUpperCase = (str: string) => str.toUpperCase();
When to Apply SOLID Strictly#
The trigger is a second implementation or a second actor, and the size of the codebase matters less than either. Apply the principles fully when one of these is already true:
- A second implementation exists today. A second payment provider, or a test fake that replaces the database, is the second implementation. The interface pays for itself on the day it is written.
- The code is a library or framework with a public API. Its consumers live in codebases you cannot edit, so the extension point has to ship before the second implementation shows up.
- Two actors already edit the same file. When API changes and design changes keep colliding in one component, the
useUserandUserCardsplit is overdue.
When to Relax SOLID#
- Prototypes and MVPs where speed matters more than architecture
- Small utility functions where abstraction overhead exceeds benefits
- Stable CRUD screens with one data source and one team. An admin form that reads and writes one table has one implementation of its data access and no second one in sight; a
Repositoryinterface there only adds a file to keep in sync. - One-off scripts and tools with short lifespans
TypeScript’s Role#
TypeScript moves several of these checks to compile time, and it marks one boundary where it cannot help:
// Explicit interfaces for ISP and DIP
interface PaymentProcessor {
process(amount: number): Promise<void>;
}
class CreditCardProcessor implements PaymentProcessor {
async process(amount: number): Promise<void> {
// Must implement or get compile error
}
}
// Type checking does not catch this LSP violation: the signature matches, the behavior does not
interface Bird {
fly(): void;
}
class Penguin implements Bird {
fly() {
throw new Error('Cannot fly'); // Compiles fine, fails at runtime
}
}
// Better: segregate the interfaces so the compiler can rule out the bad call
interface FlyingBird {
fly(): void;
}
interface SwimmingBird {
swim(): void;
}
class Sparrow implements FlyingBird {
fly() { console.log('Flying'); }
}
class SwimmingPenguin implements SwimmingBird {
swim() { console.log('Swimming'); }
}
// Generics for type-safe abstraction (DIP and LSP)
interface Repository<T> {
findById(id: string): Promise<T | null>;
save(entity: T): Promise<T>;
delete(id: string): Promise<void>;
}
class UserRepository implements Repository<User> {
async findById(id: string): Promise<User | null> {
return null;
}
async save(user: User): Promise<User> {
return user;
}
async delete(id: string): Promise<void> {}
}
// Union types as alternative to class hierarchies: new functions are cheap,
// new shapes are not (the expression problem from the OCP section)
type Shape =
| { type: 'circle'; radius: number }
| { type: 'rectangle'; width: number; height: number }
| { type: 'triangle'; base: number; height: number };
// The declared return type makes a fourth shape a compile error here until it gets a case
function calculateArea(shape: Shape): number {
switch (shape.type) {
case 'circle':
return Math.PI * shape.radius ** 2;
case 'rectangle':
return shape.width * shape.height;
case 'triangle':
return (shape.base * shape.height) / 2;
}
}
Where to Draw the Line#
The default holds when a principle lands on a boundary the code already has. A custom hook that answers to one actor, a strategy added with one table entry and one input type, and no edit to processPayment, a prop list narrowed to the fields a component actually reads, a constructor that receives its database instead of building one: those four moves carry most of SOLID’s value into a TypeScript codebase, and not one of them needs a class hierarchy.
Override the default when the abstraction outlives its justification. An interface with a single implementation, a factory with a single branch, or a hook that only forwards its arguments all pay setup cost for flexibility nobody has needed yet. Wait for the second implementation before abstracting. In a prototype or a script with a known end date, skipping the layer is the correct call, and the result stays readable because there is less of it to read.
References#
- Clean Code Episode 8: SOLID Principles - Robert C. Martin (opens in new tab) - Uncle Bob’s foundational lectures on SOLID in object-oriented design
- The Single Responsibility Principle - Robert C. Martin (opens in new tab) - Martin’s essay explaining that the reasons to change are people, with the CFO/COO/CTO example
- Single-responsibility principle - Wikipedia (opens in new tab) - Traces the definition from “one reason to change” to the actor wording in Clean Architecture
- React: useEffect - Fetching data with Effects (opens in new tab) - The cleanup pattern against race conditions and the recommended alternatives (a framework’s built-in data fetching, TanStack Query, SWR)
- MDN: Window.fetch() (opens in new tab) - Documents that
fetch()does not reject on HTTP error statuses and thatResponse.okhas to be checked - The Expression Problem - Philip Wadler (opens in new tab) - The original note naming the trade-off between adding new cases and adding new operations
- Refactoring.Guru: Design Patterns (opens in new tab) - Practical catalog of patterns that complement SOLID principles, with TypeScript examples
- MDN: JavaScript Classes (opens in new tab) - Reference for class syntax underlying OOP and SOLID in JavaScript
- typescript-eslint: Getting Started (opens in new tab) - Tooling to enforce SOLID-aligned TypeScript rules at compile time
- MDN: Using Classes - JavaScript Guide (opens in new tab) - Detailed guide to JavaScript class mechanics and prototype inheritance
Related posts
How Decorator, Adapter, Facade, Composite, and Proxy patterns evolved in React and TypeScript: when HOCs give way to hooks and how adapters isolate third-party APIs.
typescript · react · design-patterns +2
How Singleton, Factory, Builder, and Prototype patterns evolved in TypeScript: when ES modules replace singletons and when factory functions beat classes.
typescript · design-patterns · architecture +1
A comprehensive introduction to Domain-Driven Design: core concepts, building blocks, strategic patterns, and when and how to apply DDD in practice.
domain-driven-design · architecture · design-patterns +2
A lifecycle test for CDK stack layout: give a resource its own long-lived stack when it outlives any single deployer, then reach it by a well-known name.
aws-cdk · infrastructure-as-code · typescript +3
Match architecture weight to the requests each init serves: lean handlers where Lambda traffic is sparse, light DI on a Lambdalith, full OOP/DI on long-lived runtimes.
architecture · lambda · serverless +3