<?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 Marlon Rodrigues on Medium]]></title>
        <description><![CDATA[Stories by Marlon Rodrigues on Medium]]></description>
        <link>https://medium.com/@marlon.gerodrigues?source=rss-e226a4cd06cd------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Pp9Uo3vT5hDWf7NZLusdhw.jpeg</url>
            <title>Stories by Marlon Rodrigues on Medium</title>
            <link>https://medium.com/@marlon.gerodrigues?source=rss-e226a4cd06cd------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 28 Nov 2026 23:06:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@marlon.gerodrigues/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[What is the Role of an AI Software Engineer in a Data Science Team?]]></title>
            <link>https://medium.com/data-science/what-is-the-role-of-an-ai-software-engineer-in-a-data-science-team-eec987203ceb?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/eec987203ceb</guid>
            <category><![CDATA[ai-software-engineer]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[data-science]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 02 Apr 2018 16:51:57 GMT</pubDate>
            <atom:updated>2021-06-11T15:07:06.808Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9tqdtTOq_UXvspzE" /><figcaption>Photo by <a href="https://unsplash.com/@marvelous?utm_source=medium&amp;utm_medium=referral">Marvin Meyer</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I recently joined the Enterprise Insight Studio team at Accenture’s global centre for innovation in Dublin as an Artificial Intelligence (AI) Software Engineering. Given that this is a new role in the team — and in the field in general — there are still a lot of questions around what an AI Software Engineering does and how the role fits within a Data Science team. To help answer some of those questions, I have highlighted in this post some of the key skills that an AI Software Engineer brings to the table and how they integrate within a Data Science team. In practice, several people work on a Data Science team to build analyses and data products. The final product will only be as good as the team that is responsible for collecting, building and analyzing the underlying data. Not too long ago, Data Science teams were mainly composed by Data Scientists, Data Architects and Business Analysts. However, there was a still a big gap to be filled to turn the Data Science work into scalable and stable products, and there is exact where the AI Software Engineer comes into play.</p><p>The main role of an AI Software Engineer in a Data Science team is to productize the data science work so it can serve an internal stakeholder or external customers. The AI Engineer must collaborate with the Data Scientists, Data Architects and Business Analysts to ensure alignment between the business objectives and the analytics back end. And, to justify the AI portion in the job title, an AI Software Engineer is responsible for staying up to date and informed about breakthrough artificial intelligence technologies with the potential to transform business, the workforce or consumer experience and how that can be leveraged by the Data Science team. That all sounds very good, but in practical terms, what exactly does it mean? It means, to put it in a simple statement, that the AI Engineer is responsible for bringing a Software Engineering culture into the Data Science process. That is a massive task and involves things like:</p><h4><strong>Build Infrastructure as Code</strong></h4><p>Automatization of the Data Science team infrastructure. This important Software Engineering concept is a key part of a successful Data Science project. The AI Software Engineer is responsible for making sure that the environments created during the model development and training can be easily managed and replicated for the final product. Tools such as Anaconda, for Python package management, and Docker or Vagrant, for creation of easily transportable and self-contained environments, should be part of a Data Science team process to help with the collaboration between team members and with easily deployable models. Is the responsibility of the AI Software Engineer to build and manage that pipeline, allowing the Data Scientists to focus exclusively on the models development.</p><h4><strong>Continuous Integration and Versioning Control</strong></h4><p>This is another important fact for a Software Engineer that can be easily missed in a Data Science team. Tools such as TFS or GIT should be part of the daily process of a Data Science project. During the model development, there are so many iterations and different updates that is impossible to keep track of all that has been done without a proper versioning control system in place. Concepts such as candidate releases, different branches for different type of issues/user stories, all under one common location that is accessible by everyone in the team are extremely important to transform the Data Science work into an actual product. That also allows the introduction of concepts such as code reviews, which guarantees that more Data Scientists will be aware of how a code/model works and it will help improve the quality of the work that is created.</p><h4><strong>Tests</strong></h4><p>Any product, that being a model with a simple user interface or a fully integrated application, should be thoroughly tested. Obviously, from a Software Engineer point of view, those tests should be fully automated. That means that unit testing, branch testing, integration testing and security testing should be embedded into the Data Science core process. Of course, that is aside from A/B testing, which are a different case and done at a different stage of the development, but they are equally important and should not be discarded.</p><h4><strong>API Development</strong></h4><p>Development of APIs to help integrate data products and source into applications. The AI Software Engineer is responsible for build and maintain a platform to easily “convert” the models into APIs that can be consumed by other applications. That means the development of tools or custom APIs that follow a standard approach and a common language. That also means that the Data Science team can quickly spin a model into an API that is consumed by the “outside world”. This is a key step for transforming the science models into a product and the AI Software Engineer should bring all of his/her expertise into play to guarantee that the APIs created from the models are scalable, flexible and reliable.</p><h4><strong>Development of Pilots and MVP Applications</strong></h4><p>Although not always required, as some Data Science work can be simply presented through Jupyter or other data visualization tools, the development of Pilots and MVPs is still very important in a Data Science process. The MVP is the final product that encapsulates all the other aspects I have mentioned so far, from the creation and testing of the models through the API development all the way down to a final product that can be demoed and consumed by the end users. The main point here is to have applications — either MVPs or final releases — that are so solid that the end users won’t even realize there is a data product underneath it.</p><p>The AI Software Engineer should also consider the implementation of other Software Engineer concepts into a Data Science team, such as continuous delivery, application monitoring and auto-scale, which should also all be part of the core process. However, before going further into the Engineering aspect of it, the points mentioned above, which I believe are the most important of the whole process, should have been implemented and be totally integrated with the team’s culture. Only then more advanced Engineering concepts should be brought into the table.</p><p>To conclude, we can think of an AI Software Engineer as the person responsible for making the life of the Data Scientists and Data Architects easier. They should be focusing on the important aspect of their work: analyzing data and creating models with high accuracy or working on the overall architecture of the project. The AI Software Engineer comes in as the guy that will be responsible for create the APIs, test and deploy the models, create any user interfaces that might be needed to display a more relevant view of the models — model visualization, automatize our infrastructure, etc — and bridge the gap between the Data Scientists and the Data Architects. In a nutshell, the AI Software Engineer is responsible for wrapping the data science work into a final product.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*rtFPuT34e3__8A9kzdbayw.png" /><figcaption><em>Overview of a Data Science Team</em></figcaption></figure><p>This is just a basic overview of the role of an AI Software Engineer in a Data Science team and what kind of contributions that person brings to the table. Hopefully that will help you understand what the role entails and why it is important to have software engineering concepts behind a data science work. Giving that this is a new role within the Data Science scope, there are still a lot of questions to be answered and the AI Software Engineer has to be flexible enough to implement his/her ideas within the team and to take action on areas that are not necessarily related to Software Engineering. Nonetheless, that is a very exciting position to be, with lots of opportunities to learn and grow. It is also a great opportunity for a Software Engineering to step into the exciting and ever so growing Data Science field. If you are interested in talking more about what an AI Software Engineer does or if you have any questions or suggestions, feel free to reach out, I would love to hear from you. In the meantime, stay curious and keep coding.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eec987203ceb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/what-is-the-role-of-an-ai-software-engineer-in-a-data-science-team-eec987203ceb">What is the Role of an AI Software Engineer in a Data Science Team?</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Modern Web Security — Content Security Policy]]></title>
            <link>https://blog.vanila.io/modern-web-security-content-security-policy-9ad347a4a860?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ad347a4a860</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[http2]]></category>
            <category><![CDATA[content-security-policy]]></category>
            <category><![CDATA[https]]></category>
            <category><![CDATA[security]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 05 Mar 2018 08:26:52 GMT</pubDate>
            <atom:updated>2019-04-02T01:15:36.340Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*Bygk2pomsAT7LULf." /></figure><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><p>One of the most important facts when it comes to web development is security. Countless are the cases where companies failed to protected their websites/web applications and let users valuable information fall into the wrong hands. There are a lot of things developers can do to protect websites/web applications in the first instance. The web is nothing more than a network of devices communicating among themselves. So, when we think about web security, the first thing that comes to mind is how we can protect the data that traffics through the web. We need to make sure that the communication is secure. If the communication is not secure, everything else seems almost pointless. That’s where HTTPS encryption comes into play. We need to encrypt data that goes over the internet. In fact, we are actually seeing the largest drive towards encryption in history right now. For instance, the new HTTP protocol — HTTP/2 as we call it — has a lot of things straight out of the box that we basically had to hack to have it working with HTTP 1.1. For example, to make pages load faster we could do things like image sprites, JS/CSS concatenation into bigger single files or domain sharding — where you have an image subdomain to load your images from so you could pull down more assets and tandem them. With HTTP/2 and HTTPS, we get all of those and much more by default in the protocol. But these are not the only benefits of HTTPS. A lot of the APIs available today have been deprecated on HTTP. For example, geolocation APIs that rely on GPS coordinates have to rely on secure connections. Another big thing is Brotli compression. Brotli Compression is the new compression algorithm that will very soon replace gzip. Brotli is simple and more efficient, we can basically take our pages and squish them down even smaller than if we used gzip, which translates into page speed. Finally, Google now considers HTTPS as a ranking signal. If we have two equally ranked sites, but only one of them servers HTTPS, that site will get a higher SEO boost and it will appear higher in the search engine result pages. That is just to say that there are loads of other reasons beyond the obvious ones — security and privacy — to use HTTPS over HTTP.</p><p>Now that we covered some of the advantages of HTTPS, we can take a step further and discuss how we can use HTTPS to improve page security. If we think about it, in our traditional browser scenario, we have the browser talking to the web server and because of that, that is where historically all of efforts in security were focused. Basically, we wanted to make our server secure. Over the last decade, our responsibility towards security has expanded out into what I call the transport layer, the bit in between the browser and the server — where the data traffics over the internet. As we discussed earlier, this comes in the form of HTTPS. With HTTPS, we can leverage security headers, which are response headers that configure some kind of security policy or some kind of security mechanism. Those response headers are called <em>content-security-policy</em> or CSP.</p><h3><strong>Content Security Policy — CSP</strong></h3><p>CSP is an incredible powerful feature. Originally, it was designed to stop content injection attacks — where somebody gets something into your page that is not supposed to be there. For example, let’s say we have a page with a comment section, where users are supposed to submit a comment that gets rendered into the page. That’s all good, but what if somebody just entered a script tag like this:</p><pre>&lt;html&gt;<br>    &lt;body&gt;<br>        &lt;comment&gt;<br>            &lt;script src=”notsafe.com/resource.js”&gt;&lt;/script&gt;<br>        &lt;/comment&gt;<br>        …<br>&lt;/html&gt;</pre><p>This is called cross-site scripting and is one of the most basic forms of attack we see against websites/web applications. There are ways to defend against this, for instance we could have input filtering or output encoding, but ultimately, what we would like is to not have that script loaded into our page. The problem is that browsers do not have that kind of context, they simply look at the script tag and go get it. With CSP we can change that. We can actually give the browser more information so it can make informed decisions.</p><p>Because CSP itself is just a response header, we can easily define a new response header on the page called <em>content-security-policy</em> with our policies as its value. The policy is made up of one or more of what we call the CSP directives.</p><pre>cache-control: max-age=0, no-cache<br>content-encoding: gzip<br>content-security-policy: [policy goes here]<br>date: Mon, 05 Mar 2018 16:10:00<br>server: TheServer<br>status: 200</pre><h4>CSP Directives</h4><ul><li>child-src</li><li>connect-src</li><li>default-sr</li><li>font-src</li><li>frame-src</li><li>img-src</li><li>media-src</li><li>object-src</li><li>script-src</li><li>style-src</li></ul><p>For example, we can take the <em>font-src</em> directive and provide a list of locations the browser is allowed to load fonts from. With that, the browser knows it can only load fonts from the list of resources listed with the directive. The same applies for the i<em>mg-src</em> and <em>script-src</em> directives, where we simply specify the locations where the different types of content can be loaded from.</p><p>Let’s take a look at an example. In the policy below, the <em>default-src</em> is the default for everything — every resource — and <em>self</em> is a keyword for our own domain — that means by default we are ok with loading resources from our own domain and also from a third domain defined as <em>example.com</em>. The script injection we saw earlier would now be completely fixed because. If somebody puts a script tag into our page loading a resource from notsafe.com, the browser would be able to verify that notsafe.com is not part of the allowed domains, so it would never load that script.</p><pre>content-security-policy: default-src &#39;self&#39; example.com</pre><p>The problem with the header we defined above is that we load resources/contents from all sort of locations. That means it would be impossible to deploy our website/web application with that directive. To solve that issue, we need to fine tune our policy:</p><pre>content-security-policy: default-src &#39;self&#39;;<br>script-src &#39;self&#39; cdnjs.cloudflare.com ajax.googleapis.com</pre><p>As you can see, we can specify all sources for script files, stylesheets, images, frames and etc. following this pattern. That means we can control all the locations where our pages resources will be loaded from in the browser with CSP. Also note that the defined directive — <em>script-src</em> in this case — overrides anything that is defined with the <em>default-src</em> directive.</p><p>That is the basic intention of CSP, but there are other really awesome things that we can do with it. For instance, if we have to migrate our site from HTTP to HTTPS — for those that have done it, you know how painful it can be — we would most certainly get what is called mixed content. Mixed content is when you have a page on HTTPS but one of the page’s image tags or assets are loaded through HTTP. That means you are loading two different types of content: one secure and the other one not. Each browser handles this issue differently: Chrome, for example, will completely block the script — it will not even try to load it — and remove it because it will see that as a dangerous action. However, you can manually allow it by clicking on the URL bar icon with the error message and telling Chrome that it is OK to load that script — which is a terrible practice by the way. In case of an image, Chrome will actually load the image, but the site will lose the HTTPS flag — the green lock icon at the left of the URL bar. We can use CSP to fix this. CSP has a directive called <em>block-all-mixed-content</em>. This directive literally blocks all mixed content. So, if we have a page on HTTPS and we try to load an insecure image, CSP will tell the browser to block that image and we will not get any warning in the browser, which means the browser will just skip over the image tag. OK, we fixed the mixed content, which means the user will not get that degradation of the UI and the browser will not display the page as insecure, but what if that website could post securely? What if this is just a bit of legacy code that we did not even use protocol relative schemes? Well, there is another directive in CSP to fix this. It’s called <em>upgrade-insecure-requests</em>. What that will do in contrast to <em>block-all-mixed-content</em> is that when the browser gets to that image tag, it will rewrite it to HTTPS and proceed normally, now, how cool is that?</p><p>CSP is very powerful and there are tons of things we can achieve with it. For instance, testing CSP policies is super easy. We can easily deploy it in report mode by appending the report only section directive to the response header, so instead of actually blocking any contents or resources, the browser will just output the error messages to the console. That means we can make sure our policies are safe to deploy and our pages will not look awful because of mixed content issues for example.</p><pre>content-security-policy-report-only: [policy]</pre><p>We can actually take this even further and instead of writing the errors to the console, we can send the error messages as a JSON file to a server that is able and ready to consume these JSON payloads that are sent by the browser.</p><pre>content-security-policy-report-only: [policy]<br>report-uri <a href="https://report-uri.io/">https://report-uri.io</a></pre><p>If you think about it, we have actually turned the browser into a QA tester. The browser will send us a report whenever a page that has an issues is clicked. That means we can turn every single user of our website/web application into a member of our QA team.</p><p>As far as browser support goes, CSP is available pretty much across all of the mainstream browsers — Chrome, Firefox, Safari and IE. However, it doesn’t really matter that much, because if we deploy it and the browser supports it, that user will get the protection, otherwise, if the browser does not supports it, the directive will just be ignored. That means that there is no negative sides on having the directives in place, as they will just be ignored if not supported by the user’s browser.</p><p>I just touched the surface of what CSP can do. I strongly suggest you do head over to the documentation at <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP">https://developer.mozilla.org/en-US/docs/Web/HTTP/CSP</a> and take a look at all the features offered by CSP. If you have been using CSP already, let me know in the comments below, I am curious to see how other developers have been using it. And remember, stay curious and keep coding!</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ad347a4a860" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/modern-web-security-content-security-policy-9ad347a4a860">Modern Web Security — Content Security Policy</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bring on the Big Guns: JavaScript Higher-Order Methods]]></title>
            <link>https://blog.vanila.io/bring-on-the-big-guns-javascript-higher-order-methods-64e1bf44943?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/64e1bf44943</guid>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[arrow-functions]]></category>
            <category><![CDATA[higher-order-function]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 19 Feb 2018 12:15:26 GMT</pubDate>
            <atom:updated>2019-04-02T01:17:32.803Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/0*KWc7qFOVk3Gusvn_." /></figure><p>Let’s up our JavaScript game and talk about higher-order methods. Although JavaScript offers a lot of powerful features, sometimes some of those features are not that obvious and clear for new comers, or even for more experienced developers. Higher-order functions are one of those gems. They not only make your code shorter and easier to be understood, but they also help you reduce the amount of lines of code you need to write to get the results you want, which translates into your code being less prone to errors.</p><p>If you have seen methods such as map(), sort(), filter() and reduce() and never really understood how they work, this is post is for you. I will explain how they work and what are the benefits of using those methods if compared to a for loop for example. Hopefully, that will give you a better idea of why you should be using them. Aside of that, those methods will really help you become a better developer, because even if you master a framework like Angular or React, you still should understand the language that’s underneath those frameworks. By understanding and taking full advantage of JavaScript, you will not only up your game as a developer but you will also have much better understanding of how those frameworks work under the hood.</p><p>To start, let’s assume with have an array of objects and an array of numbers as the following:</p><pre>const cars = [<br>     { name: &quot;Car One&quot;, maker: &quot;Honda&quot;, firstYearModel: 1981, lastYearModel: 2004  },<br>     { name: &quot;Car Two&quot;, maker: &quot;Toyota&quot;, firstYearModel: 1982, lastYearModel: 1996  },<br>     { name: &quot;Car Three&quot;, maker: &quot;Honda&quot;, firstYearModel: 1991, lastYearModel: 2001  },<br>     { name: &quot;Car Four&quot;, maker: &quot;BMW&quot;, firstYearModel: 1987, lastYearModel: 1999  },<br>     { name: &quot;Car Five&quot;, maker: &quot;BMW&quot;, firstYearModel: 1992, lastYearModel: 208  },<br>     { name: &quot;Car Six&quot;, maker: &quot;Honda&quot;, firstYearModel: 1979, lastYearModel: 1991  },<br>     { name: &quot;Car Seven&quot;, maker: &quot;Audi&quot;, firstYearModel: 1995, lastYearModel: 2009  },<br>     { name: &quot;Car Eight&quot;, maker: &quot;Honda&quot;, firstYearModel: 1999, lastYearModel: 2014  },<br>     { name: &quot;Car Nine&quot;, maker: &quot;Honda&quot;, firstYearModel: 2011, lastYearModel: 2018  },<br>     { name: &quot;Car Ten&quot;, maker: &quot;Toyota&quot;, firstYearModel: 2002, lastYearModel: 2018  },<br>];</pre><pre>const ages = [44, 77, 5, 7, 33, 3, 14, 2, 55, 28, 18, 32, 25, 19, 89];</pre><p>Before we start, if we were going to use a for loop to loop through this data and print each object, that’s how it would look like:</p><pre>for(let i=0; i&lt;companies.length; i++) {<br>    console.log(companies[i]);<br>}</pre><p>Now, let’s look at how we can use higher-order methods to handle those arrays.</p><h4><strong>forEach()</strong></h4><p>forEach() is basically an easier and better way to loop through an array rather than using a for loop. Different from the other methods we will see, it does not return anything back to you. Instead, it just executes the callback function that is passed to it once for each array element. In a nutshell, it is a much nicer and more elegant way to loop through data.</p><p>The forEach() method, as mentioned above, takes a callback function — keep in mind, this function is executed synchronously, not asynchronously. That function can take up to three different arguments: the iterator — the single object of each pass in the array — the index of the array in the current pass and the actual entire array. This is the basic argument list for all other higher-order functions as well. For example, let’s just log the company name to the console. As you can see, this looks a lot nicer than the for loop, as there is no need to set a variable i and keep track of it.</p><pre>companies.forEach(function(company) {<br>    console.log(company.name);<br>});</pre><h4><strong>filter()</strong></h4><p>The filter() method allow us to do just that: filter things out from the array. In a nutshell, it creates a new array with all elements that pass the test implemented by the callback function. For example, let’s say we want to look at the ages array and get all of the ages that are 18 and over. We could achieve that with the for loop, but we would need to have a separate array to store the filtered values as well as a variable to track the indexes and the current position in the array. The filter() method simply takes a callback function — again, remember this function is executed synchronously, not asynchronously — and within that function all we need is to build our condition. There is no need to create an array and then push on to it, we just simply check the condition and return true if the condition is valid.</p><pre>const canDrink = ages.filter(function(age) {<br>    if (age &gt;= 21) {<br>        return true;<br>    }<br>});</pre><p>We can actually make this event better. We can put all this in one line using ES6 arrow functions.</p><pre>const canDrink = ages.filter(age =&gt; age &gt;= 21);</pre><p>I will be talking about ES6 arrow functions in a future post, but if you don’t know what they are or why they are even a thing, just think of them as a more concise syntax for writing function expressions. In this case, the age variable is the only argument for our callback function, thus we can omit the parentheses — if we had more than one parameter, then the parenthesis would be required — and because arrow functions return by default, we can omit the return keyword as well.</p><p>Let’s see another example with ES6 arrow functions and filter the cars array to get all cars where Honda is the maker.</p><pre>const hondaCars = cars.filter(car =&gt; car.maker === &#39;Honda&#39;);</pre><p>Let’s now filter for all the cars where the first model was built on the 80’s:</p><pre>const eightiesCars = cars.filter(car =&gt; (car.firstYearModel &gt;= 1980  &amp;&amp; car.firstYearModel &lt; 1990));</pre><p>Finally, let’s get all the cars that had a model for at least 10 years.</p><pre>const lastedTenYears = cars.filter(car =&gt; (car.lastYearModel — car.firstYearModel &gt;= 10));</pre><p>We can see how easy and elegant it is to use the filter function with ES6 syntax.</p><h4><strong>map()</strong></h4><p>The map() method works a bit differently of the other higher-order functions we have seen so far. Instead of just filtering things out, the map() method actually creates a new array with the results of calling a callback function on every element in the calling array. That means we can create new arrays of anything from a given array. For example, let’s grab all of the car names and put them into their own array.</p><pre>const carNames = cars.map(function(car) {<br>     return car.name;<br>});</pre><p>We could, for instance, do all sort of things with the map() method. We could, for example, return all 1’s and have an array with a value of 1 for each company name. We could also create a new array with property concatenation. For example, let’s get a new array with the car name and the first year and last year models.</p><pre>const carMap = car.map(function(car) {<br>    return `${car.name} [${car.firstYearModel}-{car.lastYearModel}]`;<br>});</pre><p>As you can see, we can format this new array however we want. Let’s see how this could be made even simpler with ES6 arrow functions:</p><pre>const carMap = cars.map(car =&gt; `${car.name} [${car.firstYearModel} — ${car.lastYearModel}]`);</pre><p>Now, let’s use the map function to get the square root of each value in our ages array.</p><pre>const agesSquare = ages.map(age =&gt; Math.sqrt(age));</pre><p>Now, let’s say we want to square it and then multiply it by 2. That is easily achievable with function concatenation.</p><pre>const ageMap = ages<br>               .map(age =&gt; Math.sqrt(age))<br>               .map(age =&gt; age * 2);</pre><p>This only shows how the map() method is powerful. We can map the array with different conditions and have a final array with only the results that match all of the criterias defined.</p><h4><strong>sort()</strong></h4><p>The sort() method works similar to the other functions. It basically sorts the elements of an array in place and returns the array. For example, let’s sort the cars array by the car’s first year model. The sort() methods takes a callback function, which receives two values (it’s common practice to call those values <em>a</em> and <em>b</em>), which are the values that will be compared. In this case, it will be the two cars that are compared at each array pass. Those values are then compared within our callback function that returns 1 or -1 to move the values up and down in the array.</p><pre>const sortedCars = cars.sort(function(a, b) {<br>    if (a.firstYearModel &gt; b.firstYearModel) {<br>        return 1;<br>    } else {<br>        return -1;<br>    }<br>});</pre><p>With ES6 and ternary operators, the above method would look like this:</p><pre>const sortedCars = cars.sort((a, b) =&gt; (a.start &gt; b.start ? 1 : -1));</pre><p>Let’s also look at an example sorting the ages array. Let’s sort it by lowest to highest.</p><pre>const sortAges = ages.sort((a, b) =&gt; a - b);</pre><p>Notice how we used <em>a - b</em>. We needed this because, if we used the greater than (&gt;) operator returning 1 or -1, we would be checking for the string values of the array, not the actual integer value. In those cases, having a mathematical expression prevents the array from sorting alphabetically instead of numerically.</p><h4><strong>reduce()</strong></h4><p>The reduce() method can be used for a lot of things and it can get quite complicated. It basically applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value. To keep it simple, I will use the reduce() method to add all of the ages of the ages array together. But first, let’s remember how this would have to be done with the for loop.</p><pre>let ageSum = 0;<br>for(let i = 0; i &lt; ages.length; i++) {<br>    ageSum += ages[i];<br>}</pre><p>Now, with reduce():</p><pre>const ageSum = ages.reduce(function(total, age) {<br>    return total += age;<br>}, 0);</pre><p>As you can see, using the reduce() method makes our code much more elegant and simpler than using a regular for loop. You may also have noticed that, different from the other higher-order methods we have seen, reduce() takes 2 arguments: the total, which is the value that will hold the overall sum and it’s initialized before the callback, and the object — in this case the age — which is each individual value in the array.</p><p>To make this code even more simple, let see how this could be done with ES6 arrow functions:</p><pre>const ageSum = ages.reduce((total, age) =&gt; total + age, 0);</pre><p>For a final example with reduce(), let’s get the total number of years that each car has been build.</p><pre>const totalYears = cars.reduce((total, car) =&gt; total + (car.lastYearModel - car.firstYearModel), 0);</pre><p>Finally, now that we have seen all of the higher-order functions individually, we can actually use all of them together. For example, let’s get our ages array, multiply each individual value by 2, filter the results that exceed 40, sort those results in ascending order and finally get the total sum of all those ages.</p><pre>const combined = ages<br>                 .map(age = &gt; age * 2)<br>                 .filter(age =&gt; age &gt;= 40)<br>                 .sort((a, b) =&gt; a — b)<br>                 .reduce((a, b) =&gt; a + b, 0);</pre><p>Hopefully now you have a better understand of how higher-order functions work and how you can take advantage of them. By using higher-order functions, you can show you understand the ins and outs of JavaScript. You can write much more elegant and clear code, which is a statement to show how good of a developer you are. That’s only to say that these methods are really important. You don’t want to be doing things with for loops when you have methods like filter() and map() available. Next time you come across a case where you need to run a for loop, remember the higher-order functions, they will make your life much easier. In the meantime, stay curious and keep coding!</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=64e1bf44943" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/bring-on-the-big-guns-javascript-higher-order-methods-64e1bf44943">Bring on the Big Guns: JavaScript Higher-Order Methods</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Webpack — What is it and is it better than Gulp?]]></title>
            <link>https://blog.vanila.io/webpack-what-is-it-and-is-it-better-than-gulp-375db8011d22?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/375db8011d22</guid>
            <category><![CDATA[build-system]]></category>
            <category><![CDATA[gulp]]></category>
            <category><![CDATA[webpack]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 05 Feb 2018 14:29:55 GMT</pubDate>
            <atom:updated>2019-03-31T00:12:27.882Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><figure><img alt="Image result for webpack" src="https://cdn-images-1.medium.com/proxy/1*gdoQ1_5OID90wf1eLTFvWw.png" /></figure><p>Even if you don’t know what Webpack is, you probably have heard about it and how powerful it can be and the classic “that’s what we should be using now”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/622/0*T79Ud_MdL_QnS6NZ." /></figure><p>But before you drop everything else to hop on to the Webpack bandwagon, it’s worth to understand what exactly Webpack is, how it works and how it compares to other build systems, most specifically Gulp, which is my favorite and the most widely used today.</p><p>So, what is Webpack? In a nutshell, Webpack is a bundle system. It takes all files (SASS files, LESS files, JavaScript files with modules and dependencies, images, etc) that are connected in some way and bundles them into standard Javascript, CSS, PNG and JPG files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*uXpXHH4fvZu28GSz." /></figure><p>This is interesting, right? We are taking a bunch of stuff, running it through something — Webpack — and we are getting a bundled version that can be understood by the browser. To me that screams build process. When Webpack came out, people were very careful to not call it a build process. Definitions such as module loader or module bundler were preferred, because those terms were more aligned with the main purpose of Webpack: to be a bundle system. However, theoretically, it can be seen as a build process. If you come from Gulp — or Grunt — Webpack basically does the same things: it takes your files, runs them through some sort of conversion/transpiler system and spits out something the browser can understand. For example, with Gulp, we can add a SASS package to our pipe to get the CSS output that we expect. That’s very similar to what Webpack does. In fact, because they both are so similar, there should not be an instance where you would use both together — unless you have a Gulp process already in place and you do not want to give up on it. So, because Webpack can easily replace Gulp, I do believe that we can in fact define it as a build system.</p><p>Aside of bundling all your resources, Webpack, if configured right, can do much more. For instance, with Webpack we can:</p><ul><li>Watch for file changes and re-run tasks</li><li>Run Babel transpilation to ES5</li><li>Run a developer web server</li><li>Use auto-prefixes</li><li>Use require() for CSS files.</li><li>Have dead code elimination — that basically means that Webpack can find code that you are not actually using and not add it to the final bundle</li><li>Bundle up smaller modules of JavaScript so we are not serving your entire application to every single user that just visits your homepage</li></ul><p>As mentioned above, this is no different than what you would have in a build system. You can think of Webpack as an advanced build system.</p><p>OK, so now that we know what Webpack is and what it can do, let’s see how we can use it. First, we can easily install it through either Yarn or NPM:</p><p>Yarn</p><pre>yarn global add Webpack</pre><p>NPM</p><pre>npm i -g Webpack</pre><p>With Webpack installed, we can look at the code.</p><p><em>app.js</em></p><pre>import bar from &#39;./bar&#39;;<br>bar();</pre><p><em>bar.js</em></p><pre>export default function bar() {<br>   ...<br>}</pre><p>The Webpack configuration file s usually stored in a file named Webpack.config.js in the project root folder. On that configuration file we will tell Webpack the entry point of our application, the output file that should be generated once everything is bundled and any other additional rules or tasks we might want it to run.</p><p>Webpack.config.js</p><pre>module.exports = {<br>  entry: &#39;./app.js&#39;,<br>  output: {<br>      filename: &#39;bundle.js&#39;<br>  }<br>};</pre><p>With all that in place, all we need is to reference the bundle.js file in our HTML page. When we run <em>webpack</em> on the command-line, a file called bundle.js will be created with all of our resources bundled.</p><p>Again, if you really think about it, Webpack is really just an advanced build process that has a lot of advanced features. However, as Uncle Ben said: “with great power comes great responsibilities”, because Webpack is so powerful and flexible, the configuration file can become a total mess and be extremely difficult to parse. Let’s look at an example where we have a basic dev server, code transpilation, auto-prefixes and some basic plugins to help us with our CSS:</p><pre>const ExtractTextPlugin = require(&#39;extract-text-Webpack-plugin&#39;);<br>const autoprefixer = require(&#39;autoprefixer&#39;);<br>const precss = require(&#39;precss&#39;);<br>const svgFragments = require(&#39;postcss-svg-fragments&#39;);<br>const pxtorem = require(&#39;postcss-pxtorem&#39;);<br>const cssnano = require(&#39;cssnano&#39;);<br>const path = require(&#39;path&#39;);</pre><pre>module.exports = {<br>   entry: {<br>     app: [<br>       &#39;Webpack-dev-server/client?http://localhost:8881/&#39;,<br>       &#39;./app/App.js&#39;<br>     ]<br>   },</pre><pre>   output: {<br>     path: path.resolve( __dirname, &#39;public&#39; ),<br>     publicPath: &#39;/js/&#39;,<br>     filename: &#39;main.js&#39;,<br>     sourceMapFilename: &#39;main.js.map&#39;<br>   },</pre><pre>   resolve: {<br>     extensions: [&#39;&#39;, &#39;.js&#39;, &#39;.jsx&#39;, &#39;.es6&#39;],<br>     modulesDirectories: [&#39;node_modules&#39;]<br>   },</pre><pre>   module: {<br>     preloaders: [<br>       { test: /\.jsx$|\.es6$|\.js$/, loader: &#39;source-map&#39;, query: {   presets: [&#39;react&#39;, &#39;es2015&#39;] }, exclude:   /(node_modules|bower_components)/ }<br>     ],<br>     loaders: [<br>       { test: /\.jsx$|\.es6$|\.js$/, loader: &#39;babel&#39;, query: { presets: [&#39;react&#39;, &#39;es2015&#39;] }, exclude: /(node_modules|bower_components)/ },<br> { test: /\.css$/, loader: ExtractTextPlugin.extract(&#39;style-loader&#39;, &#39;css-loader!postcss-loader&#39;) },<br> { test: /.*\.(gif|png|jpe?g|svg)$/i, loaders: [&#39;file?hash=sha512&amp;digest=hex&amp;name=[hash].[ext]&#39;, &#39;image-Webpack?bypassOnDebug&amp;optimizationLevel=5&#39;] }<br>     ]<br>   },</pre><pre>   devtool: &#39;eval&#39;,</pre><pre>   postcss: function() {<br>       return [<br>          autoprefixer( { browsers: [&#39;last 2 versions&#39;] } ),<br>          precss,<br>          svgFragments,<br>          cssnano,<br>          pxtorem( {<br>              propWhiteList: [] // Enables converting of all properties — default is just font sizes.<br>          } )<br>       ];<br>   },</pre><pre>   plugins: [<br>       new ExtractTextPlugin( &#39;public/styles.css&#39;, {<br>          allChunks: true<br>       } )<br>   ]<br>};</pre><p>As you can see, the syntax is not as concise and nice as in Gulp — where you basically write functions and everything is easily trackable — but instead filled with a lot of jargon terms like loaders, modules, rulers, which can be intimidating and hard to pick up. That’s not to say Webpack is unreadable, but the learning curve can be steep. On a bright side, the documentation on Webpack’s website is great and it’s definitely the first stop for someone learning the ins and outs of Webpack.</p><h4>Webpack vs Gulp</h4><p>OK, now that we know what Webpack is, how can we actually compare it to Gulp? First, we need to understand that Gulp’s purpose is completely different from Webpack. It’s not meant for bundling, it’s just meant to run tasks. You set up a basic JavaScript function that gets called and executed. It’s so simple that many people have extended it beyond its initial intend. Webpack, on the other hand, is all about bundling. That entails a more complex syntax, as I previously mentioned, as well a more complex approach for cases such as when you need your modules to be on their own files or if you need your CSS to be taken out of that bundle, as things like these are not core to Webpack — there are plugins to do all those things and more, but what you end up with is getting stuck in the spider web of this massive configuration file that you can’t easily break it or give it to the next person to understand it.</p><p>Now, let’s compare the implementation of a simple task to see how Gulp and Webpack syntax differ. The simplest thing we can do is to convert our LESS or SASS files into CSS files. With Gulp, that’s incredible simple:</p><pre>&#39;use strict&#39;;<br> <br>var Gulp = require(&#39;Gulp&#39;);<br>var sass = require(&#39;Gulp-sass&#39;);<br> <br>Gulp.task(&#39;sass&#39;, function () {<br> return Gulp.src(&#39;./sass/**/*.scss&#39;)<br> .pipe(sass().on(&#39;error&#39;, sass.logError))<br> .pipe(Gulp.dest(&#39;./css&#39;));<br>});<br> <br>Gulp.task(&#39;sass:watch&#39;, function () {<br> Gulp.watch(&#39;./sass/**/*.scss&#39;, [&#39;sass&#39;]);<br>});</pre><p>With Webpack, because it really just supports Javascript bundling, we have to compile our SASS/LESS and CSS files into a JavaScript file. Once that file is compiled, we can use a plugin to extract the CSS text from the JavaScript file and put it on its own file.</p><pre>const ExtractTextPlugin = require(&#39;extract-text-Webpack-plugin&#39;);</pre><pre>const extractSass = new ExtractTextPlugin({<br>   filename: &quot;[name].[contenthash].css&quot;,<br>   disable: process.env.NODE_ENV === &quot;development&quot;<br>});</pre><pre>module.exports = {<br> …<br> module: {<br>    rules: [{<br>       test: /\.scss$/,<br>       use: extractSass.extract({<br>            use: [{<br>                loader: &quot;css-loader&quot;<br>            }, {<br>                loader: &quot;sass-loader&quot;<br>            }],<br>            // use style-loader in development<br>           fallback: &quot;style-loader&quot;<br>       })<br>    }]<br> },<br> plugins: [<br>    extractSass<br> ]<br>};</pre><p>As we can see, Gulp is extremely simple, as Webpack is more complex and require plugins and rules to execute the tasks we need. However, on a regular project, there are many more tasks involved other than just converting SASS/LESS files into CSS files. That’s when developers starting using Gulp to do more things, such as bundling files, which is the main purpose of Webpack. That might be fine, because you start small and scale your code as you need, but because you need to be constantly scaling up your Gulp file, that can become a cumberstone task and you might end up pushing Gulp too far from it’s main purpose. Things like error catching and reloading or running tasks in a certain order can turn your Gulp file into a monster on its own — things like these are not supported in Gulp, so you actually need packages such as plumber and run-sequence to achieve those tasks. That’s why Webpack is so powerful. Even though it’s syntax might be complex, once you understand it, it can become a very amazing tool that allows you to do a lot of the things you would struggle with Gulp. Again, with Gulp, when you add complexity, you are basically pushing its boundaries, as Webpack is actually meant for that kind of environment.</p><p>If you just need some basic bundling, just stick with Gulp, you don’t need to bother with Webpack. However, if you need to mix in multiple JavaScript files and maybe have some of them split up in certain ways or if you need to have jQuery and Bootstrap split out but still want to share them between files, or if you need multiple HTML files, then stop using Gulp and look at Webpack. Webpack is an incredible, powerful tool that can do quite a lot for you when you are dealing with a massive application. For instance, one of the things it does very well it’s called tree shaking. Let’s say, for example, that you only need a couple of functions from a massive library like lodash. You can actually leverage Webpack tree shaking and only grab the functions you need, without needing to load the entire library. Again, if you are using Gulp and you get yourself needing more and more advanced features, that’s when you should switch to Webpack.</p><p>So, if you ask me, is Webpack worth it? Absolutely, it’s the best build system around even if you don’t want to call it a build tool or build system. It handles modern JavaScript applications in a way that you could not necessarily do before with all of the modern bells and whistles. But at the end of the day, you will have to decide which one is better for you based on your situation and on our project. Regardless of your choice, both Webpack and Gulp are amazing tools and have a great community behind them.</p><p>Let me know in the comments below which one you have been using, I would love to hear what people have to say about both systems. And remember, stay curious and keep coding!</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=375db8011d22" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/webpack-what-is-it-and-is-it-better-than-gulp-375db8011d22">Webpack — What is it and is it better than Gulp?</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Beauty of Bad Code]]></title>
            <link>https://blog.vanila.io/the-beauty-of-bad-code-586e1ccb0aac?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/586e1ccb0aac</guid>
            <category><![CDATA[development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[developer]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 12:28:55 GMT</pubDate>
            <atom:updated>2019-03-31T00:23:19.998Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kwFwNhQfllA0DKC4." /></figure><p>How many of you have written bad code? I know, it’s hard to admit, but we all have been there, at least once. Unfortunately, bad code is a common thing in a developer’s life. We have either come across it or we have helped create it. Since it’s so common, why is it so hard for us to actually admit and embrace the fact that at some point we created code that is not, let’s say, our best piece of art? Well, I guess it all boils down to the fact that bad code is always associated with negative outcomes. And although for the most part that is true, we should always try to look at things from a different perspective. Thus, the title of this post: The beauty of bad code.</p><p>Before I dive into why bad code should not be considered such a bad thing, we have to understand what bad code is and how we can identify it and get rid of it. When we think about bad code, the first thing we might think about is what I like to call the super-villain code. This it the morally ethically bad code. Most of us are good citizens and we work towards innovations that will be beneficial for our society. However, there are developers out there with the sole purpose of creating chaos — the so called hackers. Hackers take advantage of system vulnerabilities and leverage that to take advantage of people and/or companies. This is morally bad and it’s what I call evil code — viruses and password sniffers are a good example of what an evil code is. In theory that could be considered bad code, but that’s not what I will be talking about today.</p><p>We have written a lot of code and in fact, we have rewritten our code several times. We are constantly rewriting code because the state of things are constantly changing. That means we know bad code — we have seen it, we have played with it and we got rid of it. But, the big question is: what exactly is bad code? Well, bad code can be related to 3 major categories:</p><ul><li>Functionality</li><li>Maintainability</li><li>Readability</li></ul><p>Those are the basic 3 tenets of good code. If your code is missing one of those, then most likely your code is not that great.</p><h4><strong>Functionality</strong></h4><p>Functional code is code that always does what it’s supposed to do. So basically, functional bad code is code that doesn’t do what it’s supposed to do. One good example of non functional code is the classic happy path approach, where code is written only taking into consideration a perfect scenario. That means that if something out of ordinary happens — a run-time error for example — you will have no idea how your code will behave and what kind of output it might give to the user. Another example is the famous “never trust the user”. Whenever our code relies on any sort of user input, we need to make sure we have proper code in place to handle all sorts of inputs a user might use in our application. In the example below, we have a function that simply formats an URL and fetches data from that formatted URL. The problem is that the <em>name</em> variable is a user input. Since we have no checks to make sure the <em>name </em>variable will have a valid value, there is no way to tell how this function will behave if the user doesn’t input what we are expecting.</p><pre>function getPage(type) {<br>    return (name, next) =&gt; {<br>        var url = fmt(&#39;<a href="https://sampleurl/&#39;">https://sampleurl/&#39;</a> + type + &#39;master/%s.md&#39;,   name);<br>        request(url, (err, resp, content) =&gt; {<br>            return next(err, marked.parse(content));<br>        });<br>    }<br>}</pre><h4><strong>Maintainability</strong></h4><p>When we write code we need to always keep in mind that our code should be able to scale and evolve if needed. Code that is not maintainable is extremely hard to scale and evolve. We need to spend countless hours just trying to figure out what is the purpose of the code, and a lot of the times a complete rewrite or refactor is needed in order to achieve the scalability we require. A good example of non maintainable code is the classic spaghetti code. Spaghetti code is code which flagrantly violates the principles of structured, procedural programming. Usually this means using lots of GOTO statements, hence the term, which suggests the tangled and arbitrary nature of the program flow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/0*_tRmagM6quibHAL3." /></figure><h4><strong>Readability</strong></h4><p>Now, for everyone’s favorite section, readability. What’s important about readability? We want to make sure that anyone, whether that’s you or a teammate, understands what is happening in the code. So, it’s important that your code is readable so that other people, or you, can look at it and continue to work on it. The most classic example of unreadable code for me is clever code. When something is too clever, it makes it really difficult for anybody to get it on it. For example, let’s look at the code below. It’s a great example of how to reduce a function to just a few lines, but can you tell me without spending too much time what the heck is going on?</p><pre>function transform(type, arg, data, skip, limit) {<br>    if (!arg &amp;&amp; transformKeyArg[type]) {<br>        data = data.sort((a, b) =&gt; {<br>            return a.value === b.value ? (<br>                a.name === b.name ? 0 : a.name &lt; b.name ? -1 : 1<br>            ) : a.value &gt; b.value ? -1 : 1<br>        }).slice(skip, skip + limit)<br>    }<br>    return data;<br>}</pre><p>I know what you might be thinking: “Really? This is a ternary inside a ternary inside a ternary, what the heck?”. This is a perfect example of clever code — in this case, too clever. The rule of thumb is that if you — or someone else — needs more than 30 secs and a pen and a paper to figure it out what is happening, your code is probably not that readable.</p><h3><strong>So, how do we avoid bad code?</strong></h3><p>Before we jump into how to fix code poorly written, we have to first be able to identify it. So, what are the signs we see that might tell us that our code is not that great — also known as code smells?</p><h4><strong>Lots of branching paths</strong></h4><p>If your code has lots of if-then-else trees or a lot of ternary operations, it might be a good indication that your code is too smelly. Of course, we need to guarantee that we cover all possible scenarios, but having lots of paths doesn’t mean you have that coverage in place.</p><h4><strong>Context-dependent Understanding</strong></h4><p>Honestly, if someone needs a PhD to understand how your code works, that’s not particularly helpful. Yes, there might be some inherit knowledge, but think about a new developer: if they need to spend 6 months just to understand what is up in your code before they can contribute to it, that’s a bad code smell.</p><h4><strong>Long variable names</strong></h4><p>We all know how important it is to name our variables with meaningful and easy, self explanatory names. However, weird, long slash variable names are not good. The key point here is to have a balance between short and meaningful names.</p><h4><strong>It works on my machine</strong></h4><p>This is a classic one. How many times we have come across the case where the code might work locally, but it burns as soon as we deploy it to a different environment? It’s awesome if your code works on your machine, but if it doesn’t work on anybody else’s, that’s a code smell.</p><h4><strong>Reinventing the wheel</strong></h4><p>We love to write and create our own stuff, that’s part of the fun of our work, however, we should not reinvent the wheel. For instance, if you are a JavaScript developer, there is no need to write a new logger, you have the <em>console.log</em> for that. So, if you see code that is trying to recreate something that already exists, that’s a big code smell.</p><p>OK, now that we know to identify some of the code smells, how can we clean them?</p><h4><strong>Pair programming</strong></h4><p>Short sessions where you have someone else working with you — if you have been working in a set of code for days or weeks, you most likely will miss stuff. Having a fresh set of eyes helps you catch some of the code smells because that person will have questions, such as why you followed certain path on your implementation or because they might have a different perspective of the problem. Plus, discussing your ideas before implementation is a great way to validate them — better design means less refactoring.</p><h4><strong>Commit early and often</strong></h4><p>Every time you commit your code you are comparing your changes to what it is in the repo. That can be very helpful as you will be constantly checking to make sure you didn’t introduce anything unnecessary. For example, if you updated a function and you added 100 new lines to it, maybe you should review it to make sure all that new code is actually necessary.</p><h4><strong>Write tests</strong></h4><p>Unit and integration tests can be a pain, but they are a really good way to verify that your code is at least functional. Also, tests are a good way to actually check if your code is maintainable. If it is too hard to write tests for your code, it might be a good indication that your code is too complex.</p><h4><strong>Code reviews</strong></h4><p>That’s a very good practice to ensure accountability across the team. If you are the only one that knows how the code works and that code breaks while you are out on vacation, then everyone else is kind of stuck. So make sure that you have at least another developer reviewing your code. That will guarantee that, first, someone else is able to understand your code — maintainability/readability checks — and also that someone else in your team has a full knowledge of how things were implemented.</p><h3><strong>So, how bad code can be good?</strong></h3><p>When we write bad code, a lot of us don’t know it is bad code at that time. We don’t know it’s bad until later when we go back to it and find a bug and we need to refactor it. That’s a great opportunity because it’s a learning opportunity. Bad code is a learning opportunity for us to improve ourselves. It’s an opportunity for your code to give you feedback so you can be better. So, when you go back and refactor, now you learned and you will ensure that you don’t write that kind of bad code again in the future.</p><h3><strong>And what is wrong with bad code?</strong></h3><p>We all like to mock bad code and that’s OK, as long as it’s your own code. If we make fun of other people’s code, then things start to get a bit weird. It’s like a passage thing, where if someone makes fun of our code we will find someone’s else code to make fun of it. That’s not good, because new people that come in are afraid to publish anything because they are afraid that they will get mocked too. That’s not a fun environment.</p><p>People also tend to get too attached to their code. Always remember that code it’s just… code. We shouldn’t be too attached to it. Detach yourself from your code and understand that if someone comes up with suggestions for improvements, that person is not talking about you or your personality, they are talking about your code. Code is ultimately zeros and ones, it’s a thing for computers and it’s not about us at all.</p><p>Writing good code is hard. I have been writing code for almost 10 years now and I’m still learning new things and trying to improve. So, the takeaway here is to <strong>accept the bad code so you can become great a developer</strong>.</p><p>If you have any comments or suggestions on how we can turn bad good into good code, or if you have any fun stories from a time where you have written some terrible code, leave it on the comments below. And remember, stays curious and keep coding.</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=586e1ccb0aac" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/the-beauty-of-bad-code-586e1ccb0aac">The Beauty of Bad Code</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Handling Concurrency with Async/Await in JavaScript]]></title>
            <link>https://blog.vanila.io/handling-concurrency-with-async-await-in-javascript-8ec2e185f9b4?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec2e185f9b4</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 22 Jan 2018 18:30:24 GMT</pubDate>
            <atom:updated>2019-03-31T00:22:35.299Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8sKcmssbXLKFugLI." /></figure><p>If you are a JavaScript developer, I’m sure you have heard the infamous phrase “callback hell” before — if you haven’t, or if you don’t even know what a callback means, stick around, I will get to it. But what exactly does it mean? To understand that we have to talk about concurrency and how it is handled in JavaScript. But what exactly is concurrency? To put it simply, concurrency means the execution of multiple tasks over a period of time. For example, we can think about a web server that wants to serve multiple requests for a web page, or a script that wants to read multiple values from a database before it returns the request. When it comes to computer and processors, some tasks can be executed in parallel and some tasks have to done one at a time. But generally speaking, concurrency happens in order-independent or partially-ordered units of work.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/592/0*2T4U5PhDovBPedgV." /></figure><p>Concurrency is one of those real life situations that, although essential, are extremely hard to achieve with computers. Without concurrency, our interaction with computers would be totally different. Can you imagine requesting a file in your network and having the whole OS put on hold while the file is retrieved? OK, that might have been common back in the days but today that would be unacceptable. Concurrency becomes very important when we are dealing with anything that is considered a synchronous activity — a type of activity where the main actor (user, CPU, etc) needs to stop and wait for another activity to be completed.</p><p>So, how programs actually implement concurrency for those kind of activities? Well, there are typically 2 ways, or patterns, for a program to tackle those kind of tasks:</p><ul><li>The first pattern is called blocking — also known as synchronous — style. This pattern heavily relies on multithreading as it needs to continue to serve user requests independently if one of the threads in the list is blocked or not. The blocking style basically stops the execution of a thread and waits for the task to be completed before moving on with that thread. PHP, Ruby and most server-side technologies implement this approach. Since everything is done sequentially, code written following this pattern is readable and also easier to be implemented and maintained.</li><li>The second pattern is the non-blocking — also known the event loop — style. This style relies on a single thread — everything runs in that one thread — which means we cannot block the thread, otherwise the program would stale until the thread is unblocked. This pattern is especially good because we get very high concurrency with low memory consumption. It is also very good for user experiences, as there is always a continuous flow in the application. Thus, that’s why it’s the pattern style adopted by browsers and of course, by JavaScript.</li></ul><p>What happens if we actually force a block — halt any other execution — in JavaScript then? Well, we can use the alert as an example. The alert blocks every other action in the browser. That means that users can’t interact with the page, can’t scroll or even press a button. We should all agree that this is an extremely poor user experience, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/237/0*d2YdoKt3uD7-jJUT." /></figure><p>With that in mind, how do we actually write concurrent software in JavaScript without blocking the browser? Generally, we use what is called callbacks. Callbacks are just the name of a convention for using JavaScript functions. They are pretty straightforward: simply pass a function to the task and make sure that it will be called when the task is completed. For instance, an on-click event is a callback function. You pass a function to the browser document and whenever a user clicks a button, the callback gets fired. Similarly, we have a network request, where we wait for the network request to be finished to fire the callback.</p><pre>// callback style</pre><pre>readFile(&#39;file.txt&#39;, (content) =&gt; {</pre><pre>    console.log(content);</pre><pre>});</pre><p>What are the good things about callbacks? Callbacks are a good low level abstraction for concurrency for asynchronous actions. They perform really well with low overhead and they can execute almost any asynchronous task. What about the downsides? First and most important, using the callback style is really difficult. Writing code to be executed in sequence is already hard, using callbacks and having things being executed in parallel is even harder. Callbacks make code readability very poor. Systems become hard to maintain when there are a lot of callback asynchronous code and are more prone to errors. Second, with callbacks we have to give up on some of the basics constructors such as for/while and try/catch as we can’t have those in a parallel environment. Finally, error handling is also difficult, as tasks can fail during the execution of the process and we have to make sure we have code in place to handle all possible scenarios.</p><p>For example, what is wrong with the code below?</p><pre>// Every day on StackOverflow</pre><pre>function getUserName() {</pre><pre>    let name;</pre><pre>    $.get(&#39;/users/123&#39;, (user) =&gt; {</pre><pre>        name = user.name;</pre><pre>    });</pre><pre>    return name;</pre><pre>}</pre><pre>// Why doesn’t it work?</pre><pre>console.log(&#39;User Name:&#39;, getUserName());</pre><p>For a programmer from a non asynchronous world, this code would have no problems. But for us, JavaScript die hards, this code won’t execute as expected, as the name variable will be returned before it gets set on the fetch task. And because a lot of JavaScript developers also have experience with other programming languages, they tend to write code that resembles those other languages. Thus, they run into what is known as callback hell. The main cause of callback hell is when people try to write JavaScript in a way where execution happens sequentially. You would be surprised by how many people make this mistake.</p><pre>a(function(resultsFromA) {</pre><pre>    b(resultsFromA, function(resultsFromB) {</pre><pre>        c(resultsFromB, function(resultsFromC) {</pre><pre>            d(resultsFromC, function(resultsFromD) {</pre><pre>                e(resultsFromD, function(resultsFromE) {</pre><pre>                    f(resultsFromE, function(resultsFromF) {</pre><pre>                        console.log(resultsFromF);</pre><pre>                    }</pre><pre>                }</pre><pre>            }</pre><pre>        }</pre><pre>    }</pre><pre>});</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*diMheby8HsQsK2Ki." /></figure><p>Now that we know what a callback is, and most important, what a callback hell is, we can talk about what I like to call “callbacks on steroids”.</p><h3><strong>Promises</strong></h3><p>Promises are basically a thin wrapper around callbacks that do a better job at creating code that behaves like sequential code. Promises provide the chaining that we need — execute task 1, wait until it finishes, execute task 2 and continue — and it also provides helpers to execute code in parallel aside of providing a much easier and cleaner way of implementing error handling. Promises work by passing around a representation of a future value. So basically, a promise is nothing more than an object that represents what the value will be when the operation finishes.</p><pre>// Promise style</pre><pre>readFile(&#39;config.json&#39;)</pre><pre>    .then(…)</pre><pre>    .catch(…);</pre><p>On then(). we can attach a handler — or callback — that gets executed whenever the data is finished. This is a much cleaner and linear approach when compared to callbacks.</p><p>With promises, chaining is much easier to implement. In the example below, we need to fetch some data about users logged into an application and then get that user’s friends information. This would be very hard to be done with callbacks because both the user fetch and the friends fetch have to happen in sequence — you can’t get the friends without getting the user first. But with promises, we can call fetchJSON() to get the logged in user — which will return a promise and then get a second promise with all the user’s friends IDs. Now, this is where promises becomes powerful, because now we can take those IDs and use the map function to map each ID with a promise that will get that user’s — the friends — information. We are inf fact creating an array of promises. Finally, we can call promises.all(), which basically just waits for all the promises in the array to finish before returning the final results. That will give us all the details for every friend in the order that they were provided.</p><pre>// This would be very difficult with callbacks</pre><pre>fetchJSON(&#39;/user-profile&#39;)</pre><pre>    .then((user) =&gt; {</pre><pre>        return fetchJSON(`/users/${user.id}/friends`);</pre><pre>    })</pre><pre>    .then((friendIDs) =&gt; {</pre><pre>        let promises = friendIDs.map((id) =&gt; {</pre><pre>            return fetchJSON(`users/${id};`);</pre><pre>        });</pre><pre>        return Promise.all(promises);</pre><pre>    })</pre><pre>    .then((friends) =&gt; console.log(friends));</pre><p>Finally, with promises we can leverage the catch() function to handle errors. That means we don’t have to check every single callback for errors, we can simply attach a catch after all of the promises have been executed. That catch will handle any errors that might happen in each one of the promises.</p><pre>fetchJSON(&#39;user-profile&#39;)</pre><pre>    .then((user) =&gt; { … })</pre><pre>    .then((friendIDs) =&gt; { … })</pre><pre>    .then((friends) =&gt; { … })</pre><pre>    .catch((error) =&gt; {</pre><pre>        console.error(&#39;And error occurred.&#39;);</pre><pre>    });</pre><p>OK, promises are pretty great and much easier to implement and to maintain if compared to callbacks. However, as you may have noticed, we are still relying on callbacks to achieve the sequential functionality that we want — we are still having a callback handler inside our .then() functions. Put in different words, promises are a nicer way of doing callbacks, but we eventually have to pass those callback functions to achieve the desired behavior.</p><p>So, can we do better? To answer that question, we need to fully understand what we want. In short, we just want to have sequential programming, like we are used to in other programming languages. Basically, we want to get our promise, wait for that promise to finish and then continue with the execution of the program. The problem is, as I mentioned in the beginning, JavaScript is fundamentally single-threaded, so we can’t simply pause the execution of the program, wait for the promise to finish and then continue. That is because we don’t want to block the entire thread and have the same bad experience as we have when we use the alert. So what can we do given JavaScript’s architecture? Well, JavaScript has this special thing called a generator function. The generator function allow us to pause a function and get back to it later. That means that only that function is stopped, while the rest of the application continues with its flow. Generators are not about being asynchronous or concurrent, they are just about pausing stuff. Generators work through the “yield” property. The idea behind the yield is that we can use it to pause the execution of the function, wait for something and then later resume it. However, generators can become very complex and they require some other function to control it, resuming the regular flow of the generator function whenever the yield is completed.</p><pre>function* generatorFunc() {</pre><pre>    let result = fetch(&#39;/users&#39;);</pre><pre>    // Pause execution by yielding</pre><pre>    yield result;</pre><pre>    // Later something caused us to resume</pre><pre>    console.log(`We’re back!`);</pre><pre>}</pre><p>So, why am I talking about generators then? Well, because when we combine it with promises, we get exactly what we want: sequential programming style, or async/await!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*87YiF6vZmvtxkjRG." /></figure><h3>Async/await</h3><p>Basically, async/await is nothing more than just a layer of syntax over promises. I dare to say that, aside from being superficially simple, async/await is the most important feature introduced with ES6. As you will see it below, it makes writing code in JavaScript so much easier and it makes the language itself so much more powerful.</p><pre>async function getUsers() {</pre><pre>    // Here’s the magic</pre><pre>    let result = await fetchJSON(&#39;/users&#39;);</pre><pre>    console.log(result);</pre><pre>}</pre><p>The async function is very similar to the function generator. But instead of using the yield, we use the await followed by a promise. The await will pause the execution of the function and wait until the promise is returned. In the meantime, the event loop is still doing its thing. Eventually, when the promise is completed, the function is resumed — without needing any other actors, like with the generator function — and continues with its regular flow. This is the whole idea of async/await. That’s a win because we get back our traditional constructs (for/while, try/catch), our code becomes readable and it flows like normal programming, just like in any other normal threading blocking programming language.</p><p>In the example below we see how simple it is to combine a for loop with async/await. We are just taking a regular browser element and we are looping 100 times and moving it a little bit to the right by increasing the left value by one pixel. But because we want it to behave like an animation, we want to wait in between the frames, so we are going to wait 16 milliseconds between every adjustment of the value of the style. This would be extremely difficult to be achieved with callbacks, but because async/await pauses our function in the middle of the loop, our animation behaves like we expect and the code itself is very simple and readable.</p><pre>async function animate(element) {</pre><pre>    for (let i = 0; i &lt; 100; i++) {</pre><pre>        element.style.left = `${i}px`;</pre><pre>        await sleep(16);</pre><pre>    }</pre><pre>}</pre><p>We can also rewrite our logged in user friends retrieval function and even wrap it in a try/catch constructor. With async/await, the exception is just a traditional, normal regular JavaScript exception. The try block will work exactly as you would expect, and it will send the error to our catch no matter what problem happens. We don’t have to think about async callback errors being different from any other error. We can also still leverage the promises features, as async/await not only needs a promise to work, but also behaves like a promise by returning one — which means we can await on another async function and use it interchangeably with promises.</p><pre>async function getUserFriends() {</pre><pre>    try {</pre><pre>        let user = await fetchJSON(&#39;/users/me&#39;);</pre><pre>        let friendIDs = await fetchJSON(`/friends/${user.id}`);</pre><pre>        let promises = friendIDs.map((id) =&gt; {</pre><pre>            return fetchJSON(`/users/${id}`);</pre><pre>        });</pre><pre>        let friends = await Promise.all(promises);</pre><pre>        console.log(friends);</pre><pre>    } catch(error) {</pre><pre>        console.log(&#39;An error occurred.&#39;);</pre><pre>    }</pre><pre>}</pre><pre>let promise = getUserFriends();</pre><p>Async/await is great, but there are some important points that we need to keep in mind when working with it:</p><ul><li>We can only use await inside of a async function.</li><li>Don’t forget the await and don’t forget that it has to work with promises.</li><li>Be careful about doing too much sequentially, especially if we can actually do it in parallel. For example, if we have too many awaits inside a for loop, that loop will be paused at every iteration. That can directly interfere with the speed of our application and with the user experience.</li><li>Even though it looks synchronous, we have to remember that our code has been paused/resumed. So some of the assumptions we might make about the global state or the global variables might no longer be true after our function has been resumed, because things might have changed in the world while our function was paused.</li></ul><p>As far as support goes, async/await is supported in Chrome, FireFox, Edge, Safari and Node 7.6 and above. Because async/await is just a thin layer on top of generators and promises, for the browsers that don’t support it, we can simply use Babel as it is not that harmful since there isn’t too much Babel needs to do to make it work.</p><p>As we saw, with async/await our code is much cleaner and easier to read when compared to both promises and callbacks. It’s definitely one of the most powerful features in ES6 and one of the driver factors in transforming JavaScript into a more robust language. Hopefully this article helped you have a better understanding of callbacks, promises and most specifically async/await. Now, get out there and shed some light on your fellow friends stuck on a callback hell. And remember: stay curious and keep coding.</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Community of digital makers — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec2e185f9b4" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/handling-concurrency-with-async-await-in-javascript-8ec2e185f9b4">Handling Concurrency with Async/Await in JavaScript</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Blockchain in JavaScript]]></title>
            <link>https://medium.com/@marlon.gerodrigues/blockchain-in-javascript-391eac4e9b09?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/391eac4e9b09</guid>
            <category><![CDATA[blockchain]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 15 Jan 2018 18:36:43 GMT</pubDate>
            <atom:updated>2018-01-15T18:46:21.201Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*NZvC00jM5k8ctfVM_fXnsg.png" /></figure><p>Blockchain. If I had a penny for every time I’ve heard that word in the past 6 months I would probably have as much money now as if I had invested in Bitcoin back when I was in college. Jokes aside, blockchain is definitely a very interesting technology and it has the potential to be one of those players that disrupt not one, but many different industry segments. However, even though it has been the main topic in many debates and it has been the center of attention lately, a lot of people still do not understand how it works. So, what exactly is blockchain? In one sentence, is just a trusted distributed ledger, a record of transactions that occur in a network. OK, I know that, you might say, but why do we need it and why is so disruptive? Well, let’s think about an example: a car leasing business network.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/0*uxPTDc0kuF85qMB4." /></figure><p>In a car leasing network, we usually have different participants. We have the car manufacturer, the dealer, the leasing company, the lessee, the merchant and the regulator. Each one of those participants maintain their own ledgers and their own logs of all the transactions that they make within this business network. This is extremely inefficient, expensive and redundant, as everyone is recording the same log transactions. There is also the problem that if someone’s record disagrees with someone else’s, there is no resolution apart from going to court and letting a judge decide who holds the truth. Blockchain solves this problem by providing a shared replicated ledger. That means that there is only one ledger in the network, with each participant having a copy of it and being able to update it. In our example, the ledger is also permissioned, which guarantees that each participant only has permission to see what they are allowed to see on that ledger.</p><p>With that said, we can state that blockchain has 4 key characteristics:</p><ul><li>Consensus — everyone in the network has to agree on the changes that get recorded on the ledger.</li><li>Provenance — participants can use the blockchain ledger to track the history of an asset and see where it came from.</li><li>Immutability — once something gets recorded on the blockchain ledger, it’s there forever and that is guaranteed by the blockchain.</li><li>Finality — the blockchain is the single source of truth. Participants can’t use their own ledger to compare it to the blockchain ledger. The blockchain ledger should be the source of truth, forever.</li></ul><p>Now that we now what a blockchain is and how it can be used, we can move on into how we can actually implement a simple blockchain, which hopefully will help you make sense out of everything that has been said so far. I will use JavaScript simply because that’s my favorite programming language, but you could implement this in any other programming language of your choice. Keep in mind, it won’t be anything too fancy but it will be just enough so you can understand how a blockchain actually works. Because a lot of of the hype around blockchain was triggered by Bitcoin — and also because it seems like there is a new ICO every other day now — let’s imagine we are creating a new coin, and because that coin is better than any other coin out there, let’s call it theBestCoin — I know, very clever.</p><p>We start by creating a new JavaScript file in our <a href="https://medium.com/@marlon.gerodrigues/whats-your-favorite-code-editor-ff0eb024b03c">favorite code editor</a> to store all of our code. Let’s call this file main.js. We then start defining what a block on our blockchain will look like. Let’s create a class called Block and let’s give it a constructor. This constructor will receive a set of properties that will represent a block. To keep things simple, each block will have an index (a unique identifier that tell us where the block sits in the cain), a timestamp (when the block was created), some data and a previous hatch. The data could be any type of data that you want to associate with this block (in case of currency, you might want to store the details of the transaction, such as how much money was transferred and who were the sender and the receiver. The previous hash is a string that contains the hash of the previous block. This is very important and it ensures the integrity of our blockchain.</p><pre>class Block {<br>    constructor(index, timestamp, data, previousHash = &#39;&#39;) {<br>        this.index = index;<br>        this.previousHash = previousHash;<br>        this.timestamp = timestamp;<br>        this.data = data;<br>    }<br>}</pre><p>In our constructor, we will also add another property called hash. The hash property will contain the hash of our block, which means we need to calculate it. That will be handled by the calculateHash() method.</p><pre>constructor(index, timestamp, data, previousHash = &#39;&#39;) {<br>    this.index = index;<br>    this.previousHash = previousHash;<br>    this.timestamp = timestamp;<br>    this.data = data;<br>    this.hash = this.calculateHash();<br>}</pre><p>The calculateHash() method calculates the hash of the block by running all the block’s properties through a hash function and then returning that hash. That hash will be used to identify our block on the blockchain. For the hash, we will use SHA256 as the hash function. Since that is not available in JavaScript by default, we will need to import a library that can do that for us. Let’s install crypto-js through NPM.</p><pre>npm install crypto-js — save</pre><p>The crypto-js library will be added to our node_modules folder and we will be able to require it in our main.js.</p><pre>const SHA256 = require(&#39;./node_modules/crypto-js/sha256&#39;);</pre><p>With that in place, here’s how our calculateHash() function will look like:</p><pre>calculateHash() {<br>    return SHA256(this.index + this.previousHash + this.timestamp +<br>                  JSON.stringify(this.data)).toString();<br>}</pre><p>Note that we need to cast the result of the SHA256 function to a string, otherwise we get an object.</p><p>Let’s now create a new class for our blockchain. The new class, called Blockchain, will have a constructor where our blockchain will be initialized. The constructor will initialize the property chain, which will represent an array of blocks. The first block on a blockchain is called a genesis block and it should be added manually. We will create a function called createGenesisBlock() that will return a new block with index 0 and some data. In the genesis block, we will also set the previousHash property to 0 since this is the first block in the chain and it cannot point to any previous block.</p><pre>class Blockchain {<br>    constructor() {<br>        this.chain = [this.createGenesisBlock()];<br>    }</pre><pre>    createGenesisBlock() {<br>        return new Block(0, &quot;14/01/2017&quot;, &quot;First Block&quot;, &quot;0&quot;);<br>    }<br>}</pre><p>Let’s also add other methods to our Blockchain class that could be useful. Let’s add the getLatestBlock() and the addBlock() methods. The getLatestBlock() method simply returns the latest block in the chain — the last element in the chain array.</p><pre>getLatestBlock() {<br>    return this.chain[this.chain.length — 1];<br>}</pre><p>The addBlock() method is responsible for adding a new block on to the chain. It receives a new block and sets both the previousHash and the hash properties of the new block. The previousHash is simple the hash of the last block on our chain, while the hash is calculated by the block’s calculateHash() method.</p><pre>addBlock(newBlock) {<br>    newBlock.previousHash = this.getLatestBlock().hash;<br>    newBlock.hash = newBlock.calculateHash();<br>    this.chain.push(newBlock);<br>}</pre><p>Keep in mind that in reality, you shouldn’t be able to add new blocks so easily as there are numerous checks in place, however, for our little blockchain, this is more than enough and it demonstrates how a blockchain actually works.</p><p>With both of our classes completed, its time to test it. Let’s create a new instance of our blockchain and called it theBestCoin. We will add a few blocks to our theBestCoin to verify that our blockchain is working properly.</p><pre>let theBestCoin = new Blockchain();<br>theBestCoin.addBlock(new Block(1, &quot;15/01/2017&quot;, { value: 5 }));<br>theBestCoin.addBlock(new Block(2, &quot;15/01/2017&quot;, { value: 10 }));</pre><pre>// show results<br>console.log(JSON.stringify(theBestCoin, null ,4));</pre><p>Once we run our code, we will the get the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/642/0*8WvIsIa28PbeWWp6." /></figure><p>We have our blockchain object with a property called chain, which is an array containing all of the blocks in our chain. We can also see that each block references the previous block. Celebrate my friend, we have a working implementation of a blockchain.</p><p>Now that we know that it works, let’s try to improve our blockchain a bit more. Blockchains are great because once a block is added, it cannot be changed without invalidating the rest of the chain, but in our implementation, there is no way for us to verify the integrity of our blockchain. So let’s add a new method to our Blockchain class called isChainValid(). This method will return either true, if the chain is valid, or false if something is wrong. In order to verify the integrity of our chain, we will loop over the entire chain starting from index 1 — we will skip the genesis block as this is guaranteed to be truthy — and verify that the blocks are correctly linked and that each block has the correct hash.</p><pre>isChainValid() {<br>    for (let i = 1; i &lt; this.chain.length; i++) {<br>        const currentBlock = this.chain[i];<br>        const previousBlock = this.chain[i — 1];</pre><pre>        if (currentBlock.hash !== currentBlock.calculateHash()) {<br>            return false;<br>        }</pre><pre>        if (currentBlock.previousHash !== previousBlock.hash) {<br>            return false;<br>        }<br>    }</pre><pre>    return true;<br>}</pre><p>Let’s now verify the integrity of our block. Since we haven’t done anything to tamper with our chain, our blockchain should be valid.</p><pre>console.log(`Is Blockchain valid? ${theBestCoin.isChainValid()}`); // will return true</pre><p>Now, let’s try and tamper with our blockchain. Let’s change block 2 (index 2) and override its data. The isChainValid() method will now return false because the calculated hash of the updated block is different than the actual block’s hash.</p><pre>theBestCoin.chain[1].data = { value: 50 };<br>console.log(`Is Blockchain valid? ${theBestCoin.isChainValid()}`); // will return false</pre><p>We can check even further and actually update the hash property by re-computing the hash once the block is updated. The isChainValid() method will still return false, because the relationship of that block with its previous block has now been broken.</p><pre>theBestCoin.chain[1].data = { value: 50 };<br>theBestCoin.chain[1].hash = theBestCoin.chain[1].calculateHash();<br>console.log(`Is Blockchain valid? ${theBestCoin.isChainValid()}`); // will return false</pre><p>The blockchain is meant to add blocks to it, but never to delete or change a block. Of course, if you detect that a new block broke the chain or if something is wrong with the chain, then you should have a mechanism that rolls back the changes and puts the blockchain back in a correct state, but we won’t go into that to keep our blockchain as simple as possible.</p><p>And there you go, we have our own blockchain. It lacks many features such as proof of work and peer-to-peer network to allow communication between miners. There is also no checks to verify that a user has enough funds to make a transaction. However, aside all of its limitations, our little blockchain perfectly demonstrates how a blockchain works behind the scenes. Now, get out there, start your own ICO and become a millionaire. And remember: stay curious and keep coding.</p><p>You can see the full implementation of our blockchain at <a href="https://github.com/marlon-rodrigues/BlockchainJS/blob/master/main.js">https://github.com/marlon-rodrigues/BlockchainJS/blob/master/main.js.</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=391eac4e9b09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ES6 Modules]]></title>
            <link>https://blog.vanila.io/es6-modules-ccd896b50d22?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ccd896b50d22</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[modules]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 19:14:03 GMT</pubDate>
            <atom:updated>2019-04-02T01:16:49.434Z</atom:updated>
            <content:encoded><![CDATA[<figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*weDRSo8Hz1DUWOtBXrm33A.jpeg" /></figure><p>Thanks to ES6, we finally have a proper native option to load our JavaScripts files into our projects without having to rely on script tags. Up to the ES6 specification, JavaScript didn’t have any sort of import system, which is part of the basic structure of any programming language. That meant that we had to rely on script tags and hope that they would be imported in the order we needed them to run. That’s far from ideal and could introduce a lot of problems to the project, as the order of the script tags would directly interfere on the code flow. ES6 introduced the concept of modules in JavaScript, which is basically the idea to import/export files within your project. ES6 modules — also known as JavaScript modules — are supported by all major browsers — which obviously exclude our beloved IE, although Edge does support it.</p><p>But what do they do and how do they work? Modules can be seen as self contained files with a very specific task. You can have your own modules — for example, different JavaScript files for the different pages of your application — or you can download modules via NPM or Yarn — there are plenty of modules available out there, with anything ranging from jQuery to HTML preprocessors. You can also have module dependencies — where a module imports from another module — as well as circular dependencies, with the caveat that some exports aren’t available until completion. ES6 modules have very simple specifications. You can create a module following one of the patterns below:</p><ul><li>Include a script to run as a module:</li></ul><pre>&lt;script type=&quot;module&quot; src=&quot;code.js&quot;&gt;&lt;/script&gt;</pre><ul><li>Add an inline script tag as a module:</li></ul><pre>&lt;script type=&quot;module&quot;&gt;<br>     console.log(&quot;Hi, I’m a module!&quot;);<br>&lt;/script&gt;</pre><ul><li>Use the export keyword on your JavaScript file on the functions/objects you want to export. It’s important to notice that there are two kinds of exports: Named exports and default exports. Named exports are useful to export several values, which is the opposite of default exports, whereas there can be only one default export. Check out the <a href="https://developer.mozilla.org/en-US/docs/web/javascript/reference/statements/export">MDN</a> documentation for more details on the differences between both types. Here is an example of a named export:</li></ul><pre>// code.js<br>export function helloWorld() {<br>     return &quot;Hello World, I am a module!&quot;;<br>}</pre><p>Now, you can simply import those modules by using the <em>import </em>keyword:</p><pre>// view.js<br>import {helloWorld} from &quot;./code.js&quot;;<br>console.log(helloWorld());</pre><p>And that’s it, easy peasy, isn’t it? But you might be asking yourself, what exactly can I export in my modules? Basically, you can export anything that is dynamically generated, such as functions, classes, objects or primitive values. What you cannot do is have an optionally export statement, such as the following:</p><pre>// code.js<br>export const foo = &quot;I’m a module&quot;;  // allowed</pre><pre>const index = 0;<br>if (index === 0) {<br>    export index; // NOT allowed<br>}</pre><p>Now, if we look at the other end, the rules for Import are also quite simple. There are basically 3 rules for imports:</p><ul><li>Your imports have to happen at the top level of the file</li></ul><pre>// Import not at top level<br>try {<br>    import {helloWorld} from &quot;./code.js&quot;;<br>} catch (e) {}</pre><ul><li>You cannot import from an unqualified path</li></ul><pre>import * from &quot;myCode.js&quot; // not a qualified path</pre><ul><li>You cannot import a dynamically generated script</li></ul><pre>import {helloWorld} from &quot;./&quot; + vendor + &quot;.js&quot; // dynamic import</pre><p>As I mentioned earlier, ES6 modules are only supported by modern browsers, which means that older browsers, such as IE11 and below, don’t offer support to it — <a href="https://caniuse.com/#feat=es6-module">see full list of supported browsers</a>. So, what to do in those cases? We basically have 2 options: We can either use a transpiler, such as Babel, or we can ship 2 sets of code for our application, one for modern browsers and a legacy version for older browsers. For the second option, we can rely on the fact that older browsers simply ignore what they don’t understand. So we can simply tell them, ‘hey, here is this module script’, and they will simply ignore it, which means that none of our ES6 modules will be used. For modern browsers, we use the <em>nomodule</em> tag to send code to legacy browsers, which browsers that support ES6 modules will also ignore it.</p><pre>// Legacy script with nomodule tag<br>&lt;script src=&quot;codeLegacy.js&quot; nomodule&gt;&lt;/script&gt;</pre><p>OK, so ES6 modules are great and represent the next step in JavaScript development, but if we still need to support legacy browsers in our application, why should we bother with it at all? First, ES6 modules represent immediate dev cycle. If you are not using modular code, to test your application, you have to build and run the application after every change to check the output. With ES6 modules, you can simply save a file and refresh your browser to see the output, seriously, how cool is that? That’s the modern — and effective — way of doing web development. Second, it’s an ECMAScript6- A.K.A. ES6 — feature. That means that any browser that supports ES6 modules, will also support a load ton of other ES6 features — such as async/await, promises, custom elements, etc — that can basically help us rewrite our application in a more modern and effective way. The web moves fast and legacy browsers will soon — hopefully — be just a vague memory of simpler times. We should definitely be focusing on writing applications that work and take full advantage of what the future of the web can offer. With that approach in mind, we will be rewarding users that use modern browsers, which will push more and more people to abandon legacy browsers.</p><p>OK, now we know what ES6 modules are, what they do and where they are supported. But how exactly your JavaScript code changes when you starting using modules? To start, modules always run in strict mode, which means that by default, your mistakes — sorry to break it down to you buddy, but perfect code is not a thing — will turn into actual errors. Module code is always effectively invoked in what we call an IIFE — an immediately invoked function expression. That means that the functions/objects found in a module won’t populate your global scope. This is a huge advantage, as we all know how important it is to keep our global scope clean in JavaScript. With that in mind, it’s import to note that even though ES6 modules don’t populate the global scope, they still can access things in the global scope, which is perfect for cases where you want to handle objects available in the global scope in your modules. Modules are deferred by default, which means they aren’t actually allowed to run synchronously, the reason for this being that if you have a lot of dependencies, your browser can be sitting there for a long time fetching all those files before your page can continue running. If you need to, you can set your modules to run asynchronously, which means that fast-loaded or cached modules will run in any order as soon as they are downloaded. Modules are imported only once. No one actually accidentally includes multiple versions of the same code — at least we hope that’s the case — but because modules are kind of like a tree graph, two files that include the same dependency will actually get the same module back and it will only run the module once. That’s a big gain, as it prevents the same code from being run multiple times. And last but not least, module imports, just like functions, are hoisted, which means we can reference module functions/object before the actual module import, since hoisting will guarantee that the modules are actually imported before any other code is executed.</p><p>ES6 modules are definitely one of the features that helps JavaScript evolve into a more robust programming language. Any developer considering doing proper web development should definitely take advantage of it. With modules, the way we write JavaScript code changes a bit, but it’s a pretty subtle and beneficial change, with most of it related to the way we interact with files. Now that you have a basic understanding of ES6 modules, give it a go and let me know what your thoughts are in the comments below. And remember, stay curious and keep coding!</p><figure><a href="https://community.vanila.io/"><img alt="" src="https://cdn-images-1.medium.com/max/880/1*oBt6QPSGBCr5krApJ4ruZw.png" /></a><figcaption>Let’s grow together — <a href="https://community.vanila.io/">Join now</a></figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ccd896b50d22" width="1" height="1" alt=""><hr><p><a href="https://blog.vanila.io/es6-modules-ccd896b50d22">ES6 Modules</a> was originally published in <a href="https://blog.vanila.io/">Vanila Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Let’s Encrypt]]></title>
            <link>https://medium.com/@marlon.gerodrigues/lets-encrypt-8e94d5aec4d0?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e94d5aec4d0</guid>
            <category><![CDATA[security]]></category>
            <category><![CDATA[encryption]]></category>
            <category><![CDATA[lets-encrypt]]></category>
            <category><![CDATA[ssl]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 19:12:39 GMT</pubDate>
            <atom:updated>2018-01-08T19:14:50.740Z</atom:updated>
            <content:encoded><![CDATA[<p>In 2017 security has been one the hot topics, with several cases of data breach been brought to our attention — Uber, Equifax, Yahoo!… the list is extensive. With that in mind, I decided to change gears in the blog for a moment to talk about one of the key components in internet security and that unfortunately is still overseen by a lot of companies: Encryption and how a new open source automated certificate authority is trying to help us, developers, maintain our applications secure.</p><p>Encryption is very important when it comes to the internet, as it is the key point on making a web site/web application a safe spot for users. A secure web application gives users the confidence to navigate and interact in a trusted environment. The easiest way to spot a secure page is by checking the URL bar on the browser. If the page has a secure connection, it will display a lock icon or a green bar.</p><p>For a long period, getting a SSL certificate — data files that digitally bind a cryptographic key to the organization details and when installed in the web server, it activates the padlock and the HTTPS protocol, allowing for secure connections between the web server and the browser — for a web site/web application was a costly and demanding process. You could either setup SSL on your own server, which required you to be familiar enough with servers and network configurations to setup it up or you could use the secured server that your web host provided.</p><p>In an effort to provide a more secure connection for every web site/web application out there, with low cost and easy-to-use service, the Internet Security Research Group (ISRG), sponsored by companies such as Mozilla, Google, Facebook and Cisco, created “Let’s Encrypt”, a free, automated and open certificate authority (CA) for the public’s benefit. With Let’s Encrypt, developers can setup a HTTPS connection for their application and have it automatically obtain a browser trusted certificate, without any human intervention. Let’s Encrypt can be installed on shared servers on host providers such as Site Ground, which means that you no longer need a dedicated server with a dedicated IP address to have a secure connection, and not to mention again, the service is free. Although Let’s Encrypt was released a little over a year ago, it already has issued more than a 100 million certificates, helping the rate of change for page loads on the web using HTTPS go up to nearly 58% — 18% more than before Let’s Encrypt was release. That’s a considerable number, especially if we take into account that it took the web nearly 20 years to get to the previous 40%.</p><p>Using the service is very simple: Let’s Encrypt simply runs a certificate management agent on your own web site/web application server (your host provider) instead of a third party server. Basically, there are two steps necessary for it to work:</p><p>1 — The certificate management agent needs to validate that your domain is in fact controlled by your webhost. To achieve this, Let’s Encrypt creates a new key par file in a specified path on the webserver and validates its content against its CA upon signature — note that when a secure connection is requested, the domain must sign in with the certificate authority. Let’s Encrypt CA simply checks that the key pair value on the file has the expected content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/772/0*HztkLJZnKD-AgRB3.png" /></figure><p>2 — Once the agent has validated the domain, it creates a PKCS#10 Certificate Signing Request that tells Let’s Encrypt to issue the certificate with a specified public key. That public key is sent back to the agent, which at that point knows that a secure connection is valid.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/0*p9PSFkC64z1Rpjd7.png" /></figure><p>Encryption and secure connections on the web are becoming more and more important. For instance, Google sees the importance of providing a secure navigation for end users, and because of that, it gives a minor ranking boost to all web sites with a secure protocol (HTTPS). Although minor, it can potentially impact SEO results, and it will put a web site under a competitor that has HTTPS. A secure connection is also important to keep user’s personal data encrypted and unavailable to hackers and malicious web sites. It is especially important on web applications where payments can be made, as you do not want to have your user’s credit card information travelling over the web without any encryption. The whole internet is moving toward a more secure place, and Let’s Encrypt is a great initiative and it will allow small and medium web sites/web applications to provide a secure connection with no cost, which will definitely help make the internet a better, and safer place. To know more about Let’s Encrypt, check it out <a href="https://letsencrypt.org/">https://letsencrypt.org/</a>. And remember, stay curious and keep coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e94d5aec4d0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What’s Your Favorite Code Editor?]]></title>
            <link>https://medium.com/@marlon.gerodrigues/whats-your-favorite-code-editor-ff0eb024b03c?source=rss-e226a4cd06cd------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff0eb024b03c</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[code-editor]]></category>
            <category><![CDATA[sublime-text-3]]></category>
            <category><![CDATA[phpstorm]]></category>
            <category><![CDATA[netbeans]]></category>
            <dc:creator><![CDATA[Marlon Rodrigues]]></dc:creator>
            <pubDate>Mon, 08 Jan 2018 19:11:38 GMT</pubDate>
            <atom:updated>2018-01-08T19:11:38.066Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating a web application takes long hours of planning, lots of designs iterations and of course, execution — which involves lots of code and countless trips to the coffee machine. Writing code can almost be compared to painting. To create a painting, you need a set of color pallets, paper, brushes and of course, your favorite caffeinated beverage. In that analogy, the brush would be the developer’s code editor. Can you imagine a painter trying to create a piece of art without a brush? — well, yes, you can use your fingers and all, but that’s a topic for another post — That’s the same for us developers. Having in hands the right code editor will definitely improve your productivity, saving you time and a few trips to the coffee machine. Back in the days there weren’t many options of code editors for web developers, with the most popular being FrontPage and Dreamweaver — if you find a website today that has that 90’s look (yes, they are still out there), trust me, it was created using one of these two editors. Fortunately, the web evolved, so did the code editors. Today there are many different options with many different functionalities suited for specific tasks/languages and project complexity. Let me tell you my favorites:</p><p><strong>Sublime Text</strong></p><p>Build by Jon Skinner, a former Google Software Engineer, Sublime is a beautiful light weight editor with great features. Considered one of the best editors out there, Sublime offers full package control, is easily manageable and its cross platform. Sublime has a built in Python complier, which allows you to experiment your code in real time. Most important, Sublime is loved and supported by a big community, with a repository containing all sorts of packages that can be easily found and installed.</p><p><a href="https://www.sublimetext.com/">https://www.sublimetext.com/</a></p><p><strong>Notepad++</strong></p><p>A free source code editor based on the powerful editing component <a href="http://www.scintilla.org/">Scintilla</a>, Notepad++ uses pure Win32 API and STL which ensures a higher execution speed and smaller program sizes. Notepad++ supports several languages — including markup languages. It also has support for macros and plugins, but most important, it has support for auto completion — although limited to a few languages — and syntax highlighting and code folding. On top of all that, Notepad++ is also good for the environment! Because of its optimization in execution speed, Notepad++ allows the PC to reduce power consumption, which results in a greener environment — how cool is that?</p><p><a href="https://notepad-plus-plus.org/">https://notepad-plus-plus.org/</a></p><p><strong>PHP Storm</strong></p><p>PHP Storm is a featured packed IDE (Integrated Development Environment) licensed by JetBrains. It has become increasingly popular overs the last couple of years due to its version control system integration, support for remote deployment and support to all major PHP frameworks. Although not free, PHP Storm provides an extreme amount of time savings shortcuts, refactoring tools and advanced syntax-highlighting that is better when compared to the free editors. It also allows developers to quickly navigate through the program flow and to integrate with Git, which by itself makes it worth the cost.</p><p><a href="https://www.jetbrains.com/phpstorm/">https://www.jetbrains.com/phpstorm/</a></p><p><strong>Netbeans</strong></p><p>Netbeans is also a full packed IDE, recommended especially for professional software development. Although more robust than the other mentioned editors, Netbeans is perfect if you want to have as much control as possible over your project. With Netbeans you can easily create FTP connections, have framework management prior to the project creation, auto-reload pages on browsers upon save, and much more. It’s user friendly interface allows users to quickly interact and share code. Netbeans supports several languages and its free.</p><p><a href="https://netbeans.org/">https://netbeans.org/</a></p><p><strong>TextMate</strong></p><p>Created by Allan Odgard, TextMate features declarative customizations, tabs for open documents, recordable macros, folding sections, snippets, shell integration and extensible bundle system. Behind the scenes, TextMate is very well designed and coded. TextMate does all the little details it has cleanly and smoothly. One of the biggest disadvantages — or advantages, depending on how you look at it — is that TextMate is only supported on Macs. So, if you are a PC user and want to use TextMate, I’m sorry but you are out of luck.</p><p><a href="https://macromates.com/">https://macromates.com/</a></p><p>At the end of the day, the editor that will fit you better is the one where you feel more comfortable and the one that allows you to be more productive. I personally love Sublime Text and use it extensively on most of my projects. When trying to decide which one is the best for you, you should just install it and give it a go, playing a bit with the different features and sticking with the one that is more applicable to the kind of project you are working on. Just like paintings, the end result and quality of your web app will depend much more on your ability to code than on the code editor of your choice, but having a good editor will definitely make the creation experience much more pleasant. If you have a favorite code editor other than the ones I mentioned, comment it below, I’m always on the lookout for the next cool thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff0eb024b03c" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>