<?xml version="1.0" encoding="utf-8"?><feed xmlns="http://www.w3.org/2005/Atom" ><generator uri="https://jekyllrb.com/" version="3.10.0">Jekyll</generator><link href="https://blog.liorp.dev/feed.xml" rel="self" type="application/atom+xml" /><link href="https://blog.liorp.dev/" rel="alternate" type="text/html" /><updated>2026-10-13T18:25:24+03:00</updated><id>https://blog.liorp.dev/feed.xml</id><title type="html">liorp@blog:~$</title><subtitle>Fullstack developer. Python, JS, React, Django. Math &amp; physics enthusiast.</subtitle><author><name>liorp</name></author><entry><title type="html">Always Be Cooking</title><link href="https://blog.liorp.dev/blog/essays/ai/always-be-cooking/" rel="alternate" type="text/html" title="Always Be Cooking" /><published>2026-04-26T10:00:00+03:00</published><updated>2026-04-26T10:00:00+03:00</updated><id>https://blog.liorp.dev/blog/essays/ai/always-be-cooking</id><content type="html" xml:base="https://blog.liorp.dev/blog/essays/ai/always-be-cooking/"><![CDATA[<h2 id="the-warmth-of-a-working-kitchen">The Warmth of a Working Kitchen</h2>

<p>There’s a thing that happens in a home kitchen around seven thirty pm that I think about constantly. You’ve got rice going on one burner, something caramelizing in a pan on another, and you’re chopping herbs for a third thing that doesn’t exist yet but will in twenty minutes. The whole kitchen is warm. You’re not rushing, you’re not stressed, you’re just… in it, totally immersed into that exact moment, moving between all of the stations - tasting, adjusting, mixing… everything is alive at once.</p>

<p>That feeling, that specific warmth of having multiple things in motion, all at different stages of becoming, is what I’ve been chasing in my work for the past year. I started calling it ABC - Always Be Cooking ©️.</p>

<p>It’s not a productivity system. I need to say that upfront, because the internet has poisoned the word “system” for me. It’s closer to a disposition, a way of relating to your own creative energy.</p>

<h2 id="the-cold-kitchen-problem">The Cold Kitchen Problem</h2>

<p>Here’s what I noticed about myself before ABC: I would work intensely on one thing for weeks, ship it, and then go completely dark. Not intentionally, but I’d just cool down. “The kitchen” would go empty.<br />
And every time I tried to start something new after one of those cold stretches, it felt like lighting a wet match. Sure, starter boilerplates are great, but yet some of my best ideas died in that gap, not because they were bad, but because I let the stove go cold and couldn’t face turning it back on. Sort of a momentum, as you may call it, died there.</p>

<p>I think a lot of builders know this feeling but don’t name it. We talk about burnout, procrastination, imposter syndrome. But sometimes the real problem is simpler and more physical than any of those: your creative engine is just cold, you haven’t made anything in weeks, your hands forgot what it feels like to be mid-creation. And the longer you stay cold, the harder it is to warm back up.</p>

<h2 id="keep-something-cooking">Keep Something Cooking</h2>

<p>ABC is my answer to that. Keep something cooking, always. Not ten things, not a frantic hustle kitchen with flames shooting everywhere. Just don’t let every burner go dark at the same time. Have a project that’s almost done, have one that’s a messy prototype, have an idea you’re lazily researching in the background with no pressure. The specific number doesn’t matter. What matters is that when you sit down tomorrow morning, something, however small or mighty it might be, is already warm.</p>

<h2 id="agents-are-the-flame">Agents Are the Flame</h2>

<p>Now, the part that makes this possible in a way it wasn’t a few years ago: AI agents changed what “keeping the kitchen warm” actually means.</p>

<p>Before agents, running things in parallel meant you personally had to context-switch between them, which is exhausting and produces mediocre work. The overhead of keeping multiple pots going was real and brutal. Most people correctly chose to focus on one thing at a time, because the alternative was spreading yourself too thin.</p>

<p>Agents dissolve that tradeoff. They’re not assistants you delegate to. They’re more like a low flame you can leave running under a pot overnight. While I’m deep in one project, agents are doing the unglamorous middle work on others: research, drafts, tests, iteration. Not autonomously shipping things. Nothing goes out without my hands on it. But they keep things from going cold.</p>

<p>The best analogy I have: agents are the warmth in the kitchen, not the chef. I’m still the one who decides what’s on the menu, who tastes everything, who says “this isn’t ready” or “kill this dish entirely.” They do the stirring that keeps the sauce from breaking, the basting that keeps the roast from drying out, the quiet maintenance work that keeps a dish alive between the moments I’m actually standing over it. You see, a chef without warmth is still a chef. Warmth without a chef is just a fire hazard. So  actually I haven’t started from zero in months - there’s always something warm to pick up.</p>

<hr />

<p>I think the reason this matters, beyond just getting more done, is psychological. When you’re always mid-creation, your relationship to ideas changes. New ideas don’t feel threatening, because there’s always an open burner. Shipping doesn’t feel precious, because another dish is right behind it. Even failure feels different. A dish that doesn’t work out just becomes compost for the next one. You stop white-knuckling every project, because your identity isn’t riding on any single thing.</p>

<p>There’s a specific kind of confidence that comes from this. Not the loud, performative kind. More like the quiet steadiness of someone who knows their kitchen is warm and there’s always something to work with. I’ve started making better decisions since adopting this mindset, not because I’m smarter, but because I’m less desperate, and have way more breadth than before. Nothing is do-or-die when you have six other things simmering.</p>

<h2 id="the-warm-prison">The Warm Prison</h2>

<p>I want to be careful not to oversell this. ABC won’t save you if you’re building the wrong things, it won’t replace taste or judgment or the willingness to kill your darlings. And there’s a real risk of using “always be cooking” as a cope for never finishing anything. If everything is perpetually simmering and nothing ever plates, you’ve just built yourself a warm prison (albeit a really cozy one!).</p>

<p>The discipline of ABC is knowing when to plate, knowing which dish is ready even if it’s imperfect, shipping the thing that’s 85% there while keeping the others warm. Not hiding behind busyness as a substitute for the vulnerability of putting something real into the world.</p>

<hr />

<p>But with that caveat: the single biggest unlock of my last year has been to keep my kitchen warm, not letting the fire die, always to have something cooking. It sounds almost stupidly simple when I write it out.</p>

<p>Maybe that’s all good creative advice ever is. Someone giving you permission to do the obvious thing you already knew but hadn’t named yet.</p>

<p>And so, at last - the stove is right there. Turn it on.</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="essays" /><category term="ai" /><category term="ai" /><category term="agents" /><category term="creativity" /><category term="productivity" /><category term="claude" /><summary type="html"><![CDATA[On keeping the creative kitchen warm, why starting from zero is so brutal, and how AI agents changed what parallel work actually means.]]></summary></entry><entry><title type="html">Teaching AI Your Codebase: From Sub-Agents to Skills</title><link href="https://blog.liorp.dev/blog/software-engineering/ai/from-subagents-to-skills/" rel="alternate" type="text/html" title="Teaching AI Your Codebase: From Sub-Agents to Skills" /><published>2026-01-08T09:00:00+02:00</published><updated>2026-01-08T09:00:00+02:00</updated><id>https://blog.liorp.dev/blog/software-engineering/ai/from-subagents-to-skills</id><content type="html" xml:base="https://blog.liorp.dev/blog/software-engineering/ai/from-subagents-to-skills/"><![CDATA[<p>AI coding assistants will happily write React components, design APIs, and refactor legacy code. They’re remarkably good at it. But if you ask Claude to build the same feature twice, you’ll likely get two completely different implementations, each valid on its own terms, neither matching how your team actually writes code.</p>

<p>Every engineering team accumulates conventions over time. How you structure data fetching, where types live, the naming patterns for hooks, whether you reach for Tailwind or SCSS modules. These decisions exist in the codebase itself, absorbed through months of code review and hallway conversations. Documentation captures some of it, but never enough.</p>

<p>AI assistants don’t have access to any of that context. They start fresh every session, unaware that your team prefers Container/Presentation patterns or that all API responses should pass through Zod schemas before reaching components. The code they produce compiles and runs, but it feels foreign in your codebase.</p>

<p>Our frontend had grown complex over time. React Query for server state, a component library wrapping Ant Design, routing with protected routes and feature flags, internationalization across 18 locales. New developers needed weeks to internalize the patterns. AI assistants never internalized them at all.</p>

<p>We wanted to change that. What follows is how we tried, what broke, and what eventually worked.</p>

<hr />

<h2 id="the-sub-agent-era">The Sub-Agent Era</h2>

<p>Our first attempt was to create specialized “agents” for different parts of the frontend. I should demystify the term immediately: an agent was just a markdown file. Nothing more. Each file contained rules, templates, and checklists for one slice of the codebase, written in plain English.</p>

<p>The data agent described how to structure API calls, when to use React Query versus local state, how to define TypeScript types that distinguish backend responses from frontend models, and the file structure expected in each feature’s data folder. The pages agent covered our Container/Presentation split. The components agent documented how we wrap Ant Design primitives and our prop naming conventions. We had agents for SCSS patterns, for custom hooks, for route constants, for i18n across 18 locales, for TypeScript strictness.</p>

<p>An orchestrator file attempted to tie these together, describing when each agent applied. Working on API calls? Consult the data agent. Building a new page? Start with pages, then components, then translations.</p>

<p>The content in these files was hard-won. The templates came from patterns we’d refined through hundreds of pull requests. The rules encoded real mistakes.</p>

<p>The trouble was everything that happened around that.</p>

<hr />

<h2 id="where-it-broke-down">Where It Broke Down</h2>

<p>The agent approach forced an artificial separation that doesn’t match how frontend development actually works. A competent developer doesn’t context-switch between “data mode” and “styling mode” and “component mode.” They hold all of it in their head simultaneously, because the layers inform each other. The shape of your API response influences your component props. Your component structure affects your styling approach.</p>

<p>Siloing Claude into separate agents broke that natural flow. You’d build a data layer with the data agent, then move to components, then realize the data structure needed adjustment. But now you’re in “component mode” and the data expertise is gone. Going back meant manually re-invoking the data agent, re-establishing context, explaining what changed and why.</p>

<p>Worse, Claude often wouldn’t invoke the right agent at all. You’d ask it to fix a styling issue and it would just… try to fix it, without the styling agent’s knowledge of our SCSS conventions and design tokens. The agent files existed, but while working on small items or when refining an ongoing feature, Claude used to ignore them.</p>

<p>Course-correction became painful. If Claude went down a wrong path three steps into a feature, unwinding required you to figure out which agent’s expertise was missing and manually inject it. The orchestration burden sat entirely on the user, which defeated much of the purpose.</p>

<hr />

<h2 id="the-shift-to-skills">The Shift to Skills</h2>

<p>The content of our agent files wasn’t the problem. The orchestration model was. We needed Claude to apply the right expertise automatically, without us having to remember and invoke it.</p>

<p>Skills are still just markdown files. The structural change is small but significant: each file now includes frontmatter that describes when it should apply. The data skill specifies that it’s relevant when working on API calls, React Query hooks, types, mutations, or files in a feature’s data folder. The styles skill triggers on SCSS, design tokens, and styling concerns. The types skill activates whenever TypeScript strictness matters.</p>

<p>The actual improvement came from Claude’s side. Skills are more lightweight than the old approach of spawning sub-agents. They’re loaded just-in-time, as the task requires them, rather than establishing a separate agent context upfront. In practice, this performs substantially better. When you ask Claude to do something that matches a skill’s purpose, it applies automatically. You don’t invoke it. You don’t coordinate an orchestrator. You ask Claude to fix a styling bug, and the styling expertise is simply there.</p>

<p>This changes how multi-domain work flows. Building a feature that touches data, components, pages, and translations no longer requires you to sequence agent invocations. Claude pulls in the relevant skills as the work demands them. When you hit a styling issue while working on a component, the styling knowledge is available without you switching contexts. When the component work reveals a problem in the data layer, that expertise surfaces too.</p>

<p>The files still contain the same hard-won templates and rules. What changed is how they reach Claude.</p>

<hr />

<h2 id="how-it-works-in-practice">How It Works In Practice</h2>

<p><a href="https://code.claude.com/docs/en/skills">A skill file</a> starts with YAML frontmatter that describes its purpose and when it applies:</p>

<div class="language-yaml highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nn">---</span>
<span class="na">name</span><span class="pi">:</span> <span class="s">data-layer</span>
<span class="na">description</span><span class="pi">:</span> <span class="s">Use when working with API calls, React Query hooks,</span>
  <span class="s">mutations, type definitions, or files in a feature's data folder.</span>
<span class="nn">---</span>

<span class="c1"># Data Layer Patterns</span>

<span class="c1">## Query Hook Structure</span>
<span class="s">...templates and rules follow...</span>
</code></pre></div></div>

<p>The <code class="language-plaintext highlighter-rouge">name</code> field identifies the skill (lowercase, hyphens allowed). The <code class="language-plaintext highlighter-rouge">description</code> field is what makes auto-discovery work—Claude reads these descriptions at startup and matches them against what you’re asking for. Only the frontmatter loads initially; the full content stays on disk until a match triggers activation.</p>

<p>This two-phase loading keeps context lean. Claude doesn’t carry all your skill content in memory at once. When a task matches a description, the relevant skill loads just-in-time. Multiple skills can activate for the same task if their descriptions all match.</p>

<p>Skills also support optional configuration. You can restrict which tools a skill can use (<code class="language-plaintext highlighter-rouge">allowed-tools: Read, Grep, Glob</code> for a read-only analysis skill), run them in isolated sub-agent context (<code class="language-plaintext highlighter-rouge">context: fork</code>), or control visibility in the slash menu (<code class="language-plaintext highlighter-rouge">user-invocable: false</code> for skills Claude should discover automatically but users shouldn’t invoke directly). We haven’t needed most of these—the defaults work well for domain knowledge skills.</p>

<p>The skill content itself mirrors what we had in the agent files: templates showing the expected file structure, rules about what patterns to follow and which to avoid, checklists for verification. A data skill template shows exactly how to structure a query hook, how to separate API types from frontend types, how to build query key factories. The styles skill covers our SCSS variable conventions and component styling patterns. The translations skill explains our i18n setup and lists all locale files that need updating.</p>

<p>What makes this work well is integration with broader workflows. We use a brainstorming skill for requirements exploration before implementation begins, which feeds naturally into domain skills when actual coding starts. A verification skill runs at the end to catch what slipped through. These external workflows compose with the domain skills rather than competing with them.</p>

<p>A planning skill handles coordination for larger features. When you’re building something that spans multiple domains, it creates a structured sequence and tracks progress across skill boundaries. But even this coordination happens through the same lightweight, just-in-time mechanism. You describe what you want to build, and the planning skill activates because the task matches its trigger conditions.</p>

<hr />

<h2 id="results">Results</h2>

<p>Claude can now one-shot most features in our codebase. Not perfectly every time, but close enough that the review process catches edge cases rather than fundamental structural problems. The code that comes out follows our conventions because the relevant skill loaded automatically and guided the implementation.</p>

<p>The “wrong approach” errors dropped significantly. When Claude builds a data layer, it uses our query key factory pattern and our type separation between API and frontend models. When it touches styling, it reaches for our design tokens rather than inventing new values. When it adds user-facing strings, it updates the locale files rather than hardcoding text. These were all mistakes we used to catch in review and send back for revision.</p>

<p>We still have hard enforcers running underneath: linters, formatters, type checking. These remain our baseline, and they’ve become easier to maintain now that Claude produces code that mostly passes them on the first try. The skills handle the patterns that static analysis can’t catch, while the tooling catches everything mechanical.</p>

<p>The skills also serve as onboarding documentation. New developers read them to understand our patterns. The difference from traditional docs is that these files are actively used, so they stay current. When we refine a pattern through pull request discussion, we update the skill. When we deprecate an approach, we remove it. The documentation evolves with the codebase because the documentation is part of how the codebase gets built.</p>

<p>We still review everything Claude produces. But the review conversations shifted from “this doesn’t match our patterns” to “this edge case needs handling” or “this abstraction might be premature.” The baseline quality improved enough that we spend review time on genuinely interesting questions.</p>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>The barrier to doing this is lower than it might seem. A skill is a markdown file with some YAML frontmatter. You describe when it applies and what patterns to follow. The hard part is having patterns worth encoding, and most teams already do. The conventions exist in code review comments, in PR discussions, in the explanations senior developers give to junior ones.</p>

<p>Writing skills is a way of capturing that knowledge in a form that Claude can use. The files live in your repository, version controlled alongside the code they describe. When the patterns change, you update the skills. When new patterns emerge, you write new skills.</p>

<p>Our agent approach failed because it required us to orchestrate the AI. Skills succeed because they let Claude orchestrate itself. The same domain knowledge, expressed in nearly the same format, but loaded just-in-time based on what the task actually requires. Sometimes a small structural change makes all the difference.</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="software-engineering" /><category term="ai" /><category term="ai" /><category term="programming" /><category term="claude" /><category term="frontend" /><category term="react" /><category term="developer-experience" /><summary type="html"><![CDATA[How we evolved from orchestrating AI sub-agents to self-applying skills, and why a small structural change made all the difference.]]></summary></entry><entry><title type="html">From LLM-Assisted Coding to LLM-Driven Development</title><link href="https://blog.liorp.dev/blog/software-engineering/ai/from-llm-assisted-to-llm-driven-development/" rel="alternate" type="text/html" title="From LLM-Assisted Coding to LLM-Driven Development" /><published>2026-01-02T10:00:00+02:00</published><updated>2026-01-02T10:00:00+02:00</updated><id>https://blog.liorp.dev/blog/software-engineering/ai/from-llm-assisted-to-llm-driven-development</id><content type="html" xml:base="https://blog.liorp.dev/blog/software-engineering/ai/from-llm-assisted-to-llm-driven-development/"><![CDATA[<p>About a year ago, I adopted <a href="https://claude.ai/code">Claude Code</a> as my primary mode of development - not for side projects, but for my main job. 
Initially, the experience mirrored what most others reported with AI coding tools: accelerated iteration, less time devoted to boilerplate, fewer consultations with Stack Overflow. Valuable, yet not transformative.</p>

<p>What I hadn’t anticipated was where I’d find myself a year later: spending all of my time in the terminal, guiding ~5 agents working on different critical tasks across the product, writing 0 code myself.</p>

<p>What follows is my attempt to document that shift while it’s still fresh - a snapshot of how the work has changed. Not the tools. The craft itself.</p>

<h2 id="when-ai-was-just-helping">When AI Was Just Helping</h2>

<p>Early on, AI sat politely in the background. It completed functions, suggested refactors, and explained unfamiliar APIs. 
I still made all the important decisions independently: architecture, structure, trade-offs. Nothing fundamental had shifted. I was still a developer who just happened to work faster.</p>

<h2 id="when-agents-stopped-waiting-for-instructions">When Agents Stopped Waiting for Instructions</h2>

<p>The shift happened gradually, facilitated in large part by ever-expanding context windows. Once agents could hold an entire repository in memory, they began planning multi-step changes and opening pull requests on their own, and my role started to evolve. I was no longer writing code line-by-line; instead, I found myself reviewing diffs, guiding direction, and fixing misunderstandings.</p>

<p>The surprising part wasn’t that agents made mistakes, but that those mistakes typically stemmed from <em>my own lack of precision</em>. The bottleneck was no longer implementation - it was articulation.</p>

<p>Here’s a concrete example. Early on, I’d prompt something like “refactor the table infrastructure.” The agent would make reasonable (and some unreasonable) guesses, touch the wrong files, and I’d spend time undoing damage. 
Now I write: “We’re rewriting the table module. URL search params are the single source of truth for filters, search, sorting, and pagination. Sync state bidirectionally. Follow industry best practices.” Same intent, radically different output. Claude Code’s brainstorming mode helps here too - transforming rough ideas into structured plans before any code gets written.</p>

<h2 id="the-moment-i-stopped-coding">The Moment I Stopped “Coding”</h2>

<p>Eventually, I noticed a pattern in my days: rewriting prompts more often than functions, refining instructions more often than tests, codifying rules rather than applying patches. When something went wrong, the fix wasn’t a better loop or a more elegant abstraction, but reshaping how the agent <em>thought</em> about the problem next time.</p>

<p>I had crossed a threshold. I was no longer writing code alongside an AI - I was orchestrating work at a different level entirely. The code still mattered, but it was no longer where the thinking happened. Andrej Karpathy <a href="https://x.com/karpathy/status/2004607146781278521">recently described</a> this as a “magnitude 9 earthquake rocking the profession” - a “powerful alien tool” handed out without a manual, where everyone has to figure out how to hold it and operate it. He’s right. And once in a while, when you hold it just right, a powerful beam erupts and melts your problem.</p>

<p>There’s a tendency to dismiss this as “prompt engineering,” as if it’s a shallow trick. In practice, it’s closer to system design. You define boundaries as rigid prompts. You encode assumptions. You decide what <em>must not</em> happen. You turn tribal knowledge into explicit rules.</p>

<p>Every failure teaches you something, and once you encode it, you don’t have to remember it again. That knowledge compounds.</p>

<h2 id="where-this-is-going">Where This Is Going</h2>

<p>If agents continue to improve - and there’s no reason to think they won’t - I see a progression along four axes: speed, autonomy, stakes, and verification infrastructure.</p>

<p>The <strong>chariot stage</strong> is already behind us. That was early adoption: reviewing every diff manually, lightweight verification (CLAUDE.md files, linting rules, pre-commit hooks). Speed already left every human developer in the dust, but you stayed close to the ground, handling mistakes and debugging yourself.</p>

<p>Now we’re in the <strong>car stage</strong>. Speed has increased significantly. Agents navigate more independently while you set the destination. You review with other agents, make them debug failures, intervening at critical points rather than inspecting every line. CI/CD pipelines aren’t optional - they’re load-bearing infrastructure. Automated testing, integration checks before any merge. 
You trust the pavement but still need to know when to brake.</p>

<p>Eventually, the <strong>airplane stage</strong> arrives. Speed is orders of magnitude higher. Autonomy is near-complete - driven by a single prompt, agents write, debate, improve, and execute complex flight plans with minimal intervention. Stakes become existential: production systems, financial software, medical devices. Verification requires redundancy at every layer: multiple verification systems, rollback mechanisms, orchestration layers coordinating agents in formation. 
You’re not the pilot; you’re the one who designed the flight plan, the safety systems, the no-fly zones.</p>

<p>The direction is clear. Trust often lags behind capability, and some domains will stay at car level for regulatory or liability reasons long after the technology is ready. But the trajectory is there.</p>

<hr />

<p>The job isn’t disappearing - it’s shifting upward. The skills that matter more by the day are shifting to become philosophical - clarity of thought, precision in language, deep understanding of the problem domain, and knowing which constraints actually matter.</p>

<p>Typing speed and syntax knowledge still help, <a href="https://wisprflow.ai">but they’re no longer the core of the craft</a>.</p>

<h2 id="ides-are-dead-long-live-the-terminal">IDEs Are Dead. Long Live the Terminal.</h2>

<p>I didn’t set out to stop writing code; I followed where the leverage led. And over the past year, that leverage moved away from implementation and toward intent.</p>

<p>The IDE - that familiar environment of syntax highlighting, autocomplete, and file trees - served us well for decades. But when your primary job becomes directing agents rather than typing characters, the IDE becomes overhead. What you need is a command center: multiple agents running in parallel, streaming their progress, ready for your intervention or approval. That’s the terminal.</p>

<p>Going back now would be like writing assembly after using a compiler. Not wrong for every task - but for most work, unnecessary. The craft is still there. It just lives at a higher level now. And the terminal, that ancient interface we thought we’d outgrown, turns out to be exactly what this new era demands</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="software-engineering" /><category term="ai" /><category term="ai" /><category term="programming" /><category term="software-engineering" /><category term="llm" /><category term="claude" /><summary type="html"><![CDATA[Reflections on a year of working with AI agents in production, and how the nature of the work has quietly shifted.]]></summary></entry><entry><title type="html">Duff’s Device</title><link href="https://blog.liorp.dev/blog/duffs-device/" rel="alternate" type="text/html" title="Duff’s Device" /><published>2025-11-10T23:00:00+02:00</published><updated>2025-11-10T23:00:00+02:00</updated><id>https://blog.liorp.dev/blog/duffs-device</id><content type="html" xml:base="https://blog.liorp.dev/blog/duffs-device/"><![CDATA[<p>Every once in a while you stumble upon a piece of code that makes you question everything you thought you knew about programming.<br />
At first glance, it looks like someone had accidentally merged a <code class="language-plaintext highlighter-rouge">switch</code> statement with a <code class="language-plaintext highlighter-rouge">do/while</code> loop. Then you realize it actually compiles, and more importantly, it does something <em>really</em> clever.</p>

<h2 id="the-original-problem">The Original Problem</h2>

<p>Tom Duff wrote this in 1983 while working on animation playback at Lucasfilm.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup> He needed to copy pixel data to a memory-mapped device as fast as possible. Compilers back then weren’t sophisticated enough to optimize tight loops automatically, so manual loop unrolling was still a viable optimization technique.</p>

<p>Here’s the code:</p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="n">send</span><span class="p">(</span><span class="n">to</span><span class="p">,</span> <span class="n">from</span><span class="p">,</span> <span class="n">count</span><span class="p">)</span>
    <span class="k">register</span> <span class="kt">short</span> <span class="o">*</span><span class="n">to</span><span class="p">,</span> <span class="o">*</span><span class="n">from</span><span class="p">;</span>
    <span class="k">register</span> <span class="n">count</span><span class="p">;</span>
<span class="p">{</span>
    <span class="k">register</span> <span class="n">n</span> <span class="o">=</span> <span class="p">(</span><span class="n">count</span> <span class="o">+</span> <span class="mi">7</span><span class="p">)</span> <span class="o">/</span> <span class="mi">8</span><span class="p">;</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">count</span> <span class="o">%</span> <span class="mi">8</span><span class="p">)</span> <span class="p">{</span>
    <span class="k">case</span> <span class="mi">0</span><span class="p">:</span>  <span class="k">do</span> <span class="p">{</span> <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">7</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">6</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">5</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">4</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">3</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">2</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
    <span class="k">case</span> <span class="mi">1</span><span class="p">:</span>       <span class="o">*</span><span class="n">to</span> <span class="o">=</span> <span class="o">*</span><span class="n">from</span><span class="o">++</span><span class="p">;</span>
            <span class="p">}</span> <span class="k">while</span> <span class="p">(</span><span class="o">--</span><span class="n">n</span> <span class="o">&gt;</span> <span class="mi">0</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<h2 id="the-inner-workings">The Inner Workings</h2>

<p>The trick is combining loop unrolling with C’s fall-through semantics. Instead of having a separate loop to handle the remainder when <code class="language-plaintext highlighter-rouge">count</code> isn’t divisible by 8, Duff uses the <code class="language-plaintext highlighter-rouge">switch</code> statement to jump directly into the middle of the unrolled loop body.</p>

<p>The math works like this: <code class="language-plaintext highlighter-rouge">(count + 7) / 8</code> calculates how many groups of 8 we need to process, rounding up. The <code class="language-plaintext highlighter-rouge">switch (count % 8)</code> determines where to enter the loop body. If <code class="language-plaintext highlighter-rouge">count = 11</code>, then <code class="language-plaintext highlighter-rouge">count % 8 = 3</code>, so execution starts at <code class="language-plaintext highlighter-rouge">case 3</code>, copies three elements (cases 3, 2, 1), then falls through to complete the <code class="language-plaintext highlighter-rouge">do/while</code> iteration. The loop continues from <code class="language-plaintext highlighter-rouge">case 0</code>, processing full 8-element chunks until done.</p>

<hr />

<p>What makes this work is that C allows <code class="language-plaintext highlighter-rouge">case</code> labels can appear inside other control flow structures, such as loop bodies, within a <code class="language-plaintext highlighter-rouge">switch</code> statement.<sup id="fnref:3" role="doc-noteref"><a href="#fn:3" class="footnote" rel="footnote">2</a></sup> The compiler treats <code class="language-plaintext highlighter-rouge">case</code> labels as regular labels that can be jumped to, which means you can enter a loop at an arbitrary point. This is perfectly valid C, though it violates most people’s mental model of structured programming.</p>

<p>The performance benefit comes from reducing loop overhead. Each iteration of a normal loop involves checking the condition, incrementing counters, and branching. By unrolling eight iterations into one loop body, you eliminate seven of those checks. On 1980s hardware where branch misprediction penalties were significant and instruction caches were small, this mattered.</p>

<hr />

<p>Duff himself noted in his original <a href="https://www.lysator.liu.se/c/duffs-device.html#duffs-device">USENET post</a> that “It amazes me that after 10 years of writing C there are still little corners that I haven’t explored fully.”<sup id="fnref:1:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup> The technique became something of a legend in C programming circles, partly because it demonstrates how flexible C’s control flow actually is.</p>

<p>Modern compilers handle loop unrolling automatically, often better than manual unrolling. The XFree86 project actually removed Duff’s Device from their codebase and saw performance improve, because the compiler’s automatic unrolling was more sophisticated.<sup id="fnref:4" role="doc-noteref"><a href="#fn:4" class="footnote" rel="footnote">3</a></sup> Today, this is more of a curiosity than a practical optimization.</p>

<h2 id="pushing-even-further">Pushing Even Further</h2>

<p>But there’s something interesting about how far you can push C’s syntax. Consider this example from <a href="https://blog.feabhas.com/2017/02/abusing-c-switch-statement-beauty-eye-beholder/">Niall Cooling’s article on switch statement abuse</a>:<sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">4</a></sup></p>

<div class="language-c highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kt">void</span> <span class="nf">process_message</span><span class="p">(</span><span class="kt">int</span> <span class="n">x</span><span class="p">)</span>
<span class="p">{</span>
    <span class="k">switch</span> <span class="p">(</span><span class="n">x</span><span class="p">)</span> <span class="p">{</span>
      <span class="nl">default:</span>
        <span class="k">if</span> <span class="p">(</span><span class="n">valid_command_message</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
        <span class="k">case</span> <span class="n">CMD1</span><span class="p">:</span> <span class="k">case</span> <span class="n">CMD2</span><span class="p">:</span> <span class="k">case</span> <span class="n">CMD3</span><span class="p">:</span> <span class="k">case</span> <span class="n">CMD4</span><span class="p">:</span>
          <span class="n">process_command_msg</span><span class="p">(</span><span class="n">x</span><span class="p">);</span>
        <span class="k">else</span> <span class="k">if</span> <span class="p">(</span><span class="n">valid_status_message</span><span class="p">(</span><span class="n">x</span><span class="p">))</span>
        <span class="k">case</span> <span class="n">STATUS1</span><span class="p">:</span> <span class="k">case</span> <span class="n">STATUS2</span><span class="p">:</span> <span class="k">case</span> <span class="n">STATUS3</span><span class="p">:</span>
          <span class="n">process_status_msg</span><span class="p">(</span><span class="n">x</span><span class="p">);</span>
        <span class="k">else</span>
          <span class="n">report_error</span><span class="p">(</span><span class="n">x</span><span class="p">);</span>
    <span class="p">}</span>
<span class="p">}</span>
</code></pre></div></div>

<p>This compiles too. The <code class="language-plaintext highlighter-rouge">default</code> case comes first, and <code class="language-plaintext highlighter-rouge">case</code> labels appear inside <code class="language-plaintext highlighter-rouge">if</code> statements. The control flow works because <code class="language-plaintext highlighter-rouge">case</code> labels are just jump targets—they don’t create scope or block execution. When you hit a matching case, execution falls through to the labeled statement, regardless of what control structures surround it.</p>

<p>The C specification is surprisingly permissive about control flow. <code class="language-plaintext highlighter-rouge">switch</code>, <code class="language-plaintext highlighter-rouge">case</code>, <code class="language-plaintext highlighter-rouge">goto</code>, and fall-through semantics give you low-level control that most modern languages deliberately restrict. This flexibility is why C remains useful for systems programming, but it also means you can write code that’s technically correct and completely unreadable.</p>

<hr />

<p>Duff’s Device sits in that interesting space between clever optimization and code that makes your colleagues question your judgment and good faith.<br />
It’s a good example of understanding your tools deeply enough to use them in unexpected ways, even if those ways aren’t always the right choice for production code.</p>

<p>The real lesson here isn’t about loop unrolling—it’s about how our mental models of programming languages are often simpler than what the language actually allows. C gives you direct access to the machine’s control flow primitives, and sometimes that means code that looks wrong but works perfectly.</p>

<h2 id="sources">Sources</h2>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p><a href="https://www.lysator.liu.se/c/duffs-device.html#duffs-device">Tom Duff’s original 1983 USENET post</a> <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a> <a href="#fnref:1:1" class="reversefootnote" role="doc-backlink">&#8617;<sup>2</sup></a></p>
    </li>
    <li id="fn:3" role="doc-endnote">
      <p><a href="https://www.gnu.org/software/c-intro-and-ref/manual/html_node/Duffs-Device.html">GNU C Manual: Duff’s Device</a> <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:4" role="doc-endnote">
      <p><a href="https://news.ycombinator.com/item?id=10175901">Hacker News discussion on Duff’s Device</a> <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p><a href="https://blog.feabhas.com/2017/02/abusing-c-switch-statement-beauty-eye-beholder/">Abusing the C switch statement – Feabhas</a> <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>liorp</name></author><category term="blog" /><category term="programming" /><category term="optimization" /><category term="c" /><summary type="html"><![CDATA[When C Syntax Went Full Galaxy Brain.]]></summary></entry><entry><title type="html">Why True Craftsmen of Code Will Always Be in Demand</title><link href="https://blog.liorp.dev/blog/software-engineering/ai/craftsmen-of-code/" rel="alternate" type="text/html" title="Why True Craftsmen of Code Will Always Be in Demand" /><published>2025-08-29T10:00:00+03:00</published><updated>2025-08-29T10:00:00+03:00</updated><id>https://blog.liorp.dev/blog/software-engineering/ai/craftsmen-of-code</id><content type="html" xml:base="https://blog.liorp.dev/blog/software-engineering/ai/craftsmen-of-code/"><![CDATA[<p>In the 1970s, when C emerged as a high-level alternative to assembly language, many predicted the death of low-level programming. Why wrestle with registers and memory addresses when C offered clean, portable syntax? The industry rushed to adopt this new abstraction - and by the late 1980s, most new systems projects had shifted from assembly to higher-level languages.</p>

<p>Yet something unexpected happened: assembly programmers didn’t disappear. Instead, they found new life in specialized, high-value niches. Hardware companies continued hiring assembly experts for optimization work. Game studios paid premium rates for developers who could squeeze performance from hardware through carefully crafted low-level code. The emergence of embedded systems, IoT devices, and security research created entirely new domains where assembly expertise commanded respect and premium compensation.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup></p>

<p>History may be rhyming again. AI coding assistants are creating a similar divide, and we’re witnessing comparable economic forces at play - though the picture is more complex than many assume.</p>

<h2 id="the-economic-reality-specialization-creates-lasting-value">The Economic Reality: Specialization Creates Lasting Value</h2>

<p>The C revolution didn’t eliminate assembly programming, but transformed it into a specialized skill. The transition revealed a fundamental pattern: when technology democratizes a field, deep expertise doesn’t vanish; it migrates to the domains that need it most. Good examples are cybersecurity and reverse engineering: “knowledge of assembly language is relatively rare” and this “scarcity increases the value of the skill” - particularly essential for malware analysis and vulnerability research.<sup id="fnref:7" role="doc-noteref"><a href="#fn:7" class="footnote" rel="footnote">2</a></sup></p>

<p>Consider how assembly programming evolved rather than disappeared:</p>

<ul>
  <li>
    <p><strong>1980s-90s</strong>: Game developers like John Carmack became legendary for assembly optimization skills.<sup id="fnref:4" role="doc-noteref"><a href="#fn:4" class="footnote" rel="footnote">3</a></sup> While id Software’s Doom was “programmed largely in ANSI C language,” it still relied on “a few elements in assembly language” for critical performance sections.<sup id="fnref:3" role="doc-noteref"><a href="#fn:3" class="footnote" rel="footnote">4</a></sup></p>
  </li>
  <li>
    <p><strong>2000s-Present</strong>: Embedded systems exploded with IoT growth. This year (2025), 75 billion IoT devices are expected globally, many requiring assembly-level optimization for resource-constrained environments.<sup id="fnref:9" role="doc-noteref"><a href="#fn:9" class="footnote" rel="footnote">5</a></sup></p>
  </li>
</ul>

<p>The lesson is nuanced but clear: abstraction doesn’t eliminate the need for foundational knowledge; it concentrates that need in specialized, high-value applications.</p>

<h2 id="todays-shift-ais-mixed-reality">Today’s Shift: AI’s Mixed Reality</h2>

<p>We’re witnessing a massive adoption of AI coding tools. GitHub reports that 92% of developers now use AI tools either at work or personally,<sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">6</a></sup> with AI generating an estimated 41% of all code - 256 billion lines in 2024 alone.<sup id="fnref:6" role="doc-noteref"><a href="#fn:6" class="footnote" rel="footnote">7</a></sup> Just as C democratized programming by abstracting away assembly complexity, AI tools are now democratizing software development by abstracting away coding complexity itself.</p>

<p>This democratization creates the same fundamental dynamic we saw in the 1970s: when AI handles routine programming tasks, the critical bottlenecks shift to problems that require deep understanding of what lies beneath the abstraction. Consider the inevitable scenarios:</p>

<ul>
  <li>AI-generated React apps that render slowly need someone who understands virtual DOM mechanics;</li>
  <li>Prompted APIs that leak memory at scale require experts who can profile heap allocation patterns;</li>
  <li>Auto-generated database queries creating performance bottlenecks demand specialists who can optimize query execution plans;</li>
  <li>AI-hallucinated security vulnerabilities necessitate professionals who can audit actual attack surfaces.</li>
</ul>

<p>The pattern from the assembly era repeats: as the abstraction handles more routine work, specialized expertise becomes more valuable, not less. However, early evidence suggests this value transfer isn’t automatic - it flows specifically to those who can bridge the gap between AI capabilities and fundamental engineering knowledge.</p>

<h2 id="the-inevitable-evolution">The Inevitable Evolution</h2>

<p>The assembly-to-C transition provides our roadmap, but not in the way many expect. Assembly programmers didn’t simply become scarce and therefore valuable - they evolved.<sup id="fnref:13" role="doc-noteref"><a href="#fn:13" class="footnote" rel="footnote">8</a></sup> The market didn’t pay premiums just for scarcity; it paid for specialized expertise that solved problems.</p>

<p>Today’s evolution follows a similar but more complex trajectory. As AI tools handle routine coding tasks, the real value lies in:</p>

<ol>
  <li><strong>Understanding when and how to use AI effectively</strong> (avoiding the 19% productivity penalty);<sup id="fnref:10" role="doc-noteref"><a href="#fn:10" class="footnote" rel="footnote">9</a></sup></li>
  <li><strong>Optimizing and securing AI-generated code</strong> at scale;</li>
  <li><strong>Architecting systems</strong> that humans and AI can collaborate on efficiently;</li>
  <li><strong>Specializing in domains</strong> where deep technical knowledge remains irreplaceable.</li>
</ol>

<p>The market rewards expertise that combines foundational knowledge with new tool mastery - not just resistance to change or blind adoption of new technologies.</p>

<h2 id="the-nuanced-conclusion">The Nuanced Conclusion</h2>

<p>History doesn’t repeat exactly, but it does rhyme with important variations. When C democratized programming in the 1970s, assembly programmers who adapted became highly paid specialists building compilers and optimizing kernels. Their evolution, not just their scarcity, transformed them from replaceable coders into irreplaceable craftsmen.</p>

<p>Today’s pattern is similar but more complex. The value won’t flow to those who simply reject AI tools or blindly adopt them - it will flow to adaptive craftsmen who master both deep fundamentals and effective AI collaboration.</p>

<p>These hybrid experts who combine irreplaceable technical knowledge with new tool mastery won’t just survive the AI revolution - they’ll define its next phase. In a world where most developers struggle with productivity-reducing AI tools, that adaptive expertise is exactly what the industry needs.</p>

<hr />

<h2 id="sources">Sources</h2>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p><a href="https://en.wikipedia.org/wiki/Assembly_language">Assembly language - Wikipedia</a> - Overview of assembly language domains and continued usage <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:7" role="doc-endnote">
      <p><a href="https://www.researchgate.net/publication/376170194_Importance_of_Assembly_Language_in_Cyber_Security_and_Reverse_Engineering">Importance of Assembly Language in Cyber Security and Reverse Engineering - ResearchGate</a> - Assembly scarcity and value in cybersecurity <a href="#fnref:7" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:4" role="doc-endnote">
      <p><a href="https://en.wikipedia.org/wiki/Fast_inverse_square_root">Fast inverse square root - Wikipedia</a> - Fast inverse square root algorithm <a href="#fnref:4" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:3" role="doc-endnote">
      <p><a href="https://en.wikipedia.org/wiki/Development_of_Doom">Development of Doom - Wikipedia</a> - Programming languages used in id Software games <a href="#fnref:3" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:9" role="doc-endnote">
      <p><a href="https://moldstud.com/articles/p-industry-insights-embedded-software-engineering-job-market-and-salary-trends">Industry Insights: Embedded Software Engineering Job Market - MoldStud</a> - IoT growth driving embedded demand <a href="#fnref:9" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p><a href="https://github.blog/news-insights/research/survey-reveals-ais-impact-on-the-developer-experience/">Survey reveals AI’s impact on the developer experience - GitHub Blog</a> - 92% AI tool adoption statistics <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:6" role="doc-endnote">
      <p><a href="https://www.elitebrains.com/blog/aI-generated-code-statistics-2025">AI-Generated Code Stats 2025 - Elite Brains</a> - 41% of code AI-generated, 256 billion lines in 2024 <a href="#fnref:6" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:13" role="doc-endnote">
      <p><a href="https://retrocomputing.stackexchange.com/questions/30314/what-happened-to-the-job-market-for-assembly-programmers-once-high-level-languag">What happened to the job market for assembly programmers - Retrocomputing Stack Exchange</a> - Programming market expansion analysis <a href="#fnref:13" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
    <li id="fn:10" role="doc-endnote">
      <p><a href="https://metr.org/blog/2025-07-10-early-2025-ai-experienced-os-dev-study/">Measuring the Impact of Early-2025 AI on Developer Productivity - METR</a> - 19% productivity decrease with AI tools <a href="#fnref:10" class="reversefootnote" role="doc-backlink">&#8617;</a></p>
    </li>
  </ol>
</div>]]></content><author><name>liorp</name></author><category term="blog" /><category term="software-engineering" /><category term="ai" /><category term="ai" /><category term="programming" /><category term="software-engineering" /><category term="career" /><category term="assembly" /><category term="low-level" /><summary type="html"><![CDATA[Abstraction creates more programmers, but makes true experts scarcer and more valuable.]]></summary></entry><entry><title type="html">Understanding Elastic Index Mappings and Field Limits</title><link href="https://blog.liorp.dev/blog/elasticsearch/elastic-index-mapppings/" rel="alternate" type="text/html" title="Understanding Elastic Index Mappings and Field Limits" /><published>2025-06-22T10:05:10+03:00</published><updated>2025-06-22T10:05:10+03:00</updated><id>https://blog.liorp.dev/blog/elasticsearch/elastic-index-mapppings</id><content type="html" xml:base="https://blog.liorp.dev/blog/elasticsearch/elastic-index-mapppings/"><![CDATA[<p>If you’ve ever worked with Elasticsearch, you might have hit an error like <code class="language-plaintext highlighter-rouge">illegal_argument_exception: Limit of total fields [1000] has been exceeded</code>. This happened to me at work when I accidentally pushed entire JSON objects into my documents - a classic case of dynamic mapping gone wrong. Because Elasticsearch, by default, tries to infer the data types and structure of every new field it encounters, each nested key in the JSON was automatically added to the index mapping. Every property - even those I never intended to search on - consumed one of the available field slots. Before long, the index hit its 1,000-field limit, and Elasticsearch refused to accept any more documents. It was a frustrating issue to debug at first, but also a valuable lesson in carefully designing mappings and turning off dynamic mapping for fields that don’t need to be individually indexed.</p>

<p>But why did this happen in the first place? To understand the cause - and how to prevent it - let’s look at the main subject of this post: <strong>index mappings</strong>. Think of mappings as Elasticsearch’s version of a database schema. Just like a relational database has tables with defined columns and data types, Elasticsearch uses mappings to control the structure and types of your fields. This schema-like approach gives you fine-grained control over how data is stored and searched, but it can also introduce pitfalls if you let it grow unchecked. Let’s dive into what mappings are, why they matter, and how to avoid blowing up your cluster with too many fields.</p>

<h2 id="what-is-an-index-mapping">What Is an Index Mapping?</h2>

<p>In Elasticsearch, an <strong>index mapping</strong> is like an SQL schema - it defines:</p>

<ul>
  <li>What fields exist</li>
  <li>The <a href="https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/field-data-types">data types</a> (<code class="language-plaintext highlighter-rouge">text</code>, <code class="language-plaintext highlighter-rouge">keyword</code>, <code class="language-plaintext highlighter-rouge">date</code>, <code class="language-plaintext highlighter-rouge">integer</code>, etc.)</li>
  <li>Analyzers and search behavior</li>
</ul>

<p>Mappings help Elasticsearch store and search data efficiently. Even if you never explicitly define one, <strong>Elasticsearch will create one for you</strong>. This automatic mapping creation is what enables the dynamic behavior we’ll explore next, but it also introduces the potential for the “too many fields” problem.</p>

<h2 id="automatic-dynamic-mapping">Automatic (Dynamic) Mapping</h2>

<p>By default, mappings are created <strong>dynamically</strong>.<sup id="fnref:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup><br />
That means whenever you send a new JSON document to an index, Elasticsearch will inspect its structure and infer the appropriate types for each new field. For example, if you send a document like this:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="p">{</span><span class="w">
  </span><span class="nl">"user"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Lior"</span><span class="p">,</span><span class="w">
  </span><span class="nl">"createdAt"</span><span class="p">:</span><span class="w"> </span><span class="s2">"2025-06-20"</span><span class="w">
</span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Elasticsearch will do the following under the hood:</p>

<ul>
  <li>Treat the <code class="language-plaintext highlighter-rouge">user</code> field as a <code class="language-plaintext highlighter-rouge">text</code> field and also add a <code class="language-plaintext highlighter-rouge">keyword</code> subfield, allowing you to both search its contents and perform exact matches or aggregations.</li>
  <li>Treat the <code class="language-plaintext highlighter-rouge">createdAt</code> field as a <code class="language-plaintext highlighter-rouge">date</code>, so it can be sorted and used in range queries.</li>
</ul>

<p>This hands-off behavior is incredibly convenient - especially when you want to iterate quickly or explore data without worrying about schema upfront.</p>

<p>However, this convenience comes at a cost. If your data contains unpredictable or highly variable shapes - for example, if you’re pushing entire nested JSON objects into one field - every new key that appears will be automatically added to the mapping. Imagine one document has a user object like:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">"user"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"firstName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Lior"</span><span class="p">,</span><span class="w"> </span><span class="nl">"lastName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Pollak"</span><span class="w"> </span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>And then the next one has:</p>

<div class="language-json highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="nl">"user"</span><span class="p">:</span><span class="w"> </span><span class="p">{</span><span class="w"> </span><span class="nl">"firstName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Lior"</span><span class="p">,</span><span class="w"> </span><span class="nl">"lastName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Pollak"</span><span class="p">,</span><span class="w"> </span><span class="nl">"middleName"</span><span class="p">:</span><span class="w"> </span><span class="s2">"Amit"</span><span class="w"> </span><span class="p">}</span><span class="w">
</span></code></pre></div></div>

<p>Suddenly, a new field (<code class="language-plaintext highlighter-rouge">middleName</code>) is created in the mapping. Over time, as variations pile up, the number of distinct fields grows - and so does the mapping size.</p>

<p>When this happens repeatedly at scale - especially if you ingest user-generated or unstructured data - your index can accumulate hundreds or thousands of unique fields before you realize it. This can lead to a nasty surprise when you hit the <code class="language-plaintext highlighter-rouge">index.mapping.total_fields.limit</code> (default is 1,000), and further document indexing fails.</p>

<p>That’s why dynamic mapping is a double-edged sword. It can speed up early-stage development or work well for stable, well-known data shapes. But without guardrails like explicit mappings or disabled dynamic mapping for certain paths, it can lead to mapping explosion, reduced performance, and index failures.</p>

<h2 id="manually-creating-mappings">Manually Creating Mappings</h2>

<p>While dynamic mapping is great for getting up and running quickly, explicitly defining your mappings up front is the safest way to control your data structure and prevent surprises. This is even recommended by elastic themselves for production use cases.<sup id="fnref:1:1" role="doc-noteref"><a href="#fn:1" class="footnote" rel="footnote">1</a></sup><br />
With manual mappings, you declare exactly which fields your documents will have and what types they should be. This lets you plan your index design for long-term stability.</p>

<p>Here’s a practical example in TypeScript using the official <code class="language-plaintext highlighter-rouge">@elastic/elasticsearch</code> client:</p>

<div class="language-typescript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">import</span> <span class="p">{</span> <span class="nx">Client</span> <span class="p">}</span> <span class="k">from</span> <span class="dl">"</span><span class="s2">@elastic/elasticsearch</span><span class="dl">"</span><span class="p">;</span>

<span class="kd">const</span> <span class="nx">client</span> <span class="o">=</span> <span class="k">new</span> <span class="nx">Client</span><span class="p">({</span> <span class="na">node</span><span class="p">:</span> <span class="dl">"</span><span class="s2">http://localhost:9200</span><span class="dl">"</span> <span class="p">});</span>

<span class="k">await</span> <span class="nx">client</span><span class="p">.</span><span class="nx">indices</span><span class="p">.</span><span class="nx">create</span><span class="p">({</span>
  <span class="na">index</span><span class="p">:</span> <span class="dl">"</span><span class="s2">my_index</span><span class="dl">"</span><span class="p">,</span>
  <span class="na">body</span><span class="p">:</span> <span class="p">{</span>
    <span class="na">mappings</span><span class="p">:</span> <span class="p">{</span>
      <span class="na">dynamic</span><span class="p">:</span> <span class="kc">false</span><span class="p">,</span>
      <span class="na">properties</span><span class="p">:</span> <span class="p">{</span>
        <span class="na">user</span><span class="p">:</span> <span class="p">{</span> <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">keyword</span><span class="dl">"</span> <span class="p">},</span>
        <span class="na">createdAt</span><span class="p">:</span> <span class="p">{</span> <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">date</span><span class="dl">"</span> <span class="p">},</span>
        <span class="na">message</span><span class="p">:</span> <span class="p">{</span> <span class="na">type</span><span class="p">:</span> <span class="dl">"</span><span class="s2">text</span><span class="dl">"</span> <span class="p">},</span>
      <span class="p">},</span>
    <span class="p">},</span>
  <span class="p">},</span>
<span class="p">});</span>
</code></pre></div></div>

<p>Here, we explicitly control:</p>

<ul>
  <li>The field names (<code class="language-plaintext highlighter-rouge">user</code>, <code class="language-plaintext highlighter-rouge">createdAt</code>, <code class="language-plaintext highlighter-rouge">message</code>)</li>
  <li>The field types (<code class="language-plaintext highlighter-rouge">keyword</code>, <code class="language-plaintext highlighter-rouge">date</code>, <code class="language-plaintext highlighter-rouge">text</code>)</li>
  <li>How those fields will be handled for searching and sorting</li>
</ul>

<p>By creating this mapping manually, you gain several clear advantages:</p>

<ul>
  <li>Fields and types are explicit - your team and tools know what to expect.</li>
  <li>No uncontrolled dynamic mappings - you won’t accumulate unpredictable fields as data shapes change. <sup id="fnref:2" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">2</a></sup></li>
  <li>You won’t accidentally exceed field limits - the index will accept the fields you define, preventing mapping explosion. <sup id="fnref:2:1" role="doc-noteref"><a href="#fn:2" class="footnote" rel="footnote">2</a></sup></li>
  <li>Easier optimization - you can choose the most efficient types (e.g. using keyword instead of text if you only need exact matches).</li>
  <li>Clear upgrade paths - when you need to add new fields, you do it consciously by updating the mapping.</li>
</ul>

<p>And while this may feel more rigid at first, explicit mappings pay off as your data scales and your queries become more complex. They also help ensure consistency across different indices or environments - making your entire Elasticsearch setup easier to maintain over time.</p>

<blockquote>
  <p>⚠️ Important: Once a field is mapped in an index, its type cannot be changed - you can only add new fields. If you need to change the type of an existing field, you must create a new index and reindex your data. If you want to change the name of an existing field, you need to use an <a href="https://www.elastic.co/docs/reference/elasticsearch/mapping-reference/field-alias"><code class="language-plaintext highlighter-rouge">alias</code></a> field to create an alternate field name, since renaming a field would invalidate data already indexed under the old field name.</p>
</blockquote>

<h2 id="conclusion">Conclusion</h2>

<p>Index mappings give Elasticsearch its speed and search power - but they require careful control. Getting them right up front can save you a ton of headaches as your data grows.</p>

<p>Here’s a quick overview of the trade-offs:</p>

<table>
  <thead>
    <tr>
      <th>Feature</th>
      <th>Benefit</th>
      <th>Limitation</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td>Explicit mappings</td>
      <td>Predictable types and search behavior</td>
      <td>Requires up-front planning</td>
    </tr>
    <tr>
      <td>Dynamic mappings</td>
      <td>Easy to prototype and ingest data quickly, up-and-running format</td>
      <td>Can cause index bloat and too-many-fields</td>
    </tr>
  </tbody>
</table>

<p>As you can see, explicit mappings offer the most control and scalability, especially in production systems where stability is key. Dynamic mappings can be handy during early development or prototyping - just remember that they may introduce surprises if left unchecked.</p>

<p>When starting a new project:</p>

<ul>
  <li>Design mappings up front for stable and scalable indices.</li>
  <li>Use <a href="https://www.elastic.co/guide/en/elasticsearch/reference/8.18/flattened.html">flattened types</a> if you need to store highly dynamic, semi-structured data without exploding your mappings.</li>
  <li>Avoid letting dynamic mapping run amok - uncontrolled field creation can hit the <code class="language-plaintext highlighter-rouge">index.mapping.total_fields.limit</code> and cause indexing errors.</li>
</ul>

<p>By keeping these considerations in mind, you’ll make sure your indices stay lean, mean, and ⚡️lightning-fast⚡️ - and you’ll spend more time building features and less time firefighting mapping errors.</p>

<div class="footnotes" role="doc-endnotes">
  <ol>
    <li id="fn:1" role="doc-endnote">
      <p>https://www.elastic.co/docs/manage-data/data-store/mapping/dynamic-mapping <a href="#fnref:1" class="reversefootnote" role="doc-backlink">&#8617;</a> <a href="#fnref:1:1" class="reversefootnote" role="doc-backlink">&#8617;<sup>2</sup></a></p>
    </li>
    <li id="fn:2" role="doc-endnote">
      <p>You can actually refine this behavior even further to reject documents with unmapped fields, using <code class="language-plaintext highlighter-rouge">"dynamic" :strict</code> <a href="#fnref:2" class="reversefootnote" role="doc-backlink">&#8617;</a> <a href="#fnref:2:1" class="reversefootnote" role="doc-backlink">&#8617;<sup>2</sup></a></p>
    </li>
  </ol>
</div>]]></content><author><name>liorp</name></author><category term="blog" /><category term="elasticsearch" /><category term="elasticsearch" /><category term="mappings" /><category term="index" /><category term="typescript" /><category term="schema" /><summary type="html"><![CDATA[Exploring what index mappings in Elasticsearch are, why they matter, and how to manage them to avoid too many fields errors.]]></summary></entry><entry><title type="html">The Math Behind the Card Game Set</title><link href="https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-2/" rel="alternate" type="text/html" title="The Math Behind the Card Game Set" /><published>2024-10-24T16:00:00+03:00</published><updated>2024-10-24T16:00:00+03:00</updated><id>https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-2</id><content type="html" xml:base="https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-2/"><![CDATA[<h3 id="the-math-behind-the-card-game-set">The Math Behind the Card Game Set</h3>

<p>The card game <a href="https://en.wikipedia.org/wiki/Set_(card_game)">Set</a> is a fast-paced puzzle game that challenges players to spot groups of three cards that form a “set”. While the gameplay seems straightforward, it is built on deep mathematical principles rooted in combinatorics and geometry. Let’s explore the math that makes Set both entertaining and complex.</p>

<hr />

<h4 id="the-structure-of-the-game">The Structure of the Game</h4>

<p>Each card in Set is defined by four features:</p>

<ul>
  <li><strong>Shape</strong>: Oval, squiggle, or diamond</li>
  <li><strong>Color</strong>: Red, green, or purple</li>
  <li><strong>Number</strong>: One, two, or three symbols</li>
  <li><strong>Shading</strong>: Solid, striped, or open</li>
</ul>

<p>There are \(3^4 = 81\) unique cards, as each feature can take one of three possible values.</p>

<hr />

<h4 id="what-constitutes-a-set">What Constitutes a Set?</h4>

<p>A “set” is made up of three cards where, for each of the four features, the cards must either all share the same value or all have different values. For example, if one card has an oval shape, the other two cards must either also have an oval shape (same value) or one must have a squiggle and the other a diamond (different values).</p>

<hr />

<h4 id="finite-geometry-and-vector-spaces">Finite Geometry and Vector Spaces</h4>

<p>The game’s mathematical foundation comes from <strong>finite geometry</strong>. The 81 cards can be thought of as points in a four-dimensional vector space over the finite field \(\mathbb{Z}_{3}\), where each feature represents one dimension. In this space:</p>

<ul>
  <li>The sum of each feature over all cards is zero.</li>
</ul>

<p>Each feature in Set can take one of three values, which can be represented by \(\{0, 1, 2\}\) in the finite field \(\mathbb{Z}_3\). Let’s assume a “set”, that is a collection of three cards, where each feature has the same value, or all three features have different values.</p>

<ul>
  <li>The case of all three features having the same value is easy to understand. For example, if all three cards have the same shape, then the sum of the shape feature over all three cards is 0 in \(\mathbb{Z}_3\), since \(3 \cdot x \equiv 0 \mod 3\).</li>
  <li>The case of all three features having different values is a bit more complex. For example, if the first card has an oval shape, the second card has a squiggle, and the third card has a diamond, then the sum of the shape feature over all three cards is 0 in \(\mathbb{Z}_3\), since \(1 + 2 + 0 \equiv 3 \equiv 0 \mod 3\).</li>
</ul>

<p>A “set” of three cards corresponds to a line within this space.</p>

<p>As we have just seen, for three cards represented by vectors \(\mathbf{v}_1\), \(\mathbf{v}_2\), and \(\mathbf{v}_3\), the condition for a “set” is:</p>

<p>\(\mathbf{v}_1 + \mathbf{v}_2 + \mathbf{v}_3 \equiv 0 \mod 3\).</p>

<p>This condition implies:</p>

<ul>
  <li>
\[\mathbf{v}_1 + \mathbf{v}_2 \equiv -\mathbf{v}_3 \mod 3\]
  </li>
  <li>By adding \(\mathbf{v}_2\) to both sides: \(\mathbf{v}_1 + 2\cdot\mathbf{v}_2 \equiv \mathbf{v}_2 - \mathbf{v}_3 \mod 3\)</li>
  <li>Of course, \(2\cdot\mathbf{v}_2 = -\mathbf{v}_2 \mod 3\), so \(\mathbf{v}_1 - \mathbf{v}_2 \equiv \mathbf{v}_2 - \mathbf{v}_3 \mod 3\)</li>
</ul>

<p>This shows that \(\mathbf{v}_1\), \(\mathbf{v}_2\), and \(\mathbf{v}_3\) lie on the same line in the 4-dimensional space. Therefore, a “set” corresponds to a line in the affine space \(\mathbb{Z}_3^4\).</p>

<ul>
  <li>The number of unique sets is 1,080.</li>
</ul>

<p>Note that every pair of cards has a unique card that completes the set. This means that the number of sets is equal to the number of ways to choose two cards from 81, which is \(\binom{81}{2} = 3,240\). However, each set is counted three times, once for each configuration of the three cards that can complete it. Therefore, the number of unique sets is \(\frac{3,240}{3} = 1,080\).</p>

<hr />

<p>At its heart, Set is more than just a fun card game—it’s a puzzle built on fascinating mathematical structures. Whether you’re a math enthusiast or simply enjoy the gameplay, knowing the geometry and combinatorics behind it adds an extra layer of appreciation to every round.</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="games" /><category term="math" /><category term="combinatorics" /><category term="geometry" /><category term="card-games" /><category term="set" /><summary type="html"><![CDATA[Part 2 of the series - Discover how the puzzle game Set is built on fascinating mathematical principles.]]></summary></entry><entry><title type="html">The Math Behind the Card Game Dobble</title><link href="https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-1/" rel="alternate" type="text/html" title="The Math Behind the Card Game Dobble" /><published>2024-10-16T16:00:00+03:00</published><updated>2024-10-16T16:00:00+03:00</updated><id>https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-1</id><content type="html" xml:base="https://blog.liorp.dev/blog/games/math/math-behind-children-games-part-1/"><![CDATA[<h3 id="the-math-behind-the-card-game-dobble">The Math Behind the Card Game Dobble</h3>

<p>Recently, at a company gathering fun day, I found myself rediscovering an old favorite: <a href="https://en.wikipedia.org/wiki/Dobble">Dobble</a>. While the quick pace and competitive spirit made for an enjoyable break, I started thinking about what makes this game tick. As we raced to spot matching symbols, I realized there must be more to the game’s design than meets the eye. This renewed my curiosity, leading me to explore the mathematical principles behind the game that ensure every pair of cards always has exactly one symbol in common. Here’s a peek into the fascinating math behind Dobble.</p>

<hr />

<h4 id="how-dobble-works">How Dobble Works</h4>

<p>Dobble is a card game that challenges players to find a matching symbol between any two cards. The clever design ensures that each pair of cards shares exactly one symbol, no matter which cards are chosen. This seemingly simple setup is based on the principles of <a href="https://en.wikipedia.org/wiki/Finite_geometry"><strong>finite geometry</strong></a> and <a href="https://en.wikipedia.org/wiki/Combinatorics"><strong>combinatorics</strong></a>, specifically <a href="https://en.wikipedia.org/wiki/Projective_plane"><strong>projective planes</strong></a>.</p>

<p>In Dobble, each card features a set of symbols, and the key to the game’s design is that any two cards share exactly one symbol in common. At first, this may seem like a coincidence, but in fact it is the result of some careful and beautiful mathematical construction.</p>

<hr />

<h4 id="how-dobble-really-works">How Dobble <em>Really</em> Works</h4>

<p>The underlying math in Dobble comes from the field of <strong>finite projective planes</strong>. A projective plane is a structure in which:</p>

<ul>
  <li>There are a set number of points (symbols) and lines (cards),</li>
  <li>Every line contains the same number of points,</li>
  <li>Any two lines share exactly one point.</li>
</ul>

<p>A <strong>projective plane of order \(n\)</strong> is a special arrangement where:</p>

<ul>
  <li>There are \(n^2 + n + 1\) points (symbols),</li>
  <li>There are \(n^2 + n + 1\) lines (cards),</li>
  <li>Each line (card) contains exactly \(n + 1\) points (symbols),</li>
  <li>Each point (symbol) appears on \(n + 1\) lines (cards),</li>
  <li>Any two lines (cards) intersect at exactly one point (symbol).</li>
</ul>

<p>In Dobble, the order \(n = 7\), and this order determines the number of cards, symbols, and the rule that any two cards share exactly one symbol.</p>

<p>This arrangement ensures that for any two cards, there will always be exactly one shared symbol. The particular projective plane used for Dobble is often based on <strong>order 7</strong> geometry.</p>

<hr />

<h4 id="construction-of-dobble-cards">Construction of Dobble Cards</h4>

<p>The cards in Dobble are constructed using a projective plane of order 7, which results in the following:</p>

<ul>
  <li>There are \(7^2 + 7 + 1 = 57\) unique cards,</li>
  <li>Each card contains \(7 + 1 = 8\) symbols,</li>
  <li>Every pair of cards shares exactly 1 symbol.</li>
</ul>

<figure class="align-right">
  <img src="/assets/images/2024-10-16-math-behind-children-games-part-1/projective-dobble.svg" style="max-width:280px;" alt="Dobble projective plane" />
  <figcaption>The image shows a set of Dobble cards, each featuring multiple symbols. The key mathematical feature is that any two cards share exactly one symbol, a property based on the finite projective plane of order 7 used in the game's design.</figcaption>
</figure>

<p>This arrangement is what makes the game work so seamlessly. Without this mathematical structure, it would be extremely difficult to ensure that all cards share one, and only one, symbol with every other card.</p>

<hr />

<p>Dobble is more than just a fun and fast-paced card game—it’s a brilliant example of how mathematics can be applied to create engaging and entertaining experiences. The game’s unique structure is a direct result of the beautiful interplay between finite geometry and combinatorics. So, the next time you sit down to play Dobble, remember that the seemingly simple task of spotting matching symbols is backed by such a fascinating and intricate mathematical design!</p>

<p>In the next part of this series, we’ll delve into the mechanics of another popular card game—Set. Stay tuned!</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="games" /><category term="math" /><category term="combinatorics" /><category term="geometry" /><category term="card-games" /><category term="dobble" /><summary type="html"><![CDATA[Part 1 of the series - Discover how does the fast-paced card game Dobble ensure that every pair of cards shares exactly one symbol.]]></summary></entry><entry><title type="html">Understanding Variable Scope and Closures in JavaScript and Python</title><link href="https://blog.liorp.dev/blog/web-development/understanding-variable-scope/" rel="alternate" type="text/html" title="Understanding Variable Scope and Closures in JavaScript and Python" /><published>2024-07-07T10:00:00+03:00</published><updated>2024-07-07T10:00:00+03:00</updated><id>https://blog.liorp.dev/blog/web-development/understanding-variable-scope</id><content type="html" xml:base="https://blog.liorp.dev/blog/web-development/understanding-variable-scope/"><![CDATA[<h3 id="understanding-variable-scope-and-closures-in-javascript-and-python">Understanding Variable Scope and Closures in JavaScript and Python</h3>

<p>Recently, while working on a timed log implementation in Node.js, I encountered an issue when trying to replicate the functionality in Python. This experience highlighted the differences in how JavaScript and Python handle variable scope within nested functions. Understanding these differences is crucial for any developer working with both languages. Let’s dive into the details.</p>

<h4 id="javascript-closures">JavaScript Closures</h4>

<p>In JavaScript, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">closures</a> are a powerful feature that allows functions to access variables from an enclosing scope. Or, to quote MSDN (emphasis mine):</p>

<blockquote>
  <p>A closure is the combination of a function bundled together (enclosed) with references to its surrounding state (the lexical environment). <strong>In other words, a closure gives you access to an outer function’s scope from an inner function.</strong> In JavaScript, closures are created every time a function is created, at function creation time.</p>
</blockquote>

<p>Here’s an example:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">test</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">let</span> <span class="nx">start</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">return</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">start</span> <span class="o">=</span> <span class="nx">start</span> <span class="o">+</span> <span class="mi">1</span><span class="p">;</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">val</span><span class="dl">"</span><span class="p">,</span> <span class="nx">start</span><span class="p">);</span>
  <span class="p">};</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">increment</span> <span class="o">=</span> <span class="nx">test</span><span class="p">();</span>
<span class="nx">increment</span><span class="p">();</span> <span class="c1">// val 1</span>
<span class="nx">increment</span><span class="p">();</span> <span class="c1">// val 2</span>
</code></pre></div></div>

<p>In this example, the <code class="language-plaintext highlighter-rouge">test</code> function returns another function that increments and logs the <code class="language-plaintext highlighter-rouge">start</code> variable. The inner function retains access to <code class="language-plaintext highlighter-rouge">start</code> even after <code class="language-plaintext highlighter-rouge">test</code> has finished executing. This is possible because of closures, which keep a reference to the variables in the outer function’s scope.</p>

<h4 id="python-closures">Python Closures</h4>

<p>Python also supports closures, but the way it handles variable scope within nested functions is slightly different. Here’s a similar example in Python:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="k">def</span> <span class="nf">test</span><span class="p">():</span>
    <span class="n">start</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">def</span> <span class="nf">t</span><span class="p">():</span>
        <span class="k">nonlocal</span> <span class="n">start</span>
        <span class="n">start</span> <span class="o">=</span> <span class="n">start</span> <span class="o">+</span> <span class="mi">1</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"val"</span><span class="p">,</span> <span class="n">start</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">t</span>

<span class="n">increment</span> <span class="o">=</span> <span class="n">test</span><span class="p">()</span>
<span class="n">increment</span><span class="p">()</span>  <span class="c1"># val 1
</span><span class="n">increment</span><span class="p">()</span>  <span class="c1"># val 2
</span></code></pre></div></div>

<p>Initially, the code may look similar, but there’s a crucial difference: the <code class="language-plaintext highlighter-rouge">nonlocal</code> keyword. In Python, variables defined in an enclosing scope (like <code class="language-plaintext highlighter-rouge">start</code> in the <code class="language-plaintext highlighter-rouge">test</code> function) are inaccessible by default within inner functions. To access such a variable, you must declare it as <code class="language-plaintext highlighter-rouge">nonlocal</code>.</p>

<h4 id="key-differences-in-default-scope-behavior">Key Differences in Default Scope Behavior</h4>

<ul>
  <li><strong>JavaScript</strong>: Inner functions can read and modify variables from the outer function’s scope without any additional declarations.</li>
  <li><strong>Python</strong>: You must use the <code class="language-plaintext highlighter-rouge">nonlocal</code> keyword in order to access variables from the enclosing scope within inner functions.</li>
</ul>

<h4 id="practical-implications">Practical Implications</h4>

<p>Understanding these differences is crucial when translating code between JavaScript and Python or when working with both languages simultaneously. For instance, if you implement a timed log in Node.js and later decide to port it to a Python script, you need to adjust how you handle variable scope to ensure your code functions correctly.</p>

<p>Here’s an example scenario:</p>

<p><strong>JavaScript Timed Log Implementation</strong>:</p>

<div class="language-javascript highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kd">const</span> <span class="nx">logWithCount</span> <span class="o">=</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
  <span class="kd">let</span> <span class="nx">count</span> <span class="o">=</span> <span class="mi">0</span><span class="p">;</span>
  <span class="k">return</span> <span class="p">()</span> <span class="o">=&gt;</span> <span class="p">{</span>
    <span class="nx">count</span><span class="o">++</span><span class="p">;</span>
    <span class="nx">console</span><span class="p">.</span><span class="nx">log</span><span class="p">(</span><span class="dl">"</span><span class="s2">Log count:</span><span class="dl">"</span><span class="p">,</span> <span class="nx">count</span><span class="p">);</span>
  <span class="p">};</span>
<span class="p">};</span>

<span class="kd">const</span> <span class="nx">logger</span> <span class="o">=</span> <span class="nx">logWithCount</span><span class="p">();</span>
<span class="k">while</span> <span class="p">(</span><span class="kc">true</span><span class="p">)</span> <span class="p">{</span>
  <span class="nx">logger</span><span class="p">();</span>
<span class="p">}</span>
</code></pre></div></div>

<p><strong>Python Equivalent</strong>:</p>

<div class="language-python highlighter-rouge"><div class="highlight"><pre class="highlight"><code><span class="kn">import</span> <span class="nn">time</span>

<span class="k">def</span> <span class="nf">log_with_count</span><span class="p">():</span>
    <span class="n">count</span> <span class="o">=</span> <span class="mi">0</span>
    <span class="k">def</span> <span class="nf">logger</span><span class="p">():</span>
        <span class="k">nonlocal</span> <span class="n">count</span>
        <span class="n">count</span> <span class="o">+=</span> <span class="mi">1</span>
        <span class="k">print</span><span class="p">(</span><span class="s">"Log count:"</span><span class="p">,</span> <span class="n">count</span><span class="p">)</span>
    <span class="k">return</span> <span class="n">logger</span>

<span class="n">logger</span> <span class="o">=</span> <span class="n">log_with_count</span><span class="p">()</span>
<span class="k">while</span> <span class="bp">True</span><span class="p">:</span>
    <span class="n">logger</span><span class="p">()</span>
</code></pre></div></div>

<p>In both implementations, the closure retains access to the <code class="language-plaintext highlighter-rouge">count</code> variable, allowing it to increment and log correctly at each interval.</p>

<p>By understanding and leveraging the nuances of variable scope and closures in both JavaScript and Python, you can write more effective and bug-free code.</p>

<p>Feel free to share your thoughts on variable scope and closures in JavaScript and Python. How have these concepts impacted your coding practices? I’d love to hear your insights and experiences!</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="web-development" /><category term="javascript" /><category term="python" /><category term="closure" /><category term="scope" /><summary type="html"><![CDATA[Exploring the differences in variable scope and closures between JavaScript and Python, and how they impact code implementation]]></summary></entry><entry><title type="html">Firgun - building a Slack workflow</title><link href="https://blog.liorp.dev/blog/web-development/firgun-building-a-slack-workflow/" rel="alternate" type="text/html" title="Firgun - building a Slack workflow" /><published>2024-06-11T10:00:00+03:00</published><updated>2024-06-11T10:00:00+03:00</updated><id>https://blog.liorp.dev/blog/web-development/firgun-building-a-slack-workflow</id><content type="html" xml:base="https://blog.liorp.dev/blog/web-development/firgun-building-a-slack-workflow/"><![CDATA[<p>I am thrilled to introduce my latest side project: <strong>Firgun</strong>, a Slack bot that enhances your LinkedIn engagement experience without disrupting your workflow.</p>

<hr />

<h2 id="what-is-firgun">What is Firgun?</h2>

<p>Firgun is a Slack bot designed to facilitate seamless LinkedIn interactions directly within Slack. When a LinkedIn link is posted in a Slack channel, Firgun detects it and provides an option to engage with the post—right from Slack. This eliminates the need to switch between applications, helping you maintain your workflow while staying active on LinkedIn.</p>

<hr />

<h2 id="development-journey">Development Journey</h2>

<h3 id="building-the-slack-workflow">Building the Slack Workflow</h3>

<p>The core functionality of Firgun revolves around the Slack Workflow Apps platform. This platform enables the creation of custom workflows that can automate tasks and integrate with external services.</p>

<h3 id="challenges-and-solutions">Challenges and Solutions</h3>

<p>During development, I encountered a few bugs within the Slack Workflow Apps platform. The support from the Slack team was invaluable—they were prompt and thorough in addressing each issue, ensuring that the development process remained smooth.</p>

<h3 id="documentation-and-community-support">Documentation and Community Support</h3>

<p>One of the standout aspects of working on this project was the quality of Slack’s documentation. It is clear, comprehensive, and easy to navigate, which significantly accelerated the development process. Additionally, the community support around Slack and Deno is robust, providing a wealth of resources and examples to draw from.</p>

<hr />

<h2 id="open-source-and-future-plans">Open Source and Future Plans</h2>

<p>Firgun is open source and available for the community to download, fork, and contribute to on GitHub. I believe in the power of community collaboration and am excited to see how others can enhance and expand Firgun’s capabilities. <a href="https://github.com/liorp/firgun">You can find the project on GitHub.</a></p>

<p>Looking ahead, I plan to continue refining Firgun, adding new features, and improving its performance. Some of the potential future enhancements include:</p>

<ul>
  <li>Integrating additional social media platforms</li>
  <li>Adding more customizable workflow options</li>
  <li>Improving the user experience for easier interaction</li>
</ul>

<hr />

<h2 id="conclusion">Conclusion</h2>

<p>Building Firgun has been an exciting journey filled with learning and problem-solving. The combination of Slack’s powerful API, Deno’s modern runtime, and the supportive developer community made this project a rewarding experience. I’m eager to see how Firgun can benefit others and look forward to ongoing collaboration and feedback.</p>

<p>Feel free to connect and share your thoughts. I’m always open to feedback and collaboration!</p>]]></content><author><name>liorp</name></author><category term="blog" /><category term="web-development" /><category term="javascript" /><category term="deno" /><category term="slack" /><category term="linkedin" /><category term="open-source" /><summary type="html"><![CDATA[Building a Slack workflow with Deno and JavaScript]]></summary></entry></feed>