<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Amitws on Medium]]></title>
        <description><![CDATA[Stories by Amitws on Medium]]></description>
        <link>https://medium.com/@amitws95?source=rss-28f5d46e5c3d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*KeB4b303ewmejMno</url>
            <title>Stories by Amitws on Medium</title>
            <link>https://medium.com/@amitws95?source=rss-28f5d46e5c3d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 03:31:05 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@amitws95/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[SOLID Principles Explained with Real-World Examples: Writing Code That’s Easier to Change]]></title>
            <link>https://medium.com/@amitws95/solid-principles-explained-with-real-world-examples-writing-code-thats-easier-to-change-7a188fa4f045?source=rss-28f5d46e5c3d------2</link>
            <guid isPermaLink="false">https://medium.com/p/7a188fa4f045</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Amitws]]></dc:creator>
            <pubDate>Tue, 20 Oct 2026 10:00:37 GMT</pubDate>
            <atom:updated>2026-10-20T10:00:37.161Z</atom:updated>
            <content:encoded><![CDATA[<p>A practical guide to writing clean, maintainable, and scalable code using JavaScript and TypeScript examples — without overengineering your application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*rwRcq8vE0Ea4YztrVUAqyw.png" /><figcaption>Think for Design with SOLID before code</figcaption></figure><p><em>Good code isn’t code that works only today. It’s code that you can understand, modify, and extend six months from now without being afraid of breaking everything.</em></p><p>As developers, we’ve all seen it happen.</p><p>A simple feature request arrives. You open the codebase, change a few lines, and suddenly something unrelated stops working. A small modification requires changes across multiple files. One class handles business logic, sends emails, generates reports, and somehow knows how to connect to the database.</p><p>The problem isn’t always bad coding. Sometimes, the code has simply become too tightly coupled, too difficult to extend, or too expensive to maintain.</p><p>This is where <strong>SOLID principles</strong> become useful.</p><p>SOLID is a set of five object-oriented design principles that help us build software that is easier to maintain, test, and extend.</p><p>Let’s understand each principle through practical examples rather than memorizing definitions.</p><h3>What Are SOLID Principles?</h3><p>SOLID stands for:</p><ul><li><strong>S — Single Responsibility Principle</strong></li><li><strong>O — Open/Closed Principle</strong></li><li><strong>L — Liskov Substitution Principle</strong></li><li><strong>I — Interface Segregation Principle</strong></li><li><strong>D — Dependency Inversion Principle</strong></li></ul><p>These principles were popularized by Robert C. Martin (Uncle Bob) and are widely used when discussing maintainable object-oriented software design.</p><p>One important thing to understand before we begin:</p><p><strong>SOLID is not a collection of rules that must be followed blindly. It’s a way to think about how software should be structured as requirements change.</strong></p><p>Let’s explore the five principles using a simple e-commerce application as our running example.</p><h3>1. Single Responsibility Principle (SRP)</h3><p><strong>A class should have one reason to change.</strong></p><p>Imagine you’re building an e-commerce application. You create an OrderService class that does everything:</p><pre>class OrderService {<br>  createOrder(order) {<br>    // Save order to database<br>  }</pre><pre>  calculateTotal(order) {<br>    // Calculate order total<br>  }</pre><pre>  sendConfirmationEmail(order) {<br>    // Send email to customer<br>  }</pre><pre>  generateInvoice(order) {<br>    // Generate invoice PDF<br>  }<br>}</pre><p>Initially, this looks convenient. Everything related to an order lives in one place.</p><p>But consider what happens when requirements change:</p><ul><li>The finance team changes the invoice format.</li><li>The marketing team wants a different email template.</li><li>The business changes its pricing rules.</li><li>The database layer needs to be replaced.</li></ul><p>Now, one class is affected by several unrelated reasons for change.</p><p>That’s the problem SRP helps us avoid.</p><h3>A better approach</h3><p>Separate responsibilities into focused classes or modules:</p><pre>class OrderService {<br>  constructor(pricingService, orderRepository) {<br>    this.pricingService = pricingService;<br>    this.orderRepository = orderRepository;<br>  }</pre><pre>  createOrder(order) {<br>    const total = this.pricingService.calculate(order);</pre><pre>    return this.orderRepository.save({<br>      ...order,<br>      total,<br>    });<br>  }<br>}</pre><pre>class EmailService {<br>  sendOrderConfirmation(order) {<br>    // Send confirmation email<br>  }<br>}</pre><pre>class InvoiceService {<br>  generate(order) {<br>    // Generate invoice PDF<br>  }<br>}</pre><p>The order service focuses on order creation and coordinates the relevant dependencies. Email and invoice generation have their own responsibilities.</p><p>In a real application, an application-level workflow or event handler could coordinate these operations without putting everything into OrderService.</p><h3>Why this matters</h3><p>When the invoice format changes, you don’t need to modify order-creation logic. When email delivery changes, your pricing calculations remain untouched.</p><p>Your code becomes easier to test because each component has a narrower purpose.</p><p><strong>The key takeaway:</strong> Don’t split every method into a separate class. Group behavior that changes for the same reason, and separate behavior that changes for different reasons.</p><h3>2. Open/Closed Principle (OCP)</h3><p><strong>Software entities should be open for extension but closed for modification.</strong></p><p>Imagine your e-commerce application initially supports two payment methods: credit cards and UPI.</p><p>You might write:</p><pre>function processPayment(method, amount) {<br>  if (method === &quot;card&quot;) {<br>    // Process card payment<br>  } else if (method === &quot;upi&quot;) {<br>    // Process UPI payment<br>  }<br>}</pre><p>This works perfectly well for two payment methods.</p><p>Then the business requests net banking, wallets, and international payments.</p><p>Every new method requires modifying the same function. As conditions accumulate, the function becomes harder to reason about and more likely to introduce regressions.</p><h3>A better approach</h3><p>Define a common contract and allow each payment method to implement it.</p><pre>class CardPayment {<br>  pay(amount) {<br>    // Process card payment<br>  }<br>}</pre><pre>class UpiPayment {<br>  pay(amount) {<br>    // Process UPI payment<br>  }<br>}</pre><pre>class WalletPayment {<br>  pay(amount) {<br>    // Process wallet payment<br>  }<br>}</pre><pre>function checkout(paymentMethod, amount) {<br>  return paymentMethod.pay(amount);<br>}</pre><p>Now, adding a new payment method doesn’t require changing the checkout function, provided the new implementation follows the same contract.</p><p>In a production system, these classes would also handle provider-specific errors, validation, and payment results.</p><h3>Why this matters</h3><p>You can introduce new behavior while keeping stable, well-tested code unchanged.</p><p>However, OCP doesn’t mean existing code must never change. Sometimes a requirement genuinely changes an existing business rule. The goal is to protect stable parts of the system from unnecessary modifications.</p><p><strong>The key takeaway:</strong> Identify the parts of your application that are likely to vary, then design clear extension points around them.</p><h3>3. Liskov Substitution Principle (LSP)</h3><p><strong>A subtype should be usable wherever its base type is expected without breaking the correctness of the program.</strong></p><p>This principle is easier to understand through a common example.</p><p>Suppose we have a base Bird class:</p><pre>class Bird {<br>  fly() {<br>    // Make the bird fly<br>  }<br>}</pre><p>Now, we create two bird types:</p><pre>class Sparrow extends Bird {<br>  fly() {<br>    // Sparrow can fly<br>  }<br>}</pre><pre>class Penguin extends Bird {<br>  fly() {<br>    throw new Error(&quot;Penguins cannot fly&quot;);<br>  }<br>}</pre><p>At first glance, inheritance seems reasonable. Both are birds.</p><p>But the design breaks when code assumes that every Bird can fly:</p><pre>function makeBirdFly(bird) {<br>  bird.fly();<br>}</pre><p>Passing a penguin violates that expectation.</p><p>The issue isn’t that penguins are unusual. The issue is that the parent class promises behavior that every subtype cannot provide.</p><h3>A better approach</h3><p>Model the capabilities more accurately:</p><pre>class Bird {<br>  eat() {<br>    // Common bird behavior<br>  }<br>}</pre><pre>class FlyingBird extends Bird {<br>  fly() {<br>    // Flying behavior<br>  }<br>}</pre><pre>class Sparrow extends FlyingBird {}</pre><pre>class Penguin extends Bird {}</pre><p>Now, code that requires flying can explicitly accept a FlyingBird, rather than assuming that every bird can fly.</p><p>JavaScript doesn’t enforce these types automatically, but the design still communicates the intended contract. In TypeScript, interfaces and types can make such constraints clearer.</p><h3>Why this matters</h3><p>LSP prevents inheritance hierarchies that look correct on paper but fail at runtime.</p><p>The same problem appears in business software. A subclass might throw unexpected errors, ignore required operations, or return results that violate the assumptions made by its parent type.</p><p><strong>The key takeaway:</strong> Inheritance should preserve behavioral expectations, not merely represent an “is-a” relationship.</p><h3>4. Interface Segregation Principle (ISP)</h3><p><strong>Clients should not be forced to depend on methods they don’t use.</strong></p><p>Imagine you’re building an application that manages different types of workers.</p><p>You define this interface:</p><pre>interface Worker {<br>  work(): void;<br>  eat(): void;<br>  sleep(): void;<br>}</pre><p>A human worker can perform all three operations.</p><p>But what about a robot worker?</p><pre>class RobotWorker implements Worker {<br>  work() {}</pre><pre>  eat() {<br>    throw new Error(&quot;Robots don&#39;t eat&quot;);<br>  }</pre><pre>  sleep() {<br>    throw new Error(&quot;Robots don&#39;t sleep&quot;);<br>  }<br>}</pre><p>The robot is forced to implement methods that make no sense for it.</p><p>This is a sign that the interface is doing too much.</p><h3>A better approach</h3><p>Separate the capabilities into smaller interfaces:</p><pre>interface Workable {<br>  work(): void;<br>}</pre><pre>interface Eatable {<br>  eat(): void;<br>}</pre><pre>interface Sleepable {<br>  sleep(): void;<br>}</pre><pre>class HumanWorker<br>  implements Workable, Eatable, Sleepable {<br>  work() {}<br>  eat() {}<br>  sleep() {}<br>}</pre><pre>class RobotWorker implements Workable {<br>  work() {}<br>}</pre><p>Now each worker implements only the capabilities it actually supports.</p><h3>Why this matters</h3><p>Small, focused interfaces reduce unnecessary dependencies. Changes to eating-related behavior won’t force unrelated robot implementations to change.</p><p>This is especially useful in larger applications where different modules need different subsets of functionality.</p><p><strong>The key takeaway:</strong> Prefer several focused interfaces over one oversized interface that tries to describe everything.</p><h3>5. Dependency Inversion Principle (DIP)</h3><p><strong>High-level modules should not depend directly on low-level modules. Both should depend on abstractions.</strong></p><p>This principle is often confused with dependency injection. They are related, but they are not the same thing.</p><p>Dependency inversion is a design principle. Dependency injection is one technique for supplying dependencies to a component.</p><p>Consider a notification service:</p><pre>class EmailService {<br>  send(message) {<br>    // Send email<br>  }<br>}</pre><pre>class NotificationService {<br>  constructor() {<br>    this.emailService = new EmailService();<br>  }</pre><pre>  notify(message) {<br>    this.emailService.send(message);<br>  }<br>}</pre><p>The notification service directly creates and depends on a specific email implementation.</p><p>Now, suppose the application needs SMS or push notifications. The high-level business logic becomes tied to infrastructure details.</p><h3>A better approach</h3><p>Make the notification service depend on an abstraction:</p><pre>interface MessageService {<br>  send(message: string): void;<br>}</pre><pre>class EmailService implements MessageService {<br>  send(message: string) {<br>    // Send email<br>  }<br>}</pre><pre>class SmsService implements MessageService {<br>  send(message: string) {<br>    // Send SMS<br>  }<br>}</pre><pre>class NotificationService {<br>  constructor(<br>    private messageService: MessageService<br>  ) {}</pre><pre>  notify(message: string) {<br>    this.messageService.send(message);<br>  }<br>}</pre><p>The application can now provide the appropriate implementation:</p><pre>const emailNotifier =<br>  new NotificationService(new EmailService());</pre><pre>const smsNotifier =<br>  new NotificationService(new SmsService());</pre><p>The notification logic doesn’t need to know how emails or SMS messages are delivered.</p><h3>Why this matters</h3><p>You can replace infrastructure implementations, create test doubles, and test business logic without making real network calls.</p><p>For example, a unit test can inject a mock MessageService and verify that the notification service requests the correct message.</p><p><strong>The key takeaway:</strong> High-level business rules should not be tightly coupled to low-level implementation details.</p><h3>Putting SOLID Together: A Real-World Example</h3><p>Let’s return to our e-commerce application.</p><p>Suppose the business wants to introduce a new payment provider and send order notifications after checkout.</p><p>A design influenced by SOLID might look like this:</p><ul><li>OrderService handles the order-creation workflow.</li><li>PricingService calculates the total.</li><li>PaymentProcessor exposes a payment contract.</li><li>Individual payment providers implement that contract.</li><li>NotificationService depends on a messaging abstraction.</li><li>Focused interfaces define the capabilities each component needs.</li></ul><p>The result is not necessarily more files for the sake of having more files. The goal is to make the boundaries between responsibilities clear.</p><p>When a payment provider changes, order-pricing logic should not need to change. When an email provider changes, payment processing should remain unaffected.</p><p>This separation makes the application easier to test and extend as the business grows.</p><h3>Common Mistakes When Applying SOLID</h3><p>SOLID can improve design, but applying it mechanically can create a different problem: unnecessary complexity.</p><p>Here are five mistakes worth avoiding.</p><p><strong>1. Creating an interface for every class</strong></p><p>Not every class needs an interface. Add abstractions when they provide a useful boundary, multiple implementations, or a meaningful testing benefit.</p><p><strong>2. Splitting code into too many tiny classes</strong></p><p>SRP is about reasons to change, not a rule that every method deserves its own class.</p><p><strong>3. Treating OCP as a ban on modifying existing code</strong></p><p>Sometimes changing existing code is the correct solution. Avoiding every modification can create more complexity than it prevents.</p><p><strong>4. Using inheritance when composition would be simpler</strong></p><p>LSP becomes difficult to maintain when subclasses cannot honor their parent’s behavioral contract. Composition often provides a more flexible alternative.</p><p><strong>5. Confusing dependency injection with dependency inversion</strong></p><p>Passing a dependency through a constructor is useful, but the design still needs appropriate boundaries. Injecting a concrete dependency everywhere doesn’t automatically produce good architecture.</p><h3>Do You Need SOLID in Every Project?</h3><p>No.</p><p>For a small script that will never grow, introducing five layers of abstraction might be unnecessary.</p><p>For a growing application with multiple developers, changing requirements, external integrations, and a long maintenance life, SOLID can provide substantial value.</p><p>The important question isn’t whether your code follows all five principles perfectly.</p><p>Ask yourself:</p><ul><li>Is this class changing for too many unrelated reasons?</li><li>Does adding a new feature require modifying stable code everywhere?</li><li>Can implementations be substituted without breaking expected behavior?</li><li>Are modules forced to depend on methods they don’t need?</li><li>Is business logic unnecessarily tied to infrastructure?</li></ul><p>If you repeatedly encounter these problems, SOLID gives you a useful vocabulary and a set of design techniques to address them.</p><h3>Final Thoughts</h3><p>Good software architecture isn’t about predicting every possible future requirement. It’s about making likely changes less painful without making today’s code unnecessarily complicated.</p><p>SOLID principles help us separate responsibilities, define reliable contracts, and reduce unnecessary coupling.</p><p>But the real skill is knowing when to apply them.</p><p><strong>Write the simplest design that solves today’s problem while keeping reasonable room for tomorrow’s changes.</strong></p><p>Because maintainable code isn’t code that never changes. It’s code that can change without turning every new feature into a risky project.</p><p><em>Which SOLID principle has made the biggest difference in your projects? Share your experience in the comments.</em></p><p>#SoftwareEngineering #SOLIDPrinciples #CleanCode #SystemDesign #JavaScript #TypeScript</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7a188fa4f045" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>