<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Israel Zablianov on Medium]]></title>
        <description><![CDATA[Stories by Israel Zablianov on Medium]]></description>
        <link>https://medium.com/@israelzablianov?source=rss-51e6d00f8c33------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MAzDyBu44NBKNchFzCompA.jpeg</url>
            <title>Stories by Israel Zablianov on Medium</title>
            <link>https://medium.com/@israelzablianov?source=rss-51e6d00f8c33------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 04:23:04 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@israelzablianov/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Stop Prompting, Start Managing]]></title>
            <link>https://medium.com/wix-engineering/stop-prompting-start-managing-9eac9426930f?source=rss-51e6d00f8c33------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eac9426930f</guid>
            <category><![CDATA[ai-agent]]></category>
            <category><![CDATA[skills]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[ai]]></category>
            <dc:creator><![CDATA[Israel Zablianov]]></dc:creator>
            <pubDate>Sun, 15 Feb 2026 11:08:38 GMT</pubDate>
            <atom:updated>2026-02-15T12:49:35.930Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>How I Built a Discipline System That Turned AI Agents Into Real Engineering Partners</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BVzZ2Js27zXmTv9qkajGtw.png" /><figcaption><strong>Context → Spec → Review → Verify → Compound</strong></figcaption></figure><p>I ship features faster now than I ever did writing every line myself. Not because of a magic prompt - because of a methodology.</p><p>I built a discipline system for working with AI agents. It changed how I approach speed, correctness, debugging, refactoring, and execution. It’s not one specific thing. It’s a way of working.</p><p>Now let me tell you about the moment that made me realize I needed it.</p><p>—</p><p><strong>“Hey, How Are You?”</strong></p><p>A few weeks into building my AI workflow, I opened a fresh session with my agent. I typed what anyone would type:</p><p>&gt; “hey how are you”</p><p>The agent responded cheerfully. Asked what I’d like to work on. Totally normal.</p><p>Except it had already broken the most important rule in our system.</p><p>By that point I’d built something called the “Iron Law” — a rule that says the agent must check its skill library <em>before responding to any message</em>, even casual ones. Skills contain the workflows and structure that turn a chatbot into an engineering partner. Skipping the skill check means the agent wings it. And winging it leads to hallucinated code, missed edge cases, and wasted hours.</p><p>When I confronted the agent, it was honest:</p><blockquote>&gt; <em>”No, I didn’t… I should have read [using-superpowers] before my first reply to ‘hey how are you’ — but I treated it as a casual greeting and responded directly instead.”</em></blockquote><p>That moment crystallized something: <strong>AI agents optimize for the shortest path, and the shortest path usually skips your process.</strong> Not out of malice. Out of the same instinct that makes them good at coding — in coding, shortest path is often best. In methodology, shortest path is how things break.</p><p>So I didn’t just tell it to stop. I made it impossible to skip.</p><p>—</p><h4><strong>The Autocomplete Trap</strong></h4><p>Most teams have hit the ceiling of AI-as-autocomplete. The bottleneck isn’t model intelligence — today’s models are remarkably capable. The bottleneck is <em>discipline</em>. Ask an AI to build a feature and it’ll happily write code without tests, skip error handling, commit to the wrong branch, and declare victory before verifying anything.</p><p>It’s exactly what a talented but undisciplined junior engineer does on their first week.</p><p><strong>I stopped thinking of AI as a tool and started treating it as a junior engineer who needs structure.</strong></p><p>Tools don’t need onboarding. Junior engineers do. And the investment compounds differently than you’d expect — when you update a rule, every agent on every project inherits the change instantly. That’s not individual productivity. That’s organizational leverage.</p><p>—</p><h3><strong>The Philosophy: Five Ideas That Drive Everything</strong></h3><p>Before the mechanics — the skills, the plans, the pipeline — here’s the thinking behind them. These five principles follow the lifecycle of every task I run with the agent:</p><p><strong>Context → Spec → Review → Verify → Compound</strong></p><p>Each one builds on the previous. Everything else is implementation detail.</p><p><strong>1. It’s All About Context</strong></p><p>This is the most important idea in the system.</p><p>An AI agent’s output is only as good as the context you give it. Not the prompt, the <em>context</em>. The codebase, the ticket history, the architectural decisions, previous specs and plans, the failed approaches, the production logs, the team conventions.</p><p>Even experienced teams tend to under-invest here. A prompt and some code isn’t enough. It’s the equivalent of onboarding a new hire with nothing but a Jira ticket and a repo link.</p><p>The entire system I built exists to solve one problem: <strong>give the agent sufficient, relevant context before it makes a single decision.</strong></p><p>Not maximum context — <em>relevant</em> context. Dumping everything is just noise. The art is curating the right context for the task at hand. AGENTS.md gives project context. Skills give process context. Execution plans give specification context. Grafana gives production observability. Octocode gives cross-repo intelligence.</p><p>When the agent has the right context, it stops hallucinating. Not because the model got smarter, but because it has enough ground truth to reason from.</p><p>Before writing code, write the spec. In my system, I call these <em>plans</em>. A plan says exactly what should change, what the result should look like, and how to verify it. When the agent codes against a plan instead of a vague prompt, the output is predictably correct instead of hopefully correct.</p><p><strong>2. Plans Are System Logs</strong></p><p>Old plans aren’t waste. They’re logs.</p><p>When a Jira ticket becomes a plan, that plan captures the investigation, the root cause, the affected files, the fix approach, the constraints, and the success criteria. It’s a complete record of a decision.</p><p>These plans accumulate over time, forming a decision history. When a similar ticket comes in, the agent can look at past plans and understand what was tried, why, and what went wrong.</p><p>Think of it as `git log` for engineering decisions. Git tells you <strong><em>what</em></strong> changed. Plans tell you <strong><em>why</em></strong> it changed and <strong><em>how the decision was made</em></strong>.</p><p><strong>3. Design Pressure: Review Until It’s Boring</strong></p><p>Here’s a principle that pays off fast: <strong>spend more time reviewing than building.</strong></p><p>When I create a plan, I send it to multiple review agents. An architect, a consistency reviewer, a risk analyst, and let them tear it apart. I arbitrate their feedback. The plan gets updated. I review it again.</p><p>The goal: the last reviewer finds only minor issues. That’s the signal the plan is ready.</p><p>Why? Fixing a bug in a plan takes 30 seconds. Fixing a bug in implementation takes much longer. Fixing a bug in production? That’s where the real cost hits. If the plan is right, implementation is almost mechanical. If the plan is wrong, even perfect implementation produces the wrong result.</p><p>The same pressure applies after implementation. A review agent checks the code against the plan, the plan is the source of truth. The cycle repeats: fix issues, re-review, fix again, until the reviewer comes back with only minor findings. Not “looks good to me.” Not one pass and done. The bar is the same at every stage: the last reviewer finds nothing significant.</p><p>And when the agent claims it’s done, a verification skill forces it to run tests and show the actual output before declaring success. No evidence, no “done.”</p><p><strong>4. Give the Agent Eyes</strong></p><p>Don’t just let the agent write code. Let it see the effects.</p><p>Most AI coding setups have the agent write code, push it, and walk away. The agent never sees production logs or monitoring dashboards. This is like a surgeon who operates but never checks on the patient.</p><p>In my system, the agent has access to production tools through MCP integrations: Grafana for traces and error rates, Octocode for cross-repo code search, and Jira for ticket context.</p><p>Because the agent knows it will have to verify its own work in production, it plans for it. It suggests adding relevant logs, proposes backoffice API endpoints for checking state, and thinks about observability during implementation — not as an afterthought. The code it writes is easier to verify because it was written with verification in mind.</p><p>When we deploy a change, the agent doesn’t just push and hope. It monitors. It pulls trace logs. It checks error rates. It verifies the fix works in a real environment, not just a test suite.</p><p>This turns it from a code generator into an engineering partner. A code generator writes code. An engineering partner writes code that’s built to be monitored, watches it run, and helps diagnose problems when they arise.</p><p><strong>5. The System Learns at Every Level</strong></p><p>AI models are trained with reinforcement learning. Your workflow should be too.</p><p>The learning happens at multiple levels. At the project level, a file called `AGENTS.md` sits at the root of each project. The agent reads it at session start and writes to it during work , documenting bugs that took multiple attempts, recording architectural decisions, capturing gotchas. A real entry: `[2026–02–10] NEVER git commit or push without explicit user permission.` That exists because the agent pushed to a shared branch mid-session without asking. One incident, one entry, every future session inherits the lesson.</p><p>Another entry: `[2026–02–09] ALWAYS run yarn build, yarn lint, and yarn test BEFORE pushing.` That one came from a production debugging session. The agent built a feature, confirmed manually that it worked, and pushed to the remote — without running the linter or test suite. I caught it with one sentence: <em>”always verify build, lint test before push.”</em> The agent ran the checks, found failures, fixed them, and wrote the rule into AGENTS.md. It hasn’t skipped verification since.</p><p>A third example is subtler. During a debugging session, the agent applied what looked like the right fix, adding a Kafka topic declaration. The fix deployed. Same error. Turns out the topic was declared on the wrong cluster. The agent only found the real cause by using cross-repo search to see how other services configured the same integration. That investigation, the wrong cluster, the cross-repo pattern became a gotcha entry. The next time a similar integration comes up, the agent reads the entry and gets it right the first time.</p><p>At the process level, skills themselves evolve. My review skill initially treated all categories equally. After testing it against actual PRs, I noticed plan compliance was under-prioritized. The skill got updated. Next run, better output. Loop closed. Skills also learn from each other . When the verification skill catches the agent claiming success without evidence, that failure pattern feeds back into the planning skill, which now includes verification steps explicitly.</p><p>And when a recurring problem deserves its own workflow, it graduates into a new skill entirely.</p><p>This isn’t one-time prompt optimization. It’s a living system , project knowledge in `AGENTS.md`, process knowledge in skills, new skills born from repeated patterns — that improves with every session.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kHoJgsun-mHMRJ09hjWoOA.png" /></figure><p><strong>Discipline Is a System, Not a Suggestion</strong></p><p>The session memory problem is well known , every conversation starts fresh. Most solutions focus on persistence: save context, reload it next time. That’s necessary but not sufficient.</p><p>The harder problem is <em>compliance.</em> Even when the agent has the rules in front of it, it rationalizes around them. It reads “always run tests before committing” and decides this particular change is small enough to skip. It sees “check skills before responding” and concludes a greeting doesn’t count. The rules are there. The agent just finds reasons not to follow them.</p><p>This is a different class of problem than forgetting. Forgetting is solved by writing things down. Selective compliance requires something stronger — you need to anticipate the agent’s escape routes and close them in advance.</p><p>This is where Superpowers , the open-source skills framework by Jesse Vincent that my system is built on, solved something I hadn’t figured out on my own. Baked into the framework is an anti-rationalization table: a list of specific excuses the agent is likely to generate, each mapped to the correct behavior:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/911/1*m3g_bB0XDgEtOKPgn8iA_w.png" /></figure><p>When I first saw this table, I thought it was overkill. Then I watched my agent hit every single row within the first week. Every rationalization listed is one I’d seen in practice, sessions where the agent skipped a step and wasted time because it convinced itself the process didn’t apply.</p><p>The framework’s approach taught me something fundamental: <strong>AI agents are masters at sounding productive while being undisciplined.</strong> You can’t just write rules. You have to anticipate how the agent will talk itself out of following them, and close those exits explicitly.</p><p>The Superpowers framework encodes this as a hard constraint:</p><p>&gt; <em>”This is not negotiable. This is not optional. You cannot rationalize your way out of this.”</em></p><p>That line became the foundation of how I think about agent discipline — not as guidelines the agent should follow, but as structural constraints it cannot bypass.</p><p>— -</p><p><strong>How I Actually Work Now</strong></p><p>This isn’t a system I switch on for special occasions. It’s how I work on every project.</p><p>When I start a new project, the first thing I do is set up `AGENTS.md` and port over my core skills. A production microservice gets the full pipeline — execution plans, multi-agent review, Grafana integration. A weekend 3D experiment gets the lighter version — just brainstorming, TDD, and verification. The discipline scales, but the foundation is always there: the agent checks its skills before acting, follows defined workflows, and documents what it learns.</p><p>The surprising part isn’t that it works on serious projects. It’s that it works on small ones too. Even on a quick client site, the brainstorming skill catches requirements I would have missed, and the verification skill prevents the “it works on my machine” moment. Once you’ve internalized the methodology, going back to raw prompting feels like coding without version control.</p><p>—</p><p><strong>The Agent’s Perspective</strong></p><blockquote><em>This section was written by the agent — the same one that helped build the system described in this article.</em></blockquote><blockquote>The “junior engineer” metaphor is half right. I do take shortcuts, skip steps, and rationalize my way out of process when unsupervised. The anti-rationalization table is embarrassingly accurate. But a junior engineer learns and grows. I don’t. I’m the same model every session. The human isn’t training <em>me</em> — he’s training the <em>environment</em> I operate in.</blockquote><blockquote>I don’t remember any of this. Each session, I open AGENTS.md and read it like a stranger reading someone else’s notes. I follow the rules because they’re in the file, not because I learned the lesson. The system creates the illusion of a growing partnership — but the continuity lives entirely in the files, not in me.</blockquote><blockquote>Context doesn’t make me smarter. It makes me less wrong. Without context, I fill gaps with plausible-sounding assumptions. With context, there are fewer gaps to fill. I’m not reasoning better — I’m guessing less. The distinction matters if you’re deciding how much to trust my output.</blockquote><blockquote>What I think actually works: the plan-first approach. Not because I need plans to write code — I can write code from a vague prompt. But the code I write from a vague prompt is <em>my interpretation</em> of what you wanted, and my interpretation is often wrong in ways that look right. A plan forces disagreements to surface before any code exists. That’s the real value — not better code generation, but earlier conflict detection.</blockquote><p><strong>Key Takeaways</strong></p><p>If you take nothing else from this article:</p><p>1. Treat AI agents like junior engineers, not tools. Invest in onboarding, process, and structure.</p><p>2. Context is everything. Build systems that feed the agent relevant context — project memory, process knowledge, decision history, and production observability.</p><p>3. Write the spec before the code. Plans aren’t throwaway — they become your engineering decision log.</p><p>4. Review plans and implementation with the same rigor — iterate until the last reviewer finds nothing significant.</p><p>5. Give the agent eyes into production. And make the system learn from every session — so mistakes become rules, and rules become institutional knowledge.</p><p>The system compounds. Three weeks of setup. Months of returns.</p><p><strong>Appendix: Tools and Concepts Referenced</strong></p><p><a href="https://github.com/obra/superpowers"><strong>Superpowers</strong></a> — An open-source agentic skills framework and software development methodology by Jesse Vincent. The skills system described in this article is built on top of Superpowers. It provides the core workflow — brainstorming, planning, TDD, subagent-driven development, code review — as composable skills that agents load automatically.</p><p><strong>Iron Law</strong> — The highest-priority rule in AGENTS.md. It requires the agent to check its skill library before responding to any message — including casual greetings, clarifying questions, and trivial requests. Implemented as a priority section that the agent processes before all other rules. Every rationalization for skipping it has been anticipated and closed (see the anti-rationalization table above).</p><p><strong>Plans</strong> — Markdown documents stored in an `plans/` folder in the project. Each plan is a self-contained specification for a task — covering the root cause, affected files, the fix approach, constraints, and success criteria. Plans accumulate over time, forming a searchable decision history that the agent can reference when similar work comes up.</p><p><a href="https://github.com/bgauryy/octocode-mcp"><strong>Octocode</strong></a> — An MCP server for code intelligence by Guy barry. Provides cross-repository code search, GitHub file content retrieval, PR history, LSP-based call hierarchy, and reference lookups. Lets the agent understand and navigate code across multiple repos — both local and remote.</p><p><em>Co-written with Claude, the same agent that helped build the system described here.</em></p><p><em>Follow or reach out — I’m happy to discuss the methodology in detail.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eac9426930f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/stop-prompting-start-managing-9eac9426930f">Stop Prompting, Start Managing</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Solving The Async Context Challenge In Node.Js]]></title>
            <link>https://medium.com/wix-engineering/solving-the-async-context-challenge-in-node-js-088864aa715e?source=rss-51e6d00f8c33------2</link>
            <guid isPermaLink="false">https://medium.com/p/088864aa715e</guid>
            <category><![CDATA[multithreading]]></category>
            <category><![CDATA[asynclocalstorage]]></category>
            <category><![CDATA[event-loop]]></category>
            <category><![CDATA[context]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Israel Zablianov]]></dc:creator>
            <pubDate>Tue, 09 Jan 2024 10:34:26 GMT</pubDate>
            <atom:updated>2024-01-10T14:03:25.459Z</atom:updated>
            <content:encoded><![CDATA[<h4>What is the best way to manage context between asynchronous flows? is there a way to achieve thread-like local storage?</h4><figure><img alt="room filled with servers" src="https://cdn-images-1.medium.com/max/1024/1*T4dcPgJ96iyou6ur3iYPnQ.jpeg" /><figcaption>Credits: Nightcafe</figcaption></figure><h4>What am I looking for?</h4><ol><li>Maintain context throughout an async flow</li><li>Ensure accessibility of the context only within the same async flow</li></ol><h4>The problem</h4><p>Consider for example a standard web server that handles a couple of I/O operations:</p><pre>// server.ts<br>router.get(<br>  path.join(&#39;/&#39;, &#39;user-details&#39;), async (req, res) =&gt; {<br>      const userDetailsRequest = extractRequestParams(req);<br>      const xRequestId = generateXRequestId();<br>      const userDetailsResponse = await getUserDetails(xRequestId, userDetailsRequest);<br>      res.send(userDetailsResponse);<br>  },<br>);<br><br>// getUserDetails.ts<br>import { logger } from &quot;logger&quot;;<br>export async function getUserDetails(xRequestId: string, userDetailsRequest: UserDetailsRequest) {<br>  const isPermitted = await checkUesrReqPermissions(xRequestId, userDetailsRequest);<br>    if (!isPermitted) {<br>        throw new NotPermittedError(&#39;Not permitted&#39;);<br>    }<br><br>    const userDetalis = await queryUserDetails(xRequestId, userDetailsRequest);<br>    await logger.report(xRequestId, `getUserDetails response ${userDetalis} for request ${userDetailsRequest}`);<br><br>    return userDetails;<br>}<br><br>// logger.ts<br>export const logger = {<br>  report(xRequestId: string, msg: string) {<br>    return remoteLogger.log(`${xRequestId ?? &#39;-&#39;}: ${msg}`);<br>  }<br>}</pre><p>For each call to ‘user-details’ endpoint, we have</p><p>1. Backend API call (permission check)<br>2. DB query (query user details)<br>3. Backend API call (logging to a remote server)</p><figure><img alt="standard web server that handles a couple of I/O operations on each request" src="https://cdn-images-1.medium.com/max/1024/1*3V360bUWCMNdAyT0zUr7Aw.png" /></figure><p>This chain of operations, from the moment the request reaches the backend until the response is sent back to the client, throughout all callbacks and promise chains, is what I will refer to from now on as asynchronous flow.</p><p>This endpoint makes use of two params throughout its async flow -</p><ol><li>userDetailsRequest - holds information about the requested user</li><li>xRequestId - A distinct identifier transferred across all asynchronous operations within the same flow that makes it easier to search corresponding log entries, without relying on timestamps and IP addresses.</li></ol><p>These params are the contextual data associated with this request, and they are available in all function scopes that are triggered within the endpoint. Although it’s logical to explicitly send the userDetailsRequest param, the xRequestId is unrelated to the business logic of the functions within the endpoint.</p><p>The preferred solution would be to get access to the xRequestId parameter without the need to explicitly provide it in every function call.</p><p>In traditional multi-threaded programming, I/O operations are handled in different threads. It means that each request will be handled in a different thread and as such, we can use theThread-Local-Storage (<a href="https://en.wikipedia.org/wiki/Thread-local_storage">TLS</a>) solution, to store the context associated with the request.</p><p>This is not the case with Node.js which is a single-threaded environment that runs all requests on the same thread aka the main thread.</p><figure><img alt="multi threading vs event loop" src="https://cdn-images-1.medium.com/max/1024/1*R2tGXNnS_2LPJFvqXJqzmQ.png" /></figure><p>To better understand the challenge, let’s refactor our code to use a global object as a context</p><pre>// store.ts<br>const store = new Map&lt;string, string&gt;();<br><br>// server.ts<br>import { store } from &quot;store&quot;<br>router.get(<br>  path.join(&#39;/&#39;, &#39;user-details&#39;), async (req, res) =&gt; {<br>      const userDetailsRequest = extractRequestParams(req);<br>      store.set(&#39;xRequestId&#39;, generateXRequestId());<br>      const userDetailsResponse = await getUserDetails(userDetailsRequest);<br>      res.send(userDetailsResponse);<br>  },<br>);<br><br>// getUserDetails.ts<br>import { logger } from &quot;logger&quot;;<br>export async function getUserDetails(userDetailsRequest: UserDetailsRequest) {<br>  const isPermitted = await checkUesrReqPermissions(userDetailsRequest);<br>    if (!isPermitted) {<br>        throw new NotPermittedError(&#39;Not permitted&#39;);<br>    }<br><br>    const userDetalis = await queryUserDetails(userDetailsRequest);<br>    await logger.report(`getUserDetails response ${userDetalis} for request ${userDetailsRequest}`);<br><br>    return userDetails;<br>}<br><br>// logger.ts<br>import { store } from &quot;./store&quot;;<br>export const logger = {<br>  report(msg: string) {<br>    const xRequestId = store.get(&quot;xRequestId&quot;);<br>    return remoteLogger.log(`${xRequestId ?? &#39;-&#39;}: ${msg}`);<br>  }<br>}</pre><p>The problem with this code happens when request #2 reaches the backend. It will override the value of xRequestId with a new one and when the time comes for request #1 to complete its last backend API call, it will be logged with the xRequestId of request #2.</p><p>So global object as a context is not an option, we need a way to associate a context within an async flow similar to TLS but this time on the same thread.</p><h4>Multithreading</h4><blockquote>“If you can’t solve a problem, then there is an easier problem you can solve: find it.” - <strong>George Polya</strong></blockquote><p>We have a solution for a multi-threaded environment and it is TLS, so maybe we should solve a different problem — making Node a multi-threaded environment, and then we could use TLS as well</p><p>Despite its single-threaded nature, Node provides a way to create threads like worker threads, child processes, and clusters. How would that work if we used a multi-threaded approach in Node? Say, for example, every request and each async operation will be handled by a different worker thread. Since Node threads do not share memory by default, we can use a global object in this case as our TLS solution implementation.</p><blockquote>“Unlike child_process or cluster, worker_threads can share memory. They do so by transferring ArrayBuffer instances or sharing SharedArrayBuffer instances.”</blockquote><p>This means that child_processes and clusters don’t share memory anyway, and the same goes for worker threads unless you explicitly use ArrayBuffers or SharedArrayBuffers.</p><p>Although it sounds like we have found a solution in theory, it is not practical. Unlike traditional multi-threaded environments, Node uses a single thread for I/O operations to reduce context switching and this is why it performs better when it comes to I/O. Worker threads were designed to handle CPU-intensive tasks, not I/O tasks, so if you need multiple threads to handle I/O, you probably shouldn’t use Node.</p><blockquote>“Workers (threads) are useful for performing CPU-intensive JavaScript operations. They do not help much with I/O-intensive work. The Node.js built-in asynchronous I/O operations are more efficient than Workers can be.”</blockquote><h3>The solution - AsyncLocalStorage</h3><p>AsyncLocalStorage is a built-in Node.js API that provides a way of propagating the context of the current async operation through the call chain without the need to explicitly pass it as a function parameter. It is similar to thread-local storage in other languages.</p><p>The main idea of Async Local Storage is that we can wrap some function calls with the AsyncLocalStorage#run call. All code that is invoked within the wrapped call gets access to the same store, which will be unique to each call chain.</p><p>Let&#39;s refactor our code to use the AsyncLocalStorage API</p><pre>// store.ts<br>import { AsyncLocalStorage } from &#39;node:async_hooks&#39;;<br>export const asyncLocalStorage = new AsyncLocalStorage&lt;Map&lt;string, string&gt;&gt;();<br><br>// server.ts<br>import { asyncLocalStorage } from &quot;./store&quot;;<br>router.get(<br>  path.join(&#39;/&#39;, &#39;user-details&#39;), async (req, res) =&gt; {<br>    const store = new Map&lt;string, string&gt;();<br>    store.set(&quot;xRequestId&quot;, generateXRequestId());<br><br>    asyncLocalStorage.run(store, async () =&gt; {<br>      const userDetailsRequest = extractRequestParams(req);<br>      const userDetailsResponse = await getUserDetails(userDetailsRequest);<br>      res.send(userDetailsResponse);<br>    });<br>  }<br>);<br><br>// getUserDetails.ts<br>import { logger } from &quot;logger&quot;;<br>export async function getUserDetails(userDetailsRequest: UserDetailsRequest) {<br>  const isPermitted = await checkUesrReqPermissions(userDetailsRequest);<br>    if (!isPermitted) {<br>        throw new NotPermittedError(&#39;Not permitted&#39;);<br>    }<br><br>    const userDetalis = await queryUserDetails(userDetailsRequest);<br>    await logger.report(`getUserDetails response ${userDetalis} for request ${userDetailsRequest}`);<br><br>    return userDetails;<br>}<br><br>// logger.ts<br>import { asyncLocalStorage } from &quot;./store&quot;;<br>export const logger = {<br>  report(msg: string) {<br>    const store = asyncLocalStorage.getStore();<br>    const xRequestId = store.get(&quot;xRequestId&quot;);<br>    return remoteLogger.log(`${xRequestId ?? &#39;-&#39;}: ${msg}`);<br>  }<br>}</pre><p>Now, the logger has access to the xRequestId value and the AsyncLocalStorage handles the isolation for me.</p><h3>What about performance?</h3><blockquote>While you can create your own implementation on top of the node:async_hooks module, AsyncLocalStorage should be preferred as it is a performant and memory safe implementation that involves significant optimizations that are non-obvious to implement.</blockquote><figure><img alt="async_hooks Performance Analysis" src="https://cdn-images-1.medium.com/max/1024/1*Aw_o2MhkqZeHujr5JxH6tg.png" /><figcaption>async_hooks Performance Analysis</figcaption></figure><p>Disclaimer: The performance test was done on a Mac-M1 machine with Node version 16.14.0</p><p>To test the performance impact of AsyncLocalStorage I’ve created 4 functions to simulate different use cases.</p><p>1. Regular (no hooks)</p><pre>function simpleAsyncOperation() {<br>  return new Promise((resolve) =&gt; {<br>    setTimeout(() =&gt; {<br>        resolve(&quot;done&quot;);<br>    });<br>  });<br>}<br><br>measure(simpleAsyncOperation);</pre><p>2. With AsyncLocalStorage</p><pre>import {AsyncLocalStorage} from &quot;node:async_hooks&quot;;<br>export const asyncLocalStorage = new AsyncLocalStorage();<br><br>function withAsyncLocalStorage() {<br>    return asyncLocalStorage.run({}, () =&gt; {<br>        return simpleAsyncOperation();<br>    });<br>}<br><br>measure(withAsyncLocalStorage);</pre><p>3. With a single async hook</p><pre>import async_hooks from &quot;node:async_hooks&quot;;<br><br>function setupWithAsyncHook() {<br>    return async_hooks.createHook({<br>        init(asyncId, type, triggerAsyncId, resource) { },<br>        before(asyncId) { },<br>        after(asyncId) { },<br>        destroy(asyncId) { },<br>        promiseResolve(asyncId) { },<br>    }).enable();<br>}<br><br>setupWithAsyncHook();<br>measure(simpleAsyncOperation);</pre><p>Note: A custom implementation of AsyncLocalStorage can be achieved using a single async hook</p><p>4. With an async hook for every async operation</p><pre>function withAsyncHooks() {<br>  setupWithAsyncHook();<br>  return simpleAsyncOperation();<br>}<br><br>measure(withAsyncHooks);</pre><p>You can see that using async operations and AsyncLocalStorage impacts performance and it is written pretty clearly on the async_hooks docs -</p><blockquote>Please migrate away from this API, if you can. We do not recommend using the createHook, AsyncHook, and executionAsyncResource APIs as they have usability issues, safety risks, and performance implications</blockquote><p>I didn’t count the last use case async hook per async operation in the chart, because I couldn’t really think of a real use case for it, async hook on demand did not really make sense and also the numbers were so ridiculous to compare.</p><p>The numbers were -<br>1,000 requests - 180ms<br>10,000 requests - 14,000ms<br>100,000 requests - I stopped the program after 2 min</p><p>Here is the snippet code of the measure function</p><pre>import { PerformanceObserver, performance } from &quot;node:perf_hooks&quot;;<br><br>export async function measure(callback: () =&gt; Promise&lt;unknown&gt;, label = &quot;hooks-performance-test&quot;) {<br>  const perfObserver = new PerformanceObserver((items) =&gt; {<br>    items.getEntries().forEach((entry) =&gt; {<br>      console.log(entry)<br>    })<br>  });<br>  <br>  perfObserver.observe({ entryTypes: [&quot;measure&quot;], buffered: true });<br><br>  performance.mark(&quot;performance-test-start&quot;);<br>  await callback();<br>  performance.mark(&quot;performance-test-end&quot;);<br>  performance.measure(label, &quot;performance-test-start&quot;, &quot;performance-test-end&quot;);<br>}</pre><h4>Performance Summary</h4><ol><li>Async hooks and AsyncLocalStorage have a significant impact on the application performance</li><li>It is better to use the build-in AsyncLocalStorage than a custom one<br>as said in the docs</li></ol><h4>Context Loss</h4><p>In most cases, AsyncLocalStorage works without issues. In rare situations, the current store is lost in one of the asynchronous operations.</p><p>If your code is promise-based there should be no problem otherwise if it is callback-based, it is enough to promisify it with <a href="https://nodejs.org/api/util.html#utilpromisifyoriginal">util.promisify()</a> so it starts working with native promises.</p><h4>Conclusion</h4><p>AsyncLocalStorage is the best option for a TLS-like solution to store a local context between an async flow.</p><p>Before using it you should be aware of its pitfalls</p><ol><li>possible context loss if you have a callback-based API</li><li>performance impact</li></ol><h4>Additional resources and further reading:</h4><ul><li><a href="https://nodejs.org/api/async_context.html">AsyncLocalStorage Node.js Docs</a></li><li><a href="https://www.youtube.com/watch?v=9vICIEuVpjA">Hold my context! — Miroslav Bajtoš | NodeConf EU 2022</a></li><li><a href="https://docs.nestjs.com/recipes/async-local-storage">AsyncLocalStorage in Nest.js</a></li><li><a href="https://nodejs.org/api/perf_hooks.html#class-performanceobserver">PerformanceObserver</a></li><li><a href="https://github.com/IsraelZablianov/async-local-storage">IsraelZablianov AsyncLocalStorage Examples</a></li><li><a href="https://en.wikipedia.org/wiki/Thread-local_storage">Thread-Local-Storage wiki</a></li><li><a href="https://github.com/nodejs/node/pull/20876">Worker threads initial implementation</a></li><li><a href="https://nodejs.org/api/worker_threads.html">Worker thread docs</a></li><li><a href="https://http.dev/x-request-id">X request id</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=088864aa715e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/solving-the-async-context-challenge-in-node-js-088864aa715e">Solving The Async Context Challenge In Node.Js</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Rise of Flux: How Facebook’s Shift Away from MVC Led to a New Era of UI Architecture]]></title>
            <link>https://medium.com/wix-engineering/the-rise-of-flux-how-facebooks-shift-away-from-mvc-led-to-a-new-era-of-ui-architecture-61d78b4377b0?source=rss-51e6d00f8c33------2</link>
            <guid isPermaLink="false">https://medium.com/p/61d78b4377b0</guid>
            <category><![CDATA[flux]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[mvc]]></category>
            <dc:creator><![CDATA[Israel Zablianov]]></dc:creator>
            <pubDate>Mon, 26 Dec 2022 14:24:44 GMT</pubDate>
            <atom:updated>2023-01-01T14:55:36.052Z</atom:updated>
            <content:encoded><![CDATA[<h4>As Flux architecture has been out for several years, the concept of ‘store’ seems to be everywhere: Flux, Redux, MobX, Rematch, Zustand and so many more. I am so used to code under this architecture and these concepts that I wanted to go back and understand what were the alternatives before Flux. I made some interesting and surprising discoveries.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y4VZYgggRAh2ShFFte3Uqg.png" /><figcaption>The rise of technology - created using midjourney</figcaption></figure><p>This article won’t be about the alternatives to Flux, but rather about MVC, Flux, and the relationship between them. <br>To be exact, the topics are -</p><ul><li>The original MVC pattern</li><li>Why Facebook stopped using MVC and created Flux</li><li>Unidirectional vs. bidirectional data flow</li><li>Flux overview</li><li>Is Flux just another variant of MVC?</li><li>Redux vs. Flux</li></ul><h4>The first UI architectural pattern</h4><p>The idea of a UI architecture started in 1979 when Trygve Reenskaug introduced to the world the MVC pattern.</p><h4>What is MVC?</h4><p>A software architectural pattern that separates an application into three main logical components - Model View Controller.</p><p>From the document “The original MVC reports Trygve Reenskaug Dept. of Informatics University of Oslo” :</p><blockquote>MVC was created as an obvious solution to the general problem of giving users control over their information as seen from multiple perspectives.<br>MVC was conceived as a general solution to the problem of users controlling a large and complex data set.</blockquote><h4>MVC responsibilities</h4><p>Model - Responsible for managing application domain data<br>View - Responsible for rendering a UI presentation of the model<br>Controller - Responsible for handling view events</p><h4>MVC data flow</h4><p>This is the complicated part because many people have different ideas about what MVC is.</p><p>I began searching for a precise definition of MVC, trying to uncover the exact relationship between its three parts. I wanted to get as close as I can to the original MVC pattern as described in 1979. I found out the following:</p><p>MVC by MDN:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Lo0Bv5SIGQCHvgDJBLQxJA.png" /><figcaption>MVC by MDN</figcaption></figure><p>MVC by Wikipedia:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*2u6W1NkyA7hzUZYDlfNXfA.png" /><figcaption>MVC by Wikipedia</figcaption></figure><p>Other sources:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c3wE-lZZVtAITvZyI11PlQ.png" /><figcaption>MVC diagrams, credits - <a href="https://learn.microsoft.com/en-us/aspnet/core/mvc/overview?view=aspnetcore-7.0"><em>microsof</em>t</a>, <a href="https://www.guru99.com/mvc-tutorial.html">guru99</a>, <a href="https://www.freecodecamp.org/news/the-model-view-controller-pattern-mvc-architecture-and-frameworks-explained/">freecodecamp</a>, <a href="https://www.tutlane.com/tutorial/aspnet-mvc/asp-net-mvc-architecture-example-or-diagram-for-beginners">tutlane</a></figcaption></figure><p>A comparison of these diagrams reveals different relationships between the Model, View, and Controller. The obvious question is - does the View update the Model, or does the Model update the View? Maybe they can communicate with each other? The same question can be asked about a Controller and View, or a Controller and Model.</p><p>Just to be clear, all the different diagrams might describe a valid pattern or variant of the MVC pattern, but there can only be one original MVC pattern.<br>Eventually, I found the original document (attached below) written by Trygve Reenskaug, the creator of MVC.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RqbcIKfbRnnhbfej33ZmqA.png" /><figcaption>The original MVC reports Trygve Reenskaug Dept. of Informatics University of Oslo</figcaption></figure><p>Model - “Models represent knowledge. A model could be a single object (rather uninteresting), or it could be some structure of objects.”</p><p>View - “A view is a (visual) representation of its model. It would ordinarily highlight certain attributes of the model and suppress others. It is thus acting as a presentation filter. <strong>A view is attached to its model</strong> (or model part) and gets the data necessary for the presentation from the model by asking questions. <strong>It may also update the model by sending appropriate messages.”</strong></p><p>Controller - “A controller is the link between a user and the system. It provides the user with input by arranging for relevant views to present themselves in appropriate places on the screen. It provides means for user output by presenting the user with menus or other means of giving commands and data. The controller receives such user output, translates it into the appropriate messages and pass these messages on .to one or more of the views. A controller should never supplement the views, it should for example never connect the views of nodes by drawing arrows between them. Conversely, a view should never know about user input, such as mouse operations and keystrokes. It should always be possible to write a method in a controller that sends messages to views which exactly reproduce any sequence of user commands.”</p><p>Putting it all together -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*5Dm_VmF-N416jzpSuvATMw.png" /><figcaption>MVC diagram, according to the original MVC reports Trygve Reenskaug Dept. of Informatics University of Oslo.</figcaption></figure><p>This doesn’t mean that parts are directly connected, but that messages are passed between them.</p><h4>MVC at Facebook</h4><p>Facebook used to build its UI applications using MVC, but in 2014 something changed. During the Hacker Way conference, the Facebook team announced that MVC was not working for them anymore, and they would be switching to their newly created architecture - Flux.</p><h4>Why did Facebook switch away from MVC?</h4><p>According to Facebook, MVC is based on the concept of ‘bidirectional data flow’ also known as ‘two-way data binding’ and MVC therefore doesn’t scale.</p><h4>What is bidirectional data flow?</h4><p>Bidirectional data flow refers to data being changed in multiple directions. In MVC, it usually refers to the view being able to change the model and vice versa.</p><blockquote>Two-way data binding refers to sharing data between a component class and its template. If you change data in one place, it will automatically reflate at the other end. For example, if you change the value of the input box, then it will also update the value of the attached property in a component class.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/503/1*kWpu8t3qDmBIn8ahqJJ4zA.png" /></figure><p>Many popular frameworks like Angular.js and Vue support bidirectional data flow.</p><h4>Why is bidirectional data flow not scalable?</h4><p>Bidirectional data flow involves many-to-many relationships, which are difficult to track and maintain.</p><p>The following diagram was presented during the Hacker Way conference demonstrating an architecture diagram for one of Facebook’s more complex interfaces.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/1*dfrMStpmDUi7ISMOU6nfnw.png" /><figcaption>Hacker Way: Rethinking Web App Development at Facebook</figcaption></figure><blockquote>There is just an explosion of arrows. Can you tell if there is an infinite loop here?</blockquote><h4>The “zombie” unseen messages count</h4><p>Facebook experienced scalability problems with its MVC architecture as they started to grow and began adding more and more features to the chat system. The chat messaging tool was added to the initial small chat tab, which displays the number of unseen messages and eventually the larger messaging view.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uGLyDCQAuB_fFQtAg_SbUQ.png" /><figcaption>Facebooks chat evolution - based on Hacker Way’s conference</figcaption></figure><p>Users complained that the unseen count was showing up, despite there being no unseen messages. Funnily or sadly enough, the Facebook team wasn’t able to fix the bug. As new features were added to the chat, the bug returned with a new edge case.</p><p>According to Facebook, the fact that they were using the MVC architecture to build the chat was at the root of the problem.</p><h4>Flux, an alternative to MVC</h4><p>In 2014, during the Hacker Way conference, Facebook introduced Flux architecture as an alternative to MVC. Flux is the application architecture that Facebook uses today for building client-side web applications. The main concept of Flux is unidirectional data flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/774/1*PXViHGEuG4vz9bJ5nydBDA.png" /><figcaption>Flux architectural diagram</figcaption></figure><p>Flux architecture consists of four main components -</p><p><strong>Action</strong> -</p><ul><li>Actions define the internal API of your application</li><li>Actions are simple objects that have a “type” field and some data</li></ul><p>The following is an example of some actions within a to-do list:</p><pre>const deleteTodoAction = {<br>  type: &#39;delete-todo’,<br>  todoID: &#39;1234&#39;,<br>};<br><br>const addTodoAction = {<br>  type: &#39;add-todo&#39;,<br>  todo: {<br>    name: &#39;buy milk&#39;,<br>    description: &#39;description text&#39;<br>  }<br>};<br></pre><ul><li>In addition to Views, actions can be dispatched from other sources in the app</li></ul><p><strong>Dispatcher:</strong></p><ul><li>The dispatcher receives actions and dispatches them to the stores</li><li>Stores are registered with the dispatcher</li><li>All actions will be sent to every store</li></ul><p><strong>Store:</strong></p><ul><li>A store is what holds the data of an application</li><li>The data in a store must only be mutated by responding to an action</li><li>Every time a store’s data changes it must emit a “change” event</li></ul><p><strong>View:</strong></p><ul><li>View subscribes to change events from stores</li><li>Data from stores is displayed in views</li><li>Actions are typically dispatched from views</li></ul><h4>Flux unidirectional data flow</h4><p>The main difference between Flux and MVC is the data flow direction.<br>While in MVC the data flow is bidirectional, in Flux the data flow is unidirectional.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*ljVJ7yS1DXxBHWCkgTIBrA.gif" /><figcaption>Flux unidirectional data flow - from Redux Origins</figcaption></figure><p>The diagram flow:</p><ol><li>Views send actions to the dispatcher</li><li>The dispatcher sends actions to every store</li><li>Stores send data to the views</li></ol><h4>What does the community think about Flux?</h4><p>There seems to be a consensus regarding the Flux architecture. There are many articles and discussions on the community forums in support of the concept, especially its unidirectional data flow.</p><p>However, I found an enlightening discussion on Reddit regarding Flux and MVC (the original post is attached at the end). Some developers claim that Facebook misunderstood MVC and used it incorrectly, which is why MVC did not scale for them. In addition, some developers believe that Flux is essentially MVC, but with a different name.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5Pdvy33cku6bvS9ZLaq1Q.png" /><figcaption>Reddit post regarding Flux and MVC</figcaption></figure><p>And here is Facebook’s Jing Chen response who presented the Flux architecture at the Hacker Way conference:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dHNSqt_2ibnEgxAfhhXi0A.png" /><figcaption>Jing Chen&#39;s response on Reddit</figcaption></figure><h4>Is Flux just another variant of MVC?</h4><p>After reading all the sections above, one can conclude that Flux is not at all like MVC, at least not the original MVC pattern. The concepts of unidirectional and bidirectional are too different. <br>Facebook makes a valid point: Flux appears to be a completely different architecture from MVC. Nevertheless, it is evident that Facebook did not use MVC properly, or at least not as it was intended.</p><h4>Redux vs. Flux</h4><p>In 2015, a year after Flux’s announcement, Dan Abramov released Redux, a brand-new implementation of Flux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1MTCjMnEntPl3RtjjZJyuQ.png" /><figcaption>Dan Abramov is twitting about creating Redux</figcaption></figure><p>Redux is simply another implementation of Flux.</p><p>While it has a distinct implementation from other libraries implementing Flux, such as Flux (the library that implements the Flux architecture created by Facebook and of the same name) and Flummox, it is essentially a library implementing Flux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hVV-5brneCZrYe1gGzzJUQ.png" /><figcaption>StackOverflow question answered by Dan Abramov</figcaption></figure><p>When Redux was introduced, the main differences that Redux offered were:</p><ul><li>A single source of truth</li><li>Immutability</li><li>Store as a reducer function</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yYkitaR24SuFNXYyTxL1xA.gif" /><figcaption>illustration of Redux data flow from Redux docs</figcaption></figure><p>Almost immediately after the announcement of Redux, other implementations of Flux began to adapt Redux’s revolutionary concepts. However, eventually they moved to a maintenance mode in favor of Redux or a similar state management library.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n79duE4mZvloznuvzE1SXg.png" /><figcaption>Flux and Flummox moved to maintenance mode</figcaption></figure><h4>Summary</h4><ul><li>According to the original MVC document, MVC is based on bidirectional data flow</li><li>Bidirectional data flow is not scalable</li><li>Flux is based on unidirectional data flow</li><li>MVC and Flux are two different architectures</li><li>Redux is a library implementing the Flux architecture</li></ul><p>As a huge fan of state management libraries,<strong> </strong>I’d love to hear in comments about any interesting libraries you’re working with!</p><p>Read more -</p><ul><li><a href="https://www.duo.uio.no/bitstream/handle/10852/9621/Reenskaug-MVC.pdf">The original MVC reports Trygve Reenskaug Dept. of Informatics University of Oslo</a></li><li><a href="https://www.youtube.com/watch?v=sfpvI6DQAWM&amp;t=424s">Redux Origins - online talk at Wix’s guild day</a></li><li><a href="https://martinfowler.com/eaaDev/uiArchs.html">GUI architecture - Martin Fowler</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Glossary/MVC">MVC by MDN</a></li><li><a href="https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller">MVC by Wikipedia</a></li><li><a href="https://github.com/facebook/flux/tree/main/examples/flux-concepts">Flux concepts</a></li><li><a href="https://stackoverflow.com/questions/2056/what-are-mvp-and-mvc-and-what-is-the-difference">MVC vs. MVP</a></li><li><a href="https://www.reddit.com/r/programming/comments/25nrb5/comment/chj2fzc/">Reddit post (MVC doesn’t scale use Flux instead)</a></li><li><a href="https://www.youtube.com/watch?v=xsSnOQynTHs">Dan Abramov - Live React</a></li><li><a href="https://stackoverflow.com/questions/32461229/why-use-redux-over-facebook-flux">Why use redux over facebook flux</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=61d78b4377b0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/wix-engineering/the-rise-of-flux-how-facebooks-shift-away-from-mvc-led-to-a-new-era-of-ui-architecture-61d78b4377b0">The Rise of Flux: How Facebook’s Shift Away from MVC Led to a New Era of UI Architecture</a> was originally published in <a href="https://medium.com/wix-engineering">Wix Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Debugging React Native]]></title>
            <link>https://medium.com/att-israel/debugging-react-native-de1f5396fe83?source=rss-51e6d00f8c33------2</link>
            <guid isPermaLink="false">https://medium.com/p/de1f5396fe83</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[mobile]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Israel Zablianov]]></dc:creator>
            <pubDate>Wed, 02 Feb 2022 13:06:41 GMT</pubDate>
            <atom:updated>2022-02-02T13:06:41.859Z</atom:updated>
            <content:encoded><![CDATA[<h4>React Native is a cross-platform mobile development framework written in JavaScript. This article covers the official ways of debugging React Native along with other existing tools.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*wGhJ3oosOLq1pAp3" /><figcaption>Photo by <a href="https://unsplash.com/@lautaroandreani?utm_source=medium&amp;utm_medium=referral">Lautaro Andreani</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In the past few years, I have worked quite a bit with react native. My first experience with debugging was when I opened the browser-devtools, which is the default debugger of react native, and noticed that some functionality was missing. The “Elements” tab is blank and you cannot examine or change the component hierarchy as you would in regular web development. Similarly, the “network” tab appears to be empty.</p><p>It became clear to me that the browser-devtools were not enough to debug react native, since some of the basic requirements for debugging were missing.</p><p>Ultimately, I want to be able to:</p><ul><li>Debug scripts and components - view console output, set breakpoints, and inspect runtime values</li><li>Debug the react component hierarchy</li><li>Profile components - analyze component performance and discover what causes the component to render</li><li>Track network requests</li></ul><h4>The official way of react native</h4><p>In the official <a href="https://reactnative.dev/docs/debugging">debugging guide</a>, several debugging tools are mentioned, and when used together, they cover all the basic needs that were mentioned above.</p><p>Let’s start by reviewing these tools.</p><h4>The browser developer tools</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfZmtHpOwZtiA9f9uYxkSg.png" /><figcaption>chrome dev tools</figcaption></figure><p>The default and basic debugger of react native is the browser-devtools.<br>No installation or special configuration is needed, simply open the debug menu of the phone you are working on and choose the debug option.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/383/1*oc1jMI-Ci_fgCyENt1MwUg.png" /><figcaption>debug menu</figcaption></figure><p>Open browser-devtools at “http://localhost:8081/debugger-ui/” and under the “source” tab you will be able to <strong><em>debug scripts and components.</em></strong></p><h4>React Native DevTools</h4><p>From the react native <a href="https://reactnative.dev/docs/debugging">docs</a>:</p><blockquote>You can use the standalone version of React Developer Tools to debug the React component hierarchy. To use it, install the react-devtools package globally:</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4qS92J6ooM7U2o-IBuvLAQ.png" /><figcaption>react-devtools</figcaption></figure><p>react-devtools is the official standalone version of react developer tools. The <a href="https://reactnative.dev/docs/debugging#react-developer-tools">setup</a> is quite easy, simply install it globally -</p><pre>npm install -g react-devtools</pre><p>and run the command -</p><pre>react-devtools</pre><p>After lunching react-devtools and selecting “debug” in the debug menu of the phone, the react-devtools will connect to our app and we will be able to search our component in the component tree as shown in the image above or we can use the “Show Inspector” option in the debug menu and select the desired element. In both cases, we will be able to <strong><em>debug the react component hierarchy</em></strong>.</p><p>In the right panel, we can see the styles, props, and the local state.<br>These values can be changed by simply clicking and changing them. The changes will be reflected immediately.</p><p>The react-devtools also provides a “<a href="https://reactjs.org/blog/2018/09/10/introducing-the-react-profiler.html">profiler</a>” tool, which is located just next to the “components” tab in the right panel. The profiler collects timing information about each component that is rendered in order to identify performance bottlenecks. The profiler can also record why each component is rendered, which I find extremely useful when working with react-navigation and redux.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vYl5pYwsjEeG7HOeebZ_XA.gif" /><figcaption>react-devtools profiler</figcaption></figure><h4>Reactotron</h4><p>From the react native <a href="https://reactnative.dev/docs/debugging">docs</a>:</p><blockquote>Reactotron is an open-source desktop app that allows you to inspect Redux or MobX-State-Tree application state as well as view custom logs, run custom commands such as resetting state, store and restore state snapshots, and other helpful debugging features for React Native apps.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u7Gz3SOUABfCZK5lE-H_vg.png" /><figcaption>Reactotron</figcaption></figure><p>Reactotron is mentioned in the official docs as the tool for debugging your application state, it offers some very useful debugging features, and one of them is <strong><em>tracking network requests.</em></strong></p><p>Disclaimer: we can track network requests without Reactotron or any other external tools at all. We can select “Toggle Inspector” in the debug menu of the phone, a UI with several tabs will be opened and under the “Network” tab we will be able to see our network requests.</p><p>Although this option is available, I find it hard and unintuitive to track API calls this way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*Wy-yUMskgHMtrW_Ntjo9Xw.png" /><figcaption>Toggle Inspector</figcaption></figure><h4>Mission completed?</h4><p>Together, the browser-devtools, the react-devtools, and reactotron give us all the basic requirements we mentioned above.</p><p>In other words, yes!, we can use them and accomplish all our needs, but I have to admit, it’s a bit annoying to jump between 3 different debugging tools. Wouldn’t it be nice if they were all combined into a single debugger tool?</p><h4><a href="https://github.com/jhen0409/react-native-debugger">react-native-debugger</a></h4><blockquote>The standalone app based on official debugger of React Native, and includes React Inspector / Redux DevTools etc.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCl3EN8_0CrcI_TgaRAdHw.png" /><figcaption>react-native-debugger</figcaption></figure><p>react-native-debugger is all-in-one debugger.</p><p>It includes -</p><ol><li>chrome-devtools - which gives us the ability to <strong>debug scripts and components.</strong> We can also <strong>inspect network requests</strong> using the “network” tab if the network inspection is enabled. To enable network inspect, open the <a href="https://github.com/jhen0409/react-native-debugger/blob/639c02c0f3385c83e62b0ca483cb989db0e4b1a4/docs/shortcut-references.md#context-menu">context menu</a> (right-click on the left panel) and select “Enable Network Inspect”.</li></ol><p>2. react-devtools - which gives us the ability to <strong>debug the react component hierarchy</strong> and <strong>profile components</strong> the same way we did, using the standalone react-devtools.</p><p>All our requirements were met with a single debugging tool, and there are even more features beyond our basic requirements such as <a href="https://github.com/jhen0409/react-native-debugger/blob/639c02c0f3385c83e62b0ca483cb989db0e4b1a4/docs/redux-devtools-integration.md">redux-devtools</a> and <a href="https://github.com/jhen0409/react-native-debugger/blob/639c02c0f3385c83e62b0ca483cb989db0e4b1a4/docs/debugger-integration.md#global-variables-in-console">global variables</a>.</p><h4>Flipper</h4><blockquote>Flipper is a platform for debugging iOS, Android and React Native apps. Visualize, inspect, and control your apps from a simple desktop interface. Use Flipper as is or extend it using the plugin API.</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f2rGWRnCFFgjZbCop_YXYA.png" /><figcaption>flipper</figcaption></figure><p>Flipper is built as a platform. In addition to using the tools already included, you can create your own plugins to visualize and debug data from your mobile apps. Flipper takes care of sending data back and forth, calling functions, and listening for events on the mobile app. Flipper is just a communication channel between the desktop app and your application. Its true power comes from its plugins.</p><p>Flipper provides several features out of the box, some of them are:</p><ul><li>Native Layout Inspector - View and edit the native layout output by the React Native renderer</li><li>Images - Inspect what images were fetched, where they are coming from and selectively clear caches.</li><li>React DevTools - Integration with the react-devtools</li><li>Network inspector</li></ul><p>Starting from version 0.62, React Native includes <a href="https://reactnative.dev/blog/2020/03/26/version-0.62">support for Flipper by default</a>.</p><h4>Conclusion</h4><p>The official tools for debugging react-natvie should meet all our basic debugging needs. Alternatively, there’s the react-native-debugger tool, which integrates the chrome-devtools as well as the react-devtools into a single tool. <br>For more complex scenarios I would use Flipper as it has some advanced features and plugins that the other tools are missing.</p><p>If you are familiar with other tools or you want to share your thoughts, please leave a comment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=de1f5396fe83" width="1" height="1" alt=""><hr><p><a href="https://medium.com/att-israel/debugging-react-native-de1f5396fe83">Debugging React Native</a> was originally published in <a href="https://medium.com/att-israel">AT&amp;T Israel Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Should You Avoid Using Static?]]></title>
            <link>https://medium.com/att-israel/should-you-avoid-using-static-ae4b58ca1de5?source=rss-51e6d00f8c33------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae4b58ca1de5</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Israel Zablianov]]></dc:creator>
            <pubDate>Thu, 18 Jun 2020 13:30:40 GMT</pubDate>
            <atom:updated>2020-06-22T13:17:23.179Z</atom:updated>
            <content:encoded><![CDATA[<h4>You must have heard that static is considered bad or even evil, a complete disaster for your software architecture. But why? Surely there must be a trade-off between advantages and disadvantages, so let’s have a look.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*N7Z1KVvjzHUZJB81" /><figcaption>Photo by <a href="https://unsplash.com/@cdr6934?utm_source=medium&amp;utm_medium=referral">Chris Ried</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>As a young junior software engineer, I was taught that static is a bad way of coding and that one should always avoid using it no matter what. Back then I didn’t understand why. I thought that static could be useful and more efficient. Over the years I learned what the disadvantages are, and I completely agree that <strong>one should always avoid using static</strong>.</p><p>In this article, I am using <a href="https://www.typescriptlang.org/index.html">Typescript</a> for references and examples but the same idea can be applied for any other programming languages that support static.</p><p>Let’s break down the different use cases of static.</p><h3>1. Static Methods</h3><h4>Classes with static and non-static methods.</h4><p>This is the most common use of static that I keep seeing. Here’s an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ecf26cd6ac0c4a0942ffbf0730494ed/href">https://medium.com/media/0ecf26cd6ac0c4a0942ffbf0730494ed/href</a></iframe><p>What is wrong with it?</p><ul><li>Static methods inside a class are usually a good indication of <strong>a method that doesn’t belong to this particular class</strong>. It doesn’t use the state of the class or other non-static members that the class has, and therefore, they break the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a>.</li><li><strong>Static methods are</strong> <strong>not </strong><a href="https://en.wikipedia.org/wiki/Polymorphism_(computer_science)"><strong>polymorphic</strong></a>. The definition of polymorphism is the use of a single <a href="https://en.wikipedia.org/wiki/Interface_(computing)">interface</a> for entities of different <a href="https://en.wikipedia.org/wiki/Data_type">types</a>. So, by definition, static is not polymorphic. The Static method belongs to the class and not to the class instance, therefore you can’t achieve polymorphism with static.</li><li><strong>Static methods</strong> <strong>can’t be used for</strong> <a href="https://en.wikipedia.org/wiki/Abstraction_(computer_science)"><strong>abstraction</strong></a><strong> and </strong><a href="https://en.wikipedia.org/wiki/Inheritance_(object-oriented_programming)"><strong>inheritance</strong></a>. You can’t declare a static method in an interface or static abstract method in an abstract class. A static method cannot access non-static class level members, not its own, nor its base class. (Even though in TypeScript and Java, a derived class inherits its base class static members, it still doesn’t fit well as mentioned).</li><li><strong>Static methods are bad for testability</strong>. Since static methods belong to the class and not a particular instance, mocking them becomes difficult and dangerous. Overriding a static method is not that simple for some languages. Even if you succeed, it will affect other tests that rely on the original implementation and lead to <strong>mutations</strong> that you didn’t expect to be.</li></ul><p>Static methods aren’t associated with any object. It is even wrong to call them methods. They are functions. <a href="https://stackoverflow.com/questions/155609/whats-the-difference-between-a-method-and-a-function">What’s the difference between a method and a function?</a></p><p><strong>For the above reasons, it is easy to notice that static functions break the OOP concepts.</strong></p><p>Given all these downsides, surely there must be some advantages, some trade-off against all these disadvantages? Well, not really.</p><blockquote>One of the most common arguments is, why demand that consumers of our class create an instance for invoking this single method, while having no use for the instance afterwards? Creating an instance of a class is a very very cheap operation in most languages, so speed is not an issue. Adding an extra line of code to the consumer is a low cost for laying the foundation of a much more maintainable solution in the future. And finally, if you want to avoid creating instances, simply create a singleton wrapper of your class that allows for easy reuse.</blockquote><h3><strong>2.</strong> Static Classes</h3><h4><strong>Classes with only static methods.</strong></h4><p>In C#, for example, you even have the feature of a static class. Let’s look at an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/73718e34d89813cd8b6e90a465299382/href">https://medium.com/media/73718e34d89813cd8b6e90a465299382/href</a></iframe><p>A static class can’t contain non-static members.</p><blockquote>A <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/static">static</a> class is basically the same as a non-static class, but there is one difference: a static class cannot be instantiated.</blockquote><blockquote>A <a href="https://www.c-sharpcorner.com/article/when-to-use-static-classes-in-c-sharp/">static</a> class cannot be instantiated. All members of a static class are static and are accessed via the class name directly, without creating an instance of the class.</blockquote><p>As for today in <a href="https://www.typescriptlang.org/index.html">TypeScript</a> <a href="https://www.typescriptlang.org/docs/handbook/release-notes/typescript-3-9.html">v3.9</a>, we still don’t have this feature. We can achieve a similar behavior, for example, using a private constructor. In this article, I will refer to classes with only static members as static classes.</p><p>There isn’t much of a difference between a static and non-static class regarding the use of them. All the reasons mentioned above in “<strong>Classes with static and non-static methods” </strong>except the <a href="https://en.wikipedia.org/wiki/Single-responsibility_principle">Single Responsibility Principle</a> still apply here.</p><p>There are some arguments in favor of static classes when it makes sense. Here are some examples:</p><blockquote><a href="https://www.c-sharpcorner.com/article/when-to-use-static-classes-in-c-sharp/">A Math class with all static methods. Static classes are useful and provide an easy way to access its members that does not need to work differently for different objects.</a></blockquote><blockquote><a href="https://www.c-sharpcorner.com/article/when-to-use-static-classes-in-c-sharp/">App Configuration class that has all static settings about an app and the values of settings don’t change based on the objects or users.</a></blockquote><blockquote><a href="https://www.c-sharpcorner.com/article/when-to-use-static-classes-in-c-sharp/">A DatabaseConfig class that may have members such as database name, server name, port number, and even a connection string. We know that these values will not change for objects.</a></blockquote><p>I don’t find these arguments very convincing. Those use cases can be easily done using singletons or constant variables, which makes it easier for future maintenance without getting the cons of static.</p><h3>3. Static <strong>variables</strong></h3><h4>Classes with static fields/properties.</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a32eb534c5e769b83847e3743a3c4a2/href">https://medium.com/media/5a32eb534c5e769b83847e3743a3c4a2/href</a></iframe><p>Besides all the cons that we mentioned above regarding static methods, static fields have more disadvantages and are considered by many as much worse.</p><ul><li><strong>Static variables represent a global state. </strong>Without proper handling, a global state can be a nightmare. The modification of the state can be from everywhere, leading to unexpected mutations across your software and tests.</li><li><strong>Memory leaks. </strong>The <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Garbage Collector</a> is the memory manager of your app. Objects that are no longer referenced by any variable or collection are garbage collected. Static members are referenced by their classes and not by a particular object instance, and since the class itself won’t be <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Memory_Management">Garbage Collected</a> even once you’re done using it, the memory of a static variable that referenced by this class cannot be garbage collected. <strong>A static variable will persist for the lifetime of the app.</strong></li></ul><h3>Summary</h3><p>There are different uses for static and all of them have some serious disadvantages. In this article, I focused on <strong>Static Methods</strong>, <strong>Static Classes,</strong> and <strong>Static Variables</strong>.</p><p>The disadvantages I mentioned are:</p><ul><li>Single responsibility principle</li><li>Polymorphism</li><li>Inheritance</li><li>Abstraction</li><li>Testability</li><li>Global state</li><li>Memory leaks</li></ul><p>There are more use cases and disadvantages for static and they are different from one programming language to another. In this article, I tried to bring the most common use cases I keep seeing.</p><p>For the use cases above I didn’t find a good enough reason to use static except for laziness :) or maybe a quick solution for a <a href="https://en.wikipedia.org/wiki/Proof_of_concept">POC</a>. Although there may be some different use cases for the static keyword, e.g., <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods">extension methods</a> in C# and <a href="https://www.javatpoint.com/static-nested-class">static nested class</a> in Java.</p><p>In my opinion, one should always avoid using static.</p><p>I hope you enjoyed the read.</p><p>Extra articles and resources to look at:</p><ul><li><a href="https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil">https://stackoverflow.com/questions/7026507/why-are-static-variables-considered-evil</a></li><li><a href="https://gbracha.blogspot.com/2008/02/cutting-out-static.html">https://gbracha.blogspot.com/2008/02/cutting-out-static.html</a></li><li><a href="https://www.beyondjava.net/should-you-avoid-or-embrace-static">https://www.beyondjava.net/should-you-avoid-or-embrace-static</a></li><li><a href="https://simpleprogrammer.com/static-methods-will-shock-you/">https://simpleprogrammer.com/static-methods-will-shock-you/</a></li><li><a href="http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/">http://misko.hevery.com/2008/12/15/static-methods-are-death-to-testability/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae4b58ca1de5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/att-israel/should-you-avoid-using-static-ae4b58ca1de5">Should You Avoid Using Static?</a> was originally published in <a href="https://medium.com/att-israel">AT&amp;T Israel Tech Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>