Key takeaway
- Learn the five SOLID principles in JavaScript and TypeScript, with corrected code examples, when not to apply them and how they help testing and AI agents.
SOLID is a set of five class and module design principles: single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion. In JavaScript and TypeScript they keep code easy to change, because each unit has one reason to change, new behaviour is added without editing old code, and high-level logic depends on abstractions instead of concrete services.
This guide gives a short definition, a corrected code example and a "when not to" note for each principle. SOLID is about how classes and modules depend on each other. For the function-and-data side of the same goal, read our guide to functional programming in JavaScript.
What are the SOLID principles?
Robert C. Martin describes five principles of class design that "expose the dependency management aspects" of object-oriented design (source: Principles of OOD). His one-line statements are in the table below.
| Principle | Statement | What it looks like in JavaScript |
|---|---|---|
| Single responsibility | A class should have one, and only one, reason to change. | Split calculation, formatting and persistence into separate classes or modules. |
| Open-closed | You should be able to extend a class's behaviour without modifying it. | Add a new strategy object instead of another if branch. |
| Liskov substitution | Derived classes must be substitutable for their base classes. | A subclass must honour what callers expect from the parent. |
| Interface segregation | Make fine-grained interfaces that are client specific. | Small TypeScript interfaces, or small duck-typed contracts in plain JavaScript. |
| Dependency inversion | Depend on abstractions, not on concretions. | Pass a service into a class instead of creating it inside. |
Why do coupling and cohesion matter before SOLID?
Coupling is how much one unit knows about another. Cohesion is how closely the parts inside one unit belong together. SOLID pushes towards low coupling and high cohesion, so a change in one place does not ripple through the codebase. The old advice that a unit should have only limited knowledge of other units is the same idea.
How do you apply the single responsibility principle?
Group code by the reason it changes, which usually means by the person or team who asks for the change. If finance changes how salary is calculated and engineering changes how hours are counted, one class holding both will be edited for two reasons and each edit can break the other.
// One class, two reasons to change
class Employee {
calculateSalary() { /* finance rules */ }
hoursWorked() { /* time-tracking rules */ }
save() { /* database access */ }
}
// Split by reason to change
class SalaryCalculator {
calculate(employee) { /* finance rules */ }
}
class TimesheetService {
hoursWorked(employee) { /* time-tracking rules */ }
}
class EmployeeRepository {
save(employee) { /* database access */ }
}
When not to: do not split a class so far that one small feature needs six files. Split when two different reasons to change already exist, not in advance.
How do you apply the open-closed principle?
A long chain of if or switch statements that grows with every new case is the usual sign of a violation. Each new case means editing tested code. Replace the chain with a lookup of small strategy objects, so a new case is a new entry.
// Closed to modification: add a rule, do not edit applyDiscount
const discountRules = {
standard: (total) => total,
member: (total) => total * 0.9,
seasonal: (total) => total * 0.8,
};
function applyDiscount(customerType, total) {
const rule = discountRules[customerType];
if (!rule) throw new Error(`Unknown customer type: ${customerType}`);
return rule(total);
}
When not to: two cases do not need a strategy registry. Wait until the third variation appears.
How do you apply the Liskov substitution principle?
Code that works with a parent class must keep working when it receives a subclass. The classic breach is a mutable Square extending Rectangle. A caller that sets the width and expects the height to stay the same gets a surprise.
class Rectangle {
constructor(width, height) { this.width = width; this.height = height; }
setWidth(w) { this.width = w; }
setHeight(h) { this.height = h; }
area() { return this.width * this.height; }
}
class Square extends Rectangle {
setWidth(w) { this.width = w; this.height = w; } // changes more than callers expect
setHeight(h) { this.width = h; this.height = h; }
}
function widenBy1(rect) {
const h = rect.height;
rect.setWidth(rect.width + 1);
return rect.area() === (rect.width) * h; // true for Rectangle, false for Square
}
A safer design drops the false "is-a" relationship. Give both shapes a common area() contract and make each one immutable, or prefer composition over inheritance.
class Rectangle {
constructor(width, height) { this.width = width; this.height = height; }
area() { return this.width * this.height; }
}
class Square {
constructor(side) { this.side = side; }
area() { return this.side * this.side; }
}
When not to: if a subclass needs to refuse or weaken behaviour of its parent, that is the signal to stop inheriting, not to add checks.
How do you apply interface segregation when JavaScript has no interfaces?
JavaScript has no interface keyword. TypeScript does, and according to its handbook an implements clause is only a check that a class can be treated as the interface type (source: TypeScript handbook, classes). Types are erased at compile time, so the discipline matters most at design time: keep each contract small so that no client depends on methods it never calls.
// Too broad: a read-only report must still see write methods
interface Storage {
read(id: string): Promise<string>;
write(id: string, data: string): Promise<void>;
delete(id: string): Promise<void>;
}
// Segregated: each client takes only what it uses
interface Reader { read(id: string): Promise<string>; }
interface Writer { write(id: string, data: string): Promise<void>; }
class ReportBuilder {
constructor(private source: Reader) {}
}
Angular's lifecycle hooks show the same habit. Each hook has its own small interface, such as OnInit, and according to the Angular documentation you can optionally implement these interfaces (source: Angular component lifecycle).
When not to: in plain JavaScript, document the small contract in a comment or JSDoc type rather than inventing runtime interface objects.
How do you apply dependency inversion?
High-level code should not create its own concrete services. It should receive something that matches an abstraction. Then a payment provider, a data store or a language model client can be swapped without editing the code that uses it, and tests can pass in a fake.
interface PaymentService {
pay(to: string, amount: number): Promise<{ result: 'Success' | 'Failure'; message?: string }>;
}
class CardPaymentService implements PaymentService {
async pay(to: string, amount: number) { /* call provider */ return { result: 'Success' as const }; }
}
class CheckoutController {
constructor(private payments: PaymentService) {}
checkout(to: string, amount: number) { return this.payments.pay(to, amount); }
}
// Production
new CheckoutController(new CardPaymentService());
// Test
new CheckoutController({ pay: async () => ({ result: 'Success' }) });
When not to: do not add an abstraction for something that will only ever have one implementation and is not a boundary such as I/O, a network call or a vendor SDK.
Where do SOLID principles help when you build AI agents?
The same boundaries appear in agent code. A tool, a model client and a policy check are dependencies, so inverting them lets teams swap a model provider or add an approval step without rewriting the agent loop. Small, single-purpose tools are also easier to test and to review. This is a design opinion, not a measured result. For how agent steps are structured, see our guide to agentic workflows; ElixirClaw is an agentic OS platform to build, orchestrate and govern AI agents and automation workflows while keeping humans in control, and AgentQA covers automated quality assurance for AI.
How does SOLID connect to testing?
Small units with injected dependencies are the easiest to test. Our guides to unit testing and shift-left testing cover how to use that in a delivery pipeline.
What is the adoption sequence and the trade-off?
| Step | Action | Trade-off |
|---|---|---|
| 1 | Find the class that changes most often and split it by reason to change (S). | More files to navigate. |
| 2 | Replace its growing if chain with a strategy lookup (O). | Indirection for a simple case. |
| 3 | Inject the I/O and vendor dependencies (D) and keep contracts small (I). | Wiring code in one place. |
| 4 | Review inheritance for broken substitution (L). | May mean rewriting a class hierarchy. |
To map one agent decision in your own system, and the context and policy it depends on, book a Context Workshop. See what happens in the workshop. ElixirData keeps governed context, versioned policy and decision traces in one decision layer above AI agents.
Frequently asked questions
What does SOLID stand for?
Single responsibility, open-closed, Liskov substitution, interface segregation and dependency inversion.
Does JavaScript support SOLID without TypeScript?
Yes. JavaScript classes support inheritance with extends, and duck typing lets any object with the right methods act as a dependency. TypeScript adds interfaces that are checked at compile time and erased afterwards.
Is SOLID only for classes?
Martin states the principles for class design, but the ideas of one reason to change and depending on abstractions also apply to modules and functions.
Which principle is hardest to apply in JavaScript?
Interface segregation, because there is no interface keyword at runtime. Small TypeScript interfaces or JSDoc contracts fill the gap.
How is SOLID different from functional programming?
SOLID manages dependencies between classes and modules. Functional programming focuses on pure functions and immutable data. The two can be combined, as our functional programming guide shows.
Follow XenonStack on LinkedIn: XenonStack on LinkedIn for new guides on agentic AI, data and platform engineering.
Explore the XenonStack platform family: ElixirData · ElixirClaw · ElixirHub · NexaStack · MetaSecure · Neural AI · AgentGRC · AgentSRE · AgentAnalyst · AgentInstruct · AgentRAI · AgentScrum · AgentSearch · AgentForce · AI Aviator · SAIF Aviator · CohortIQ · XenonStack AI · XenonStack UAE