<?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 Erich Oliveira on Medium]]></title>
        <description><![CDATA[Stories by Erich Oliveira on Medium]]></description>
        <link>https://medium.com/@ericholiveira?source=rss-51fe3dc584d5------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*BIu5_XR2aiyL_0LI.jpg</url>
            <title>Stories by Erich Oliveira on Medium</title>
            <link>https://medium.com/@ericholiveira?source=rss-51fe3dc584d5------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 22:55:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ericholiveira/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[Agents are writing and reviewing code. Who tells the final approver where to look?]]></title>
            <link>https://ericholiveira.medium.com/agents-are-writing-and-reviewing-code-who-tells-the-final-approver-where-to-look-8cb267de5888?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8cb267de5888</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[devtools]]></category>
            <category><![CDATA[open-source]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Wed, 28 Oct 2026 15:03:49 GMT</pubDate>
            <atom:updated>2026-10-28T15:03:49.713Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_NbG9BD7GLNjyDgXBAMF4Q.png" /></figure><p>Nowadays we are creating a lot more pull request, mostly using AI, and we are also using an AI reviewer to do the first pass. The bottleneck resides now in the last approval which still is human-based (and should be). When a person opens a 30 file PR, he doesnt know which files deserves more attention, giving it roughly the same attention (in most cases almost none), as no tools shows which files deserves more attention.</p><p>Risk in a PR is distributed evenly, so attention also shouldn`t. A one-line change in a model used by several endpoints, a new route shadowing old ones, a major dependecy bump, or the changed lines that no test ever run deserves more attention then a renamed variable in a leaf component.</p><p><a href="https://github.com/winnin/farol">farol</a> is an open source tool that was created to answer, basicalle, two questions for the approver before they start:</p><p>1. <strong>**How risky is this merge?**</strong> A grade from 0 to 100 and a verdict: fast track, quick review or careful review. No LLM involved, just static analysis, idempotent and predictable.</p><p>2. <strong>**Where does the risk live?**</strong> Which files, untested code, contract broken in API. Also what to test/check by hand. It builds a call graph for every change, the more central is the node in the graph, the riskier is the change.</p><h4><strong>How it works</strong></h4><p>farol is static analysis ONLY. No AI/LLM is involved in the score, so it is idempotent and reproducible by construction, no hallucination and it never executes the code nor touches the network while analyzing it.</p><p>It works building the project’s dependency graph using the standard tools (Typescript compiler, `go/types` for Go and `ast` for Python), and for each changed file it works out the REACH of it, and walks back from every changed line to the entry points using it: React routes, Next.js pages, GraphQL operations, REST endpoints, CLI commands, FastAPI routes, Go handlers, Temporal workflows and more.</p><p>Then it reads the coverage report your CI already creates and keeps only what touches the changed lines:</p><p>- <strong>**diff coverage**</strong>: how well covered by test the changed lines are and which changed lines ran in the tests;</p><p>- <strong>**lint and security**</strong> on changed lines;</p><p>- <strong>**dependency changes and advisories**</strong>: a major bump, a `0.x` minor, a vulnerable package;</p><p>- <strong>**API contract changes**</strong>: removed response fields or new required argument.</p><p>It weights each signal becomes a weight and the final score is sum of it.</p><p>The more central a file is (more entry points reach it) bigger is the weight, it decreases when the more the changed lines are covered by tests. A breaking contract change weighs a lot. A file that only declares types weighs almost nothing.</p><h4><strong>What the reviewer sees</strong></h4><p>The final result is an HTML artifact which farol can post as a comment on the pull request:</p><p>- the merge risk and the verdict;</p><p>- one sentence on where the risk comes from;</p><p>- <strong>**Must check**</strong>: what has to be verified by hand (breaking API changes, security findings, vulnerable dependencies, anything farol could not read);</p><p>- the High and Medium risk files, each with its share of the score and its coverage.</p><p>With this you can decide if you want to approve directly or review the files deserves more your attention, every time you check a file or risk it recalculates automatically the total risk, so you can approve as soon as you feel confident. It also includes other relevant informations, like who knows the file (through git blame). At the end, <em>*Results*</em> gives you a Markdown summary of what you checked, to paste back into the PR.</p><p>There is a [live demo on a FastAPI + React PR](https://winnin.github.io/farol/demo/) where you can try the whole flow.</p><h4><strong>A real example</strong></h4><p>The demo is the artifact based on PR to FastAPI full-stack template. It gives a score of 69/100, with <strong>**careful review**</strong> needed, the first comment is:</p><p>&gt; Most of the risk comes from a breaking change to `GET /api/v1/items/` and a security finding in `items.py`.</p><p>The PR added a breaking change when it removed the `count` field from the API response. It also finds a security issue on a SQL created using f-string. Neither of it is in the biggest file in this PR. The model file used in 23 endpoints is fully tested and for this reason it weight less in the final result.</p><h4><strong>What it does not do</strong></h4><p>It does not approve or blocks anything. The idea is to inform the person so he can decide the amount of effor he will put in this PR. It also does not replace reading the code. The point is to tell you which part to read first and most carefully.</p><p>It uses a heuristic. On large PRs it saturates (a 37-file PR easily reaches 90+), and there the count of reviewed files says more than the number. But even in that scenario you can easily find what are the riskiest files and give more attention to it, as it shows the individual risk for each file.</p><h4><strong>How it got here</strong></h4><p>The first version was posted on Show HN last weekend. We received a lot of feedback on the final report being larger than it should be, and also bad UI/UX. But even with that we received 100+ stars in a single day on github, it sinalizes to me that other people are suffering the same problem. Since the feedback i’ve already launched a new release with way better UI/UX and more straightforward findings.</p><p>farol also reviews itself.</p><h4><strong>Try it</strong></h4><p>To see it working and get the comment and the report on every pull request on your repo, add the GitHub Action ([setup in the README](https://github.com/winnin/farol#get-started)) and point it to your coverage and lint reports.</p><p>Currently we support: React (React Router, Next.js, TanStack Router), TypeScript backends (GraphQL, REST, CLIs), Go (chi, gin, echo, net/http, gRPC) and Python (FastAPI, Flask, Django, Celery and more). MIT licensed.</p><p>Feedbacks are highly welcomed, and would love to know which languages/frameworks you wanna see it supporting next.</p><p>If anything looks wrong on your code, please [open an issue](https://github.com/winnin/farol/issues). That is how we can keep improving the platform.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8cb267de5888" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Reduce in javascript (Part 2)]]></title>
            <link>https://winnintech.winnin.com/implementing-reduce-in-javascript-part-2-922b884e086c?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/922b884e086c</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[node]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[frp]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Fri, 18 May 2018 01:30:58 GMT</pubDate>
            <atom:updated>2018-05-22T22:53:30.863Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NNVZUNW_Fxi5f0FEeWR1g.jpeg" /></figure><p><em>You can see the part 1 here: </em><a href="https://medium.com/@ericholiveira/implementing-reduce-in-javascript-part-1-7ea8711e194"><em>https://medium.com/@ericholiveira/implementing-reduce-in-javascript-part-1-7ea8711e194</em></a></p><p>On last week we talked about reduce. We learned what it is, how to implement and finally how to use it to implement some other common functions.</p><p>This week we will learn how we can implement the function <em>map</em>, <em>filter</em> and <em>flatMap</em> using only the <em>reduce</em> function, and as a bonus we will see how we can serialize the execution of promises using it.</p><p>Implementing a function is the best way to learn how to use it, so lets skip to implementation :)</p><p><strong>Map</strong></p><p>Our <em>map</em> function receives two parameters, an array and a function. The result of it is a new array containing the result of the execution of the given function to each element of the given array.</p><p>Implementing it using only the <em>reduce</em> function:</p><pre><strong>const </strong>map = <strong>function</strong>(iterable,fn){<br>  <strong>return </strong>reduce(iterable,(acc,n)=&gt;acc.concat([fn(n)]),[])<br>}<br>console.log(map([1,2,3],i=&gt;i+1)) //Prints [2,3,4]</pre><p><em>This surely isn&#39;t the best implementation for the map function, i will be using it just to show how far we can go with reduce.</em></p><p>To implement the map function, we call the reduce function passing the given array, a functions and an empty array which will be used as the accumulator and will be returned by map.</p><p>The function passed as the second parameter of reduce, is really simple, it just accumulate in the new array the result of the mapping function (in our example i=&gt;i+1) for each element of the given array.</p><h4>Filter</h4><p>The <em>filter</em> function also receive two parameters, the array, and a condition function. The result of it is a new array containing only the elements satisfying the given condition.</p><pre><strong>const </strong>filter = <strong>function</strong>(iterable,fn){<br>  <strong>return </strong>reduce(iterable,(acc,n)=&gt;fn(n)?acc.concat([n]):acc,[])<br>}<br>console.log(filter([1,2,3,4],i=&gt;i&lt;3)) // Prints [1,2]</pre><p>As you can see the implementation is similar to that used on map, but now, the function passed to reduce, checks if the current element satisfies the given condition and if it is true, puts it in the result.</p><h4>FlatMap</h4><p>Look at the following code:</p><pre>console.log(map([1,2],i=&gt;[i,i+1])) //Prints [[1,2],[2,3]]</pre><p>When we are using the map function, if the result of the passed function is also an array, the result will be an array of arrays. If what we want is to flat this to be a simple array of elements, we will use flatMap.</p><p>Putting it simple, flatMap, basically do the mapping and then flatten the result.</p><p>The implementation of it is also really simple:</p><pre><strong>const </strong>flatMap = <strong>function</strong>(iterable,fn){<br>  <strong>return </strong>reduce(iterable,(acc,n)=&gt;acc.concat(fn(n)),[])<br>}<br>console.log(flatMap([1,2],i=&gt;[i,i+1]))//Prints [1,2,2,3]</pre><p>The implementation is similar to map, the only change is that we do <em>concat(fn(n))</em> instead of <em>concat([fn(n)])</em> (on the map function), because in the first case, if the result of <em>fn(n)</em> is an array it will concatenate with the accumulator array keeping a flat structure.</p><h4>Promises</h4><p>For the last another really cool use of reduce is to use it to execute promises one after another and accumulate the result.</p><pre><strong>const </strong>sumPromises = <strong>function</strong>(promiseFunctions){<br>  <strong>return </strong>reduce(promiseFunctions,<strong>async </strong>(accPromise,next)=&gt;{<br>    <strong>const </strong>accumulator = <strong>await </strong>accPromise<br>    <strong>const </strong>currentResult = <strong>await </strong>next()<br>    <strong>return </strong>accumulator + currentResult<br>  },Promise.resolve(0))<br>}<br><strong>const </strong>promiseFunctions = [<br>  ()=&gt; Promise.resolve(1),<br>  ()=&gt; Promise.resolve(2),<br>  ()=&gt; Promise.resolve(3)<br>]<br><br>sumPromises(promiseFunctions).then(console.log)// Prints 6</pre><p><em>Take your time to look at the code above.</em></p><p>The sumPromises functions receives an array of asynchronous functions, we use reduce over this array, passing also a async function, this async function waits for the last promise and stores the result in the <em>accumulator</em> constant, then waits for the next promise and stores the result in the <em>currentResult</em> constant, and finally returns the sum. Notice this is an async function so the return is a promise containing the sum. We start the accumulator of the reduce function with a promise containing the value 0.</p><p>Thats it, clap if you liked, and don’t forget to follow me here and on twitter <a href="https://twitter.com/Oliveira_Erich">https://twitter.com/Oliveira_Erich</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=922b884e086c" width="1" height="1" alt=""><hr><p><a href="https://winnintech.winnin.com/implementing-reduce-in-javascript-part-2-922b884e086c">Implementing Reduce in javascript (Part 2)</a> was originally published in <a href="https://winnintech.winnin.com/">winnintech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Reduce in javascript (Part 1)]]></title>
            <link>https://winnintech.winnin.com/implementing-reduce-in-javascript-part-1-7ea8711e194?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/7ea8711e194</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[mapreduce]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[node-for-begginners]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Thu, 10 May 2018 02:04:27 GMT</pubDate>
            <atom:updated>2018-05-10T21:03:52.237Z</atom:updated>
            <cc:license>http://creativecommons.org/publicdomain/zero/1.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-NNVZUNW_Fxi5f0FEeWR1g.jpeg" /><figcaption>Daily javascript :)</figcaption></figure><p>I&#39;ve spent a lot of time trying to learn the map/reduce functions, and more after that trying to use it in a daily basis.</p><p>For this reason i&#39;ve decided to write this tutorial, but i don&#39;t want to simply explain how/when to use this function, we are going to implement the <em>reduce</em> function together, and using ONLY this function we are going to implement map, filter, flatMap and some other function to work with iterable objects.</p><h4>Why implement reduce?</h4><p>Because it will help you to understand how the function works, and you will be able to use it to any iterable object in javascript (like Set and Map), also you can implement it in any language you&#39;re using.</p><h4>WTF is reduce?</h4><p>The <em>reduce</em> function returns the result of applying a given function to an iterable object, accumulating the result in each iteration. So the idea is (like the name says) to transform the iterable object in a single object (or a &quot;smaller &quot;iterable), so it is perfect to sum all the elements of an array for instance.</p><h4>Implementing reduce</h4><p>A possible implementation for reduce is:</p><pre><strong>const </strong>reduce = <strong>function</strong>(iterable, reduceFn, accumulator){<br>  <strong>for</strong>(let i <strong>of </strong>iterable){<br>    accumulator = reduceFn(accumulator, i)<br>  }<br>  <strong>return </strong>accumulator<br>}</pre><p>As you can see our reduce function receive 3 parameters, the first one is the iterable object, the second the function (<em>reduceFn</em>) to be applied to each element of the iterable object (this function receives 2 parameters, the first is the accumulator and the second an elemento of the iterable object), the last is an initial value for the accumulator.</p><p>Looking at this implementation, we can see that reduce is just an iteration over each element of an iterable which substitutes the accumulator for the result of applying the given function to the current accumulator value and the next element.</p><p>We can test our code using it to sum all the elements in an array:</p><pre>console.log(reduce([1,2,3], (acc,elem)=&gt;acc+elem , 0)) // Prints 6</pre><p>If you go step-by-step, in the first iteration the accumulator is 0 and the element is 1, so it will accumulate 1 (0 + 1), on the second iteration the accumulator is 1 (from the previous iteration) and the next element is 2, so it accumulates 3 (1 + 2), for the last iteration the accumulator is 3 (from the previous iteration) and the next element is 3, so it accumulates 6 (3 + 3), since we don&#39;t have any other elements, we return the accumulator (6).</p><p>Our reduce function uses <strong>for … of</strong> and for this reason can be applied to any iterable object in javascript as a Set:</p><pre><strong>const </strong>mySet = <strong>new </strong>Set([1,2,3])<br>console.log(reduce(mySet, (acc,elem)=&gt;acc+elem , 0)) // Prints 6</pre><p>Now we can implement new functions using only reduce. We already seem how easy it is to implement a sum function:</p><pre><strong>const </strong>sum = <strong>function</strong>(iterable){<br>  <strong>return </strong>reduce(iterable ,(acc, elem)=&gt; acc+elem, 0)<br>}<br>console.log(sum(1,2,3)) // Prints 6</pre><p>That was easy, now how we can find the maximum number in an array:</p><pre><strong>const </strong>max = <strong>function</strong>(it){<br>  <strong>return </strong>reduce(it,(acc, elem)=&gt; Math.max(acc,elem),it[0] )<br>}<br>console.log(max([0,2,3,-1,9])) // Prints 9</pre><p>Or the minimum:</p><pre><strong>const </strong>min = <strong>function</strong>(it){<br>  <strong>return </strong>reduce(it,(acc, next)=&gt; Math.min(acc,elem),it[0])<br>}<br>console.log(max([0,2,3,-1,9])) // Prints -1</pre><p>On the next post we will see what is and how to implement the functions map, filter and flatMap using ONLY the reduce function.</p><p><em>Ps: Clap if you liked, and don&#39;t forget to follow me here and on twitter @oliveira_erich</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7ea8711e194" width="1" height="1" alt=""><hr><p><a href="https://winnintech.winnin.com/implementing-reduce-in-javascript-part-1-7ea8711e194">Implementing Reduce in javascript (Part 1)</a> was originally published in <a href="https://winnintech.winnin.com/">winnintech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Short-circuit operators in javascript]]></title>
            <link>https://medium.com/series/short-circuit-operators-in-javascript-8a60517c5902?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a60517c5902</guid>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Wed, 09 May 2018 02:03:01 GMT</pubDate>
            <atom:updated>2018-05-09T02:03:01.270Z</atom:updated>
            <content:encoded><![CDATA[<p>AND ( &amp;&amp; )</p><p>If the first value is &quot;falsy&quot; returns it, otherwise returns the next</p><p>false &amp;&amp; false //false</p><p>false &amp;&amp; true // false</p><p>true &amp;&amp; true // true</p><p>0 &amp;&amp; 1 // 0</p><p>10 &amp;&amp; 800 // 800</p><p>39 &amp;&amp; &quot;bhd&quot; &amp;&amp; {} //{}</p><p>OR ( || )</p><p>If the first value is “truthy” returns it, otherwise returns the next</p><p>false || false //false</p><p>false || true // true</p><p>true || true // true</p><p>0 || 1 // 1</p><p>10 || 800 // 10</p><p>39 || “bhd” || {} //39</p><p>COMMA ( , ):</p><p>Always return the last element</p><p>false , false //false</p><p>false , true // true</p><p>true , true // true</p><p>0 , 1 // 1</p><p>10 , 800 // 800</p><p>39 , “bhd” , {} //{}</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a60517c5902" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nodejs microservices. From Zero to Hero. Pt3 (Plugins and clustering)]]></title>
            <link>https://ericholiveira.medium.com/nodejs-microservices-from-zero-to-hero-pt1-plugins-and-clustering-ddb60e9a8ee0?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddb60e9a8ee0</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[studiojs]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Thu, 12 May 2016 00:27:40 GMT</pubDate>
            <atom:updated>2016-05-20T01:40:44.550Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s time for a new post teaching the basics of <a href="https://github.com/ericholiveira/studio">studio</a> and how to implement microservices in nodejs.</p><p>On the past weeks we talked about the <a href="https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt1-279548cb4080#.nvwvbzchz">motivations</a> and learned the <a href="https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt2-72fbb2a1b1c4#.8u0ji451q">basic microservice implementation using studio</a> , now on part 3 we will learn how to distribute the services and add some plugins like realtime metrics.</p><p>Studio plugins are based on <a href="https://en.wikipedia.org/wiki/Aspect-oriented_programming">aspect-oriented programming</a> , besides the weird name it is REALLy easy to use.</p><p>A plugin lets you add behavior that are not central to business logic, so with a plugin you can, track the time needed to execute a service call, adds a timeout to the service or event try again in case of errors among other possibilities, the sky is the limit.</p><p>Plugins must be the first thing you add on your code, and it is really simple to use, just add a line of code and you’re ready to go:</p><pre>studio.use(SOME_PLUGIN);</pre><p>The “use” methods accepts up to 2 parameters, the first one is the plugin itself and the second one is a filter for that plugin, the filter might be a function, a string, a regex or an array of filters, so the following code enables the SOME_PLUGIN plugin to the service named foobar:</p><pre>studio.use(SOME_PLUGIN,&#39;foobar&#39;);</pre><p>Now lets go back to the code of the past week, lets change the all_services.js file to support 2 plugins, the retry plugin and the timer plugin, to do this we use the code above:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3fe04b8016058e4a5a808e3463c845a7/href">https://medium.com/media/3fe04b8016058e4a5a808e3463c845a7/href</a></iframe><p>The timer plugin calculates the time to execute every service call, when adding this plugin it automatically binds to all started services, after calculating this time, it calls the function it received as parameter with time info. On this example we just want to log it to the console, but you could easily send it to <a href="https://github.com/etsy/statsd">StatsD</a> or any other place.</p><p>Now running the code with the timer plugin it is going to print the time taken to execute the services.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/438/1*l07_MBBXaq6M93pGkEhoZw.png" /><figcaption>Time taken to execute each service call</figcaption></figure><p>The retry plugin lets you decide to retry a service call in case of failure, so lets add a code on reddit_service.js to retry one time in case of failure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9db40691c9bc01076897e6906ef23d82/href">https://medium.com/media/9db40691c9bc01076897e6906ef23d82/href</a></iframe><p>The line 25 tells the service to retry 1 time the search in case of any failure on the searchForContent service.</p><p>Adding a plugin is just that simple, now you might be wondering how hard it would be to distribute your code…</p><p>Never forget:</p><p><em>“ A cluster is just another plugin”.</em></p><p>So lets distribute our application.</p><p>I’m going to create a cluster of 2 process on the same machine, just because most of the readers will have only one machine available, but i will also show the code to multiple machines.</p><p>So first, lets npm install the cluster plugin</p><pre>npm install studio-cluster --save</pre><p>Now we can change our all_services.js to add this plugin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb49cf7a806a4e3a53cac03e86008375/href">https://medium.com/media/fb49cf7a806a4e3a53cac03e86008375/href</a></iframe><p>We have only 2 changes, first we required the studioCluster plugin, and added it using port 8001 to enable service communication. And then we removed the require of youtube_services, if we execute all_services.js now and hit <a href="http://localhost:3000/new">http://localhost:3000/new</a> it is going to print the following error on console:</p><pre>Unhandled rejection ROUTE_NOT_FOUND: The route Youtube/fetch doesnt exists</pre><p>So its telling us it wasn’t able to find a service named Youtube/fetch, but to fix this all we need to do is, add the cluster plugin on youtube_service.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c15d492ae885fc3fcbd9cdf768315fcb/href">https://medium.com/media/c15d492ae885fc3fcbd9cdf768315fcb/href</a></iframe><p>We are using a different rpcPort, just because im running on the same machine, by default studio-cluster use the port 10120 to communication, so if you’re in different machines you don’t need to pass this parameter.</p><p>Now you can run youtube_service.js (you don’t need to stop all_services.js, they are going to find each other):</p><pre>node youtube_service.js</pre><p>Then when you hit <a href="http://localhost:3000/new">http://localhost:3000/new</a> again you will see your response with no error, running exactly like it was a single process.</p><p>Studio-cluster is built on top of <a href="https://github.com/primus/primus">primus</a> and websockets, so it can handle reconnections, timeouts, unexpected crash or any other problem of communication, the cluster does the best effort possible to keep everything running no matter what.</p><p>But… What if you want to distribute your services across the globe?</p><p>It is important to learn how to distribute your application if you have several machines to use. If all those machines are on the same network and this network have a broacast feature, than no configuration is required:</p><pre>studio.use(studioCluster());</pre><p>If you’re running on multiple networks than studio cluster needs a redis server to handle the service discovery and the following code does the work:</p><pre>var rpcPort = 10120;//any port<br>Studio.use(studioCluster({ <br>   rpcPort:rpcPort, <br>   publisher:studioCluster.publisher.redis(rpcPort,&#39;REDIS_ADDRESS&#39;)}<br>));</pre><p>Its also important to notice that redis is used ONLY to service discovery, so the real service call is done through websocket and the cluster can handle unexpected crashes or any other issue.</p><p>I think now you agree with me when i say that is REALLY easy to distribute services using studio.</p><p>The final code for this post is available at:<a href="https://github.com/ericholiveira/example-studio-microservices/tree/pt3">https://github.com/ericholiveira/example-studio-microservices/tree/pt3</a></p><p>See you next week.</p><blockquote>Wants to learn more? Join our slack channel:<a href="https://studiojs.herokuapp.com/">https://studiojs.herokuapp.com/</a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddb60e9a8ee0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nodejs microservices. From Zero to Hero. Pt2 (Basic usage)]]></title>
            <link>https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt2-72fbb2a1b1c4?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/72fbb2a1b1c4</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[studiojs]]></category>
            <category><![CDATA[adopting-microservices]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Fri, 06 May 2016 00:24:18 GMT</pubDate>
            <atom:updated>2016-06-15T19:46:51.190Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This is part 2 of a series of posts on motivations for microservices on nodejs and how to implement it using </em><a href="https://github.com/ericholiveira/studio"><em>Studio</em></a><em> . You can read Part 1 </em><a href="https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt1-279548cb4080#.szdykdnbr"><em>here</em></a><em>.</em></p><p>On this new post we will finally start to implement our microservices the final code for this post is available on github <a href="https://github.com/ericholiveira/example-studio-microservices/tree/pt2">here</a> , I will keep the main project with a branch for each new post, so the branch for this post is <a href="https://github.com/ericholiveira/example-studio-microservices/tree/pt2">pt2</a>.</p><p>We are going to implement a simple web application, it is basic, but will help us to see the features and advantages of Studio, on this post we will keep it simple, and on the next we are going to start using plugins and clusterize our application and you will see how we can do big improvements with really small changes.</p><p>On reddit there is a subreddit exclusive for videos (<a href="https://www.reddit.com/r/videos">https://www.reddit.com/r/videos</a>) on this subreddit you can search for the <a href="https://www.reddit.com/r/videos/new/">newest</a>, the <a href="https://www.reddit.com/r/videos/top/">top</a> among other options. Our application consists on a web server listening on port 3000, and when you get a path it will fetch data from reddit, search for this videos on youtube and show title and description, so, if you hit in your browser <a href="http://localhost:3000/new">http://localhost:3000/new</a> it needs to fetch title and description info for all new youtube videos posted on the subreddit videos. Really simple.</p><p>For the implementation I will be using node 4 and some es6 features (class and generators), this wayI can better show you how Studio can also help with code readability. Studio is es6 ready, but is completely compatible with es5 and is able to run on node &gt;= 0.11 . When using es6 features i will also add a gist on how to do this on es5 (or older node versions).</p><p>So, lets start creating our application, to do this create a folder named <a href="https://github.com/ericholiveira/example-studio-microservices">example-studio-microservices</a> (or anything you want), navigate to the folder and type:</p><pre>npm init</pre><p>You can keep hitting enter to choose the default options, then execute the following commands to install the dependencies we will need.</p><pre>npm i express —-save<br>npm i request —-save<br>npm i snoocore —-save<br>npm i studio —-save</pre><p>We will use <em>express</em> for our http server, <em>request</em> to call youtube api, <em>snoocore</em> is the library for reddit api and <em>studio</em> for our services.</p><p>First we will implement the service to fetch video from youtube (you will need a google account and an api key that for youtube data api, you can get it <a href="https://console.developers.google.com/apis/api/youtube/overview?project=apt-theme-130323">here</a>). Create a file called youtube_service.js with the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6af1390d855dc0a428f61f680935d0dd/href">https://medium.com/media/6af1390d855dc0a428f61f680935d0dd/href</a></iframe><p>On the code above we can see some cool features from studio. First studio supports async calls through generators out-of-the-box, normally yield would wait for promises response, but studio have the method Studio.defer which allows you to easily support the old callback interfaces (without the need of promisify all your code).</p><p>The other important thing to notice is, studio services ALWAYS returns a promise, even if you’re just returning a “sync object” (imagine an url from other website, we would return <em>null </em>, but studio handle this so the caller will receive a promise instead of the sync object, this way you <a href="http://blog.izs.me/post/59142742143/designing-apis-for-asynchrony">don’t release zalgo</a>)</p><p>And for the last you will notice we won’t module.exports anything, this happens because studio enables you to create a completely decoupled application, studio have an internal route to deal with service calls.</p><p>Ok, this is cool, now we can go to reddit code, create a file called reddit.js, I’m not going on details on this files this is just basic instantiation of snoocore library, you only need to change the credentials with your own reddit credentials (you will need to create a user on reddit and create a new reddit app <a href="https://www.reddit.com/prefs/apps/">here</a> , mark it as a script) and type the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b57249fcb4399a9e2ab5df22a77856c8/href">https://medium.com/media/b57249fcb4399a9e2ab5df22a77856c8/href</a></iframe><p>And lets implement the reddit services on a file called reddit_service.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52a0140800f6f8863dc64576757df0b2/href">https://medium.com/media/52a0140800f6f8863dc64576757df0b2/href</a></iframe><p>Here the key is to understand that we don’t need to require the youtube_service.js , as i said you are building decoupled services. Also you will see that you can create several services for a class easily. Another cool feature is the yield for an array of promises, this way you can execute concurrent code easily. And again we exports nothing.</p><p>Now we only have to create our server, create a file called express.js:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42f448f7fd1e128a348e85e1f5261be3/href">https://medium.com/media/42f448f7fd1e128a348e85e1f5261be3/href</a></iframe><p>Nothing new on this file, for the last, we need a file to make everything work together (you do need to require all files so studio can load your services), I like to create it in a different file so I can easily create different builds for the project (all services together or groups of service per machine), as we are in the basic, lets create an all_services.js file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/170a145adb525c4a49a17f2ceab3815a/href">https://medium.com/media/170a145adb525c4a49a17f2ceab3815a/href</a></iframe><p>The last important thing here is to note that Studio really don’t mind about orders, you probably remember that reddit service (searchForContent) calls youtube fetch service, so you would expect some kind of order, but studio handles it for you, you can even require ./express for last, you can play with the require order and see it working no matter what.</p><p>To test your application you can run node all_services.js on your terminal and open <a href="http://localhost:3000/new">http://localhost:3000/new</a> on your browser.</p><p>Thats enough for today, on the next post i will teach how to use plugins this way we will create a cluster, log realtime metrics, add timeouts and retries.</p><p>See you.</p><p>Es5 versions of the files:</p><p><a href="https://gist.github.com/ericholiveira/4e6fe70e071eea7ff50f6ecb4e03478f">youtube_service.js</a></p><p><a href="https://gist.github.com/ericholiveira/1cc37ec4a5a189ea6a3e9103b99570bf">reddit_service.js</a></p><p><a href="https://gist.github.com/ericholiveira/36761c3b09af8e837434bcace857ad8e">express.js</a></p><p><em>Pt3 (plugins and clustering) is already available at: </em><a href="https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt1-plugins-and-clustering-ddb60e9a8ee0#.qfm0hayb3"><em>https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt1-plugins-and-clustering-ddb60e9a8ee0#.qfm0hayb3</em></a></p><blockquote><strong><em>Wants to learn more? Join our slack channel:</em></strong><a href="https://studiojs.herokuapp.com/"><strong><em>https://studiojs.herokuapp.com/</em></strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=72fbb2a1b1c4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt2-72fbb2a1b1c4">Nodejs microservices. From Zero to Hero. Pt2 (Basic usage)</a> was originally published in <a href="https://medium.com/adopting-microservices-architecture">Microservices Practitioner Articles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Nodejs Microservices. From Zero to Hero. Pt1 (Motivation)]]></title>
            <link>https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt1-279548cb4080?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/279548cb4080</guid>
            <category><![CDATA[studiojs]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[adopting-microservices]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Sat, 30 Apr 2016 00:21:09 GMT</pubDate>
            <atom:updated>2016-09-27T22:37:33.404Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve decided to create this series of posts explaining what are microservices, how can you make it scale, and how to implement it on nodejs. For this first medium I just want to show you what are the advantages, what are scalable systems and I will start to teach you how to implement it, on the next medium using my brand new framework <a href="https://github.com/ericholiveira/studio">Studio</a> and its plugin for automatic service discovery and remote procedure call <a href="https://github.com/ericholiveira/studio-cluster">Studio-cluster</a> . I also want to talk about what are the next steps for Studio platform.</p><p>First of all, what are microservices? So, copying Martin Fowler’s definition:</p><blockquote><em>The microservice architectural style is an approach to developing a single application as a suite of small services, each running in its own process and communicating with lightweight mechanisms, often an HTTP resource API. These services are built around business capabilities and independently deployable by fully automated deployment machinery. There is a bare minimum of centralized management of these services, which may be written in different programming languages and use different data storage technologies.</em></blockquote><p>The keys concept here are <strong>small services</strong> , <strong>lightweight communication</strong> , <strong>independently deployable</strong> and <strong>minimum management centralization</strong>.</p><p>So what we really need is an architecture where we can create our services COMPLETELY DECOUPLED, this way you can deploy your services in several process or even in several machines without having to rewrite your codebase. The only way to make your services completely decoupled is using message passing for service calls, this message passage system needs to be lightweight (so it can keep your system responsive) and the only way to implement it is having a centralized management.</p><p>Nowadays we have high expectation from our users, they want a system fast, reliable and with 100% uptime,trying to achieve this on different domains, developers found some patterns which can make this possible, and they decided to create the <a href="http://www.reactivemanifesto.org/">reactive manifesto</a> . This manifesto states 4 pillars to achieve scalability, they are:</p><ol><li><strong>Responsive</strong>: Responsive systems focus on providing rapid and consistent response times, establishing reliable upper bounds so they deliver a consistent quality of service. This will improve your system <em>usability</em> and <em>utility.</em></li><li><strong>Resilient: </strong>The system stays responsive in the face of <a href="http://www.reactivemanifesto.org/glossary#Failure">failure</a>.Resilience is achieved by <a href="http://www.reactivemanifesto.org/glossary#Replication">replication</a>, containment, <a href="http://www.reactivemanifesto.org/glossary#Isolation">isolation</a> and<a href="http://www.reactivemanifesto.org/glossary#Delegation">delegation</a>. Failures are contained within each <a href="http://www.reactivemanifesto.org/glossary#Component">component</a>, isolating components from each other and thereby ensuring that parts of the system can fail and recover without compromising the system as a whole. This will improve your system <em>availability</em>.</li><li><strong>Elastic: </strong>The system stays responsive under varying workload.This implies designs that have no contention points or central bottlenecks, resulting in the ability to shard or replicate components and distribute inputs among them. Reactive Systems support predictive, as well as Reactive, scaling algorithms by providing relevant live performance measures.</li><li><strong>Message Driven: </strong>Reactive Systems rely on <a href="http://www.reactivemanifesto.org/glossary#Asynchronous">asynchronous</a> <a href="http://www.reactivemanifesto.org/glossary#Message-Driven">message-passing</a> to establish a boundary between components that ensures loose coupling, isolation and <a href="http://www.reactivemanifesto.org/glossary#Location-Transparency">location transparency</a>. This boundary also provides the means to delegate <a href="http://www.reactivemanifesto.org/glossary#Failure">failures</a> as messages.Location transparent messaging as a means of communication makes it possible for the management of failure to work with the same constructs and semantics across a cluster or within a single host.</li></ol><p>So it’s not that hard to see the resemblance between both, the big problem is, no one wants to care about all the details of how to implement this concepts at the very beginning of a system. Ensuring this four pillars on your code is very hard.</p><p>On a nodejs perspective what you really need to meet this criteria is:</p><ol><li><strong>Router:</strong> To create a message driven system, you need someone capable of finding and delivering messages. A good router also lets you create decoupled system ensuring that you don’t keep a hard reference on your code, and if you don keep a hard reference, this router also have to be ready if you try to call a service that isn’t available. So you’re free from import/require/instantiation order and your system stay responsice even if a service goes down or is deprecated.</li><li><strong>Immutability:</strong> It’s IMPOSSIBLE to distribute a system if you deal with a lot of internal states, imagine that service A calls service B with a parameter foo, if A and B are in the same machine and A relies on B changing foo internal state, this will never work on different process/machines , so if you don’t ensure immutability on day one of your system implementation you cant never say your system is distributable.</li><li><strong>Serializable objects: </strong>Javascript functions are just not serializable, i see on the internet a lot of people trying to create packages to serialize functions using the function code, but none of them will ever work with curry, trying to serialize functions are just unsafe and should be avoid as you avoid eval. This way cant create services based on callbacks you need to use promises.</li><li><strong>Modules/Namespace: </strong>When dealing with lots of services you need some way to avoid name collision on your router, so you need a good namespace based approach</li><li><strong>Plugins: </strong>Thats the way Studio uses to deal with other more specific criterias like realtime perfomance metrics, timeouts, retries, better error tracking, service mocks and other cool stuffs</li></ol><p>Studio implements this 5 concepts, and make it really easy to use. I ensure you that a system built with Studio is way more readable than a system without it because Studio just enforces you to use good practices it also takes off all boilerplate, any regular function in Studio can be a service and have all the advantages. Also Studio is es6 ready, which means it is COMPLETELY written and compatible with es5 and older versions of node, but it really shines on newer versions, is completely up to you to decide if you want a better flow control with generators instead of promises or to use proxies to improve readability.</p><p>It’s enough for today, on the next medium i will teach the key concepts and start to write an example application. See you there.</p><p><em>Pt2 (completely hands-on) is already available at: </em><a href="https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt2-72fbb2a1b1c4#.8hzhqoxeb"><em>https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt2-72fbb2a1b1c4#.8hzhqoxeb</em></a></p><p><em>Pt3 (plugins and clustering) is already available at: </em><a href="https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt1-plugins-and-clustering-ddb60e9a8ee0#.qfm0hayb3"><em>https://medium.com/@ericholiveira/nodejs-microservices-from-zero-to-hero-pt1-plugins-and-clustering-ddb60e9a8ee0#.qfm0hayb3</em></a></p><blockquote><strong>Wants to learn more? Join our slack channel: </strong><a href="https://studiojs.herokuapp.com/"><strong>https://studiojs.herokuapp.com/</strong></a></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=279548cb4080" width="1" height="1" alt=""><hr><p><a href="https://medium.com/adopting-microservices-architecture/nodejs-microservices-from-zero-to-hero-pt1-279548cb4080">Nodejs Microservices. From Zero to Hero. Pt1 (Motivation)</a> was originally published in <a href="https://medium.com/adopting-microservices-architecture">Microservices Practitioner Articles</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Truques com arguments em javascript]]></title>
            <link>https://ericholiveira.medium.com/truques-com-arguments-em-javascript-27942ea807ee?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/27942ea807ee</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Tue, 06 Oct 2015 21:03:45 GMT</pubDate>
            <atom:updated>2015-10-06T21:03:45.421Z</atom:updated>
            <content:encoded><![CDATA[<p>Muitos iniciantes no mundo do js não sabem, mas dentro do escopo de toda função existe uma variável chamada <em>arguments </em>que contém algumas informações sobre aquela execução. Basicamente, essa função indexa todos os argumentos passados como parâmetro para aquela função, então por exemplo:</p><pre>var minhaFuncao = function(a){<br>  console.log(arguments[0]);<br>  console.log(a);<br>  console.log(arguments[1]);<br>};</pre><p>Ao ser executada como:</p><pre>minhaFuncao(&#39;foo&#39;);<br>//imprime<br>foo<br>foo<br>undefined</pre><p>Ou seja, arguments[0] é o primeiro argumento (&#39;foo&#39;), e arguments[1] é o segundo argumento, como nenhum foi passado, imprime &#39;undefined&#39;.</p><p>Se está função fosse executada como:</p><pre>minhaFuncao(&#39;foo&#39;,&#39;bar&#39;);<br>//imprime<br>foo<br>foo<br>bar</pre><p>Veja que agora ela imprime o segundo argumento, mesmo ele não tendo sido declarado. Esse comportamento torna muito fácil instrumentar funções já que você sempre pode ler quais são os argumentos sendo passados (pense numa função que é um proxy para outra função).</p><p>Uma outra coisa importante é que &#39;arguments&#39; não é um array, ele é um objeto que indexa utilizando números como chave, porém existe um truque muito simples para transformá-lo em array caso você precise:</p><pre>function outraFuncao() {<br>    var argumentsArray = Array.prototype.slice.call(arguments);<br>}</pre><p>Uma outra coisa interessante sobre o &#39;arguments&#39; é que ele possui uma propriedade chamada callee, que é um wrapper para a própria função, ele foi criado, porque nos primórdios do javascript não existiam funções nomeadas, e essa era uma forma de referenciar a própria função, esta propriedade já está <em>deprecated,</em> mas continua disponível para a gente, então como sempre gosto de fazer aqui, vou ensinar um pequeno hack usando ela.</p><pre>function foo(){<br>  console.log(arguments.callee.caller.name);<br>}<br>function bar(){<br>  foo();<br>}<br>bar();</pre><p>Alguma ideia do que será impresso na tela???</p><p>…</p><p>…</p><p>…</p><p>…</p><p>Se você disse bar , acertou. arguments.callee.caller é sempre uma referência pra função que chamou nossa função atual, e a propriedade name é o próprio nome de uma função (toda função nomeada possui essa propriedade).</p><p>Essa foi uma dica rápida. Espero que tenham gostado e aprendido um pouco mais sobre o mundo doido do javascript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=27942ea807ee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Slides FRP em javascript]]></title>
            <link>https://ericholiveira.medium.com/slides-frp-em-javascript-bcf39c0a9a68?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/bcf39c0a9a68</guid>
            <category><![CDATA[frp]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[baconjs]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Fri, 25 Sep 2015 20:29:24 GMT</pubDate>
            <atom:updated>2015-09-25T20:30:37.275Z</atom:updated>
            <content:encoded><![CDATA[<p>Ontem eu tive a felicidade de palestrar no the developers conference em Porto Alegre, e aqui estão os slides</p><p><a href="http://www.slideshare.net/ErichOliveira1/programao-funcional-reativa">http://www.slideshare.net/ErichOliveira1/programao-funcional-reativa</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bcf39c0a9a68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Short-circuit operators. Como escrever um código mais conciso e expressivo.]]></title>
            <link>https://ericholiveira.medium.com/short-circuit-operators-como-escrever-um-c%C3%B3digo-mais-conciso-e-expressivo-8bb2d877484f?source=rss-51fe3dc584d5------2</link>
            <guid isPermaLink="false">https://medium.com/p/8bb2d877484f</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Erich Oliveira]]></dc:creator>
            <pubDate>Thu, 10 Sep 2015 21:10:05 GMT</pubDate>
            <atom:updated>2021-06-24T15:15:10.502Z</atom:updated>
            <content:encoded><![CDATA[<p>Uma das intenções desse blog é mostrar aspectos do javascript que muitos programadores não conhecem. Hoje além de operadores de curto-circuito eu vou falar também sobre o operador VÍRGULA (sim, vírgula pode ser usado como operador em javascript).</p><p>Antes de explicar o que são operadores de curto-circuito é preciso entender que javascript usa o conceito de <em>falsy </em>e<em> truthy. </em>Valores<em> falsy </em>são aqueles que são traduzidos como false quando avaliados em um contexto booleano, são eles <em>false</em>, <em>null</em>, <em>undefined</em>, <em>“”</em>(string vazia), <em>0</em> (zero), <em>NaN</em> (not a number) e também document.all em alguns browsers (mas você não deveria se preocupar com isso). Todos os outros valores são considerados <em>truthy</em>.</p><p>Operadores de curto-circuito são aqueles em que o segundo operando só é avaliado caso o primeiro não seja o suficiente pra resolver uma operação. Como no exemplo abaixo:</p><pre>false &amp;&amp; expr; <br>//Não preciso avaliar expr, pois o resultado é sempre false<br>true || expr;<br>//Não preciso avaliar expr, pois o resultado é sempre true</pre><p>&amp;&amp; e || são os operadores de curto-circuito disponíveis em javascript, e o mais legal deles é que eles testam contra booleanos, mas retornam o resultado original, ou seja:</p><pre>console.log(false &amp;&amp; 1);//imprime false<br>console.log(0 &amp;&amp; 1); // imprime 0<br>console.log(false || 1); // imprime 1<br>console.log(0 || 1 ); // imprime 1</pre><p>Sendo assim, podemos facilmente utilizar essa sintaxe para implementar valores padrão para variáveis com o operador || , como no exemplo abaixo:</p><pre>function imprimeZeroOuOArgumento(n){<br>  n = n || 0;<br>  console.log(n);<br>}<br>imprimeZeroOuOArgumento(1); // imprime 1<br>imprimeZeroOuOArgumento(); // imprime 0<br>imprimeZeroOuOArgumento(0); // imprime 0</pre><p>Este código é exatamente igual ao código abaixo, porém muito mais sucinto:</p><pre>function imprimeZeroOuOArgumento(n){<br>  if(!n){<br>    n=0;<br>  }<br>  console.log(n);<br>}<br>imprimeZeroOuOArgumento(1); // imprime 1<br>imprimeZeroOuOArgumento(); // imprime 0<br>imprimeZeroOuOArgumento(0); // imprime 0</pre><p>Já o operador &amp;&amp; pode ser utilizado para implementar <em>safe navigation, </em>como abaixo:</p><pre>function getPreco(produto){<br>  var preco = produto &amp;&amp; produto.preco;<br>  return preco;<br>}<br>getPreco(null); // return null , sem erro de null pointer<br>getPreco({preco:2}); // return 2</pre><p>Que é o mesmo que:</p><pre>function getPreco(produto){<br>  var preco=null;<br>  if(produto){<br>    preco = produto.preco;<br>  }<br>  return preco;<br>}<br>getPreco(null); // return null , sem erro de null pointer<br>getPreco({preco:2}); // return 2</pre><p>Combinando &amp;&amp; e || você pode até substituir if ternário, como abaixo:</p><pre>function getPreco(produto){<br>  var preco = produto ? produto.preco : 0;<br>  return preco;<br>}<br>// O mesmo que <br>function getPreco(produto){<br>  var preco = produto &amp;&amp; produto.preco || 0;<br>  return preco;<br>}</pre><p>Na verdade com a combinação certa de &amp;&amp; e || você pode substituir todos os <em>ifs </em>do seu projeto (não é recomendado, mas vale para ilustrar o poder desses operadores.</p><p>Esses são os operadores de curto-circuito, e com esse conceito em mente fica fácil entender o operador vírgula, este operador sempre avalia todos os operandos, porém só retorna o último, como no exemplo abaixo:</p><pre>function testeVirgula(arg){<br>  return 1 , 2 , 3 , arg;<br>}<br>testeVirgula(5);//retorna 5<br>testeVirgula(10);//retorna 10</pre><p>Ou ainda em uma expressão mais bizarra:</p><pre>function somaDez(n){<br>  return n + (1,10)<br>}<br>somaDez(1); // retorna 11<br>somaDez(5); // retorna 15</pre><p>Não conheço nenhuma utilidade prática pra esse operador (talvez, possa ser útil com arrow function), mas é bom conhecer para conseguir ler qualquer código bizarro que você encontre por aí.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8bb2d877484f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>