<?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 Samuel Coelho on Medium]]></title>
        <description><![CDATA[Stories by Samuel Coelho on Medium]]></description>
        <link>https://medium.com/@codingsam?source=rss-58cf94a36c97------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*6C8lL-kotEXB-7qULVCuhw.jpeg</url>
            <title>Stories by Samuel Coelho on Medium</title>
            <link>https://medium.com/@codingsam?source=rss-58cf94a36c97------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 07:08:10 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@codingsam/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 really is a constant in Javascript and what it is not]]></title>
            <link>https://medium.com/@codingsam/what-really-is-a-constant-in-javascript-and-what-it-is-not-d3a8a9f655c2?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3a8a9f655c2</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sun, 11 Oct 2020 16:36:50 GMT</pubDate>
            <atom:updated>2020-10-22T21:15:42.484Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*HVikVoNhDwirnRXf" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><h3>Introduction</h3><p>I have been coding in Javascript in the last 2 years of my full time job, using the most recent <a href="https://www.ecma-international.org/publications/standards/Ecma-262.htm">ECMAScript</a> standard, which has all the cool features. One of them, is to be able to define constants. Other programming languages already had this feature. In Javascript this was not possible to do until ES6 came out and introduced the <em>const</em> keyword.</p><p>Sometimes, while I am talking to other developers, I can see some confusion around constants. Some people think that constants are more than they really are. I decided to write this post to make it clear what really is a constant in Javascript once and for all. If you are a developer who writes Javascript code, do you think you really know what constants are? For instance, if you have an object declared as a constant, can you still do the same things as if it was just a normal variable?</p><h3>What is a constant in Javascript?</h3><p>The <em>const</em> keyword allows you to assign a name to a value, just like <em>let</em> or even the <em>var </em>keyword (remember the old Javascript days?). However, once you assign a value, you cannot reassign another value. For instance, if you do const a = 2; , then, you cannot do a = 3; . When you run your code, it will return an error. This is not true for the <em>let </em>keyword. If you do let a = 2; , then you can do a = 3; .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/792/1*znbvPTNm4CzyNQH4wvUn2w.png" /><figcaption>Trying to assign another value to the same constant</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/214/1*yYlL3vcKbDbBYteVm8DPvw.png" /><figcaption>Assigning another value to the same variable</figcaption></figure><p>Pretty simple, right? If you have experience with other programming languages that have this constant feature, once you jump to Javascript ES6, you get the idea pretty quickly. For instance, in C++ there is also <a href="https://en.cppreference.com/w/c/language/const"><em>const</em></a>. In Java there is <a href="https://www.w3schools.com/java/ref_keyword_final.asp"><em>final</em></a>. They all do the same!</p><p>Even though, this <em>const</em> keyword implements a pretty simple concept, sometimes there is some confusion around it. If you come from a programming language that does not have constants or if you still code in <a href="https://www.ecma-international.org/ecma-262/5.1">ES5</a> Javascript, you only have the <a href="https://www.ecma-international.org/ecma-262/5.1/#sec-12.2"><em>var</em></a> keyword to declare variables. It might be the first time you are exposed to constants in programming languages. Once you get it, you realise how awesome such a simple feature is. It allows you to write less error-prone code. If you have some Javascript extensions for you text editor, you can even get errors about trying to change constants right on your text editor before you try to run the code!</p><h3>What is not a constant?</h3><p>At this point, this constant feature should be clear to you, right? It should be if you only think about numbers, booleans and strings. What happens when you start working with objects and arrays? What it means to do something like const person = { firstName: &#39;Sheldon&#39;, lastName: &#39;Cooper&#39; }? Can I do person.age = 30? Usually, we think about something constant as something that never changes. If I declare the <em>person</em> variable as a constant, should I be able to change it? If you try to run that code in the Javascript console of your browser, no errors are thrown!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/862/1*oyHVNdd0b9uZv8Rc6fj8BA.png" /><figcaption>Declaring an object as a constant and adding a property to that object</figcaption></figure><p>Why this happens? Because…</p><blockquote>The <em>const </em>keyword means you cannot other value to the same name. It doesn’t mean that the value is immutable!</blockquote><p>Basically, the <em>const </em>keyword only defines one rule. You can assign a value only once. Unlike <em>var</em>, both <em>let</em> and <em>const </em>keywords use block scope. If you want to know more about the difference between these keywords and their scopes, check my post about “<a href="https://blog.usejournal.com/awesome-javascript-no-more-var-working-title-999428999994">Why don’t we use var anymore?</a>”</p><p>In an assignment, if the left side of it (the variable’s name) holds a mutable value, that value is still mutable.</p><p><strong>You can do:</strong></p><p>const person = { firstName: &#39;Sheldon&#39;, lastName: &#39;Cooper };</p><p>person.age = 30;</p><p><strong>You cannot do:</strong></p><p>const person = { firstName: &#39;Sheldon&#39;, lastName: &#39;Cooper };</p><p>person = { firstName: &#39;Rajesh&#39;, lastName: &#39;Koothrappali&#39; }</p><h4>Is it possible to achieve immutability?</h4><p>Just because you use the <em>const </em>keyword, doesn’t mean you can make sure that a value cannot change. You can always change elements in an array and properties in an object.</p><p>Is it possible to create an object or an array and prevent changes to it? Yes! But, there is one small detail. Let me show you an example. Let’s use the same <em>person</em> constant with a slightly different structure:</p><p>const person = { name: { first: &#39;Sheldon&#39;, last: &#39;Cooper&#39;} };</p><p>Note that the <em>person</em> object has a <em>name</em> property, which is also an object with two properties, <em>first</em> and <em>last</em>.</p><p>You can make this <em>person</em> immutable using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/freeze">Object.freeze</a> function.</p><p>const person = Object.freeze({ name: { first: &#39;Sheldon&#39;, last: &#39;Cooper&#39; } });</p><p>Then, if you try to change the name property, nothing will happen and the <em>person</em> object will hold the same values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E09Dw-nqjgezWS8UegGxbg.png" /><figcaption>Freezing an object</figcaption></figure><p>However, this might not be enough protection. The <em>name</em> property is also an object with two properties. What happens if you try to change one property of the <em>person</em>’s name?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/514/1*AaMv_njvwcbSb2vY-Q71og.png" /><figcaption>Changing values in objects inside a frozen object</figcaption></figure><p>As you can see, you can still change some properties in a frozen object.</p><p>If you want true immutability, you have to call Object.freeze on all properties of the object.</p><h3>Conclusion</h3><p>After a lot of time coding in Javascript, I could see some confusion around constants. The feature to be able to declare a variable that cannot be reassigned is something that wasn’t part of the first version of the language. If you have experience coding in programming languages that have constants, you easily get familiar with it once you start coding in Javascript. However, it can get a bit unclear if you don’t have such experience.</p><p>You can declare constants in Javascript by using the <em>const </em>keyword, for instance const person = { firstName: &#39;Sheldon&#39;, lastName: &#39;Cooper&#39; }; . When you do that, you are not allowing to assign some other value to the same name in the same block. However, if the value is an object or an array, you can still change some properties inside, because a constant is not immutable. If you need immutability, you can use Object.freeze . But, you need to have in mind that, if some of the properties inside the frozen object are also objects, you still can change those values.</p><p>I hope you liked it and learned something!</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3a8a9f655c2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What Really Is a Smart Home?]]></title>
            <link>https://medium.com/@codingsam/what-really-is-a-smart-home-f7fca5eb1ac4?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/f7fca5eb1ac4</guid>
            <category><![CDATA[home-improvement]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[smartphones]]></category>
            <category><![CDATA[smart-home]]></category>
            <category><![CDATA[home]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sun, 31 May 2020 22:38:35 GMT</pubDate>
            <atom:updated>2020-06-02T15:35:50.616Z</atom:updated>
            <content:encoded><![CDATA[<h4>A home that can be controlled remotely by smartphone…</h4><p>Since the first time a touched a computer I got eager to learn more and more about it. Nowadays I am a grown up and I am a professional software developer. Technology is just my passion. This means, I usually read articles and watch videos about the most recent tech, the latest computers, smartphones and since a couple of months ago, smart home technology.</p><p>More than two years ago, I bought a cheap apartment. It felt like a really good deal and a lot of work at the same time. Not only filling the house with furniture but also, painting, fixing things and installing lights. You have a lot of options for lights these days. There are lights with a wireless remote controller and others that you can control using an app on your smartphone. The latter seemed to be quite cool! But, only in a tech point of view. After thinking about it for a while, it seemed to be a solution for a problem we didn’t have! So, what was the point?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qiPQalj-tMRgiH5X5mws9g.jpeg" /></figure><p>Two years ago, smart lights seemed to be just a more expensive product without that much of added value. It is awesome that you can change brightness and color with an app. But can’t you do the same with a simple remote? Are you supposed to take the smartphone out of your pocket, open the app and then turn the lights on? Even if you think this is acceptable, what happens when you have lights from one brand in the kitchen and other brand in the living room? You can try to use the same brand everywhere but, the truth is, the same brand does not make all the products.</p><p>Let’s say you want to install light bulbs on the ceiling and a lightstrip behind your TV. One brand can have good quality bulbs but is the same brand really good on lightstrips? This can get even worse when you think about adding more smart home devices, like smart vacuum cleaners, smart plugs, etc. It’s very unlikely that you find a brand that makes them all. You end up with lots of apps on your smartphone. This can get really messy.</p><p>For a long time, I didn’t play along with this smart home technology. A lot of apps to control everything. Having different apps to use lights and other devices in my house didn’t make sense. I end up installing just regular lights. However, less than a year ago, this changed. Now I have some smart lights and smart plugs. What changed? Why does it make sense now? It started to make sense when I realized what this technology is all about, which is, making your home smarter. We need to know, what really is a smart home.</p><h3>What is a Smart Home?</h3><p>If you google this question, this is the answer that you’re going to find:</p><blockquote>“<a href="https://www.lexico.com/definition/smart_home">A home equipped with lighting, heating, and electronic devices that can be controlled remotely by smartphone or computer.</a>”</blockquote><p>Pretty straightforward, right? If you install lights that can be controlled by an app on your smartphone, you are on your way to live in a smart home! The main selling point of these devices is usually the possibility to control them wherever you are. But really, how many times you think you will be in China and need to control your lights in your house somewhere in Europe? Don’t get me wrong, I think the remote control feature can be useful in some cases and it is something that is nice to have. But, is it worth your money? I asked this question myself when I thought about this… Is it worth my money?</p><p>However, some devices are really useful, with or without an app. For instance, a vacuum cleaner that automatically cleans the floor. That sounds awesome! Specially if it is capable of creating a map of your house and do its job in an efficient way.</p><h3>Can we find a better answer?</h3><p>So far, there is an answer to the previous question. Basically, you have a device and an app to control it. You install it and you just turned your home into a smart home. But, if I have to open an app to turn on the device, is it really that smart?</p><p>Let’s think about a simple example. Let’s say you have a “smart” bedside light. You wake up in the morning and want to turn that on. Since it is a smart light, you have to grab your phone, open the app, and turn on the light. In the old days, you would just press the light switch. There are products that include a controller, or at least allow you to buy a separate one and pair it with your lights. This way, you can control your lights using the app and the remote. This sounds good, but it seems that you just got yourself a light that works like the non smart ones but more expensive. Does this seem right? Sure, you can tell me that money is not a problem and you don’t mind buying these expensive “smart” technology. However, if I am buying smart lights or any other smart devices, I want it to be really smart, with or without an app. In a perfect world, you would use the app just to configure the device and use something else to control it, that is faster than grabbing your phone and open the app.</p><p>Instead of turning on those bedside lights when you wake up, wouldn’t be awesome if the lights were already turned on when you wake up? Or even better, they slowly start to turn on a couple of minutes before the time you want to wake up. Now this sound smart, doesn’t it? I think, smart home technology should be all about improving our days, making things happen without us having to think about it. The automation use cases are the ones that really show the possibilities of this smart home technology.</p><p>I just talked about a really simple use case for smart lights. You wake up and the lights automatically turn on. Most smart light apps allow you to configure these use cases in an easy way. But, what if you want, for instance, to turn on the Air Conditioner (AC) at the same time the lights start turning on? You want to wake up in a bedroom with a nice temperature. If you have a smart AC you can use its app to configure just that. What happens when, you have to wake up at a different time in a given day? You have to change your smart lights and AC configurations on each app. If you add another device from a different brand to that wake up routine, you will have to interact with yet another app. Another app that you have to use if you need to change the time you want to wake up the next day. And the number of apps keeps growing. Does this make sense? You can try to use everything from the same brand… But good luck with that! It’s very unlikely that one brand that makes really good smart lights also manufacturers AC systems.</p><p>Getting back to the question… Can we find a better answer? Of course! A smart home is the one with the technology that really helps you saving time, money or just makes your life easier (with or without apps).</p><h3>The multi brand problem</h3><p>You reached a point where you can see the real value of smart home technology. But now there is another problem. Even if you have a well defined daily routine, you have to change it from time to time. You have to change settings in different apps, because you got too excited about smart home technology and you have a lot of smart devices from different brands. I will call this the multi brand problem. It would be nice to have only one app to control everything. If there is no such app, you just give up and return to the old days technology. It’s just too much work each time you need to change something in your smart home.</p><p>The solution? A hub, which is some hardware or software that integrates all your smart devices in one place. This is the key to have smart devices without worrying about their brand and compatibility. Examples of smart hubs:</p><ul><li>Google Home: Developed by Google and allows you to use Google Assistant to control your devices.</li><li>Amazon echo: Developed by Amazon.</li><li>Apple homekit: Of course, developed by Apple and allows you to use Siri to control your devices</li><li><a href="https://www.smartthings.com/">SmartThings</a>: Developed by Samsung</li></ul><p>And, if you are a little bit techie like me, you would love to try:</p><ul><li><a href="https://www.home-assistant.io/">Home Assistant</a>: Open source project</li></ul><p>The first four ones, from really big companies, are the easiest to set up but also the less flexible. I have been using Home Assistant for the last couple of months and I simply love it. But it requires some time to set up and some technical knowledge, but you can always google for answers.</p><p>My point here is, whatever is your option, smart home technology does not make sense if you don’t have a hub. Otherwise, you have to own all devices from the same brand and that is almost impossible. When buying these devices check for compatibility badges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/257/1*6-epkcc95TLoHoIKAVWArw.png" /><figcaption>Examples of badges seen in some smart home devices boxes</figcaption></figure><p>Another important thing to have in mind when buying devices is to make sure that you can keep controlling them in your home, even when the Internet is down or when you don’t have your smartphone with you. For smart lights, I always like to add some kind of physical control, usually a remote controller. This is also good when your partner asks you if he/she needs to use the phone to control the lights, because, a button is still the simplest way to turn on or off anything.</p><h3>Conclusion</h3><p>Smart Home technology is here to stay. But it is not only about devices and apps to control them. It is about making technology work for you and make your life easier. It only makes sense when you add automation. Otherwise, the good old days technology can do the same without spending extra money. I am still learning and experimenting with these technologies. So far, I only have smart lights and smart plugs. I use Home Assistant installed on a <a href="https://www.raspberrypi.org/">Raspberry Pi</a> as a Smart Home hub. That’s right, you can use a device as cheap and simple as a Raspberry Pi!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f7fca5eb1ac4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hoisting — One of the trickiest Javascript features]]></title>
            <link>https://medium.com/@codingsam/hoisting-one-of-the-trickiest-javascript-features-edefb745a058?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/edefb745a058</guid>
            <category><![CDATA[es5]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Fri, 23 Aug 2019 22:18:47 GMT</pubDate>
            <atom:updated>2019-08-23T22:18:47.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Hoisting — One of the trickiest Javascript features</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*uqOGY3kZpsubFF3azZWgiA.png" /></figure><p>Javascript is a programming language that can be tricky for beginners. Once you understand how it works, it becomes clear, but in the beginning, you end up debugging problems that you created yourself because you didn’t know something about the language.<br>We all have been there. <br>Maybe you are learning Javascript and you are in this process of dealing with problems you don’t see happening in most programming languages.</p><p>In this post, I will show you some code snippets and for some, a link to <a href="https://codepen.io/">codepen</a>. However, you will see <em>document.write</em> calls instead of <em>console.log</em>. This is just to allow you to see the output on the codepen’s app. Otherwise, you would have to open your browser’s developer tools.</p><p>Let’s look at the following JS code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5182cc4fa3a6fd6faab438fba6f71292/href">https://medium.com/media/5182cc4fa3a6fd6faab438fba6f71292/href</a></iframe><p><a href="https://codepen.io/codingsam01/pen/BXNGqO">Try it yourself</a>!</p><p>What do you think that is going to happen? <br>Here, you are using a variable before declaring it and assigning a value. This kind of code, in most programming languages, would throw an error because you are trying to use something that is not known yet.<br>You will see the following output in the console:</p><pre>Hello my name is undefined</pre><p>There was not a single error, but you get an unexpected output.<br><em>undefined</em> is the default value of any variable.</p><p>If you don’t know what is going on, you start to ask yourself:</p><ul><li>Why didn’t the code crash when I tried to use an unknown variable?</li><li>Is there some magic that allows me to use a variable declared below? If so, why didn’t I get the right variable’s value and got <em>undefined</em> instead?</li></ul><p>In the previous code example, try to replace <em>name</em> by something else:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c82a4de9723cecc758d82e5c5ff14eaa/href">https://medium.com/media/c82a4de9723cecc758d82e5c5ff14eaa/href</a></iframe><p><a href="https://codepen.io/codingsam01/pen/NQGJxa">Try it yourself</a>!</p><p>You will get this:</p><pre>ReferenceError: somethingElse is not defined</pre><p>This error is something that any Javascript beginner would expect.<br>But it didn’t happen in the previous example. It seems that you can use variables before they are declared.</p><p>Actually, something else happens behind the scenes to allow developers to do that. It’s called <em>Hoisting</em>. Let me help you to understand one of the most tricky features of Javascript, specially for beginners. I will also show you how you can avoid it and when it can be useful.</p><h3>What is <em>Hoisting</em>?</h3><blockquote><em>Hoisting</em> is a process that moves all the declarations to the top of their scope. This is handled by the Javascript engine before running your code.</blockquote><p>But… What is the scope of a declaration?</p><p>In Javascript, you have function based scope, which means, any variable declared inside a function, will belong to that function’s scope, no matter where in the function it happens. For instance, if you declare a variable inside a for loop, that variable will be known anywhere in the function and not just in the loop.<br>But, any function or variable declared outside a function, will belong to the global scope.</p><p>Only declarations are <em>hoisted</em> (moved to the top).<br>But, which types of declarations?</p><ul><li>variable declarations using the <em>var</em> keyword;</li><li>functions using the <em>function</em> keyword;</li></ul><p>Be careful about <em>var</em> declarations. It is really easy to look at an assignment and think that the variable’s name and value will be moved to the top.</p><p>Let’s look at an example:</p><pre>var a = 2;</pre><p>In this line of code, there are two things going on, a declaration and an assignment. This line could be translated to:</p><pre>var a;<br>a = 2;</pre><p>Only the declaration var a will be <em>hoisted</em>. Like what happened in the first code snippet, if you try to use the variable <em>a</em> before the assignment, it will be <em>undefined</em> and not “2”.</p><p>However, when you declare a function, you also write its body. You can’t create a function with just a name and specify its behavior later on. That’s why, when you declare a function (using the <em>function</em> keyword) the whole function gets <em>hoisted</em>. This means that, you can declare it in a line after the first call.<br>For instance, the following example will not throw an error:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a3cb9aebf543fd01407ad736aca1e7c/href">https://medium.com/media/0a3cb9aebf543fd01407ad736aca1e7c/href</a></iframe><p><a href="https://codepen.io/codingsam01/pen/PoYzdgr">Try it yourself</a>!</p><p>You will see Hello my name is Sam on the console. The <em>getMessage</em> function got <em>hoisted</em>, which means, moved to the top, by the Javascript engine before running the code.</p><h3>Let’s see it in action!</h3><p>Look at the following code snippet:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/295d8ecb1702e4df263129c70ad8ca6e/href">https://medium.com/media/295d8ecb1702e4df263129c70ad8ca6e/href</a></iframe><p><a href="https://codepen.io/codingsam01/pen/JjPKaqv">Try it yourself</a>!</p><p>The output will be Message: undefined Sam.<br>Before running the code, declarations will be hoisted. Let’s break down <em>Hoisting</em> and follow through the steps:</p><ul><li>First, collect all declarations (<em>var</em> and <em>function</em>)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*mCg53QXLO-0nej8JmUjZNw.png" /><figcaption>Highlighting all declarations</figcaption></figure><ul><li>Move those declarations to the top of their scope</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/528/1*9IJNEl4io1k7N9ODeqsm-Q.png" /><figcaption>Moving all declarations to the top of their scope</figcaption></figure><p>After this process, the Javascript engine will look at your code like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7dd79e141a2aa981022f018a93988247/href">https://medium.com/media/7dd79e141a2aa981022f018a93988247/href</a></iframe><p>The <em>message</em> variable and <em>getMessage</em> function are global, that’s why they were moved to the top of the file. The <em>completeMessage</em> and <em>intro</em> variables were moved to the top of the <em>getMessage</em> body, because they are attached to the function’s scope.</p><p>The <em>completeMessage</em> variable will be undefined Sam, because the assignment to the variable <em>intro</em> happens one line below.</p><h3>Can you run away from it?</h3><p>How many programming languages do you know that have this <em>Hoisting</em> feature? Most programming languages don’t have it, which means, if you try to use a variable or a function that is not declared yet, you will get an error. For me, it makes a lot of sense. Why would you use a variable before you declare it in the first place?<br>I don’t really know why Javascript has <em>Hoisting</em>. But, I know that <a href="http://es6-features.org/"><em>ES6 (ECMAScript version 6)</em></a> added ways of declaring variables that are not <em>hoisted</em>.<br><em>ECMAScript</em> is a standardized specification, that Javascript is based on.</p><p>If, at this point, you think that <em>Hoisting</em> was a bad idea, maybe you are not the only one and the people that work on the ES specification think like you. Maybe that’s why they have created the <em>const</em> and <em>let</em> keywords, that allow you to define constants and variables, respectively. They are not <em>hoisted</em>.</p><p>Nowadays, a lot of Javascript developers are not using <em>var</em> anymore, because of <em>Hoisting</em> and the function based scope.</p><p>See my post on “Why don’t we use var anymore?”</p><p><a href="https://blog.usejournal.com/awesome-javascript-no-more-var-working-title-999428999994">Why don’t we use var anymore?</a></p><p>In the following example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/79808edc6bd41bceeb6a39b51bac52af/href">https://medium.com/media/79808edc6bd41bceeb6a39b51bac52af/href</a></iframe><p><a href="https://codepen.io/codingsam01/pen/wvwWYwB">Try it yourself</a>!</p><p>You will get an error inside the <em>getMessage</em> function, because you are trying to use the constant <em>intro</em> before you declare it and assign it a value.<br>Calling <em>getMessage</em> before defining it does not throw an error because, remember, functions are <em>hoisted</em>. But there is also a solution to create non <em>hoisted</em> ones. Just use <strong>arrow functions</strong>. They are not <em>hoisted</em> because they don’t have a name (you are not using the <em>function</em> keyword)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae097defb16adf5ebd2a23440a47847e/href">https://medium.com/media/ae097defb16adf5ebd2a23440a47847e/href</a></iframe><blockquote>When you create an arrow function, you are creating an anonymous function. If you want to keep a reference to it, you have to assign that anonymous function to a constant or a variable.</blockquote><h3>Is it all bad?</h3><p>So far, I have shown you what <em>Hoisting</em> is and how you can avoid it. However, I think that it is not all that bad. There is one good use case for this feature.</p><p>Let’s say you have a <em>location.js</em> file, that exports a function that any developer can use to get the user’s location. Before getting the location, you need to ask permission to get that data. Your file would look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/352ab415d024a41f3a1d30aafc0956df/href">https://medium.com/media/352ab415d024a41f3a1d30aafc0956df/href</a></iframe><p>The exported function is a constant with an arrow function as its value. But, that function uses two other functions, which are defined after the exported <em>getUserLocation</em>.<br>You can do this because, remember, functions in Javascript are <em>hoisted</em>, but not arrow functions. If these auxiliary functions were arrow functions, you would have to put them before the exported one. This is a simple example but sometimes, you can have more than two auxiliary functions. Other developers that need to work on that file would have to scroll until they find what is being exported.</p><p>If you put all the auxiliary functions on the bottom of the file, you make it easier to read, because other developers will see the main logic as soon as they open the file, instead of having to scroll through a lot of functions.</p><p>I use this pattern a lot… But you might disagree ;)</p><h3>Conclusion</h3><p><em>Hoisting</em> is a feature that can be tricky to a lot of developers. Fortunately, we have ways to avoid that process of moving all the declarations to the top of their scope. But, you can put this feature to good use. When you have a file that exports something, you can move all auxiliary functions to the bottom and make your code easier to read.</p><p>Do you like <em>Hoisting</em>? Do you think that it is useful? Do you know other ways of taking advantage of it? Let me know what you think!</p><p>Happy coding! :)</p><ul><li><a href="https://twitter.com/codingsam01">Find me on Twitter</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=edefb745a058" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bug detective — When returning JSON goes wrong]]></title>
            <link>https://medium.com/swlh/bug-detective-when-returning-json-goes-wrong-45fd54df4e56?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/45fd54df4e56</guid>
            <category><![CDATA[php]]></category>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sun, 02 Jun 2019 21:32:32 GMT</pubDate>
            <atom:updated>2019-06-03T20:53:19.322Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bug detective — When returning JSON goes wrong</h3><p>As a developer, I spend a lot of time on fixing bugs. If you are a software developer, you can relate to this, right? I love to create new things and develop new features. However, there are a lot of days that most of my time is spent around debugging. Some days are really hard and you have to act like a detective to fix a bug. Those are your detective days. I think most developers have such days from time to time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C_IL95hyfV55KbiQje_Z5Q.png" /><figcaption>The code detective</figcaption></figure><p>In this post, I will introduce a bug case and I will explain the process of fixing it. The case is based on a real problem that a coworker and I had to debug in the past, while working on a PHP codebase. I changed some variables and functions names to avoid sharing private code. This programming language has a lot of bad reputation because a lot of people wrote really bad code in it. But you can do that in any programming language, right? The focus of this post is not in PHP. You can keep reading it even if you never coded in that programing language before. The main focus is on the case itself and in the process of finding the cause. In the end, I will give you some tips to help you on those detective days.</p><p>Let’s just get started with the case!</p><h3>The case</h3><p>You work on a web application and one of the pages has a table, which is really important for your users to allow them to make use of your app. One day, you receive a lot of bug reports about this table not showing any data at all. Not a single row was there. Like any bug that is blocking your users, you have to fix it right away.</p><p>The first thing you try to do is to reproduce the behavior that your users described. You just do that and of course, they were right. There was no data at all. You check the browser’s developer tools and there is not a single error being thrown. You check your server’s logs and there are no errors there either.</p><p>You start investigating…</p><h3>The investigation</h3><p>Let’s ask the first question… <strong>How the table works and where its data comes from?</strong></p><p>An HTTP request is triggered by some code in Javascript to an endpoint written in PHP, which is supposed to return a JSON array. That array contains several objects that will be used to “feed” the table’s content on the frontend.</p><p>Pretty simple, right?</p><p><strong>What is the endpoint returning?</strong> Let’s check the response, maybe it is returning an empty array… But it’s not. <strong>The response is completely empty</strong>. Not an empty array. There is nothing in the response body but its status code is a <strong>200 OK</strong>. Now it starts to become really weird. Not a single error and not an empty array. How is it possible that no error is thrown and you get an empty response body? Something really weird is happening on the server.</p><p>How the server endpoint’s code looks like?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d41837b6dbf6a158708465397a36a142/href">https://medium.com/media/d41837b6dbf6a158708465397a36a142/href</a></iframe><p>For those of you who never saw any PHP code before, the way you initialize a variable is like this:</p><p>$variableName = value;</p><p>Let’s break it down:</p><ul><li><em>getDataFromDatabase</em> is a function in the project’s code base that sends a query to the database and returns an <a href="https://www.w3schools.com/php/php_arrays.asp">array</a> of associative arrays (key-value structures, something like Javascript objects, in PHP).</li><li><a href="https://www.php.net/manual/en/function.json-encode.php"><em>json_encode</em></a> is a built-in function, provided by the programming language, that converts an associative array or an array of associative arrays to JSON.</li><li><a href="https://www.php.net/manual/en/function.echo.php"><em>echo</em></a> is a very well known PHP construct that just outputs one or more strings. In this case, it is outputting the <em>$data</em> array in a JSON format, because of the <em>json_encode </em>call. If everything goes well, you get a JSON array out of the <em>$data</em> variable.</li></ul><p>At this point, I challenge you to take a small break and think of what can be causing this endpoint to return nothing.</p><p>Did you think about it?</p><p>You need to ask yourself… Is there any issue with the <em>getDataFromDatabase</em> function? Is there any error connecting to the database that is being caught and not being thrown to the caller?</p><p>Let’s try a top down approach. Which means, let’s start in the top level, which is the endpoint’s code in this case, if something is wrong here, you need to take a look inside the <em>getDataFromDatabase</em> function. Because this is the only function you can look at. <em>json_encode</em> is a PHP built-in function. It should be working properly. Let’s take a look at the <em>$data</em> variable’s content. To do that, you just need to call <a href="https://www.php.net/manual/en/function.var-dump.php"><em>var_dump</em></a>, which is a function that dumps the content of a given variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34c5737c311abb010b58840a4d0ec41d/href">https://medium.com/media/34c5737c311abb010b58840a4d0ec41d/href</a></iframe><p>After this change, now your response will look weird because you are dumping the variable’s content, which is expected. When the <em>var_dump</em> executes, you can see an actual array with a lot of associative arrays inside. This <em>getDataFromDatabase</em> function seems to be working just fine, right?</p><p>Right now, the only explanation is that, something is wrong with calling the <em>json_encode</em> function. But it is a built-in function. It should behave as expected.</p><p>At this point you are thinking that I lied and this is all fake, which I really understand. But, as I told you in the beginning of this post, this case is based on a real problem that I had to debug. Something like this actually happened to me. I ended up asking myself…</p><blockquote>“Is it possible that a built-in function like <em>json_encode</em> is not working properly?”</blockquote><p>And also… WTF?</p><p>This is one of those problems that you spend many hours on it, trying to fix it and the more you dig into it, the more you say “WTF?”. You start to become really desperate and you start googling about your problem. Before doing that, let’s just look at the <a href="https://www.php.net/">PHP website</a> and search “<a href="https://www.php.net/manual/en/function.json-encode.php">json_encode</a>”. There is something really interesting in the “Return values” section:</p><p>“Returns a JSON encoded <a href="https://www.php.net/manual/en/language.types.string.php">string</a> on success or <strong>FALSE</strong> on failure.”</p><p>Since the endpoint is returning nothing, the <em>json_encode</em> function must be failing and returning false. Let’s change the code to call <em>var_dump</em> to see what <em>json_encode</em> is returning:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c35a334ff12c1d22c93b166ad9b04b4/href">https://medium.com/media/0c35a334ff12c1d22c93b166ad9b04b4/href</a></iframe><p>You will see in the endpoint’s response the output of dumping the <em>$data</em> variable and another line with FALSE. That’s right, your HTTP endpoint code is returning nothing because <em>json_encode</em> function is failing and when you pass FALSE to <em>echo</em>, it doesn’t output anything . There are a lot of reasons why this could be failing. When this happened to me, some of my associative arrays had some NaN (Not a Number) values. Looks like it cannot be encoded to JSON.</p><p>How do we get the error when <em>json_encode</em> function fails?</p><ul><li>Pass <strong>JSON_THROW_ON_ERROR</strong> option to the function</li><li>Call <a href="https://www.php.net/manual/en/function.json-last-error.php"><em>json_last_error</em></a> function to get the actual error from the last <em>json_encode</em> call</li><li>Call <a href="https://www.php.net/manual/en/function.json-last-error-msg.php"><em>json_last_error_msg</em></a> function to get the error message from the error occurred in the last json_encode call</li></ul><p>What was the cause of this bug? You will have to look at the code that actually creates the data that you get from the <em>getDataFromDatabase</em> function. All these hours spent just trying to understand why the endpoint’s response was empty could be avoided if an error was being thrown. I think most times, developers don’t think too much much about errors or they try to write code that fails silently. This is a good example why, in most cases, the best solution is to just throw an error. Your users will get it but you can fix it much faster and start looking at the right place.</p><h3>What are the takeaways from this?</h3><p>Some days, I spend long hours debugging. I think most developers can relate to this. The story I told you in this post is based on a problem, that I actually had to fix, that was blocking users. You can get some takeaways that can help you in most of your detective days:</p><ul><li><strong>Use a top-down approach</strong>. This means, you start looking at the most high level code that seems to be the problem. In this case, you can avoid looking inside the <em>getDataFromDatabase </em>function because you can start looking at the endpoint code itself. If you look inside at that function first, you would spend much more time in this entire investigation</li><li><strong>Look at the documentation</strong>. If you are using some built-in functions you can’t just assume they always work the right way and there will never be errors. Try to understand how they work and how to do the proper error handling</li><li><strong>Avoid to write code that fails silently</strong>. If something is not supposed to fail don’t’ just think that it will never happen and you don’t need to do anything. Write code that gets the error and if you don’t know what do with it, just throw it. If something goes wrong your users will be affected but you will be able to fix the problem much faster</li><li><strong>Most times, the bug is not where you think it is</strong>. This goes in line with previous bullet. If you throw errors instead of thinking they will never happen, you might start looking at the right place in the beginning of your investigation</li><li><strong>Take some breaks and drink water or eat something</strong>. You will need extra energy. This can be hard while you have users and your boss yelling at you because something is not working. But really, try to do it. Otherwise your brain will just “explode” and you will take much more time that is necessary to fix the problem.</li></ul><p>I hope you enjoyed this story and took away something that will help you in your life as a software developer. Specially in those days when you have to fix really weird bugs.</p><p>Happy coding! :)</p><p>Let me know what you think and follow me for more cool content about dev stuff :)</p><ul><li><a href="https://medium.com/u/58cf94a36c97">Coding Sam</a> @ Medium</li><li><a href="https://twitter.com/codingsam01">codingsam @ Twitter</a></li><li><a href="https://www.instagram.com/codingsam01">codingsam01 @ Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45fd54df4e56" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/bug-detective-when-returning-json-goes-wrong-45fd54df4e56">Bug detective — When returning JSON goes wrong</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why don’t we use var anymore?]]></title>
            <link>https://medium.com/@codingsam/awesome-javascript-no-more-var-working-title-999428999994?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/999428999994</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[es5-vs-es6]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[development]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Thu, 28 Mar 2019 22:20:26 GMT</pubDate>
            <atom:updated>2022-04-04T21:52:50.179Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*NB8h3wmUQ7sXTs-B3EZkIQ.jpeg" /><figcaption>Embracing let and const and drop out var</figcaption></figure><p>If you used to code in Javascript in the old days, you used the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var"><em>var</em></a> keyword a lot. There was no other way to declare a variable. It was really simple. The only thing you needed to do was just something like this:</p><p>var x = 3; var y = &#39;hello&#39;; // etc...</p><p>Since ES6, there are two new keywords, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const"><em>const</em></a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let"><em>let</em></a>. The first one is a bit self-explanatory, it allows you to define a constant. If you do:</p><p>const x = 2;</p><p>You can’t reassign another value to the constant <em>x</em>. There are many programming languages that allow developers to define constants. This is a good way to write less error-prone code. However, there is also this “<em>let</em>” keyword, which allows you to declare variables. And that’s all you need, just another keyword that does the same as <em>var</em>, right? Why there is not just “var” and <em>const</em>?</p><blockquote>Why don’t we use var anymore?</blockquote><p>To answer that question, you need to know how <em>var </em>really works. In Javascript, before ES6, there was no <strong>block scope</strong>. You have <strong>function scope </strong>instead. Let’s break down these two concepts.</p><h3><strong>Block scope</strong></h3><p>When you declare a variable or a function, it will be accessible inside the block it was declared on. Most programming languages have this type of scope, for instance, Java. See the code snippet below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bfdd6162a5b59886daac734e66ec4a6/href">https://medium.com/media/3bfdd6162a5b59886daac734e66ec4a6/href</a></iframe><p>You can only use the variable <em>i</em> inside the for loop. It doesn’t exist outside that block. In Java, each time you use a “{“ you are creating a new block and the “}” means, you are closing that block. Of course, if you declare a variable outside the block, you can use it inside the block.</p><p>Let me show you the following diagram that illustrates how the block scope would work in this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*WQqkmBqRLovbfM1fp-2XlQ.png" /><figcaption>Block scope using the Example class.</figcaption></figure><p>Each rectangle is a scope. The “children” scopes can access the functions and variables in the “parent” scopes, but the “parents” cannot access the “children”. In this example, the Example class is a parent of <em>processArray</em> method, which is a parent of the <em>for loop</em> block. The Example class cannot access whatever belongs to the <em>processArray</em> method, which cannot access whatever belongs to the <em>for loop</em>. However, the <em>for loop</em> can access anything in the <em>processArray</em> method and anything in the <em>Example</em> class, for instance, a variable or any other method. This is the kind of scope that most developers are used to work with.</p><h3><strong>Function scope</strong></h3><p>Unlike Java, Javascript (ES5) creates scopes based on functions. This means, once you declare a variable inside a function, you can use it anywhere in that function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f702b0ae90f1ac21031f3655c5f0cd1f/href">https://medium.com/media/f702b0ae90f1ac21031f3655c5f0cd1f/href</a></iframe><p>Of course, you also have the global scope. Each time you declare a variable outside a function, it will belong to the global scope.</p><p>Let me show you another diagram, but this time, for the function scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*3JueUzrZxCjytZCh9_sDuw.png" /><figcaption>Function scope for the processArray function</figcaption></figure><p>Looks much simpler, right? But where is the for loop?</p><p>The for loop is a block, but there is no block scope here, that’s why, it does not have its own scope.</p><h3>Why do we stop using the <em>var</em> keyword?</h3><p>It’s all about scope! Most programming languages have block scope. Why? Because it is less error-prone. You can declare variables inside blocks (if statements, for loops and so on) without worrying about overwriting some previously declared variable.</p><p>Let me show you an example. Let’s say you are implementing a function that prints each position of a matrix. You will write a <em>for loop</em> inside another <em>for loop</em>. In ES5, where you only have the <em>var</em> keyword available, a beginner would write something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6d42466e09c064093b1a01cb4f94286/href">https://medium.com/media/a6d42466e09c064093b1a01cb4f94286/href</a></iframe><p>The output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*BvtUBy7SAw6t9pGK-mDATQ.png" /><figcaption>Output of printMatrix function in ES5</figcaption></figure><p>It only logged the first line. To help you understand what is going on, let me show you a scope diagram for this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*ijeggeoI_dbSCgIrwQrvBQ.png" /><figcaption>Breaking down the scope in the printMatrix ES5 version</figcaption></figure><p>All variables inside the <em>printMatrix</em> function are on the same level. The two <em>for loops</em> are actually using the same variable <em>i</em>!</p><p>What happened? When I started coding in Javascript some years ago, I wrote a lot of code like this, because I used to code a lot in Java, which has block scope. So, I thought that if I declared a variable inside the loop, it will stay there… But not really.</p><p>After a lot of bugs and frustration I learned that Javascript does not have block scope. There is only function scope. But, even after I learned about it, I forgot a lot of times! This is something that is really easy to forget about. The usual expectation is that, in the second for loop, you are creating a new variable. But you are not. You are just overwriting the variable <em>i </em>in the first <em>for loop</em>. After running the second loop, the condition of the first one will be evaluated again, but the variable <em>i </em>now has the value 3 (the size of the first line in the matrix), which is equal to the matrix length (3). The condition returns false and the loop stops. That’s why only the first line of the matrix gets logged.</p><blockquote>In Javascript, it doesn’t matter how many times you use the keyword “var”. If it’s the same name in the same function, you are pointing to the same variable.</blockquote><p>This function scope can be a source of a lot of bugs. Fortunately, Javascript has been changing and now we have ES6 and more. There are these two “new” keywords, <em>const</em> and <em>let</em>, which allow you to define a constant and a variable, respectively. They both work with block scope, which means, if variables or constants are declared inside a block, they will not be available to the “parent” blocks.</p><p>Let’s rewrite the previous example, logging the matrix, taking advantage of these new keywords. If you replace <em>var</em> by <em>let </em>and add use <em>const</em> for things you know you will not need to change after initialization…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29979607c3fca0eab2a5f0b551e6c883/href">https://medium.com/media/29979607c3fca0eab2a5f0b551e6c883/href</a></iframe><p>The output will be:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/84/1*Qn2GnKEM3bIgxec14dc5aQ.png" /><figcaption>Output of printMatrix function in ES5</figcaption></figure><p>All positions in the matrix got logged. It just worked and I just had to replace <em>var</em> by <em>let</em> and <em>const</em> keywords! Because in each <em>for loop</em> I am actually creating a different variable <em>i</em>. In the second loop the first <em>i</em> will not get overwritten.</p><p>Let’s see what happened under the hood in terms of scope:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/1*71bRLyJxbpXYrAFc5xzJTA.png" /><figcaption>Breaking down the scope in the printMatrix ES6 version</figcaption></figure><p>Seems a bit more complicated, but this gives you block scope and each <em>for loop</em> has its own variable <em>i</em>. In the old days Javascript, you would need to give different names to avoid this naming conflict. But seriously, when you need to do a <em>for loop</em> to iterate over an array, the first name that comes to your head, for the current array index value is “i”, isn’t it?</p><p><strong>Just a small note</strong>: I know that you have <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach"><em>forEach</em></a>, <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map"><em>map</em></a>, and more functions to deal with arrays. This is just a simple example to show how the <em>var</em>, <em>let</em> and <em>const</em> keywords work.</p><h3>Conclusion</h3><p><em>let</em> and <em>const</em> are not just two new cool keywords, they also introduce block scope that allows us to write clean and less error-prone code.</p><p>Why don’t we use <em>var</em> anymore? Because now there is a better way of declaring variables and even constants… With block scope! You don’t need to think twice when declaring variables inside blocks. I think that is easier to work with block scope than with function scope. The <em>var</em> usage has been being discouraged. For instance, if you use <a href="https://eslint.org/">ESLint</a> to check your code, you can configure a “<a href="https://eslint.org/docs/rules/no-var">no-var</a>” rule that throws an error if there is any <em>var</em> being used.</p><p>Please, keep in mind that you should use a transpiler tool, like <a href="https://babeljs.io/">Babel</a>, to transpile your code from ES6 to ES5, to make sure it will run in any browser. Not all browsers support the complete ES6 specification yet.</p><p>Embrace <em>let</em> and <em>const</em> and let <em>var</em> go forever!</p><p>I hope you enjoyed and learned something. Happy coding! :)</p><p>Let me know what you think and follow me for more cool content about dev stuff :)</p><ul><li><a href="https://medium.com/u/58cf94a36c97">Coding Sam</a> @ Medium</li><li><a href="https://twitter.com/codingsam01">codingsam @ Twitter</a></li><li><a href="https://www.instagram.com/codingsam01">codingsam01 @ Instagram</a></li></ul><figure><a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_image"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYxBP_WV7LI6zc-zdUkNqQ.png" /></a></figure><p>📝 Read this story later in <a href="https://usejournal.com/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_read_later_text">Journal</a>.</p><p>👩‍💻 Wake up every Sunday morning to the week’s most noteworthy stories in Tech waiting in your inbox. <a href="https://usejournal.com/newsletter/noteworthy-in-tech/?utm_source=medium.com&amp;utm_medium=noteworthy_blog&amp;utm_campaign=tech&amp;utm_content=guest_post_text">Read the Noteworthy in Tech newsletter</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=999428999994" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Top 5 extensions for VS Code]]></title>
            <link>https://medium.com/@codingsam/my-top-5-extensions-for-vs-code-c730506b6491?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/c730506b6491</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[developer-tools]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[tools]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sat, 16 Feb 2019 00:08:12 GMT</pubDate>
            <atom:updated>2019-02-16T00:08:12.163Z</atom:updated>
            <content:encoded><![CDATA[<p>A long time ago I used Sublime text editor to write my code. However, that “Buy this” dialog was just annoying.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*Zde17vlfkdJRtpMMF077Og.jpeg" /><figcaption>Buy sublime text dialog</figcaption></figure><p>I am not saying that the editor is not good enough for someone to buy it but seriously… Do you know someone that actually clicked the “Purchase” button?</p><p>Github released Atom, which is free but the performance was not that great (at least, from my point of view, I didn’t do any benchmarks).</p><blockquote>Because there were not enough text editors (not really), Microsoft released Visual Studio Code. I never thought that they would release such a product, but they did and guess what… It became my favorite text editor!</blockquote><p>I really like this editor because it has a really good performance (at least I don’t have any issues so far), it is free and you have a lot of extensions available to install. These extensions can make a difference in your everyday work and of course, make your editor look awesome!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QD7srEXJUpS8KSuRu8WJhg.png" /><figcaption>Just a screenshot of my favorite text editor</figcaption></figure><p>I will share what are my favorite extensions. Two of them are mostly useful for Javascript developers, but I will share them anyway because I really like them and I write JS code everyday at work!</p><h3>Extensions</h3><p><a href="https://github.com/eamodio/vscode-gitlens"><strong>GitLens</strong></a></p><p>If you are working on a project that uses git as the VCS (Version Control System) you will love this one. This basically tells you who made a given change in the line your cursor is on. It shows you the commit message and the user who made the change.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*f46Iy-ZRSL22GdaAjYepDQ.gif" /><figcaption>Using gitlens to see commit messages line by line</figcaption></figure><p>This extension also adds a new option in the left side menu where you can see in great detail, the commit logs, compare files, see branches, etc.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yFYqfp_lPA4zO-vtUisJpg.png" /></figure><p><a href="https://marketplace.visualstudio.com/items?itemName=robertohuertasm.vscode-icons"><strong>vscode-icons</strong></a></p><p>This one is also for pretty much any kind of software developer. It is nothing more than a icon package. Let me show you an example…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/406/1*cSTfrWStf9cmGh_nzlNj3Q.png" /><figcaption>Example of how icons appear using vscode-icons extension</figcaption></figure><p>As you can see, it does a lot more than just looking at each file’s extension and use the right icon. Some files don’t even have an extension in the file name, for instance, the “LICENSE” file. But somehow, the extension uses a different icon for this file, even though it is just a text file. The “Dockerfile” got its own icon too! It really is more than just an icon theme for your text editor!</p><p><a href="https://marketplace.visualstudio.com/items?itemName=CoenraadS.bracket-pair-colorizer"><strong>Bracket Pair Colorizer</strong></a></p><p>Sometimes you have a lot of “<em>(</em>“ and “<em>{</em>“ and it’s hard to find the corresponding “<em>)</em>” and “<em>}</em>” closing characters. I use this extension to solve this first world problem. It applies a different color for each pair of “()” and “{}”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/922/1*6p_Zzisd3glWVHBy1rAx4Q.png" /><figcaption>Each pair of “()” and “{}” gets a different color</figcaption></figure><p>Awesome, right?</p><p><a href="https://marketplace.visualstudio.com/items?itemName=dbaeumer.vscode-eslint"><strong>ESLint</strong></a></p><p><a href="https://eslint.org/">ESLint</a> is a tool to specify code standards. Some questions like:</p><ul><li>Should I put a space around the “=” in an assignment?</li></ul><p>const a = b;</p><p>or</p><p>const a=b;</p><ul><li>Should I leave a white space between the <em>if</em> keyword and the condition in an <em>if </em>statement?</li></ul><p>if (condition) //...</p><p>or</p><p>if(condition) //...</p><p>And much more, can be answered by this tool…</p><p>All of these code standards can be defined and enforced by ESLint. You just need to integrate this tool in your project and set your rules in a “eslintrc” file. Your build tool will raise an error if some rule is being broken. But you can do better. You can have all those errors popping up in your VS Code. There’s an extension that does just that. It looks for a configuration file and as you type, your text editor highlights errors that break the rules. Some of these errors can be automatically fixed. Just press <em>Ctrl</em> + <em>Shift</em> + <em>P</em> (on a PC) or <em>Cmd + Shift + P </em>on a Mac and type “fix” until you find an option that says “<em>Fix all auto-fixable problems</em>”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*6MQHAAbiDLkV84sqHezBeA.gif" /><figcaption>Using auto fix to fix code standard issues</figcaption></figure><p><a href="https://marketplace.visualstudio.com/items?itemName=wix.vscode-import-cost"><strong>Import Cost</strong></a></p><p>When you import something from a package, it means you are including some external code. If you have a build process in place that generates a bundle file (all code in just one JS file), each library you use will increase final bundle’s size. With this extension, each import statement is evaluated and it tells you what is the cost of that import, in terms of file size. Because here… The size matters!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*n6WqZM8glgh4xHCY-YOLSQ.png" /><figcaption>Just an example of Import Cost extension in action</figcaption></figure><h3>Conclusion</h3><p>It’s not obvious the benefits of the extensions I showed you in this post… Until you start using them! Even if some of them just solve some first world problems, I think all of them added value to my text editor and also to my everyday work. I hope you can get something awesome from this post.</p><p>Let me know what you think and follow me for more cool content about dev stuff :)</p><ul><li><a href="https://medium.com/u/58cf94a36c97">Coding Sam</a> @ Medium</li><li><a href="https://twitter.com/codingsam01">codingsam @ Twitter</a></li><li><a href="https://www.instagram.com/codingsam01">codingsam01 @ Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c730506b6491" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Awesome Javascript — Destructuring assignment]]></title>
            <link>https://medium.com/@codingsam/awesome-javascript-destructuring-assignment-55fd2e9d3dc4?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/55fd2e9d3dc4</guid>
            <category><![CDATA[web]]></category>
            <category><![CDATA[dev]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Wed, 30 Jan 2019 21:53:55 GMT</pubDate>
            <atom:updated>2019-01-30T21:58:48.042Z</atom:updated>
            <content:encoded><![CDATA[<h3>Awesome Javascript — Destructuring assignment</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*jC6q6xNDHlNS5_mVT3Qawg.png" /></figure><p>Javascript is becoming more and more a really cool language. Why? Because of all the features introduced in <a href="http://es6-features.org/">ES6</a> (ECMAScript 6 aka ECMAScript 2015) and all the other more advanced versions. ECMAScript is just the standardized specification of Javascript. Some browsers already support it. However, it is usually not safe to rely on that, because there is no guarantee that any browser will support the complete specification. The best thing to do is to use a transpiler, that converts your ES6 code to ES5, which for sure will run in any browser. <a href="https://babeljs.io/"><em>Babel</em></a><em> </em>is a well known transpiler that you can integrate in most used build tools, such as, <a href="https://webpack.js.org/"><em>webpack</em></a> or <a href="https://gulpjs.com/"><em>gulp</em></a><em>.</em></p><p>I had worked with a lot of Javascript in a web development project in one of my previous jobs. I mean… a lot! Try to work in a frontend without any framework (no React, angular or anything else!). So, as you can imagine, I got really familiar with Javascript, but it was ES5.</p><p>Since a couple months ago, I have to deal with a lot of ES6 in my full time job. It has a lot of cool features. That’s why I decided to start a new series of posts about the features I learned about (and still learning)!</p><p>This post is about the <em>destructuring assignment</em>, which I think it is a clean way to deal with objects and arrays.</p><blockquote>Basically, it is just an awesome way to get values from arrays and objects.</blockquote><p>Let’s see how it works!</p><h3>Array destructuring</h3><p>You can get some values from a given array and give them any name you want. For instance, let’s say you have an array of numbers, <em>[1, 2, 3, 5, 8, 13, 21]</em> and you want to store the first two indexes in separate variables. In “normal” Javascript you would do something like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da462b83a7b028e49920c72ce7fa51b7/href">https://medium.com/media/da462b83a7b028e49920c72ce7fa51b7/href</a></iframe><p>The variable x and y contain the indexes 0 and 1, respectively. The rest, contains all other remaining numbers <em>[3, 5, 8, 13, 21]</em>.</p><p>Now, let’s do it the ES6 way!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0930f0ad227cff4cb584c5606a2ad5b6/href">https://medium.com/media/0930f0ad227cff4cb584c5606a2ad5b6/href</a></iframe><p>This does the same as the previous code, but it looks much better. You get the first two positions from the array in variables <em>x</em> and <em>y</em>. The remaining values are stored in the <em>rest</em> constant. If you don’t know about what the “<em>const</em>” keyword means, don’t worry, it is something from ES6, it’s used to define a value that cannot be reassigned.</p><h3>Object destructuring</h3><p>In ES5, to get values from objects, you just simply need to know which keys have the values you want and type something like <em>myObject.myKey</em>. Let’s say, you have an object that describes a person with the properties: name, age, gender, address and phone number. If you want to extract the name and age properties, you just need to simply do:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e46a5d557afb46c08772845732b2bdc/href">https://medium.com/media/7e46a5d557afb46c08772845732b2bdc/href</a></iframe><p>If you are using ES6 you can do it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a06d22730d3a00ff02add5bd42780dd3/href">https://medium.com/media/a06d22730d3a00ff02add5bd42780dd3/href</a></iframe><p>You just extracted some keys from the object and also got another object with the remaining keys (gender, address and phone). Remember the weird “…” thing from the array destructuring? This “…rest” does the same, but in this case, it is an object.</p><p>I hope you get the idea, but let me give you an example to help you to get a better feeling about how awesome is this!</p><h3>Example</h3><p>Let’s say, you are implementing a 2D game in Javascript, for instance Bomberman. Who does not know about this one, right? Right??? :)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*__Qjq_ioJpGPq8h4phyyng.png" /><figcaption>Bomberman game</figcaption></figure><p>You already have the following function:</p><ul><li><em>getPosition</em>: returns the bomberman’s current position, in a pair of coordinates (<em>x</em> and <em>y</em>), in the 2D grid where all the action is happening</li></ul><p>There are two ways of defining a position, using an array or an object. In the array implementation, the zero and one indexes are the <em>x</em> and <em>y</em> coordinates, respectively. Using an object, this will have the <em>x</em> and <em>y</em> keys with the coordinates values. To use this <em>getPosition</em> function, you can use the destructuring assignment to get your code a lot cleaner than without using it.</p><p>Now, you need to implement a function:</p><ul><li><em>getDistance</em>: returns the distance (in <em>x</em> and <em>y</em> axis) between two positions.</li></ul><p>For instance, if you have the following positions:</p><ul><li><em>position0 = {x: 2, y: 4}</em></li><li><em>position1 = {x: 5, y: 3}</em></li></ul><p>The distance between them should be <em>{x: 3, y: -1}</em> because, <em>5-2=3</em> and 3–4=-1.</p><h4>Using an array</h4><p>Choosing the array implementation, if you call the <em>getPosition</em> function, you will get an array where the index zero is the <em>x </em>coordinate and the index one is the <em>y </em>value.</p><p>Let’s see how we can use this function, using the <em>destructuring assignment</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e499dcf67fcff3ea11cbfb944fbd7d29/href">https://medium.com/media/e499dcf67fcff3ea11cbfb944fbd7d29/href</a></iframe><p>What if our <em>getPosition </em>function does return an <em>undefined</em> coordinate for some reason? You can set default values, so your code does not crash!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f821abcd5e65b63323f272254b3ba1f4/href">https://medium.com/media/f821abcd5e65b63323f272254b3ba1f4/href</a></iframe><p>Remember the <em>getDistance</em> function introduced in the example? Let’s define it assuming our positions are represented using an array:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2c467544a6577022443d7067733de2de/href">https://medium.com/media/2c467544a6577022443d7067733de2de/href</a></iframe><p>It is already a really looking good code, but you can remove some lines if you do the destructuring stuff in the function’s arguments list!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f7459991f66f035ad042b5686fab574/href">https://medium.com/media/0f7459991f66f035ad042b5686fab574/href</a></iframe><p>Is this too fast? Let’s break it down because there are a lot of stuff going on here :)</p><ul><li><em>[x1 = 0, y1 = 0]: </em>this thing in the function’s header, basically means you expect an array with two positions. You are naming its indexes zero and one to <em>x1 </em>and <em>y1</em>, respectively. In case that the array has less than two positions, or is completely empty, those <em>x1</em> and <em>y1</em> values become zero. <strong>Have in mind that you can pass an empty array but you cannot omit it, otherwise, you will get an error</strong>!</li><li><em>const [xDistance, yDistance] = getDistance(position1, position2)</em>: here you are just calling the <em>getDistance</em> function that returns an array. Instead of storing that array in a variable (or a constant as I am doing in this example), you are assigning the zero and one indexes in two constants named <em>xDistance </em>and <em>yDistance, </em>respectively.</li></ul><h4>Using an object</h4><p>The same <em>getPosition</em> exercise could be implemented using an <em>object</em> instead of an <em>array</em>. Let’s write an <em>object</em> version!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19708496f61e53b0b7c5bf759af33d31/href">https://medium.com/media/19708496f61e53b0b7c5bf759af33d31/href</a></iframe><p>And you also can set <em>default </em>values, like we did in the array version!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71c38a47eed54aa9f89c292b97296ff2/href">https://medium.com/media/71c38a47eed54aa9f89c292b97296ff2/href</a></iframe><p>Awesome right? :)</p><p>Now, let’s create the <em>getDistance</em> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cff2e971e7ac1b6946761f1a86f13266/href">https://medium.com/media/cff2e971e7ac1b6946761f1a86f13266/href</a></iframe><p>I am using the destructuring assignment here with default values. Also, I am renaming its keys, so I can distinguish between the <em>x</em> and <em>y</em> from <em>position1</em> (<em>x1</em> and <em>y2</em>) and <em>x </em>and <em>y</em> from <em>position2</em> (<em>x2</em> and <em>y2</em>).</p><p>Is it possible to do better? Yes! Let’s do it!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6c3062583128fd6808898823daa6844/href">https://medium.com/media/a6c3062583128fd6808898823daa6844/href</a></iframe><p>You can save some lines if you already know that your function arguments are objects with some given keys. Like I have done in the array implementation, here I can also move the destructuring part to the function’s header! Let’s break it down:</p><ul><li><em>{ x: x1 = 0, y: y2 = 0 }</em>: Basically this means that you expect an object, as the function’s first argument, with two keys <em>x </em>and y. However, you are naming those keys <em>x1 </em>and <em>y1</em> (this is useful because the function expects two objects with the same keys). <strong>Have in mind that you are not changing anything in the object passed to the function (renaming the keys, {x: x1, y: y2}, does not change the keys names in the object). </strong>Also, if this object does not have a defined value for the <em>x </em>key, the value zero (<em>x: x1 = 0</em>) is used instead. The same is true for the <em>y</em> key.</li><li><em>const { x: xDistance, y: yDistance } = getDistance(position1, position2)</em>: This calls the getDistance function. You could just put the result in a constant, but as you can see, you can destructure that object if you already know which keys you are expecting. The “<em>x: Distance”</em> part gets the <em>x</em> value from the returned object and renames it to <em>xDistance</em>.</li></ul><h3>Conclusion</h3><p>If you already work with Javascript ES6 (and more advanced standards), it’s very likely that you already know this destructuring assignment and you love Javascript.</p><p>Anyway, have in mind that, in order to use this feature, you should transpile your code to ES5. Otherwise, there is a small chance that your code will not run in some browsers. As mentioned in the beginning of this post, go check <em>Babel</em>. I didn’t explained anything about how to setup a transpiler because I just wanted to focus on one particular feature instead of writing a really big post.</p><p>I hope you liked it and learned something. Share this, especially, with your developer friends that hate Javascript :)</p><p>Let me know what you think and follow me for more cool content about dev stuff :)</p><ul><li><a href="https://medium.com/u/58cf94a36c97">Coding Sam</a> @ Medium</li><li><a href="https://twitter.com/codingsam01">codingsam @ Twitter</a></li><li><a href="https://www.instagram.com/codingsam01">codingsam01 @ Instagram</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=55fd2e9d3dc4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Command Line — Your best friend]]></title>
            <link>https://medium.com/@codingsam/the-command-line-your-best-friend-a9e660e78fb2?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/a9e660e78fb2</guid>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[zsh]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Thu, 27 Sep 2018 20:59:19 GMT</pubDate>
            <atom:updated>2018-09-27T20:59:19.850Z</atom:updated>
            <content:encoded><![CDATA[<p>The command line is a tool used by software developers, to run framework or development tools related commands, run scripts to automate processes and a lot more. If you are learning to code or already code, I think you should not be afraid of the command line. It can seem intimidating at first, but it will improve your workflow.</p><p>I met some people that always ran away from anything that didn’t have a GUI (Graphical User Interface). In some cases, you will be just fine. For instance, if you are a C# developer, you will use Visual Studio. Actions related to running, debugging and deployment can be triggered just by clicking in some icons in the IDE (Integrated Development Environment), in this case, Visual Studio. There is nothing wrong with this approach but… When you try to explore other technologies, languages, frameworks, etc, you end up dealing with the command line.</p><p>If you are already a software developer, at this point, your reaction should be something like:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FcEYFeDKVPTmRgIG9fmo%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcEYFeDKVPTmRgIG9fmo%2Fgiphy-downsized.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcEYFeDKVPTmRgIG9fmo%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="390" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aa640dad9d0aa8f10d4709e424b8bae/href">https://medium.com/media/0aa640dad9d0aa8f10d4709e424b8bae/href</a></iframe><blockquote>“What are you talking about? I know how to open the Terminal app on my Mac or Linux or cmd on Windows and run commands in it”.</blockquote><p>I am not here to tell you that you must learn how to use the command line… Instead, let me show you, from my experience, how you can have the best command line… Ever!</p><p>First, let me tell you how I learned what I am about to share with you. Everything started when I was in a summer internship at a startup. I was a student looking for some kind of real world experience, so I was not really familiar with the command line. The CTO (Chief Technology Officer) showed me how to have a Quake like console (the one that comes down when you press the ‘\’ key in Quake video game) on my laptop that was running Linux. Then, he told me to install <em>oh-my-zsh</em>, which I will talk about later in this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/637/1*8_M_UVHiOx6CfY8tgl-mnA.png" /><figcaption>Console in Quake game</figcaption></figure><p>The CTO is basically the person that is in charge of the technology and engineering departments of a given company.</p><p>From that moment, I started to love the command line. Few years later I still use this tool and I am going to share it with you.</p><p>Basically, you will need these things:</p><ul><li>A terminal app</li><li>Z Shell</li><li>oh-my-zsh</li></ul><p>I will explain what these things are in a moment.</p><p>Just follow the two steps below :)</p><h3>First — Get a nice terminal app</h3><p>The first thing to do is to get a terminal app. You can use the one that comes with your Operating System but there are better solutions out there, especially for Windows, believe me, you wouldn’t want to use <em>cmd</em>. The goal here is to have a better terminal app with a Unix based command line. Unix is the base system of Mac and Linux Operating Systems. This is why I prefer Mac or Linux, and maybe that’s why you see a lot of developers using such systems. Anyway, if you use Windows you can still get almost the same experience.</p><p>Here are my terminal apps recommendations for Mac, Linux and Windows.</p><ul><li><strong>Mac</strong>: <a href="https://www.iterm2.com/">iTerm</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yRnyT30la5AukGoDkzG2_Q.png" /><figcaption>Iterm2 running on my own Macbook Pro</figcaption></figure><ul><li><strong>Linux</strong>: <a href="http://guake-project.org/">Guake</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dirfG6Rb4J3hbxc0aRjAHQ.jpeg" /><figcaption>Guake running on Ubuntu. Source: <a href="https://www.flickr.com/photos/xmodulo/14285529772">https://www.flickr.com/photos/xmodulo/14285529772</a></figcaption></figure><ul><li><strong>Windows</strong>: <a href="https://conemu.github.io/">ConEmu</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/672/1*SCiK5lLCZjdlEAOY7CkBrg.png" /><figcaption>ConEmu running on Windows. Source: <a href="https://commons.wikimedia.org/wiki/File:ConEmu_screenshot.png">https://commons.wikimedia.org/wiki/File:ConEmu_screenshot.png</a></figcaption></figure><p>In the Windows, installing just ConEmu will not give you the best experience. You need to install <a href="https://docs.microsoft.com/en-us/windows/wsl/install-win10">WSL (Windows Subsystem for Linux)</a> and a Linux distribution available in the Windows Store, for instance, <a href="https://www.microsoft.com/p/ubuntu/9nblggh4msv6#activetab=pivot:overviewtab">Ubuntu</a>.</p><p>This will give you a Unix like command line, which is what this entire post is all about.</p><p>I think using one of the terminal apps I mentioned before, it is already an improvement… But let’s make it even better…</p><h3>Second — Make your terminal awesome</h3><p>I will just show you something that you can install, to have, what I think is the best command line experience possible.</p><p>Now, you need to install two things:</p><ul><li><a href="http://zsh.sourceforge.net/"><em>Z Shell</em></a>, which is essentially an Unix shell (command line interpreter). The installation will depend on your Operating System. I recommend that you use a package manager. On Windows, if you successfully installed the Linux Subsystem, just use the package manager available in your Linux distribution you are using inside the WSL. If you use Linux, you can just use the package manager of your distribution. On Mac OS, I recommend you to use <a href="https://brew.sh/"><em>Home Brew</em></a><em>.</em></li><li><a href="https://ohmyz.sh/"><em>oh-my-zsh</em></a><em>, </em>is a set of plugins that adds more features to the <em>Z Shell</em>. The installation process is just a matter of copy and pasting a command to your terminal. Depending on the installation method you choose, you need <em>wget </em>or <em>curl</em>. Just use your package manager to install one of these two options.</li></ul><p>If you made this far, let me show you how awesome this is!</p><h3>See it in action</h3><p>Let’s see some examples of cool things you can do with the terminal and <em>oh-my-zsh</em> together.</p><p>All the following screenshots were taken from a Mac OS, because I own a Macbook Pro… But if you installed a terminal app and ‘oh-my-zsh’, you will be able to experience the same awesomeness.</p><ul><li><strong>Plugins</strong></li></ul><p>You have a lot of plugins available. <a href="https://github.com/robbyrussell/oh-my-zsh/wiki/Plugins">Check the complete plugins list</a> and how to install them. Is as simple as add the plugins names to the <em>plugins</em> list in the <em>.zshrc </em>file in your user’s home folder.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80c061172fa043dadb7e68ae287a08c7/href">https://medium.com/media/80c061172fa043dadb7e68ae287a08c7/href</a></iframe><ul><li><strong>Choose a theme</strong></li></ul><p><em>oh-my-zsh</em> allows you to customize the look and feel of your terminal. I just use the default one, but you are free to give it a different look. Choosing a theme just requires you to define a <em>ZSH_THEME </em>variable in your <em>.zshrc </em>file. <a href="https://github.com/robbyrussell/oh-my-zsh/wiki/themes">Check all the available themes</a> and set this variable according to your choice. For instance, if you want to use a theme named “<a href="https://github.com/robbyrussell/oh-my-zsh/wiki/themes#awesomepanda"><em>awesomepanda</em></a><em>”, </em>you need to add the following to the <em>.zshrc</em> file:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdb7a2c906ea7f790c93c9540ccff24f/href">https://medium.com/media/bdb7a2c906ea7f790c93c9540ccff24f/href</a></iframe><ul><li><strong>Using git</strong></li></ul><p>If you use <em>git</em> as the version control of your projects, you know you can use the command line for that. If you navigate to any of your projects folders, you will see the current branch’s name in the right side of the folder’s name. You also have some aliases to make your git commands shorter.</p><ul><li>git pull =&gt; gl</li><li>git push =&gt; gp</li><li>git commit =&gt; gc</li><li>git status =&gt; gst</li></ul><p>See this in action…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2PYNP6CFuwhMdG4sbLW8g.gif" /><figcaption>Using git with oh-my-zsh</figcaption></figure><ul><li><strong>Autocomplete</strong></li></ul><p>Maybe you already know that, when you are typing a command, if you press the <em>TAB</em> key, the terminal will try to complete your command. This is already a cool thing. But… <em>Z Shell </em>and <em>oh-my-zsh</em> take this autocomplete thing to another new level. That’s right, it can help you, for instance, to complete a folder name even if you start typing a word in the middle. If more than one option is available, you can use the <em>TAB</em> key to navigate through the available options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*schkIWY2CsGb7VSt_bS5DA.gif" /><figcaption>Autocomplete feature for folders and files</figcaption></figure><p>Another awesome level of autocomplete, is related with some software development tools. You have several plugins to help you autocomplete some specific tools commands. For instance, if you work with <em>nodejs</em>, you will use a lot of <em>npm</em> commands, like <em>npm install</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GwySiHrVJzHoISnYlJ3Dqg.gif" /></figure><blockquote>Because you know, developers are lazy, so they will avoid to write as much as possible.</blockquote><h3>Conclusion</h3><p>Any software developer has to deal with the command line. Some people don’t like it. Unless you work with a really specific tool set, bad news… You can’t run away from it. I can tell you that, from my experience, it can seem intimidating in the beginning because it requires you to memorize a lot of commands. But… once you begin feeling comfortable, you will love it.</p><p>Following two simple steps, you can have a really awesome experience. You just need to download a terminal app for your Operating System. Then, go ahead and install <em>z shell </em>and <em>oh-my-zsh</em> on top of it.</p><p>If you are a software developer or thinking about being one, remember…</p><blockquote>The command line is as important as any other development tool</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CioB717snwMtfEBeomP01A.gif" /><figcaption>Having fun with the command line :)</figcaption></figure><p>I talked about the terminal and <em>oh-my-zsh</em> but didn’t go into much detail of the installation process of each required package. That would require a post for each Operating System. The most important thing here, is that you become aware of these tools. Let me know if you would like to read about each OS. I think you have the best experience in Mac and Linux. At my current job, I use a Windows laptop. I came from a Macbook from my previous job, so I was used to a kind of Unix based experience. Fortunately, Microsoft somehow partnered with Ubuntu. This partnership allows you to have a Linux command line in your Windows. Anyway, sometimes there are problems… But I can write about that in a new post.</p><blockquote>Share this post with software developers that are in the beginning of their careers or always try to run away from the command line :)</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a9e660e78fb2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Common mistakes in Java]]></title>
            <link>https://medium.com/@codingsam/common-mistakes-in-java-c138499e3a8e?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/c138499e3a8e</guid>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sat, 11 Aug 2018 17:57:29 GMT</pubDate>
            <atom:updated>2019-02-02T00:54:03.644Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-YzLSnYDpxzHwKttHL6Kjw.png" /></figure><h3>Introduction</h3><p>I started coding in Java early in college. Even after college, I wrote a lot of code in Java at work due to projects with Java backends or Android apps. I made some mistakes because I was not aware of some features or just because I didn’t have much experience. Along the way, I learned a lot and improved my coding skills. Based on my experience, I compiled a list of mistakes that I have done or I saw others do.</p><p>Let’s get into it…</p><h3><strong>1- Instatiating an Array List without specifying the capacity</strong></h3><p>When you need to use a list, most times you just create an instance of an <strong>Array List</strong>. However, we need to know how it works to check if it really meets our needs.</p><p>An array list works like any linked list but, under the hood, its elements are stored in an array, which, it’s a static structure. When you instantiate it, it creates an array and then, as you add elements to it, it fills the array.</p><p><strong>What happens when the array is full?</strong></p><p>The list keeps on adding elements as you ask it to do. How does it do that if the array is full of elements? The Array List just creates a new bigger array and all the existing elements are moved to that new array. When this happens, there is the memory from the previous array that needs to be cleaned. Also, moving existing elements to the new array can take some time depending on how many elements were there. The Garbage Collector will take care of the memory cleaning but it can take some time before actually do that.</p><p>Can we avoid this reallocation process? Yes… If you know how many elements you need to add in the worst case, you can “tell” the Array List what should be the capacity of the array so you stay away from any reallocation.</p><p>Just pass the capacity argument to the Array List constructor!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1dc62679c7da89294952463732c78c0a/href">https://medium.com/media/1dc62679c7da89294952463732c78c0a/href</a></iframe><p>Otherwise, a default capacity will be used and that can be too much or can lead to a lot of reallocation processes because we need to add a lot of elements.</p><h3>2- Empty catch clause</h3><p>It’s not always obvious what we should do when there’s an exception. There are exceptions that look like they will never happen or even if they are thrown, we can proceed because it’s an acceptable error and the software shouldn’t be crashing because of that. You can log the exception but… It’s that all you should do?</p><p>For instance, if you call <em>Thread.sleep</em> the compiler tells you that you need to catch an <em>InterruptedException</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ef7d9cdf6c8e34f79373cd4ae8a73850/href">https://medium.com/media/ef7d9cdf6c8e34f79373cd4ae8a73850/href</a></iframe><p>You migh be thinking, how can this exception be thrown? You have no idea so you just print a logging message and proceed. <strong>If you can proceed in case of a specific exception happens, you should just catch that and not all of them</strong>.</p><p>Sometimes, it’s better to let the software crash and allow your users to provide you feedback and some log files.</p><p>I think that it’s easier to fix a bug that makes your software crash than something that it’s not doing what it is supposed to do.</p><h3>3- Not handling null values</h3><p>Any Java developer already faced a <strong><em>NullPointerException</em></strong><em>. </em>A <em>NullPointerException</em> happens when the code tries to access a member of a <em>null </em>value. For instance, the following code will throw such an exception because you try to invoke the <em>equals</em> method on a <em>null</em> string</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b966a45cad1ac7335dc3061891ebe7b6/href">https://medium.com/media/b966a45cad1ac7335dc3061891ebe7b6/href</a></iframe><p>For instance, you have a login method that accepts username and password parameters.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/189afd73f0fc8ac5b87455e68bf560e0/href">https://medium.com/media/189afd73f0fc8ac5b87455e68bf560e0/href</a></iframe><p>In order to allow the user to login, you need to compare the password with the one in the database. If they match, the user becomes authenticated. Otherwise, you just return an error.</p><p>Some things can go wrong here:</p><ul><li>What happens if<em> username</em> argument is null?</li><li>What happens if <em>password</em> argument is null?</li><li>What happens if <em>getPasswordFromDB</em> returns null?</li></ul><p>If you cannot make sure that all arguments are always not null, you should avoid any <em>NullPointerException </em>by checking for <em>null </em>values first.</p><p>The example above should be something like the code below to avoid any NullPointerException:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3a6fa2f7b5664e8bdb504aa0e92d6bbf/href">https://medium.com/media/3a6fa2f7b5664e8bdb504aa0e92d6bbf/href</a></iframe><p><strong>Side note</strong>: I know that you should not store a user’s password in plain text. I simplified things just for the sake of the example</p><h3>4- Not using Generics</h3><p>If you already worked with collections in Java (for instance, Lists), you have used Generics, which <a href="https://docs.oracle.com/javase/tutorial/extra/generics/index.html">“allows a type or method to operate on objects of various types while providing compile-time type safety”</a>.</p><p>For instance, if you create a list and specify a type, you can only add elements from that type. If you try something else, there is a compile-time error.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e5fb536ff2d7bbc16df8f0f22aecc328/href">https://medium.com/media/e5fb536ff2d7bbc16df8f0f22aecc328/href</a></iframe><p>Java developers that don’t have that much experience miss this mechanism when it would allow them to build a solution with less bugs.</p><p>For instance, you have a class that exposes a method to send a message to a given server and you don’t want to block your code because, sending a message can take a while. So, you just pass a <em>callback </em>that will run when the server responds to our server.</p><p>A <em>callback</em> is a function that is passed as an argument to another function and then, it is executed inside that function.</p><p>Since Java doesn’t allow you to pass functions as arguments, you need to create an interface and then, pass an instance that implements that interface.</p><p>Let’s start with the following scenario:</p><ul><li>The server receives an instance of <em>MessageA</em> and send back an instance of <em>ResponseA;</em></li><li>You have the class <em>MessageHandler</em> that accepts a <em>MessageA</em> and <em>Callback</em> parameters</li></ul><p>Given this scenario, you have the following code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/702f8ed7539d15f529127ec8ae8d32e6/href">https://medium.com/media/702f8ed7539d15f529127ec8ae8d32e6/href</a></iframe><p>If you want to use the MessageHandler you will do like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9afefc53ab6a974c9c48cefa9799acb2/href">https://medium.com/media/9afefc53ab6a974c9c48cefa9799acb2/href</a></iframe><p>Seems like legit code, right?</p><p>However, what happens if the server now accepts a <em>MessageB </em>and sends back a <em>ResponseB?</em></p><p>Your callback interface only accepts an argument of <em>MessageA</em>. You have to create another kind of callback…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/80519d8af40369bfdb961ea87708cf3b/href">https://medium.com/media/80519d8af40369bfdb961ea87708cf3b/href</a></iframe><p>And now… What happens if you need to handle <em>MessageC</em> and a <em>ResponseC</em>? A new <em>Callback</em> interface? Hell no!</p><p>Let’s try a new approach and create a new generic <em>Callback </em>interface…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0c705d43591ca5673469631492675d5/href">https://medium.com/media/a0c705d43591ca5673469631492675d5/href</a></iframe><p>Let’s see it in action…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4c694bc4e831af9526baa77e9a96248/href">https://medium.com/media/f4c694bc4e831af9526baa77e9a96248/href</a></iframe><p>You have a more “generic” callback, but now you always need to cast the argument to the right Response type, which seems boring and error prone. If <em>ResponseA</em> or <em>ResponseB</em> changes to something else you need to change the cast code everywhere you are invoking the <em>MessageHandler</em> methods.</p><p>How can we avoid these ugly casts?</p><p>Using <em>Generics… </em>If our <em>Callback</em> could be parametrized with the type it needs to handle, we will get compile time errors if something changes instead letting our software crash, because we didn’t change a cast somewhere. Let’s rewrite our solution…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9614cc5c3a1f5001587801c9f11651a/href">https://medium.com/media/c9614cc5c3a1f5001587801c9f11651a/href</a></iframe><p>Let’s see it in action…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aae9fdaab4181256f0114c64d0abc505/href">https://medium.com/media/aae9fdaab4181256f0114c64d0abc505/href</a></iframe><p>Now you can add <em>sendMessageC, sendMessageD </em>and so on… Without creating a new <em>Callback</em> interface and without any casts! Awesome, right?</p><h3>Conclusion</h3><p>Since I began coding, I have done some of the things I showed you in this post. Also, I saw others doing that. It is actually expected that an unexperienced developer does at least one of this kind of mistakes. Even experienced developers do! You need experience building a lot of solutions to learn how to avoid these mistakes. This post can be applied to any Object Oriented programing language. I have used Java just because it’s the one I have more experienced with.</p><p>I hope you learned something or at least related with this post somehow.</p><p>Share this with your developer friends and colleagues. If at least one of then learned something… It’s already worth it! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c138499e3a8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Hello World — My First Post]]></title>
            <link>https://medium.com/@codingsam/hello-world-my-first-post-a2e13dfc815?source=rss-58cf94a36c97------2</link>
            <guid isPermaLink="false">https://medium.com/p/a2e13dfc815</guid>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[hello-world]]></category>
            <dc:creator><![CDATA[Samuel Coelho]]></dc:creator>
            <pubDate>Sat, 28 Jul 2018 15:29:06 GMT</pubDate>
            <atom:updated>2018-07-28T15:29:06.426Z</atom:updated>
            <content:encoded><![CDATA[<p>Hi,</p><p>This is my first post on Medium. My name is Samuel and I am a software developer. I love coding and building stuff (such a f***ing cliché, but it is true)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D5yPCv4lau42eCxRijK2aA.jpeg" /><figcaption>My first time writing on Medium</figcaption></figure><p>I will write about things I learn about coding and technology.</p><p>This is me, testing this platform as a way to create my online “brand” and share what I know, which is something I really love to do.</p><p>Stay tunned :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2e13dfc815" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>