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

推荐订阅源

K
Kaspersky official blog
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
AI
AI
SecWiki News
SecWiki News
宝玉的分享
宝玉的分享
Scott Helme
Scott Helme
D
Darknet – Hacking Tools, Hacker News & Cyber Security
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
Engineering at Meta
Engineering at Meta
博客园 - 叶小钗
The GitHub Blog
The GitHub Blog
Microsoft Azure Blog
Microsoft Azure Blog
N
News and Events Feed by Topic
Cloudbric
Cloudbric
B
Blog
Cisco Talos Blog
Cisco Talos Blog
V
Vulnerabilities – Threatpost
N
News and Events Feed by Topic
V
Visual Studio Blog
A
Arctic Wolf
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
U
Unit 42
S
Security @ Cisco Blogs
博客园 - 聂微东
T
Threat Research - Cisco Blogs
OSCHINA 社区最新新闻
OSCHINA 社区最新新闻
Apple Machine Learning Research
Apple Machine Learning Research
Y
Y Combinator Blog
G
GRAHAM CLULEY
L
LINUX DO - 热门话题
量子位
NISL@THU
NISL@THU
Webroot Blog
Webroot Blog
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
T
Troy Hunt's Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tenable Blog
月光博客
月光博客
S
Security Affairs
K
KPMG report finds enterprise disconnect between AI and its ROI | CIO
The Hacker News
The Hacker News
Spread Privacy
Spread Privacy
D
Docker
www.infosecurity-magazine.com
www.infosecurity-magazine.com
雷峰网
雷峰网
博客园 - 司徒正美
T
The Exploit Database - CXSecurity.com
Hugging Face - Blog
Hugging Face - Blog
Help Net Security
Help Net Security
D
DataBreaches.Net

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 Common SOC 2 Failures (Real World) Stop Vibe-Checking Your AI App: A Practical Guide to Evals How to Use SonarQube and SonarScanner Locally to Level Up Your Code Quality Your Next To-Do App Is Dead — I Replaced Mine with an OpenClaw AI Sign a Nostr event in 60 lines of Python using coincurve — no nostr-sdk, no nbxplorer, no rust toolchain ITGC Audit Explained Like You’re in Big 4 Patch Tuesday abril 2026: Microsoft parcha 163 vulnerabilidades y un zero-day en SharePoint Stop scraping everything: a better way to track competitor price changes Listing on MCPize + the Official MCP Registry while routing payments OUTSIDE the marketplace — how I kept 100% of my x402 revenue Building an AI-Powered Risk Intelligence System Using Serverless Architecture Why We Ripped Function Overloading Out of Our AI Toolchain Testing AI-Generated Code: How to Actually Know If It Works SaaS Churn Is Killing Your Business. Here Is What to Do About It (Without a Support Team) The Speed of AI Is No Longer Linear - And Self-Improving Models Are Why How to Implement RBAC for MCP Tools: A Practical Guide for Engineering Teams From Standard Quote to Persuasive Proposal: AI Automation for Arborists I built a CLI that scaffolds complete multi-tenant SaaS apps Axios CVE-2025–62718: The Silent SSRF Bug That Could Be Hiding in Your Node.js App Right Now The dashboard that ended our friendship Data Pipelines Explained Simply (and How to Build Them with Python) The Hidden Cost of AI Systems Nobody Talks About. undefined vs undeclared, and how typeof behaves Switching from file-based jobs to NATS/Kafka in Rust without changing code io_uring Adventures: Rust Servers That Love Syscalls Why Agentic AI is Killing the Traditional Database The POUR principles of web accessibility for developers and designers Quantum Neural Network 3D — A Deep Dive into Interactive WebGL Visualization How To Install Caveman In Codex On macOS And Windows Automation Pipeline Reliability: Why Your Workflow Breaks When Nobody Is Watching I Built an 'Open World' AI Coding Agent — It Works From ANY Folder From Freelancing to Product: A Tech Service Company's SaaS Transformation China's AI Giants: Adding Tencent Hunyuan & ByteDance Doubao to AI University (74 Providers) On the Vibe Coders and Their Lies clerk: Auto-Summarize Your Claude Code Sessions AI Weekly — 2026/04/10–04/17 | The Model Lockdown Is Here, but the Toolchain Is the Real Battleground AI 週報 — 2026/04/10–2026/04/17 模型封鎖潮來了,但工具鏈才是真戰場 Maybe this is how Open-Source apps are born... 🚀 Fine-Tune LLMs with LoRA and QLoRA: 2026 Guide tRPC v11 + Next.js App Router: End-to-End Type Safety Without the Boilerplate ShadCN UI in 2026: Why I Stopped Installing Component Libraries and Started Owning My Components SaaS Billing in React Server Components: Stripe + Supabase Without a Single `useEffect` Join our DEV Weekend Challenge — $1,000 in Prizes Across TEN winners! Submissions Due April 20 at 6:59 AM UTC. Implementing FSRS Spaced Repetition in Flutter + Supabase — Adding Memory Science to an AI Learning App "I Texted My Localhost From the Train — Claude Code Fixed the Bug Before I Got Home" I Built a Sales Prep AI and It Went Deeper Than Expected Design to Code #2: One JSON, Eleven Outputs Solving the 100M-Row Problem: A Summary Table Pattern for High-Volume Push Notification Logs Flutter Web With Wasm: What Actually Changes For Developers I Built 50 Royalty-Free Soundtracks for My Side Project in a Weekend Using AI Music Generation The Vibe Coding Security Checklist: 7 Things to Check Before You Ship Stop Letting Googlebot Guess Fix Your React App's SEO Right Desconstruindo o Streaming do LinkedIn: Como Criar um Engine de Extração de Vídeo de Alta Performance com HLS e FFmpeg (EDA Part-1) EDA (Exploratory Data Analysis) Explained With Real Life — Why Looking at Your Data Is the Most Important Step in Machine Learning Brand Relationship Management at Scale: Our 4-Touch Outreach System for 200+ Brands Why String.fromEnvironment() Might Return an Empty String in Dart JGuardrails 1.0.0 — Hardening Java LLM Apps Against Jailbreaks, Toxicity, and Prompt Injection Plan and Schedule a Full Week of Threads Content From One Claude Conversation Coding Cat Oran Ep3, Five Tables Changed Everything Updated: BFF Pattern I'm done watching freelancers get buried by 200 proposals. So I'm building the alternative. This is my first post BFS Algorithm in Java Step by Step Tutorial with Examples Tracking LLM Pricing Monthly: An Open Dataset for 22 AI Models How We Measure Content ROI on a Comparison Site: Revenue Attribution Without Perfect Data Introducing Nova AI Ops: The AI-Native Operating System for SRE Teams I built a free desktop video downloader for Windows — Grabbit How Talkie OCR Helps Vision-Impaired & Dyslexic Users Read the World Around Them VRCFaceTracking安装和iPhone面捕配置教程,有bug Even CrowdStrike Can't See Your Agents The Automation Gold Rush: What n8n Workflows and Claude Are Opening Up for Developers Right Now
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! 🚀