惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

M
MIT News - Artificial intelligence
罗磊的独立博客
Hugging Face - Blog
Hugging Face - Blog
Apple Machine Learning Research
Apple Machine Learning Research
Last Week in AI
Last Week in AI
S
SegmentFault 最新的问题
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
美团技术团队
人人都是产品经理
人人都是产品经理
WordPress大学
WordPress大学
The Cloudflare Blog
IT之家
IT之家
雷峰网
雷峰网
小众软件
小众软件
博客园 - 叶小钗
博客园 - 聂微东
爱范儿
爱范儿
博客园 - 司徒正美
博客园 - 三生石上(FineUI控件)
V
Visual Studio Blog
博客园 - 【当耐特】
V
V2EX
博客园_首页
T
Tailwind CSS Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
SOLID Principles Explained in a Solid Way
Aabhas Sao · 2026-05-15 · via DEV Community

Hello friend,

If you have read hundreds of articles and even watched a lot of videos but still confused about SOLID. Help me help you. You are in safe hands.

What are SOLID principles

SOLID principles help write maintainable, testable code. These principles were initially pointed out by Robert C. Martin a.k.a. "Uncle Bob". If you have not watched his lectures, I would highly suggest to go on YouTube and watch, those are pure fun and knowledge.

Now let's go over each of these principles. I will try to write examples that are more real in terms of software usage (no more Bike extending Vehicle class, no offense to anyone 😊).


Single Responsibility Principle

"A class should have one, and only one, reason to change."

❌ Bad Example: The "Do-It-All" Controller

This Spring controller handles HTTP routing, manual SQL execution, external API payments, and email alerts. If your database schema or your email provider changes, this class breaks.

@RestController
public class OrderController {
    @PostMapping("/orders")
    public ResponseEntity<String> createOrder(@RequestBody OrderRequest request) {
        // 1. Validation
        if (request.getItems().isEmpty()) return ResponseEntity.badRequest().body("No items");

        // 2. Direct Database Connection & SQL
        Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/db");

        // 3. Third-party Payment API HTTP call
        HttpClient.newHttpClient().send(paymentRequest, HttpResponse.BodyHandlers.ofString());

        // 4. Email Notification
        Transport.send(emailMessage);

        return ResponseEntity.ok("Order Processed");
    }
}

Enter fullscreen mode Exit fullscreen mode

✅ Good Example: Layered Architecture

@RestController
public class OrderController {
    @Autowired private OrderService orderService;

    @PostMapping("/orders")
    public ResponseEntity<Order> createOrder(@RequestBody OrderRequest request) {
        return ResponseEntity.ok(orderService.processOrder(request));
    }
}

@Service
public class OrderService {
    @Autowired private PaymentProcessor paymentProcessor;
    @Autowired private OrderRepository orderRepository;
    @Autowired private NotificationService notificationService;

    @Transactional
    public Order processOrder(OrderRequest request) {
        paymentProcessor.charge(request.getAmount());
        Order order = orderRepository.save(Order.from(request));
        notificationService.sendConfirmation(order);
        return order;
    }
}

Enter fullscreen mode Exit fullscreen mode

Now the controller handles response handling, business logic is offloaded to service class. Even in service class the database configuration is delegated to repository classes.


Open/Closed Principle

"Software entities should be open for extension, but closed for modification."

❌ Bad Example: The Infinite If-Else
Every time your security team introduces a new auth method (like OAuth or WebAuthn), you have to modify this core security filter, risking breaking changes to existing auth flows.

@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response) {
        String authType = request.getHeader("X-Auth-Type");

        if ("JWT".equals(authType)) {
            // Complex JWT Validation logic...
        } else if ("API_KEY".equals(authType)) {
            // Complex Database API Key validation...
        } else if ("BASIC".equals(authType)) {
            // Basic Auth logic...
        }
    }
}

Enter fullscreen mode Exit fullscreen mode

✅ Good Example: The Strategy Pattern
By abstracting authentication into a strategy interface, Spring automatically injects all implementations. Adding a new auth method means writing a new class, completely leaving the filter untouched.

public interface AuthStrategy {
    boolean supports(HttpServletRequest request);
    Authentication authenticate(HttpServletRequest request);
}

@Component
public class AuthenticationFilter extends OncePerRequestFilter {
    @Autowired private List<AuthStrategy> strategies; // Automatically injected by Spring

    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response) {
        strategies.stream()
            .filter(s -> s.supports(request))
            .findFirst()
            .ifPresent(s -> SecurityContextHolder.getContext().setAuthentication(s.authenticate(request)));
    }
}

// To add OAuth, just create this class. The Filter remains untouched!
@Component
public class OAuthStrategy implements AuthStrategy { ... }

Enter fullscreen mode Exit fullscreen mode

Spring automatically injects all AuthStrategy beans into the filter. Add a new auth method? Just create a new @Component that implements the interface. The filter never changes!


Liskov Substitution Principle

"Subclasses must be substitutable for their superclasses without breaking the application."

❌ Bad Example: Shoving Incompatible Behavior into a Subclass

ReadOnlyStorage inherits from FileStorage but throws unexpected runtime crashes when a consumer tries to use a perfectly valid parent method (write).

public class FileStorage {
    public byte[] read(String path) { return Files.readAllBytes(Paths.get(path)); }
    public void write(String path, byte[] data) { Files.write(Paths.get(path), data); }
}

public class ReadOnlyStorage extends FileStorage {
    @Override
    public void write(String path, byte[] data) {
        // ⚠️ CRASH! Violates LSP because it breaks the expected behavior of the base class
        throw new UnsupportedOperationException("Cannot write to a read-only bucket!"); 
    }
}

Enter fullscreen mode Exit fullscreen mode

✅ Good Example: Splitting Contracts

Segregate capabilities into a clear hierarchy so that the type system prevents consumers from attempting invalid actions.

public interface ReadableStorage {
    byte[] read(String path);
}

public interface WritableStorage extends ReadableStorage {
    void write(String path, byte[] data);
}

// Implements both read and write
public class S3Storage implements WritableStorage { ... }

// Only implements read, perfectly honoring its type contract
public class ReadOnlyBackupStorage implements ReadableStorage { ... }

Enter fullscreen mode Exit fullscreen mode

Now ReadOnlyStorage doesn't pretend to be something it's not. The type system prevents misuse.


Interface Segregation Principle

"Clients should not be forced to depend on interfaces they don't use."

❌ Bad Example: Fat interface:

A read-only public document viewer widget is forced to provide empty implementations or throw boilerplate exceptions for admin features it shouldn't even know exist.

public interface DocumentService {
    Document getDoc(String id);
    void deleteDoc(String id);
    byte[] exportToPdf(String id);
    List<AuditLog> getAuditTrail(String id);
}

public class PublicDocumentViewer implements DocumentService {
    @Override
    public Document getDoc(String id) { return database.find(id); }

    // Forced to implement methods it doesn't need just to compile
    @Override public void deleteDoc(String id) { throw new UnsupportedOperationException(); }
    @Override public byte[] exportToPdf(String id) { throw new UnsupportedOperationException(); }
    @Override public List<AuditLog> getAuditTrail(String id) { return Collections.emptyList(); }
}

Enter fullscreen mode Exit fullscreen mode

✅ Good Example: Role-Based Micro-Interfaces

Break the large interface into focused capabilities. Clients can pick and choose only what they actually require.

public interface DocumentReader { Document getDoc(String id); }
public interface DocumentExporter { byte[] exportToPdf(String id); }
public interface DocumentAuditor  { List<AuditLog> getAuditTrail(String id); }

// The viewer widget remains simple, clean, and safe
public class PublicDocumentViewer implements DocumentReader {
    @Override
    public Document getDoc(String id) { return database.find(id); }
}

// The admin panel implements multiple interfaces as needed
public class AdminDocumentManager implements DocumentReader, DocumentExporter, DocumentAuditor {
    // Implements all required methods cleanly
}

Enter fullscreen mode Exit fullscreen mode

Each class now depends only on the interfaces it actually uses!


Dependency Inversion Principle

"Depend on abstractions, not concretions."

❌ Bad Example: Hardcoded Concrete Implementations

The high-level NotificationService is tightly coupled to a concrete TwilioSmsClient. If you want to switch to AWS SNS or mock the SMS client for local unit testing, you are forced to rewrite this core service class.

import com.yourcompany.clients.TwilioSmsClient; // Concrete import

public class NotificationService {
    private TwilioSmsClient smsClient = new TwilioSmsClient(); // Hardcoded dependency

    public void sendAlert(String userId, String message) {
        smsClient.send(userId, message);
    }
}

Enter fullscreen mode Exit fullscreen mode

✅ Good Example: Injecting Abstractions

NotificationService depends entirely on an interface. It does not know or care who is sending the message under the hood, making it decoupled and testable.

public interface MessageSender {
    void send(String target, String body);
}

@Service
public class NotificationService {
    private final MessageSender messageSender;

    // Spring injects the interface bean automatically via the constructor
    public NotificationService(MessageSender messageSender) {
        this.messageSender = messageSender;
    }

    public void sendAlert(String userId, String message) {
        messageSender.send(userId, message);
    }
}

// The concrete implementation Spring will inject
@Component
public class TwilioSender implements MessageSender {
    @Override
    public void send(String target, String body) {
        twilioClient.messages.create(target, body);
    }
}

// Swapping to SNS later? Just create this — NotificationService is untouched
@Component
public class AwsSnsSender implements MessageSender {
    @Override
    public void send(String target, String body) {
        snsClient.publish(target, body);
    }
}

Enter fullscreen mode Exit fullscreen mode

Now NotificationService doesn't know or care about concrete implementations. You can:

  • Add new channels without modifying NotificationService
  • Mock channels easily for testing
  • Swap implementations at runtime
  • Configure channels via dependency injection

Key Takeaways

Principle In one line
Single Responsibility One class, one job
Open/Closed Add new features without disrupting old ones
Liskov Substitution Subclasses should work anywhere the parent class works. Don't break contracts
Interface Segregation Many small, focused interfaces beat one large interface
Dependency Inversion Depend on interfaces, not concrete classes. Use dependency injection

Why SOLID Matters

Following SOLID principles leads to:

  • Testable code: Easy to mock dependencies
  • Maintainable code: Changes are localized
  • Flexible code: Easy to extend without breaking existing functionality
  • Readable code: Clear responsibilities and dependencies

SideNote

All these rules are like trade offs. In software engineering rules are not strict but more dependent on specific trade offs for the task at hand.

E.g. Adding interfaces that have only single implementations, just for flexibility in future, I can skip it if I'm sure I won't be adding new implementations in near future. Premature optimization is evil.

Remember: SOLID isn't about being dogmatic. It's about writing code that's easier to change when requirements inevitably evolve. Start applying these principles gradually, and you'll see the benefits compound over time.

Happy coding! 🚀