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

推荐订阅源

aimingoo的专栏
aimingoo的专栏
人人都是产品经理
人人都是产品经理
M
MIT News - Artificial intelligence
C
Cybersecurity and Infrastructure Security Agency CISA
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
爱范儿
爱范儿
Spread Privacy
Spread Privacy
P
Palo Alto Networks Blog
Security Archives - TechRepublic
Security Archives - TechRepublic
T
The Blog of Author Tim Ferriss
The Cloudflare Blog
WordPress大学
WordPress大学
小众软件
小众软件
H
Help Net Security
cs.CV updates on arXiv.org
cs.CV updates on arXiv.org
Blog — PlanetScale
Blog — PlanetScale
V2EX - 技术
V2EX - 技术
H
Hacker News: Front Page
Last Week in AI
Last Week in AI
D
DataBreaches.Net
V
V2EX
S
Securelist
C
CXSECURITY Database RSS Feed - CXSecurity.com
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
T
Tenable Blog
Cloudbric
Cloudbric
月光博客
月光博客
Y
Y Combinator Blog
博客园 - 三生石上(FineUI控件)
N
News and Events Feed by Topic
K
Kaspersky official blog
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
S
Secure Thoughts
S
Security Affairs
W
WeLiveSecurity
cs.AI updates on arXiv.org
cs.AI updates on arXiv.org
The Last Watchdog
The Last Watchdog
AI
AI
有赞技术团队
有赞技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - 【当耐特】
罗磊的独立博客
Google DeepMind News
Google DeepMind News
Exploit-DB.com RSS Feed
Exploit-DB.com RSS Feed
N
Netflix TechBlog - Medium
PCI Perspectives
PCI Perspectives
SecWiki News
SecWiki News
IT之家
IT之家
Microsoft Azure Blog
Microsoft Azure Blog
V
Visual Studio 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 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
The Rule Pattern: When Facts Meet Rules
Hamid Akhtarshenas · 2026-06-16 · via DEV Community

1. The Pain Came First

Everyone knows this. You open a class and there it is: the if-else chain. Twenty branches. Thirty. Some with comments like // TODO: refactor from 2019. You know you shouldn't touch anything — side effects, unknown dependencies, missing tests. So you add your case. At the bottom. After the last else.

And you go home with that bad feeling that you've become part of the problem.


2. My First Attempt — And Why It Didn't Make Me Happy

Eventually, I'd had enough. I refactored the if-else chain using an enum pattern:

enum OrderEvent {
    PAY("pay", () -> null),
    SHIP("ship", () -> null);

    final String event;
    final OrderValidator validator;

    OrderEvent(String event, OrderValidator validator) {
      this.event = event;
      this.validator = validator;
    }

    public String getEvent() { return event; }
    public OrderValidator getValidator() { return validator; }


    static OrderEvent fromEvent(String event) {
      for (OrderEvent e : values()) {
          if (e.event.equals(event)) return e;
      }
      throw new IllegalArgumentException("Unknown event: " + event);
    }

}

It worked. But it felt wrong. Too much ceremony. Too much boilerplate for helper methods — getting enum values, setting them, comparing them. An ugly imperative language for something that should be declarative.


3. The Realization

Then I understood what I actually wanted: facts and rules. A world where I can say:

"If this condition matches these facts — then do that."

No object hiding behavior. No inheritance hierarchy. No enum tricks. Just one truth: rules check facts. A driver iterates. Done.

This idea has deep roots — Logic Programming languages like Prolog have been built on exactly this foundation for decades: facts, rules, and an inference engine that iterates. But translating that clarity into idiomatic Java — without a framework, without a new language, just records, lambdas, and a stream — that is what this pattern is about.


4. The Pattern

// Facts — everything the driver needs to know
// globalCtxt can hold environment data, e.g., the ApplicationContext in Spring
record OrderFacts(String orderId, String event, Object globalCtxt) {}

// A rule: condition + action
record Rule(
    Predicate<OrderFacts> condition,
    Function<OrderFacts, OrderResult> action
) {}

// The rule chain
List<Rule> rules = List.of(
    // Rule: "PAY" event → PaidOrder
    new Rule(
        facts -> facts.event().equals("PAY"),
        facts -> new PaidOrder(facts.orderId())
    ),
    // Rule: "SHIP" event → ShippedOrder
    new Rule(
        facts -> facts.event().equals("SHIP"),
        facts -> new ShippedOrder(facts.orderId())
    )
);

// The driver — stateless, blind, simple
OrderResult resolve(OrderFacts facts) {
    return rules.stream()
        .filter(rule -> rule.condition().test(facts))
        .findFirst()
        .map(rule -> rule.action().apply(facts))
        .orElseGet(() -> new UnknownOrder(facts.orderId()));
}

That's all. No switch. No enum. No inheritance. Just records, lambdas, and a stream.

The order of rules in the list is intentional — findFirst() returns the first match. More specific rules go first, catch-all rules go last. This is not an implementation detail; it is part of the design.

stream().filter().findFirst() is O(n). For typical rule lists this is irrelevant. At scale — hundreds of rules on a hot path — consider grouping rules by a fast discriminator key first.


5. Testability — An Underestimated Advantage

With if-else or switch, you always test the entire block. A change in one case can affect all others. With the Rule Pattern, each rule is an independent unit — testable in isolation, without the driver, without context.

// Test a rule in isolation
Rule payRule = new Rule(
    facts -> facts.event().equals("PAY"),
    facts -> new PaidOrder(facts.orderId())
);

assertTrue(payRule.condition().test(new OrderFacts("123", "PAY", null)));
assertFalse(payRule.condition().test(new OrderFacts("123", "SHIP", null)));

// Test the driver in isolation — with arbitrary rules
List<Rule> rules = List.of(payRule);
OrderResult result = resolve(new OrderFacts("123", "PAY", null));
assertInstanceOf(PaidOrder.class, result);

Add a new rule, existing tests stay green — by construction. This isn't a coincidence. It's a direct consequence of the structure: rules are data, not hidden logic inside a class.


6. Isolation — The Golden Value

Every rule is an isolated module containing all the logic it needs.
The driver doesn't care what happens inside. It just calls the rule.

This isolation is pure gold:

  • Test each rule alone
  • Change one rule without touching others
  • Handle exceptions locally
  • Keep DB and transaction logic visible
  • Add new rules without risk

No hidden dependencies. No unexpected side effects. Just isolated, honest modules.


7. What the Pattern Replaces

Each GoF pattern solves a real problem — but each brings a cost: an interface to define, classes to implement, a wiring mechanism to maintain. The Rule Pattern collapses all three into one record and a lambda.

No hierarchy. No registration. No casting. Just a condition and an action.

When I saw the pattern in front of me, I realized: many classic GoF patterns are just special cases of this single idea.

Classic Pattern Rule Pattern Implementation
Strategy One rule, one factory
Chain of Responsibility The entire rule list
Observer Predicate<T> + List<Consumer<U>>
Command A rule that executes exactly one command
State Machine Rules + records with invariants

The difference is not what they do — it's what they cost.


8. State Machines — The Interesting Case

State machines are the hardest test for any pattern. My solution: Rule Pattern navigates, records enforce.

This first example shows a hybrid approach: sealed defines the structure and enforces invariants at compile time — the Rule Pattern handles the navigation.

Section 10 shows what happens when you drop the sealed interface entirely.

sealed interface OrderState permits NewOrder, ActiveOrder, CancelledOrder {}

record NewOrder(Order order) implements OrderState {
    public ActiveOrder activate() {
        return new ActiveOrder(order, LocalDateTime.now());
    }
    public CancelledOrder cancel() {
        return new CancelledOrder(order, LocalDateTime.now(), "before activation");
    }
}

record ActiveOrder(Order order, LocalDateTime activatedAt) implements OrderState {
    public CancelledOrder cancel() {
        return new CancelledOrder(order, LocalDateTime.now(), "after activation");
    }
    // activate() does not exist here — an impossible transition is simply absent
}

record CancelledOrder(Order order, LocalDateTime cancelledAt, String reason) implements OrderState {
    // no methods — end of the line
}

The record enforces the invariant structurally — cancelledAt is always set, always valid. No null. No invalid state possible.

The Rule Pattern handles navigation:

record OrderFacts(OrderState state, String event) {}

record OrderRule(
    Predicate<OrderFacts> condition,
    Function<OrderFacts, OrderState> action
) {}

List<OrderRule> rules = List.of(
    new OrderRule(
        facts -> facts.state() instanceof NewOrder && facts.event().equals("ACTIVATE"),
        facts -> ((NewOrder) facts.state()).activate()
    ),
    new OrderRule(
        facts -> facts.state() instanceof NewOrder && facts.event().equals("CANCEL"),
        facts -> ((NewOrder) facts.state()).cancel()
    ),
    new OrderRule(
        facts -> facts.state() instanceof ActiveOrder && facts.event().equals("CANCEL"),
        facts -> ((ActiveOrder) facts.state()).cancel()
    )
);

OrderState next = rules.stream()
    .filter(r -> r.condition().test(facts))
    .findFirst()
    .map(r -> r.action().apply(facts))
    .orElse(facts.state());

Two clear responsibilities:

  • Which transition is allowed? → Rule Pattern
  • What happens during the transition? → Record with its methods and invariants

9. Observer — Even More Elegant

record ObserverRule<T, U>(
    Predicate<T> condition,
    List<Consumer<U>> actions
) {}

List<ObserverRule<Event, Payload>> rules = List.of(
    new ObserverRule<>(
        event -> event.type().equals("ORDER_PLACED"),
        List.of(
            payload -> notificationService.send(payload),
            payload -> inventoryService.reserve(payload),
            payload -> auditLog.record(payload)
        )
    )
);

// Driver — with flatMap
void notify(Event event, Payload payload) {
    rules.stream()
        .filter(rule -> rule.condition().test(event))
        .flatMap(rule -> rule.actions().stream())
        .forEach(action -> action.accept(payload));
}

One event, one or more matching rules, each with its own list of actions. Adding a new subscriber = one new rule or one new line in an existing rule's action list. No interface, no addListener(), no casting.


10. Comparison: DOP vs. Rule Pattern — Same Domain, Two Approaches

There's a lot of well-deserved discussion about Data-Oriented Programming (DOP) in the Java community right now. Sealed types and pattern matching are making Java incredibly expressive. Let's see what happens when we take this idea of data separation to its logical conclusion — and even drop the sealed interface.

The Classic DOP Approach (Safety Through Structure)

DOP leverages compiler safety:

sealed interface OrderState permits NewOrder, ActiveOrder, CancelledOrder {}

This is fantastic when your domain is closed and the states are absolutely finite. The compiler warns you when you forget a case in a switch. That's a real safety net. But it comes at a price: the switch block must know every state and every method by name. When a new state arrives, we have to modify the switch block.

DOP — sealed types + pattern matching:

sealed interface OrderState permits NewOrder, ActiveOrder, CancelledOrder {}

record NewOrder(Order order) implements OrderState {}
record ActiveOrder(Order order, LocalDateTime activatedAt) implements OrderState {}
record CancelledOrder(Order order, LocalDateTime cancelledAt) implements OrderState {}

OrderState process(OrderState state, String event) {
    return switch (state) {
        case NewOrder n when event.equals("ACTIVATE") ->
            new ActiveOrder(n.order(), LocalDateTime.now());
        case NewOrder n when event.equals("CANCEL") ->
            new CancelledOrder(n.order(), LocalDateTime.now());
        case ActiveOrder a when event.equals("CANCEL") ->
            new CancelledOrder(a.order(), LocalDateTime.now());
        default -> state;
    };
}

Clean. Compiler-exhaustive. If you forget a case, you get a warning.

The Rule Pattern Without Sealed Interface (The Freedom of Data):

What happens when we completely decouple the records and treat the state as a universal Object?

record NewOrder(Order order) {
    public ActiveOrder activate() { return new ActiveOrder(order, LocalDateTime.now()); }
    public CancelledOrder cancel() { return new CancelledOrder(order, LocalDateTime.now()); }
}
record ActiveOrder(Order order, LocalDateTime activatedAt) {
    public CancelledOrder cancel() { return new CancelledOrder(order, LocalDateTime.now()); }
}
record CancelledOrder(Order order, LocalDateTime cancelledAt) {}

record OrderFacts(Object state, String event) {}

record FailedOrder(OrderFacts facts, Exception cause) {}

record OrderRule(
    Predicate<OrderFacts> condition,
    Function<OrderFacts, Object> action // intentionally untyped — see below
) {}

List<OrderRule> rules = List.of(
    new OrderRule(
        f -> f.state() instanceof NewOrder && f.event().equals("ACTIVATE"),
        f -> {
            try {
                return ((NewOrder) f.state()).activate();
            } catch (Exception e) { // Same exception handling can be applied to any rule
                return new FailedOrder(f,e); 
            }
        }
    ),
    new OrderRule(
        f -> f.state() instanceof NewOrder && f.event().equals("CANCEL"),
        f -> ((NewOrder) f.state()).cancel()
    ),
    new OrderRule(
        f -> f.state() instanceof ActiveOrder && f.event().equals("CANCEL"),
        f -> ((ActiveOrder) f.state()).cancel()
    )
);

Object next = rules.stream()
    .filter(r -> r.condition().test(facts))
    .findFirst()
    .map(r -> r.action().apply(facts))
    .orElse(facts.state());

The return type is deliberately Object. This is the trade-off: we gain full openness — no interface, no hierarchy — and we lose compile-time type safety on the result. A clear default case and tests compensate for that.

What is the real difference?

Even when we optimize the DOP example and move the logic into the records (so that the case only calls n.activate()), one fundamental problem remains: the switch block must know every method and every state by name. It is hard-wired.

When a new state like InReturn with a returnOrder() method arrives tomorrow, the compiler's exhaustiveness check fails. We have no choice — the switch block must be extended.

With the Rule Pattern, however, the driver is completely ignorant. It's just an assembly line worker. For the new state, we simply add a new, isolated rule to the list. Neither the driver nor the existing rules need to be touched. That's the pure essence of KISS: extending by simply adding data, without endangering existing code.

Feature DOP (sealed + pattern matching) Rule Pattern (without interface)
Focus Maximum compile-time safety Maximum extensibility
Artificial hierarchy Yes (implements OrderState required) No (completely free records)
Code coupling High (switch must know every type) Null (driver sees only Object)
Compile-time exhaustiveness ✓ Compiler warns about missing cases ✗ Only at runtime
New rule / state Open switch, add new case One line in the list
Load rules from configuration Not possible Possible
Complex conditions Switch becomes messy Predicate arbitrarily composable
Exception handling Centralized (switch catches all) Isolated per rule (each rule can handle differently)

11. Counterarguments — And My Honest Answers

"This isn't readable."

Readability is a matter of habit. Anyone who works with streams and records will quickly feel comfortable with this.

"No compile-time exhaustiveness — you only notice missing cases at runtime."

True. That's the conscious trade-off: I exchange compile-time safety for openness and simplicity. A good default case and tests compensate for this.

"What about frameworks — Spring, Hibernate?"

At the boundaries, I build adapters. The core of my application doesn't depend on heavy frameworks – that makes it easier to test, reason about, and change. The Rule Pattern describes the domain logic; it doesn't know anything about Spring. You can keep it as a property in a service and let the DI framework inject whatever is needed. That keeps the pattern pure and the integration clean.

If a rule genuinely needs framework services, pass them explicitly through the facts record as a typed context — not as Object globalCtxt, but as a dedicated record:

record RuleContext(EmailService email, OrderRepository repo) {}
record OrderFacts(OrderState state, String event, RuleContext ctx) {}

The Spring @Service builds the RuleContext and passes it in. The domain layer has no Spring annotations — rules stay testable with new RuleContext(mockEmail, mockRepo). Everything flows through facts.

"But invariants? Your entities aren't safe anymore!"

My states are records — immutable by default. Each state handles its own invariants. That's even cleaner than classic OOP.

"What about performance"

No proxies. No bytecode weaving. No reflection at runtime. A rule is a plain record — two function references, nothing more. The driver is a stream call. That is as close to raw Java as it gets.


12. Conclusion

The Rule Pattern is not a revolution. It's a quiet extension — three simple ideas:

  • Record → Facts are structure, invariants built-in
  • Rule → Condition + result, declarative
  • Driver → Stateless, blind, only iterates

Perhaps we don't need less OOP in Java. But sometimes, records, functional interfaces, and one simple idea are enough — rules that meet facts.

I'm still looking for real counterarguments. If you see something I've missed — tell me. Really. I don't want to be right. I want to know if this pattern delivers what it promises.

Or whether we in the Java world have sometimes simply forgotten how elegant and maintainable software can be when we stop thinking in rigid hierarchies and start treating logic as what it really is: rules that meet facts.