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

推荐订阅源

H
Heimdal Security Blog
A
Arctic Wolf
K
Kaspersky official blog
V
Vulnerabilities – Threatpost
Threat Intelligence Blog | Flashpoint
Threat Intelligence Blog | Flashpoint
Simon Willison's Weblog
Simon Willison's Weblog
L
LINUX DO - 热门话题
MongoDB | Blog
MongoDB | Blog
T
Threat Research - Cisco Blogs
D
Docker
爱范儿
爱范儿
T
Tenable Blog
C
Check Point Blog
B
Blog
C
Cisco Blogs
Vercel News
Vercel News
The Cloudflare Blog
T
Threatpost
NISL@THU
NISL@THU
T
Tor Project blog
V2EX - 技术
V2EX - 技术
P
Palo Alto Networks Blog
Application and Cybersecurity Blog
Application and Cybersecurity Blog
T
Tailwind CSS Blog
G
GRAHAM CLULEY
P
Privacy & Cybersecurity Law Blog
SecWiki News
SecWiki News
博客园 - 司徒正美
S
Security @ Cisco Blogs
GbyAI
GbyAI
S
Secure Thoughts
Microsoft Security Blog
Microsoft Security Blog
The Register - Security
The Register - Security
Recorded Future
Recorded Future
Cloudbric
Cloudbric
Webroot Blog
Webroot Blog
N
News and Events Feed by Topic
Y
Y Combinator Blog
博客园_首页
T
Troy Hunt's Blog
The Hacker News
The Hacker News
雷峰网
雷峰网
Google DeepMind News
Google DeepMind News
U
Unit 42
AWS News Blog
AWS News Blog
PCI Perspectives
PCI Perspectives
V
Visual Studio Blog
博客园 - 聂微东
有赞技术团队
有赞技术团队
酷 壳 – CoolShell
酷 壳 – CoolShell

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
Refactoring Legacy Code: The Jedi Move of Extracting Pure Functions
Timevolt · 2026-06-18 · via DEV Community

The Quest Begins (The “Why”)

Picture this: I’m deep in a codebase that looks like the junkyard planet from Star Wars—tangled wires, rusted droids, and a mysterious hum coming from somewhere I can’t quite locate. My task? Add a simple discount rule to an e‑commerce checkout. Sounds easy, right?

I opened the file and found a 200‑line monster called calculateOrderTotal. Inside, there were nested if statements that checked user type, coupon validity, tax rules, and even a weird side‑effect that wrote to a global audit log. Changing one line felt like trying to replace a single tile in the Death Star’s trench while dodging laser fire. After three hours of stepping through the debugger, I realized the real problem wasn’t the discount logic—it was that the function was doing everything at once, mutating state, and hiding its intentions behind a wall of imperative code.

That moment hit me like Neo seeing the Matrix for the first time: if I could isolate the pure calculations, the rest would become trivial. I needed a lightsaber, not a sledgehammer.

The Revelation (The Insight)

The treasure I uncovered? Extracting pure functions—small, deterministic pieces that take inputs, return outputs, and never touch the outside world. A pure function is like a Jedi’s lightsaber swing: predictable, repeatable, and free of side‑effects. When you isolate the “what” (the calculation) from the “how” (state changes, I/O, logging), you gain:

  • Testability – you can call the function with any inputs and assert the output, no mocks needed.
  • Reasoning – you can look at the function in isolation and know exactly what it does.
  • Composability – you can plug pure functions together like LEGO bricks to build complex behavior.

In legacy code, the opposite is common: a function that reads a global config, writes to a file, updates a database, and returns a value all at once. Change one requirement, and you risk breaking three unrelated things. Pure functions eliminate that coupling.

Wielding the Power (Code & Examples)

Let’s look at a realistic before/after scenario. Imagine we’re working on a reporting module that calculates a user’s “engagement score” based on login frequency, post count, and reaction weight. The original function looks like this (the “trap” we want to avoid):

// BEFORE: a classic legacy monster
function calculateEngagementScore(userId) {
  // 1️⃣ fetch data – side effect!
  const user = db.getUserById(userId);
  const logs = db.getLoginLogs(userId);
  const posts = db.getPostsByUserId(userId);
  const reactions = db.getReactionsByUserId(userId);

  // 2️⃣ mutable state that we keep tweaking
  let score = 0;

  // 3️⃣ tangled logic with side effects
  if (user.isPremium) {
    score += 50; // arbitrary bonus
  }

  logs.forEach(log => {
    if (log.timestamp > Date.now() - 86400000) { // last 24h
      score += 10;
      // 🙈 side effect: we update a cache here!
      cache.set(`engagement:${userId}:today`, score);
    }
  });

  posts.forEach(post => {
    score += post.length * 0.1;
    // 🙈 another side effect: increment a counter
    metrics.increment('postsProcessed');
  });

  reactions.forEach(reaction => {
    score += reaction.weight * 2;
    // 🙈 yet another side effect: write to an audit table
    db.auditLog({ userId, action: 'reactionCounted', weight: reaction.weight });
  });

  // 4️⃣ final mutating step: clamp the score
  if (score > 1000) score = 1000;
  if (score < 0) score = 0;

  return score;
}

What’s wrong?

  • The function reaches out to the database, cache, metrics, and audit log—all side effects.
  • It mutates a local score variable in many places, making the flow hard to follow.
  • Testing it means spinning up a DB, mocking the cache, and verifying a dozen external calls.

Now, watch the transformation after we extract pure functions. The idea is simple: each distinct calculation gets its own pure helper. The main orchestrator becomes a thin pipeline that calls those helpers and then deals with side effects only at the edges.

// PURE: login bonus – depends only on logs
function loginBonus(logs) {
  const now = Date.now();
  return logs.reduce((acc, log) => {
    return log.timestamp > now - 86400000 ? acc + 10 : acc;
  }, 0);
}

// PURE: post score – depends only on posts
function postScore(posts) {
  return posts.reduce((acc, p) => acc + p.length * 0.1, 0);
}

// PURE: reaction score – depends only on reactions
function reactionScore(reactions) {
  return reactions.reduce((acc, r) => acc + r.weight * 2, 0);
}

// PURE: premium bonus – depends only on user flag
function premiumBonus(isPremium) {
  return isPremium ? 50 : 0;
}

// PURE: clamp score to [0, 1000]
function clampScore(value) {
  return Math.min(Math.max(value, 0), 1000);
}

// ORCHESTRATOR: still does the I/O, but the core logic is pure
function calculateEngagementScore(userId) {
  const user = db.getUserById(userId);
  const logs = db.getLoginLogs(userId);
  const posts = db.getPostsByUserId(userId);
  const reactions = db.getReactionsByUserId(userId);

  const rawScore =
    premiumBonus(user.isPremium) +
    loginBonus(logs) +
    postScore(posts) +
    reactionScore(reactions);

  return clampScore(rawScore);
}

Why this feels like a power‑up

  • Testing becomes a breeze: I can write unit tests for loginBonus, postScore, etc., with plain arrays—no DB, no mocks.
  • Documentation is self‑evident: the function names tell the story. If I need to tweak how logs contribute, I open loginBonus and see exactly the 10‑point per‑day rule.
  • Side effects are quarantined: the only places that touch the outside world are the four db.get… calls and the final return. If I ever need to swap the database for a service call, I change those four lines, not the scoring logic.

Common traps to avoid (the “dark side” pitfalls)

  1. Extracting but keeping side effects inside the helper – e.g., moving the cache.set into loginBonus. That defeats the purpose; you’ve just hidden the impurity.
  2. Over‑extracting to the point of nonsense – creating a pure function that adds two numbers when the gain is negligible. Keep the granularity meaningful: each helper should represent a distinct business rule.
  3. Forgetting to handle errors – if a db.get… can throw, wrap those calls, but don’t let the error‑handling leak into the pure functions. Keep error handling at the orchestrator level.

Why This New Power Matters

By embracing pure functions, I turned a terrifying, tightly‑coupled monolith into a set of small, trustworthy building blocks. The immediate payoff? I added the new discount rule in under fifteen minutes, wrote three focused unit tests, and deployed without a single regression bug. The team noticed: the file went from 200 lines to about 80, and the cyclomatic complexity dropped from 12 to 4.

More importantly, the mindset shift stuck. When I now see a function that reaches out to the world and mutates state, I automatically ask: “What part of this is just a calculation?” That question has become my go‑to refactoring trigger, and it’s saved me countless hours of debugging across projects.

Think of it like learning the Force in Star Wars: once you feel it, you can’t un‑feel it. You start seeing the hidden flows, the unnecessary side effects, and you know exactly where to apply a gentle push to restore balance.

Your Turn – Embark on Your Own Quest

I challenge you: pick one legacy function in your codebase that makes you sigh every time you open it. Identify the pure calculation hiding inside it, extract it into a small helper, and watch the rest of the code simplify.

What’s the first function you’ll refactor? Drop a comment below with a before/after snippet (or just the name of the function) and let’s celebrate each other’s victories. May your refactors be clean, your tests be green, and your bugs be as rare as a well‑placed Easter egg in a Marvel post‑credit scene. Happy coding!