<?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 Leigh Steiner on Medium]]></title>
        <description><![CDATA[Stories by Leigh Steiner on Medium]]></description>
        <link>https://medium.com/@steinerleigh?source=rss-a48494e6a2ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*NopyU7z7sztvOADbKni6jg.png</url>
            <title>Stories by Leigh Steiner on Medium</title>
            <link>https://medium.com/@steinerleigh?source=rss-a48494e6a2ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:35:58 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@steinerleigh/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[React + D3 : The Macaroni and Cheese of the Data Visualization World]]></title>
            <link>https://medium.com/data-science/react-d3-the-macaroni-and-cheese-of-the-data-visualization-world-12bafde1f922?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/12bafde1f922</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[d3js]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Mon, 03 Dec 2018 22:31:05 GMT</pubDate>
            <atom:updated>2018-12-04T22:30:53.165Z</atom:updated>
            <content:encoded><![CDATA[<h3>React + D3 : The Macaroni and Cheese of the Data Visualization World</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*DHCXyBiUlVWM3EwDnP8R-Q.jpeg" /><figcaption>React and D3, just melting all over one another in gooey, data-driven deliciousness (aka a slice of mac ‘n cheese)</figcaption></figure><p>React is at the forefront of SPA UI development — there’s no other technology which is as powerful and widely used right now. And when we talk about data visualization on the web, we pretty much <em>are</em> talking about D3 (seriously, if all you’ve seen of D3 is whacking out some quick histograms, I have to recommend this <a href="https://www.udemy.com/d3-4x-mastering-data-visualization/">fantastic D3 v4 course</a>, which takes you deep into the nitty gritty of what this library is actually capable of. Spoiler: it’s pretty nuts. PS: I am not affiliated with that course in any way, I just took it and dug it).</p><p>But, a TRAGEDY looms ahead: <em>apparently you can only have one of these awesome libraries in your codebase at a time, right?</em></p><p>See, part of what makes React so fast and light is that it is super clever at updating the DOM efficiently, and so when you use React, you mostly don’t touch the DOM directly — you just chill out and let all that sweet, declarative MVC jazz take care of everything for you.</p><p>Whereas D3 is all about giving you nice clean routes directly to DOM manipulation.</p><p>So that overlap of implementation is what can potentially cause problems for us — if you don’t plan it properly, React and D3 can just…get in one another’s way, and behave really unpredictably. There are some packages that folks have written that will handle this problem for you, but the downside is that you’re then locked into a third system on top of React and D3. This often means that you are stuck using a relatively limited number of pre-made templates, or walled off from a number of the more out-there D3 features. It seems a real pity to limit yourself, especially when, getting them to behave and take turns is really pretty straightforward.</p><p>To illustrate how we want to sort this out, take, for example, my cats.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*nK9wKo-lMiMgZ9I1oZ3LRw.png" /><figcaption>Ellis and Sol about to fight over a windowsill spot on the left, and the two of them comfortably snoozing and sharing on the right.</figcaption></figure><p>Essentially, we want to treat React and D3 like they’re my cats. We’ll just pretend that Ellis in the dapper evening tux is React, and Sol, in in the suave morning suit on the right is D3, and the sunny spot in front of the window is the DOM.</p><p>If there’s only one spot, and we just let them try to work it out amongst themselves, as in the photo on the left, well…those raised paws might look super adorable in the photo, but let me tell you, about three seconds after this was taken, there was some serious brawling. There’s only one spot and they both are determined to have the entirety of it to themselves.</p><p>Whereas, the sunny window on the right is exactly the same size, gets the same amount of sun, but, because we’ve given each of them a separate pillow, which they can call their own and of which they can be the utter boss, they’re both doing their thing perfectly peacefully.</p><p>By giving them just a bit of breathing space, and the illusion of total dominion, I can get the best behavior out of both of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*41_nZjp9zTJ41X-h" /><figcaption>a screenshot of what we’re building — live at <a href="https://d3-react-tutorial.herokuapp.com/">https://d3-react-tutorial.herokuapp.com</a></figcaption></figure><p>So, much as I am loathe to do this, let’s leave the allegory of my cats behind, and talk about what we’re going to make. To make sure that we’re letting each library actually do what it was meant to do, we’ve got a user interface that lets you pick a color and a size, and generate cute little flying SVG circles based on those choices. It’s a pretty trivial toy, but it’s exactly the amount of code we need to get the job done. You can check out the code <a href="https://github.com/leighsteinerlocus/d3-react-tutorial">here</a> or play around with the toy itself <a href="https://d3-react-tutorial.herokuapp.com/">here</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*3Kzq3bUte7SFtMsJ" /><figcaption>a relatively simple Controller Component, which renders a form and keeps track of form submission results in its state.</figcaption></figure><p>Like with the cats, I want to give React and D3 their own separate spaces where they can be in charge and do what they do, and this works really well with a “React-y” way of thinking — we want to assign each library an appropriate role, and isolate the work of that role (and therefore the library) into separate components. This way, when we want to know who gets to manipulate the DOM, the answer becomes really simple: whose component are we in?</p><p>React is great at interactivity, state management and structuring user interfaces, and so that’s what I’m going to let it do — in this component shown above, Controller. It’s just a nice, straightforward form, where each change and submission gets stored in the component’s state — we know what our user is doing now, and what they’ve done already. And that’s all we’re doing here — there’s no SVGs, and we haven’t even imported d3 into this file.</p><p>All of that gets managed down on line thirty nine, where “Viz” is a child component whose sole job will be to take the data that the Controller generates, and use D3 to draw pictures with it.</p><p>While technically we could reverse these roles (people do, for instance, build entire UI’s that only use D3), the point is to get the best out of each library, and this, to me is the most logical breakdown.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*FLCAh8IqP83Li2bA" /><figcaption>a teeny, tiny, tidy, twelve-line Viz component, which renders a single, empty div</figcaption></figure><p>The D3 component, Viz, is going to be super small, even though the visualization we’re using it to make is going to take up the vast majority of the viewport — we don’t want React to get involved or have access to it, so all we really need is a single reference point — that empty Div on line thirteen. That div is basically a little garden fence, marking where React stops, and D3 picks up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jHEFARLfNPNzdJsB" /><figcaption>a helper function which searches out an empty div with a ‘.viz’ class on it, and uses it as a reference to hang the SVG element and all its children on.</figcaption></figure><p>And this is what it looks like when D3 picks up! We have a helpful “draw” function here. It’s tempting to define this as a method on your Viz class, but it’s not necessary to do so, and ultimately, I’d advise against it.</p><p>Once we’re in D3, we want to try to do everything “the D3 way” as much as possible, right? Both because it’s a good way to ensure that D3 can work at the highest level, and also because it’s a good way to ensure that whoever next touches your codebase has an idea of what’s going on and how to effectively build on it.</p><p>Because D3 is going to be touching the DOM directly, outside of React’s Model-View-Control jam, it doesn’t have to know anything about the component where it will eventually be called — it has nothing to do with overall React structure of the application, and can live perfectly comfortably in some helpers.js file somewhere. Just like we don’t reference D3 in our React space, we’re not going to reference React here.</p><p>The big key in all of this is that <em>everything</em> that D3 touches gets created here, and lives only here. We use that empty to div to hang our SVG on, and create every part of the picture — all of its children and their properties, and any interactions they might have, inside this space. Even the styles for these elements live here — this reduces the likelihood of having CSS conflicts with unpredictable outcomes and it also means that you have one-stop shopping any time you need to change the look and feel of your visualization, which is especially handy when you start using some of D3’s more out-there scale building capabilities. ( Did you know by the way that you can generate color scales that will map on to whatever numeric values you use as the range? It’s pretty wild.)</p><blockquote>Before we move on, just a quick note on accessibility: There are a few things you can do relatively easily to give a broad range of users the fullest experience when they encounter your application.</blockquote><blockquote>First: did you know that SVG’s have a &lt;title&gt; element, which can be set to function similarly to alt text for images? For it to work, it has to be the direct first child of the SVG. Coming up with ways of automatically generating appropriate and informative titles/alts for your Data Viz can be challenging, but is absolutely worth the effort to make an inclusive application. What’s the most important thing to understand about the image you’ve created? What do you want your user to walk away with?</blockquote><blockquote>Second: are you planning on making your visualization interactive? Is there more information, or actions that become available by clicking or hovering? Not all of your users will be able to access these — folks using screen readers or who have motor impairments may not be using a mouse. Any functionality that’s important to your UX should be accessible via keyboard navigation alone. Fortunately, that’s not too difficult! SVG shapes effectively take a tabindex attribute, which will allow your users to tab through each part of your visualization. Once there, what if you duplicated your element.on(&#39;hover&#39;,...)behavior to element.on(&#39;focusin&#39;,...) and your element.on(&#39;click&#39;,...) to an element.on(&#39;keydown&#39;,...) where you check to make sure that the keystroke is from a confirmation key? How many more people would get to enjoy the fruits of all the hard work you’ve done?</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/852/0*FLCAh8IqP83Li2bA" /><figcaption>a teeny, tiny, tidy, twelve-line Viz component, which renders a single, empty div</figcaption></figure><p>So, back to our Viz component for a second. Once we have that draw function all set up, all we need to do is to use it. If you remember how our controller component works, it will only be rendering Viz when it actually has shapes to draw, so once we’ve mounted our component, obviously at that point we want to call draw and pass it the data we’ve got. But what if our user adds more shapes? Well, the componentDidUpdate hook will fire, because the information about those shapes will change the props that Viz gets from Controller, and we can tell draw to do its thing again, but this time with the most up to date data. And we don’t have to worry about React interfering, because, effectively, React doesn’t even really know that our SVG is there — it just receives new props and does what it’s told.</p><p>If you were doing this last year (or indeed, you read my first article on getting React and D3 to behave themselves when hanging out), you might remember this process being a tiny bit more complicated — where you had to use shouldComponentUpdate to manually turn off React re-renders, and componentWillReceiveProps to handle your redraws with nextProps before they have even, strictly speaking become this.props. Fortunately, both of these lifecycle methods have been deprecated, and their functionality encompassed in fewer function calls, which is nice.</p><p>Which leads one to wonder, is there any better, cooler, tighter, more cutting-edge way we could be doing this?</p><p><em>I’m so delighted that you asked. Check this shit out, guys:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/718/0*8fzjq7lWWG-3rv2K" /><figcaption>A six — count ’em SIX — line Viz Component, just as functional, but short and sweet</figcaption></figure><p>React Hooks are still in alpha, so they’re probably not quite fit for your production-level code, but look at how slick that component looks! Hooks let us keep our components functional, even if we need lifecycle methods or internal state. Which makes debugging and reading our code just that much easier.</p><p>What’s happening in this component is exactly the same as the class based one above it. useEffect is essentially taking the place of both our componentDidMount and componentDidUpdate functions from before. useEffect takes two parameters to get the job done— a function, which will run anytime the component has a render (in this case, our old, familiar draw function), and a comparator that it uses to judge whether or not enough change has happened to bother running that function. In this case, we’re telling useEffect to only run its function if the length of the shapes array changes, because that’s how we know we have a new shape to draw. Pretty straightforward, right? React has promised us that classes aren’t going anywhere for the foreseeable future, and I don’t particularly want them to, but it is pretty cool to have another option available.</p><p>I hope this quick essay has illustrated how easy and un-intimidating using D3 in your React applications can be (and by the way, this is a pretty good roadmap for using React with <em>any </em>third party library that plays fast and loose with DOM) — has it inspired you to make cool stuff with it? Show me! Tell me about it! Or like, tell me where you think I’m wrong, that’s always fun too.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mLBYsFreM_hwR080taFdTw.png" /><figcaption>a gratuitous cat picture of Ellis, holding a catnip banana</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12bafde1f922" width="1" height="1" alt=""><hr><p><a href="https://medium.com/data-science/react-d3-the-macaroni-and-cheese-of-the-data-visualization-world-12bafde1f922">React + D3 : The Macaroni and Cheese of the Data Visualization World</a> was originally published in <a href="https://medium.com/data-science">TDS Archive</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How To Write CSS When You Hate CSS]]></title>
            <link>https://codeburst.io/how-to-write-css-when-you-hate-css-feb5a235b7f1?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/feb5a235b7f1</guid>
            <category><![CDATA[web-accessibility]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding-style]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 17:16:55 GMT</pubDate>
            <atom:updated>2018-11-27T15:40:57.662Z</atom:updated>
            <content:encoded><![CDATA[<h4>Go From Cee-Ess-Ess To Cee-Ess-YES!</h4><p>I hate CSS.</p><p>Well, I <em>hated</em> CSS. While learning to write code, CSS seemed like an inoperable black box. The twin tasks of deciding how something should look, and then making it look that way seemed just impossible. Which resulted, very naturally, in a deep-seated hatred of the entire art.</p><p>It turns out, though, that a lot of that distaste sprung from not having a process in place to structure and write good CSS rules. As I’ve moved between building applications from scratch, and jumping into already established codebases, I started to compile a little set of, not <em>rules</em> per se, but rather <em>things-that-work</em>, which is, y’know, like having rules but good for us anti-authoritarian types. And one day I got into work and realized that I was really stoked for the tasks I had on my to-do list that day… and they were <em>all</em> CSS.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HdejD2-KF-5mDbfxsJlPJw.png" /><figcaption>my cat, Ellis, with a look of shock and surprise on his face</figcaption></figure><p>Shock. Awe. Mild-to-moderate terror. How in the name of hand-built components did that happen?</p><p>It turns out that CSS is ultimately like any other kind of programming. It is first and foremost a task of problem decomposition, and once you have a tidy set of discrete to-do’s, it’s just as satisfying and delightful as any other kind of programming (fight me, internet).</p><p>What follows is a collection of standards and practices for writing effective CSS. This is far from the only way to do it — if you only take one thing away from this post, it will hopefully be that it’s more important to have <em>a</em> system than it is to have <em>this</em> system, but if you don’t have any system, this one is not a bad place to start. With just four, fairly straightforward guidelines, you too can hate CSS less than you do now.</p><h3>1. Classes Are For Styles.</h3><p>Tags are for semantics, Ids are for references.</p><p>Every CSS rule I write is tied to a class, and ideally, only to a class. Right from the start, it means that when I am looking at my document and trying to understand why it looks the way it does, I know exactly where to start tracking down the applicable CSS rules, and it helps minimize conflicts with unpredictable outcomes and spaghetti code.</p><p>This has been key to keeping my CSS clean and well-organized, and it has a big payoff for the usability of any application where you apply it as a principle. That payoff is a good old coding favorite: the separation of concerns. In this case, the separation of visual presentation from semantic meaning.</p><p>If you’re writing your HTML (or, let’s be real, your JSX, because who is even writing HTML these days) properly, you probably don’t have a ton of &lt;div /&gt;s in your codebase — why use a plain old &lt;div&gt; when you can have an &lt;article&gt; or a &lt;form&gt; or a &lt;nav&gt; or a &lt;footer&gt;?(Or a &lt;main&gt;? You’re not forgetting to add proper landmarks to your page views, right?) And it might be tempting to style on those elements, especially if you think, “well, hey, we probably want all of our menus to be consistent, don’t we?”</p><p>But writing good semantic HTML means that you choose your elements based on their function in your page, and the meaning of their content, <em>not</em> based on how you want them to look. An &lt;h1&gt; is the single most important bit of context on your view, not “text you want to be big and in a stylized signage typeface.” And while a lot of times, these two concerns will flow together, occasionally they will diverge, and if you’ve written your styles on that &lt;h1&gt; , at that point, you have two options:</p><ol><li>You can write some extra CSS rules so that you have &lt;h1 class=&quot;special-not-big-h1&quot;&gt;( or worse, &lt;h1 id=&quot;special-not-big-h1&quot;&gt; which is <em>really</em> going to cause some heartache down the line), adding to the complexity and lowering the readability of your codebase. (Which, if you do it once, won’t be such a problem, but we all know how quickly these little hacks and special cases start to add up, don’t we?)</li><li>You can decide not to use an &lt;h1&gt; for that view’s important content, and thus leave folks using screen readers or other assistive technologies in the dark about the hierarchy of your page. And that would really suck.</li></ol><p><strong>Whereas</strong>, if you haven’t made your &lt;h1&gt;&#39;s do double-duty as semantic elements and stylers, all you have to do is <em>not</em> add that particular class to the special-case element. Isn’t that easier? And cleaner?</p><p>A big part of the point here is break the mental association between “semantic element” and “visual style.” If what you want is “big text”, put that in your css, don’t reach for an element that doesn’t necessarily belong there.</p><h3>2. BEM will Block the Modification of your Elements from being a Certifiable Trash Fire (The CTF Paradigm of CSS)</h3><p>BEM stands for “Block, Element, Modifier,” and is a set of naming conventions that help keep your CSS organized. There are quite a few systems of naming conventions out there, and there’s no single one that is the best option for all circumstances and projects — as with a CSS system generally, it’s more important to have one than to have any particular one. But BEM is pretty handy, and I think it’s a great place to start for a wide range of applications (in part because it’s well known, so it won’t be hard to explain to new devs joining your project in the future), so let’s talk about what it is, and why it’s great.</p><p>BEM separates our CSS rules into three categories, which give a logic to how visual style is applied to your html. Instead of taking each visual requirement as a standalone task, BEM encourages you to think of entire structure of your view, and to break down your styles accordingly. Wherever you store your CSS, all of your rules should be grouped into these three sections (organized either hierarchically or alphabetically, whatever makes sense to your team).</p><ol><li><strong>Blocks</strong>: Blocks are standalone entities in your code, which contain meaning entirely on their own. Good examples are headers, inputs, menus, checkboxes, and so on. A block is something that essentially, contains all of its own rules without any reliance on or reference to parent elements. Classes for blocks are defined without underscores or hyphens, and using camel-case to separate different words, like so: .button, .mainNav, .orderedList. (Frequently, you’ll see BEM where a single hyphen is used to separate words in blocks, since that’s a more common CSS convention outside of BEM, but I think personally that it causes visual confusion with the naming of elements and modifiers, and adds to the likelihood of typos ).</li><li><strong>Elements</strong>: Elements are component pieces of Blocks, and their names should be semantically tied to their parent Block. They do not work as standalone pieces — we’re talking about things like nav links, list items, or input captions. Elements are named with their parent block followed by their own descriptive name, separated by two underscores: .mainNav__link, .orderedList__item, .checkbox__caption.</li><li><strong>Modifiers</strong>: Modifiers are flags that can go on Blocks or Elements, to change appearance or behavior of the particular item (often, these are your special cases, where the color, size or placement has to be treated differently). Modifiers are named by appending two hyphens and then a descriptive name after the Block or Element: .button--danger, .orderedList__item--last, .list--collapsed, and so on. Modifiers are also where I’ll group style rules for pseudo-classes, since that’s essentially what they are.</li></ol><p>It was hard at first for me to really see the utility of this system, until I took an existing project and migrated it over to BEM conventions. The next feature/view set I build out went so much more smoothly than the ones before it, I was completely floored.</p><h3>3. Accessibility Is A Great Design Guide</h3><p>Sometimes, and I know that this is hard to believe but bear with me, you write code without high-fidelity, full-featured wireframes. Sometimes your graphic designer sucks, or doesn’t exist, or is doing twelve million other projects and just isn’t a part of your daily workflow. And more and more often, front-end and full-stack web developers are expected, at least in part, to do the work of a designer.</p><p>So, if you’re trying to develop your aesthetic, and you just don’t know where to start, start by thinking about what, visually, will make your application usable. And <em>naturally</em>, when I say usable, I mean usable to as many people as possible, not just the currently able-bodied ones (that’s what we all mean, RIGHT EVERYBODY?).</p><p>The nice thing about developing accessible applications is that, for the most part, they make things better for all of your users, regardless of how they consume your content. If you’re not sure how something should look, start thinking about how to style it in a way that works for as many people as possible. Make sure your line-heights are at least 1.5em, your font-sizes are big enough, your color contrast is 4.5:1 or higher, and that your line-lengths are bounded to keep text at 80 characters per line or less. And <em>definitely</em> don’t use color alone to communicate important information to your user (especially, especially not red vs. green).</p><p>True accessibility is outside the scope of this essay, but I encourage anyone who writes code, especially code that touches a UI, to learn more about it, and to be an active advocate for usable, accessible design on their team. <a href="https://dequeuniversity.com/">Deque</a> has a phenomenal online curriculum available to anyone with a web connection (and with a full scholarship to anyone with a disability), and the World Wide Web Consortium (W3C), has a <a href="https://www.w3.org/WAI/standards-guidelines/wcag/">checklist on how to meet different levels of accessibility standards</a>, for folks who don’t have the resources for Deque, or who just need to make a quick reference check. Even when you <em>do</em> have a designer working with you every step of the way, they may not know any more about accessible design than you do, and the voice of someone who knows what’s going on under the hood can be an important one.</p><h3>4. The Only Good Shame Is Shame.css</h3><p>I wish I were smart enough to have coined the phrase and concept of Shame.css. Alas, I did not, so I have to start by crediting and singing the praises of <a href="https://twitter.com/csswizardry">Harry Roberts</a>, a literal CSS Wizard, who explains what Shame.css is and why it is so handy <a href="https://csswizardry.com/2013/04/shame-css/">here</a> and <a href="https://csswizardry.com/2013/04/shame-css-full-net-interview/">here</a>.</p><p>But let me talk to you a little bit about how and why I use it in my projects or those I work on. I’d be lying (and unconvincingly, too), if I told you that I followed all the principles I’ve laid out here with perfect consistently 100% of the time. Sometimes, you just need to tinker with what a heading looks like a million times, and you don’t want to go in and add a new class on all your headings. Sometimes you need something fixed <em>now-now-</em><strong><em>NOW</em> </strong>and clean code has to take a back seat to functionality. Sometimes, it’s a Friday afternoon and you’re just too exhausted to think straight. Whatever the reason, sometimes you do it the easy way instead of the right way.</p><p>These things happen, and if we pretend that they don’t, we lose the opportunity to contain the destruction that they cause.</p><p><em>Enter, Shame.css</em>: when you write some CSS that is hack-y and gross, own it. Put it in its own special CSS file (or just as a fourth section along with /* blocks */, /* elements */, and /* modifiers */ — have a /* FIX THIS SHIT ASAP */ portion too). Now your code is working, but you’ve taken steps towards ensuring that future-you doesn’t wind up with a snarled mess of bad styles to deal with in the future.</p><p>The key with Shame.css (just for the record, in my own code, I usually call it “to-fix.css” or “hacks.css”, just to be less <em>negative and blamey</em> about it), is that now, part of your workflow has to be circling back to that file, and actually straightening out whatever CSS-sins you’ve committed in the name of having a quiet life. Ideally, you should get right to it the next time you have a down moment, but since those can be hard to come by organically, I like to officially schedule time no less frequently than once a week for it. Monday mornings can actually be a great time for this — it’s a really nice way to ease in to the week with some not-too-hard, virtuous-feeling wins that don’t require a ton of decision making.</p><p>Whenever you do it, just make sure you <em>do it</em>, otherwise, you’re not reducing complexity, you’re just ignoring your own system.</p><p>As always, I want to hear all about where you think I’m wrong, what you think I’ve missed, and how you totally would do it better. How did <em>you</em> start to hate CSS less? How did <em>you </em>start writing it better?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=feb5a235b7f1" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/how-to-write-css-when-you-hate-css-feb5a235b7f1">How To Write CSS When You Hate CSS</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stateful Peanut Butter and SVG-elly: A React + D3 Tutorial]]></title>
            <link>https://codeburst.io/stateful-peanut-butter-and-svg-elly-a-react-d3-tutorial-c959f5a9ed49?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/c959f5a9ed49</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[d3js]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Tue, 03 Jul 2018 19:28:10 GMT</pubDate>
            <atom:updated>2018-12-03T22:35:55.967Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UMWhnoVA-Nz7AyYvT7Amqw.png" /><figcaption>React and D3, living in harmony</figcaption></figure><p>AUTHOR’S NOTE: Hey guys! this article is deprecated, because it isn’t up to date with the most recent stable version of React, and encourages you to do some things that are not, now, the best way to do them. Check out the updated version, with all new content on web accessibility and React Hooks, <a href="https://medium.com/@steinerleigh/react-d3-the-macaroni-and-cheese-of-the-data-visualization-world-12bafde1f922">right here</a>!</p><p><a href="https://medium.freecodecamp.org/yes-react-is-taking-over-front-end-development-the-question-is-why-40837af8ab76">React is, right at this moment, taking over front end development in a way that, to me at least, is pretty exciting</a>. Tomorrow, that may not be true, but the number of codebases that rely heavily on React is large and growing. If you’re here, reading this, you probably don’t need me to tell you any more about that. And then there’s D3. There are fewer people and projects using D3 than React, but it’s hard to argue this point: when it comes to creating data visualization in 2018, there really isn’t anything that comes close, whether we’re talking about the sheer depth and power of the library (have you seen what D3 can do with <a href="http://bl.ocks.org/jfreyre/b1882159636cc9e1283a">string interpolation and scales</a>?), or the immense quantity and quality of community support and information that exists.</p><p>Both React and D3 give a programmer rich resources for DOM querying and manipulation that leave alternatives like jQuery and even native JavaScript pretty well in the dust. The problem? They do so in totally different ways, which means that trying to use both at the same time isn’t as straightforward as one might like it to be. Both libraries try to update the DOM and, if not managed properly, can conflict with one another and prevent both from giving you their expected output. Which, let me tell you from is experience, is irksome when you really would like to use both at once — if you were say, building a feature where you wanted to create SVG graphics based on user inputs (which is what we’re gonna do in a second).</p><p>Never fear! What follows is a quick and simple tutorial that will have React and D3 braiding each other’s hair and going splits on a rich dessert in no time.</p><p>(If you love-love-love spoilers, you can check out the end result of this tutorial on its feet here: <a href="https://d3-react-tutorial.herokuapp.com/">https://d3-react-tutorial.herokuapp.com/</a>, or you can follow along in the code base here: <a href="https://github.com/LeighSteiner/d3-react-tutorial">https://github.com/LeighSteiner/d3-react-tutorial</a>.)</p><p><strong>The Set Up</strong></p><p>The idea here is not to build a full-scale application, but to create a modular set of practices that you can port into any project with React + D3, so we’re going to keep things as simple as possible, and that means…create-react-app! Go ahead and create-react-app &lt;your-app-name&gt; in your terminal (don’t forget to install it globally if you haven’t already), npm install --save d3, and meet me back here.</p><p>All set? Awesome. Your file structure should look a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/472/1*FaPVn9MU2G1iBhQf-B9VSw.png" /></figure><p><strong>The Magic</strong></p><p>So, the goal here is to prevent React’s virtual-DOM shenanigans from interrupting D3’s more directly surgical approach. And the simplest way to do that is to just literally separate them. (I told you this was going to be easy. Didn’t I? Well, this is going to be easy) I said before that we wanted to build a feature where our application would draw SVG graphics based on some kind of user input. The first thing to do is think about what the responsibilities of React are going to be, and what we want D3 to handle. We know that React is pretty slick when it comes to forms and controlling and (temporarily) storing user input, and that D3 is the hot shot when we’re talking about SVG’s, especially SVG’s that are dynamically based on data. Sounds like we have a nice, neat division of labor, right?</p><p>A good principle generally in application building is to let each component do one thing, so that it can do it both well and thoroughly, so let’s make a component for our controller tasks (Controller.js), where we’ll let React run the show, and our drawing tasks, where D3&#39;ll call the shots (Viz.js), both in that same src folder. In Viz, even though we’ll be exporting a React component, we’re going to stop React from doing most of the things we usually want it to do, while over in Controller, even though we’re going to hold all the information about <em>what</em> we want D3 to draw, we’re not even going to import the D3 library into the file.</p><p><strong>Controller.js</strong></p><p>This is our aptly named file that houses the form that takes in our user inputs. Under the hood, it’s also going to keep track of every shape the user creates and wants to draw, in its state. If you’re reasonably familiar with React already, this is 100% straightforward. We just write up the form with whatever information we need from the user (in this case, the color and size and each circle the user requests), along with the appropriate change handling functions to store the current shape in the React component’s state. Your code might at this point look a little something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GAwrco8ch3FIy3P0SWVLRA.png" /><figcaption>A nice, tidy React form</figcaption></figure><p>The fun gets started when a user has made their most-auspicious selections, and decides they’re ready to go ahead and hit that draw button. Our React state isn’t only going to keep track of the selections the user is in the process of making, but it’s also going to keep a running tally of previous selections, so that we can draw as many circles as we would like. So, when a user submits their selection, we’re going to grab the chosen color and width, and add them to the toDraw list. And that list is going to be passed down to our D3-eriffic Viz as props, which will handle everything from here on out. Just to keep you up to speed, here is what our Controller.js file should look like when we’re done with it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*e4gy3e08gmdJGjhQHCVkKw.png" /><figcaption>Ready to send all that tricky data visualization work off to D3, where it belongs</figcaption></figure><p>Ta-Da!</p><p><strong>Viz.js</strong></p><p>We’re going to keep Viz as simple as possible, as far as React goes. We want React to put up its feet and have a drink — in fact, all we want in our render method is an empty div with some snappy id to reference and hang things on when we start our drawing.</p><p>I know I keep saying this, but here’s where it gets cool. I bet you already know, roughly, how React updates the DOM so quickly and cheaply, right? Essentially (and <em>extremely</em> briefly), whenever there’s a change to a component’s state or props, React compares its model of how the DOM should look (that is, the Virtual DOM) and how it really is, and only spruces up the elements that have actually changed. What you might not have known is that React comes with a built in switch that we can flick to tell it to knock all that fancy shit off. I’m talking about the lifecycle hook shouldComponentUpdate. (You can learn more about it <a href="https://reactjs.org/docs/react-component.html#shouldcomponentupdate">here</a>. Note: The React docs warn that future versions of React may not implement this perfectly, and suggest using a PureComponent instead of a standard one if you need to control updates. However, the relevant code we’re looking at will remain almost exactly the same in that case, so I’ve gone ahead and kept everything in basic class components.)</p><p>So, for the Viz component, we want React to do as little as possible. We don’t want React to update the DOM at all, because we’re letting D3 do all of the updating in this component. Our handy new lifecycle hook will be an almost-empty function that simply returns false in all cases. Like so:</p><pre>shouldComponentUpdate() {<br>    return false;<br>}</pre><p>That clears React out of the way. But where do we let D3 do its thing? Logically enough, we want to draw our initial SVG and children in the componentDidMount lifecycle hook (You could just as easily use componentWillMount in this case, but I use the former so that nothing is blocked that doesn’t need to be, if say, we want to render our SVG based on data that might arrive asynchronously, for instance). If you have a very simple feature in mind, you might be able to stop right there — draw once, and you’re done. But probably, if you’re talking to the user anyway, as we are here, we want to keep talking to them. We don’t just want our user to be able to add one circle, or to have to wait until they’ve decided how many circles they want total before we draw them — we want the user to be able to see their graphic update as they add to it. So what we’re going to do is pull out the D3 code we’ve written into its own function, that simply takes the component props as an argument. Here’s what mine looks like:</p><pre>draw(props) {<br>    const w = Math.max(document.documentElement.clientWidth, window.innerWidth || 0);<br>    const h = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);<br>    d3.select(&#39;.viz&#39;).append(&#39;svg&#39;)<br>    .attr(&#39;height&#39;, h)<br>    .attr(&#39;width&#39;, w)<br>    .attr(&#39;id&#39;, &#39;svg-viz&#39;)</pre><pre>const bubbles = props.shapes<br>   let min = bubbles[0].number<br>   let max = bubbles[0].number<br>   for (let i = 1 ; i &lt; bubbles.length; i ++){<br>    if (bubbles[i].number &gt; max) {<br>      max = bubbles[i].number<br>    }<br>    if(bubbles[i].number &lt; min) {<br>      min = bubbles[i].number<br>    }<br>   }<br>   const radiusScale = d3.scaleSqrt().domain([0, max]).range([0, max])</pre><pre>const simulation = d3.forceSimulation()<br>  .force(&#39;x&#39;, d3.forceX(w/3).strength(0.05))<br>  .force(&#39;y&#39;, d3.forceY(h/3).strength(0.05))<br>  .force(&#39;charge&#39;, d3.forceManyBody().strength(-1300))<br>  .force(&#39;collide&#39;, d3.forceCollide(d =&gt; radiusScale(d.number)+1))</pre><pre>const circles = d3.select(&#39;#svg-viz&#39;).selectAll(&#39;circle&#39;)<br>   .data(props.shapes)<br>   .enter()<br>   .append(&#39;svg:circle&#39;)<br>   .attr(&#39;r&#39;, d =&gt; d.width/2+&quot;px&quot;)<br>   .style(&#39;fill&#39;, (d) =&gt; d.color ? d.color : &#39;purple&#39;)</pre><pre>simulation.nodes(props.shapes)<br> .on(&#39;tick&#39;, ticked)<br> <br> function ticked() {<br>     circles<br>     .attr(&#39;cx&#39;, d =&gt; d.x)<br>     .attr(&#39;cy&#39;, d =&gt; d.y)<br>   }<br>  }</pre><p>As you can see, the d3 grabs that single &lt;div className=&quot;viz&quot;/&gt; that the render method returns, and uses it to hang an SVG on, where we’ll draw out all the circles the user has sent us. What’s nice about doing it this way is that not only are all of our SVG elements generated in this function, but all of the styles that apply to them are right here too — we don’t have to go hunting through our CSS files to figure out why things look the way they look, and if we later want to export the SVG file we create (but hey, that’s another blog post), we won’t have to do any fancy file-reading backflips to make sure that we’ve got everything we need.</p><p>Done and dusted, right? Not quite! Like I said, we’re first going to call this in our componentDidMount function, where we will pass it this.props as its sole argument. But what about when our user adds a new circle? We’ve already told the component not to update!</p><p>componentWillReceiveProps comes very handily to our rescue. This hook takes the incoming new props as its parameter, which we can compare to the existing props to decide if there’s a change that matters to us (for instance, the length of our new shapes array is different from our old one), and update accordingly. (Note: When React 17 comes out, this method will be deprecated, and can be replaced with getDerivedStateFromProps — as above, however, the principle remains the same in either version.) In the case of our little drawing app, if we’ve received new bubbles, then we want to redraw our SVG with the updated list. So, in this case our hook might look something like this:</p><pre>componentWillReceiveProps(nextProps) {<br>   if(this.props.shapes.length !== nextProps.shapes.length){<br>     d3.select(&#39;.viz &gt; *&#39;).remove();<br>     this.draw(nextProps)<br>   }<br>  }</pre><p>What next, you ask? Well, we have our controller component organizing and sending our data to be visualized to our d3-viz component, which draws our SVG, updates it appropriately, and cleans up the mess when it’s done.</p><p>You guys, I think we did it.</p><p>Obviously, this is kind of a silly application. But I wanted to keep it as little and simple as possible, so that it would be clear how simple this really is, and how portable to more complex business-logic needs, and even to other sorts of third party libraries, the principles laid out here really are. At the end of the day, all we’re really doing is following good programming practice — allotting out responsibilities, one per module, and keeping everything else <em>out.</em></p><p>(If you want a little more guidance about how I did it, this is a reminder to check out the codebase at <a href="https://github.com/LeighSteiner/d3-react-tutorial">https://github.com/LeighSteiner/d3-react-tutorial</a>, play with the app at <a href="https://d3-react-tutorial.herokuapp.com/">https://d3-react-tutorial.herokuapp.com/</a>, and to ping me with questions, ideas, or how you like to make your data viz pop.)</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c959f5a9ed49" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/stateful-peanut-butter-and-svg-elly-a-react-d3-tutorial-c959f5a9ed49">Stateful Peanut Butter and SVG-elly: A React + D3 Tutorial</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Get In With the In-Set: JavaScript Sets]]></title>
            <link>https://codeburst.io/get-in-with-the-in-set-javascript-sets-b1217bb03424?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1217bb03424</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 12:37:20 GMT</pubDate>
            <atom:updated>2018-03-12T12:37:20.711Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the great things about JavaScript is that it is an incredibly forgiving language — it bends over backwards to never give you an error message if there’s any possible way to avoid it, coerces type if you so much as blink at it, and lets you treat arrays with the elasticity of a Grow Monster.</p><p>This can feel great and safe when you’re a beginning developer — fewer errors and fewer rules <strong>must</strong> be a good thing, right?</p><p>That sound you hear is the uproarious, embittered laughter of all the older devs reading this over your shoulder.</p><p><a href="https://codeburst.io/the-console-frogger-javascript-debugging-101-7f2268662777">Errors and restrictions, in fact, mostly overall help us create better code. </a>Ideally, if something is going wrong, we want to know about it, and if being able to do something is going to screw us up later on, it might just be better if we’re not allowed to do it in the first place. In that way, while JavaScript is often touted as a beginner-friendly language, it has a number of deceptively innocuous pitfalls. Think of it kind of like the difference between using free weights and weight machines at the gym — the former give you more freedom, but that’s also more freedom to make a mess of yourself. The good news is: the good people of Ecma International are constantly coming up with new ways to save you from your own bad choices. And JavaScript sets are a part of that.</p><p><strong>So, what is a set? </strong>A set is kind of like an array, and kind of like an object, and kind of its own thing altogether. Basically, a set is that really strict, judge-y teacher you had in high school whom you loathe while you’re in her class, but then realize years later in a touching black and white montage that she taught you all sorts of Important Life Lessons about discipline and clear thinking.</p><p>More practically: a set is a complex data-type which stores other pieces of data (or references to them — more on that later), which can be of any type (even other sets!). The most important thing to remember about sets is that they are always a collection of unique values — a set, unlike an array or an object, will only ever store a given value once.</p><p><strong>How can I use sets? (The Fun Part)</strong></p><p>Making a set: Set is a JS class, so you can <strong>instantiate</strong> a set using the ‘new’ keyword, like this:</p><pre> let thingy = new Set(); //this creates an empty set</pre><p>This will give you a squeaky-clean, totally empty set. You can also pass any “iterable” to the set and have its elements added (excluding any repeats). An iterable sounds like it should be a fairly intuitive category, but let’s talk about it anyhow: an array is one, a set is one. Those are nice and straightforward! A string is an iterable in this case too — if you pass a string to the set constructor, you will get a set with each unique character as an element in the set. So that means these sets:</p><pre>const code = new Set(‘code’);</pre><pre>const moreCode = new Set(‘ccooddee’); //repeats excluded</pre><pre>const extraCode = new Set([&#39;c&#39;,&#39;o&#39;,&#39;d&#39;,&#39;e&#39;]);</pre><pre>const codeClone = new Set(code); //referencing our first set, of which this will be a clone</pre><p>will all result in a set that looks like this:</p><pre>Set { ‘c’, ‘o’, ‘d’, ‘e’ }</pre><p>Neither numbers nor objects can be used in this way, although they can both be added to already established sets. (We <em>can</em> add numbers or objects to a set when we instantiate it — by putting them in an array or another set).</p><p>Once you have a set, you can <strong>add </strong>to it using the add method, which will take any data-type as its value. What’s really cool is that the add method actually returns the set itself, so that you can do <strong>THIS:</strong></p><pre>const mySet = new Set([‘you’]);</pre><pre>mySet.add(‘can’).add(‘chain’).add(‘sets’).add(‘wow’).add(‘!’);</pre><pre>console.log(mySet) <br>// prints: Set { ‘you’, ‘can’, ‘chain’, ‘sets’, ‘wow’, ‘!’); </pre><p>Chaining, guys. It’s rad.</p><p>Because a set is <em>not</em> an array, even though it is a list, it doesn’t have a .length property — it has a .size one instead, which will return the number of elements in a set.</p><p>Already, we can start to see how this could solve some problems very neatly and efficiently, right? Say we had a dozen mailing lists that we had bought, and wanted to combine them, so that we had one mega list. We’d want to be sure that there were no duplicates in our master list, so that we didn’t spam anyone, right? And, surely, we’d want to know how many real, non-duped people we actually had altogether?</p><pre>const mailingList = new Set(list1).add(list2).add(list3) //etc.</pre><pre>const sumOfList = mailingList.size;</pre><p>And just like that, we have our perfect list, and we know exactly how long it is. And, if we ever need to remove someone from our list, we don’t need to go looking for them — we don’t even have to be 100% sure that they were ever in our list to begin with. We can just:</p><pre>const byeBye = mailingList.delete(personLeaving);</pre><p>and the set will be guaranteed to not have that value in it anymore. And, if we took a peek at byeBye, we’d find that we had a boolean, reflecting whether or not that value had in fact needed to be deleted in the first place.</p><p>What we don’t have, for better or worse, is random access. Which is a little funny, because sets <em>do</em> possess some order, like but unlike in an array. We can use set.values() to give us an iterator object that has all the values in a set in their order of insertion (thus, this order cannot be manipulated, except by removing and re-inserting elements). Despite this, we have no way to say either set[0] or set.someProperty. We can check for the presence of a value using the set.has(val) method, which will return a boolean. But we can’t use that to grab or otherwise alter that particular piece of data.</p><p>If what we want is to systematically access every value in a set, we will need a set.forEach() — again, both like and unlike our trusty, familiar array method. Set’s forEach() takes a function as a parameter, and will execute once on each value in the set. We <em>technically</em> can do some manipulation on the Set itself this way, some of the things we might do to mutate an array with array.forEach() just won’t wash. (If you use .add in the same way you could use .push in an array forEach(), you will quickly find yourself with a fatal error, and your forEach() valiantly trying to reach the end of a set that forever lengthens in front of it.) Certainly, if we have objects in our set, we can add properties or reset existing ones them, but we don’t have any straightforward way of entirely replacing values.</p><p>This is partially because we shouldn’t really <em>want</em> to, with sets. The nature of the way that they are set up makes them an excellent tool for making a single source of truth where the main question to be answered is simply an on/off case of membership. If what you want is a data-set you can twist around, chop up, and replicate, arrays and objects haven’t gone anywhere. Sets are fantastic when you have unpredictable input to clean, or when you want to be able to ensure membership without worry about duplicates, particularly with primitive data types.</p><p>One last thing!</p><p>Once we’re all done with all of our set manipulation, we can always set.clear() and leave no trace that we were ever there at all.</p><figure><a href="http://bit.ly/codeburst"><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i3hPOj27LTt0ZPn5TQuhZg.png" /></a></figure><blockquote>✉️ <em>Subscribe to </em>CodeBurst’s<em> once-weekly </em><a href="http://bit.ly/codeburst-email"><strong><em>Email Blast</em></strong></a><strong><em>, </em></strong>🐦 <em>Follow </em>CodeBurst<em> on </em><a href="http://bit.ly/codeburst-twitter"><strong><em>Twitter</em></strong></a><em>, view </em>🗺️ <a href="http://bit.ly/2018-web-dev-roadmap"><strong><em>The 2018 Web Developer Roadmap</em></strong></a><em>, and </em>🕸️ <a href="http://bit.ly/learn-web-dev-codeburst"><strong><em>Learn Full Stack Web Development</em></strong></a><em>.</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1217bb03424" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/get-in-with-the-in-set-javascript-sets-b1217bb03424">Get In With the In-Set: JavaScript Sets</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pair Programming For Introverts]]></title>
            <link>https://codeburst.io/pair-programming-for-introverts-dab230879c84?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/dab230879c84</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[agile-development]]></category>
            <category><![CDATA[agile-methodology]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Sat, 24 Feb 2018 16:52:30 GMT</pubDate>
            <atom:updated>2018-02-27T15:23:09.371Z</atom:updated>
            <content:encoded><![CDATA[<p>But first: a definition.</p><blockquote>Pair Programming is a work-style common in agile software development where two programmers work in concert on one task. They occupy two distinct roles: A driver, who writes the code and manages the tactical decisions, and a navigator, who inspects the code being written and manages the strategic decisions. Each programmer should switch roles frequently.</blockquote><p>Depending on who you ask, pair programming is the way of the future, a toxic cult ideology, or everything in between. My suspicion is that the truth (shockingly) lies at neither pole — while not the be-all and end-all of development, pair programming is a powerful tool that <em>can</em>, under the right circumstances, yield fantastic results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sruXxtdR0sxXDg2WSNEb2w.jpeg" /><figcaption>Pair like these buddies</figcaption></figure><p>One of those “right circumstances” though, is the ability of both parties to pair effectively and sort out any conflicts that turn up. And, since more and more companies are structuring their workflow to encourage or even require pairing, it certainly pays to figure out what will make you a competent pair partner. Plus, there’s a not insubstantial collection of data out there suggesting that, at least sometimes, <a href="https://collaboration.csc.ncsu.edu/laurie/Papers/XPSardinia.PDF">pairing results in stronger code and happier devs</a>.</p><p>Let’s talk about some tactics to make pair programming effective and less harrowing, especially for those among us to whom a work day of unbroken one on one human interaction sounds worse than debugging two thousand lines of nested callback hell. I’m a dyed-in-the-wool introvert myself, but I’ve come to love pair programming and the code it produces. When I think about good experiences with it versus bad ones, the main difference is very simple: <strong>structure.</strong> Having clear expectations, and a clear road map, will take pairing from pulling teeth to pull requests.</p><ul><li><strong>Know why you’re pairing: </strong>What is it that you hope pairing will improve about your code in this particular case? Are you trying to maximize your output? Are you trying to minimize future bugs? Are you bridging two different areas of expertise or levels of experience? ‘The best way to pair’ depends a lot on why you want to pair.</li><li><strong>Know how you’re pairing— before <em>anyone</em> touches a keyboard: </strong>Whether you just met at a hackathon, or you’ve been working together for years, it’s best to leave your assumptions at the door. Take a little time and compare notes about how you like to work. Do you like to plan every last thing and do a ton of research before you start working with a new technology, or do you prefer to just dive in and learn by doing? Or somewhere in between? What’s your plan of attack when it comes to <a href="https://codeburst.io/the-console-frogger-javascript-debugging-101-7f2268662777">bugs and errors</a>? If you two disagree on something, how should that disagreement be resolved? Whatever your preference on a particular point, the odds are good that your partner falls somewhere else on the spectrum. <br> Before you get cracking, agree on a plan that suits the task at hand.</li><li><strong>You probably aren’t done talking yet: </strong>One of the really great things about pairing is that it can be a structured, safe way to step outside your comfort zone and try new techniques and work styles. Some of my most effective tricks and habits are things I picked up from pair partners who had radically different work styles to me. Even without such a dramatic lightbulb moment, it’s always beneficial to have facility with a broader ranges of approaches. The bigger your toolbox, the more problems you can solve! <br>This isn’t just about big picture work-styles, but also the nitty gritty: what linter (if any), do you use? What formatting conventions are you using? What’s your Github practice? Should the navigator point at the screen (agh!) or mention a line number if they’re concerned about a chunk of code? How often do you take breaks? How bright or zoomed in is the screen? Talk it out, people.</li><li><strong>Refactor your image of reconciliation: </strong>One thing that made me a much more effective pair programmer was ditching the notion that good compromise always means blending opposing approaches. Sometimes, you and your colleague will have different styles that interlock with one another very neatly — so you can do things a bit your way and a bit their way. Not all MO’s can be fitted together in a way that makes sense, and getting too locked into one vision of ‘fairness’ can mean weighing down your workflow with steps that are actually impeding each other. There are times when compromise means making a concrete choice between A and B — be honest about what the goals of your project are, and if one way of working is more likely to bring you where you need to go than the other.<br> For instance, consider how you might decide on naming conventions for variables and files — you probably need them to be consistent across an entire codebase, and to be able to make decisions about how to name new assets without much thought, and so mixing two or more people’s preferences is a great recipe for spending hours debugging mismatched file paths.</li><li><strong>Really commit to a driver/navigator division of labor: </strong>Pairing at first can feel like yoking two people to the work of one. It’s tempting to treat pairing like a mini-delegation — you do this task, I’ll do that one, and we’ll meet back at the ranch. Don’t fall for this; it’s a trap! Working in parallel is really the worst of both worlds. You’ll wind up having to teach one another everything you’ve worked on, so your production time slows down. You won’t know one another’s code well enough to spot bugs more easily than anyone else would, so your output is shoddier. You won’t be working directly together in ways that help you teach and grow skills, so your overall team cohesion doesn’t benefit. Pairing isn’t the right approach for every problem, but if you’re gonna do it, <em>do it.</em> <br> When you’re the navigator, keep your hands off the text editor. Your job is to figure out higher order logic, research documentation and bugs, and be that fresh pair of eyes. Even if you know, <em>just know</em>, that you have the right solution sitting, pristine, in your head, don’t grab that keyboard. If you can’t explain it clearly to your driver, then it’s possible that it’s not as clear a solution as it seems! <br>When you’re the driver, remember that this is not the same as being The Boss. You may be making the moment to moment decisions of how to implement the strategy, but both of you are going to be equally responsible for the code you submit. Trust the process, and trust that your partner has insight and knowledge that is worthwhile. Otherwise, why bother? (And if the answer to that question is “someone else made me,” consider trusting <em>them</em> for a minute. Basically, I’m asking you to take a fake it till you make it kind of approach.)</li><li><strong>Switch roles often! </strong>When pairing is working, it can really work. It might even feel like you’ve achieved <a href="https://www.goodreads.com/book/show/66354.Flow">flow</a>. Still, you wouldn’t carpool on a long road trip and then drive for twelve hours at a stretch — don’t do it when you pair program either. Switching roles regularly and often means that your work gets the benefit of the most possible talent — your ability to drive, your ability to navigate, your partner’s ability to drive and your partner’s ability to navigate. It’s worth doing especially if you’re pairing at a time when a lot of folks mightn’t: when time is of the essence. If you two don’t have time to take big long breaks to rest and refresh yourselves if you want to make a tight deadline, well…they do say that a change is as good as a rest, don’t they? Changing your perspective opens the door for an intuitive leap, where you might otherwise be stuck. I’ve found that the best way to make sure you switch it up without wasting too much mental effort on tracking it is just to set a timer — every hour or two, you hear the first three bars of the Mary Tyler Moore theme song, and you go “hey, it’s time to switch places.”</li><li><strong>Prepare for turbulence: </strong>Sometimes, conflict happens. Hopefully, you two chatted it all out like adults when you were so conscientiously following step two, so when you come across an intractable disagreement, you have a plan in place for how to handle it. But regardless of what the protocol is, if you treat conflict like an expected and normal event, you make space for your partner to be just as chill. People are attuned to the cues you give them — a disagreement doesn’t have to signal the inefficiency of a partnership, or an unmanageable bug, or be a prelude to a screaming row. Often, taking time to really untangle why you both feel differently can result in insights about your approach that would never have been uncovered otherwise. My favorite scheme for those moment when I am sure-sure-sure that I’m right and my partner’s got it upside down is to ask them, really honestly and straightforwardly, to help me understand their approach. One of two things usually happens at that point — either, in trying to explain it, they spot some error they’ve made, or, better yet (and more frequently), I realize in listening that it was me that had it upside down all along. And even if we come out of that still not knowing what to do, we’ve made it easier to work together by respectfully hearing one another out. And that’s one of those things that tends to be habit-forming.</li></ul><p>So, what did I miss? What makes pairing work for you? What is an absolute mood-killer in a pair? I want to hear all about it — I’d like to get better at pair programming myself.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dab230879c84" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/pair-programming-for-introverts-dab230879c84">Pair Programming For Introverts</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Async Await Saves The Day (Sort Of)]]></title>
            <link>https://codeburst.io/async-await-saves-the-day-sort-of-738e6b1cde64?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/738e6b1cde64</guid>
            <category><![CDATA[asyncawait]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Thu, 08 Feb 2018 15:27:58 GMT</pubDate>
            <atom:updated>2018-02-11T15:27:47.651Z</atom:updated>
            <content:encoded><![CDATA[<p>No human is an island, and no chunk of code, either. Async/Await is awesome, but it isn’t going to replace JavaScript promises in our asynchronous world. Async/Await relies heavily on promises, so if you are shaky in what they are or how to use them, start by checking out my <a href="https://medium.com/quick-code/javascript-promises-in-twenty-minutes-3aac5b65b887">Sixteen Minute Guide to JavaScript Promises</a>. (We’ll do a very short review here, but it’s more to set the stage than anything else.)</p><p>So, on we go. You’ve probably heard great things about async await and how it’s going to revolutionize your code and whiten your teeth and clear your skin. Let’s do a teensy-tiny bit of set up:</p><p><strong>Why do we need Promises?</strong></p><p>We need promises to handle asynchronous actions in JavaScript. JavaScript happens mostly in a non-blocking way — we kick off an asynchronous action, and then move on with our lives and our code, without waiting see when or even if it finishes. This is great, as far as our end products go — if JavaScript could only run synchronous, blocking code, the internet as we know it wouldn’t exist. Every time we did something like using fetch or axios, anything that happened “slowly” by computer standards, our entire browser page would effectively lock until each thing finished. Instead, our event loop manages the tasks that need to happen after an async action completes, and magically, our expressions don’t need to wait in long lines for things to finish that don’t matter to them. This is great for our end user, who gets shiny, smooth interactive experiences, but suddenly is kinda crappy for the developer. There are a lot of things that we ultimately want to make wait because they rely on information that we haven’t finished getting yet. That’s where promises come in — they give us an imaginarily-synchronous pipeline where we can deal with the data once it arrives, while still giving us a lot of the freedom of multi-threaded program execution.</p><p><strong>So why aren’t they good enough?</strong></p><p>Before we had promises, we used vanilla async callbacks. And while, functionally, callbacks gave us a lot of the same abilities, they were nightmarish to look at, debug and maintain (we called it “callback hell” for a very good reason). Promises are a lot better, but all of those thens and catches that actually take callbacks are still a lot to keep track of, and they still limit the flow of our data in some really obnoxious ways. Let’s look at an example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjbH0wC-huEB3y3_PNGbug.png" /><figcaption>Imaginary Promises</figcaption></figure><p>We have a problem here. We can’t really use the result of somePromise after we go to get the reliantNewPromise. Theoretically, we could do them both at the same time using Promise.all(), but it <em>looks</em> like we need the result of somePromise in order to actually structure our reliantNewPromise request. As it stands, we need to contain everything we want to do with each piece of data inside of the the single .then() which receives it.</p><p><strong>How does Async Await make it all better?</strong></p><p>Async Await gets rid of chaining for us (well, almost. more on that later). It turns our async function into a peaceful, magical bubble of scope where we can trigger asynchronous actions that, within this sorcerous realm, obey synchronous rules, while still not blocking anything that goes on outside of that function.</p><p><strong>Implementation</strong></p><p>Implementation is very, very straightforward. Pretty much any sort of function can use async/await — all you have to do is preface the function with the word “async,” and you’re in business. In async-ed functions (as opposed to simply asynchronous functions), you have the ability to place the “await” keyword in front of any expression <strong>that returns a promise. </strong>Your function will pause at those labeled points and <em>await</em> that promise’s fulfillment before moving on with the rest of the function. Synchronous code wrapped in a sea of non-blocking goodness! The only catch is this — like Cinderella’s coach, our data will turn right back into pumpkins outside of our async-ed function scope. In fact (and this will be important in a minute, I promise), a function that is async-ed returns a promise that itself will resolve with the return value.</p><p>(This is why I said that you have to have a pretty good grasp of promises to use async/await — they are here to stay.) Let’s check it out:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pf689zX2pOQMh6XQ2VJmXA.png" /><figcaption>a function that returns some async express middleware, which is a great use case</figcaption></figure><p>So, you can see in this example, we’re going to return some express middleware that modifies our request body going forward. We make simple, async calls to our DB that we want to run consecutively, rather than concurrently, because we can’t go looking for the right docs without the necessary user information already in place — this means that Promise.all() would be no help to us here.</p><p>The fantastic thing is this: we <em>await</em> each DB call individually, but when they’ve finished, we still have access to both the full user and all of the docs at the same time. We can just assign them to variables, as we’ve done here, and then push those variables around anyway we might push normal, non-promise-y data around. We can mutate them, compare them, put them into other objects, whatever we need. Things that would be just about impossible with a promise chain. Within the bounds of that async function, we can treat these variables just like any other type of data.</p><p>Async/Await is powerful, simple to use, and a great way to shape code flow in a readable, human way. Looking at the snippet above, we can easily intuit what’s going on, and confidently assess what will happen when.</p><p>Pretty fantastic, right? But what about…<strong>when things go wrong?</strong></p><p><strong>Error Handling in Async/Await</strong></p><p>We’re going to spend more time on this than you might expect. Because implementing async/await is really <em>just that easy</em> — there’s not a ton of obscure methods or tricky use cases: async-ify a function, await a promise inside of it, boom.</p><p>In some ways, error handling is the most important part of the code you write — if we want people to rely on our applications, then we need them to not be impressed with the smooth functioning of our application. We need them to take it for granted. And that means having good safety nets in place so that, when some promise just doesn’t play us true, our app still runs the way we need it to run.</p><p>There are four pretty straightforward ways to manage errors in async-ed functions.</p><ol><li><strong>Try/Catch Blocks:</strong></li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OypMiI94kvQh3IKnGutCWw.png" /><figcaption>our middleware generator, refactored to handle errors</figcaption></figure><p>The simplest way to handle errors with async/await is simply to wrap your relevant code in a try block, and catch the errors beneath it. Functionally, this is effective, but some developers find it messy and unintuitive to follow.</p><p>2. <strong>The Error Handler Factory (Higher Order Functions):</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Mv_6qJkQ9mCbIc1D9gjEaA.png" /><figcaption>build it once, use it over and over again</figcaption></figure><p>An await-ed expression is still essentially a promise, underneath. Just a promise with ‘extras.’ So what can we do with promises? We can chain .catch()’s off of them, right? One solution to our need for error handling is to write a higher order function that takes our awaited action as a function and returns a new function that is essentially the same function with a .catch() appended with our error handling inside of it. This is a slick, modular way to handle lots of errors with very DRY code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/891/1*-BjJp7LXvnJQdplI7v6ozg.png" /><figcaption>look at hot-shot over here, doing it all in one line</figcaption></figure><p>3. <strong>Catch It In The Moment:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gDki4gOJL13JWUeLM1Nn5g.png" /></figure><p>So, if we can make a HOF to automatically make our functions error handling by chaining .catch()’s on them, it stands to reason that we can just…chain a .catch() after a given async-ed action. This is a good solution for moments when you expect to encounter unique errors that require special handling.</p><p>4. <strong>Handle The Unhandle-able:</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*hIgea9FlCgLU4YgxSjDfcw.png" /><figcaption>very global error handling</figcaption></figure><p>Fun fact — Node.js wants to help us and make everything better. Every time we do something promise-y without an attached error handler, an event is emitted called ‘unhandledRejection.’ So one way to be sure that you never miss an error is to write the error handling straight on to your process — it can listen directly for those events and fire the appropriate callback when it encounters them. What’s fun about this is that it’s a great catch-all (get it?) — any more specific handlers that you attach elsewhere will essentially “overwrite” this one, as they will prevent an unhandledRejection event from emitting.</p><p><strong>The Limitations of Async/Await</strong></p><p>Alas, async/await is not perfect, or at least, does not solve every possible synchronicity related issue that we might have perfectly. As we talked about earlier, async/await’s powers are limited — once you cross the border of an async-ed function’s scope, you’re back into quotidian, chaining promise-land. You can’t, unfortunately, await a promise inside a function and return its value as raw data.</p><p>Furthermore, async/await is not always a preferable option over straight up promises (compared to how, once we have promises, we pretty much should never be bothering with vanilla async callbacks ever again). Promises have the <em>potential</em> to be more efficient than awaiting, depending on our specific needs. We can only await one thing at time, no matter what — there is no await.all(). If we want to make asynchronous requests that fire concurrently, async/await is not a good solution. It’s not all bad news though — because async/await operates directly on promises, there’s nothing stopping you from mixing the two tools in your codebase. One great approach is to use async/await as a default, in the name of clean, easy to follow code, and to revert to promises when and only the needs of your application call for their extra flexibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=738e6b1cde64" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/async-await-saves-the-day-sort-of-738e6b1cde64">Async Await Saves The Day (Sort Of)</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Promises in Sixteen Minutes]]></title>
            <link>https://medium.com/quick-code/javascript-promises-in-twenty-minutes-3aac5b65b887?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3aac5b65b887</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[asynchronous]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Sun, 04 Feb 2018 20:25:56 GMT</pubDate>
            <atom:updated>2021-06-11T10:24:15.481Z</atom:updated>
            <content:encoded><![CDATA[<p>(A Beginner’s Guide)</p><p><strong>Introduction</strong></p><p>I think that most good stories start with a truism, so let’s do that. The best programmers are lazy. They like being lazy so much that they will stay up all night inventing a new, more efficient way to be lazy, and get into passionate arguments with twenty thousand of their best friends about what form of laziness is in fact the laziest (and therefore, the best).</p><p>More seriously, figuring out ways to just <strong>do less</strong> is a key part of making applications that are readable, maintainable and efficient. You’ll find that in coding, very little that we do is done “for its own sake” — every tool that we use (hopefully) makes doing something that we need to do easier.</p><p>Promises are no different. It can be tricky to wrap your head around exactly what they are and how to use them when you are thinking about them in the abstract. Understanding them conceptually <em>first</em> is, to my mind, a chump’s game. Very organically, there will come a moment as you build out some application when you will look at your code and say, “Oh, crap. What I really need to do here is make sure that my program doesn’t try to use something I’ve sent it to get until it’s actually gone and gotten it.” And I’ll happily bet you all an internet dollar that that’s the moment when promises will suddenly click for you.</p><p>Let’s see if I can help you get there though, anyhow. In order to talk about what promises do, we need a little bit of information about why we need them. Let’s talk about what happens when you tell node, or V8, to run a file. This will help us understand what the problems of managing asynchronous actions are, how they arise, and why promises are such an awesome, usable solution to those problems. In doing this, we’re probably going to tread some pretty familiar ground. The goal of this article, however, is not just to give you some informal documentation of promises, but to fit them within the <em>narrative</em> of how we build our applications. So bear with me if the beginning feels a little…basic.</p><p><strong>Part I: The Land Before Promises</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GZDLKUqXf6S_b1N9KEKvbQ.jpeg" /><figcaption>A Dark Time</figcaption></figure><p>How does our code normally execute? Each expression runs, and then moves on to the next one. It’s unidirectional, right? This is great, because it’s predictable. When we invoke a function on line fifty, we expect it to have access to any information that’s been established on line forty. No surprises. And if all we’re doing is running code that is contained in one space and executes at a normal speed, that’s exactly how it will work.</p><p>But sometimes, we have to do things that are so big or complicated that even our super fast computers do them slowly — by computing standards — stuff that might take hundreds of milliseconds. Like talking to a database, or reading a file.</p><p>JavaScript is a single-threaded language, which means that it can only do one thing at a time. This is predictable and easy to manage. But if that’s literally true — that we can’t ever move on to the second thing until the first thing has run its course — then we can’t possibly have all of the smooth, interactive experiences with our applications that, in 2018, seem totally quotidian and on which we absolutely rely. If we had to just wait the whole second or two that it could take for a piece of data to be fetched before changing anything else about a page or application, we couldn’t have even very simple web page behavior, like having a text color change in response to a mouseover, while anything else is happening. It is simple and easy to <a href="https://coursesity.com/best-tutorials-learn/javascript">learn JavaScript</a> due to its agile nature.</p><p>Fortunately, it’s not quite that simple. Our call stack isn’t the only thing that manages our code. Along with it, we have a series of APIs (Web or C++, depending on whether we’re in the front or back end), that help us handle asynchronous actions.</p><p>So, if we do this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iuWZ30aA4hZ5__Op-ievuQ.png" /><figcaption>which, i mean, <em>don’t do this</em></figcaption></figure><p>That fs.ReadFile will run, and head right off of our callstack, freeing us to run the console.log statement on line twenty. Great, right? Except we have one, pretty serious problem: that console.log is not going to have our veryImportantFile in it — line twenty is going to execute long before fs.ReadFile ever gets back with data to fill up ourStuff. And our code still executes unidirectionally: we can’t just DC Al Coda back up to the variable declaration whenever it just happens to be convenient for us. So what do we do?</p><p>One thing we can do is to give that asynchronous function (the fs.ReadFile) a callback function, and put anything we need done with the data there. When an async function takes a callback, that argument will run upon the completion of the asynchronous action, right? Not quite.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*cSrciPSq3rNh3vLYOut6EA.jpeg" /><figcaption>A very simplified and delicious diagram</figcaption></figure><p>We don’t know how long any given async action will take to complete. Could be a tenth of a second, could be two seconds, who knows? If we could somehow trigger an async’s callback to run whenever it happened to finish, it could theoretically just execute in the middle of some other function, which would be weird and probably break things. It would completely rob us of that predictability we’re relying on. Fortunately, that’s not how it works.</p><p>When an async action is done doing its thing, the callback function gets pushed on to the task queue, but it doesn’t run there. The only place our callback will run is in the call stack, just like any other function. And how it gets from the queue to the stack is handled by the event loop.</p><p>The event loop has just one job: it is constantly watching the call stack. When the call stack is empty, the event loop checks the task queue and grabs the first operation waiting in the queue to put on the stack. What this means in practice is that our callback function will run at the first point after the asynchronous action completes that the call stack becomes clear. Which isn’t totally predictable, but sounds a lot better than where we were a minute ago, right?</p><p>So, at this point, our code will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AyKM5CjnjRxYLgDs_2Nwhg.png" /><figcaption>Baby’s First Vanilla Async Callback!</figcaption></figure><p>That’s not too terrible to look at, is it? It’s not really any worse at this point than using any old array method — array.map() isn’t something that we think of as really kludging up our code. But what if, instead of just logging that information, we actually need to do something more substantial with it? What if, say, we’re reliant on some data in veryImportantFile.txt in order to direct us to the next file we have to read? That would be another asynchronous action, wouldn’t it? And that would have it’s own callback, that would run once both things had completed and the call stack had cleared at least twice. And what if <em>that</em> file was something that we actually needed to do something asynchronous with…</p><p>Oh, and before I forget: did I mention that we’re actually skipping a step here. What if, when our program went to get our veryImportantFile, something went wrong? Maybe there was a typo in the name, maybe the file is corrupted, maybe there’s just some other problem that we couldn’t anticipate. What then? For our callback function to have any purpose, it presumably relies on whatever the results we’ve been waiting for are, so it wouldn’t make sense to run the same function if what we get back is a bunch of error messages.</p><p>Vanilla asynchronous callbacks actually take two functions as arguments — one for handling the success case, and one for the failures. And they’re actually “error first” (as in, the first function parameter will be treated as the error case callback) — just to make things even less intuitive and easy for humans to parse. Our application needs don’t have to get very complicated at all before our code starts to look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-vIo8uS6IAzuBlInL3TxlA.png" /><figcaption>CALLBACK HELL</figcaption></figure><p>You might say, “Well, that’s a pain in the ass, but it works, doesn’t it? Why not just suck it up and code? Our runtime environment doesn’t care if our code is pretty or ugly, does it? Why should we?”</p><p>We should care. This set up means that our code is not portable — when we ask for data, we have to manage absolutely everything we want to do with it in a single callback function. It’s not easy to set up a chain of tasks that are all inter-reliant on one another, and it still isn’t easy to manage the order of operations.</p><p>All that snarly, gnarly nesting means that our code is going to be really hard to debug. Which might not be the end of the world if you just held you breath, carefully coded your application out once and moved on to the next thing, never to return. But the reality of programming almost never looks like that. It’s pains me to tell you this, but at some point, you will probably make a mistake in your code (although, when you do, you can always check out my <a href="https://medium.com/@steinerleigh/the-console-frogger-javascript-debugging-101-7f2268662777">basic debugging guide</a>), and I don’t envy the poor sap who has to go trudging through that endless tangle of callback hell trying to find a lonely hanging bracket or mis-assigned variable. And there’s no guarantee that the person doing that debugging is going to be the person who wrote the code in the first place — very few real world developer tasks are managed from beginning to end by lone JavaScript Cowboys. So you might not even have the vague memory of having set the code up in the first place when you go on this massive bug hunt. Not to mention that, sooner or later, you or someone else will want to refactor this code to make way for new or updated features.</p><p>This ugliness is not just cosmetic. It has a real, negative impact on how well your code works, and how well you and your team will be able to put it together and maintain it. If it was all we had, we’d make do, but…what if there were a better way?</p><p><strong>Part II: The Land Not Before Promises</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*y7lnJk6i7oAC8uMGmyqs8w.jpeg" /><figcaption>Paradisiacal, isn’t it?</figcaption></figure><p>Spoiler alert: there is. So, what is a promise, and how will it get us out of the mess that we’ve apparently been making all this time?</p><p>The A+ specification defines a promise this way:<em> A promise represents the eventual result of an asynchronous operation. The primary way of interaction with a promise is through its then method, which registers callbacks to receive either a promise’s eventual value or the reason why the promise cannot be fulfilled.</em></p><p>Did that make any sense to you? Don’t worry, like I said, it’s a chump’s game. Instead, let’s talk about what a promise does. A promise is basically a container for an asynchronous action — what this tells us is that, at a minimum, promises have to give us everything in terms of capability that vanilla async callbacks give us, because a promise is something that is taking a vanilla async callback and putting it into a format that will be less heinous to actually implement. Otherwise, there would be no point in having them — remember how we were talking early about how this is all in the name of making our jobs easier?</p><p>Promises are going to free us entirely from nesting. Promises are going to give us a really easy to follow breadcrumb trail of inter-reliant actions. Promises are going to give us multiple options for handling errors all at once, or customizably, all in formats that are easier to keep track of than what we have now. Promises are going to go a long way towards making the asynchronous, non-blocking code that we write just as predictable and unidirectional as the synchronous, “fast” blocking code that we’re used to writing. Which is pretty cool. How do we do that?</p><p>The badass thing is, promises don’t rely on anything other than basic JavaScript. Javascript now has promises supported natively in its code (as of ES6) — you can instantiate a new promise any time you like. But you don’t have to do it that way. Before promises were available in JavaScript, plenty of intrepid JavaScript writers wrote their own promise libraries that you could install in your codebase. You may still want to use them, as some of them are more efficient than the JS promise, and some may have additional features that are useful to you. <a href="https://promisesaplus.com/implementations">Here is a pretty solid list from A+ of libraries that meet their specifications</a>.</p><p>So. <strong>What is a promise? </strong>A promise is literally just a plain old object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GHKL3CTBezKEe4rtvKoPsQ.png" /><figcaption>see, told you so.</figcaption></figure><p>This is not any different than any object you’d make yourself (check out that list and see how many other coders have done just that). It’s an object created by a constructor, that has a bunch of useful properties and methods on it. Essentially, there are four things that make a promise a promise:</p><p>1. A promise takes an <em>executor</em>. This is the thing. The thing we actually need to get done. An executor is some kind of function that we’re using, whose return results we need to control asynchronously.</p><p>2. A promise has an internal state (which we cannot access or alter directly). Every promise starts out having a state of “pending.” Only once, in it’s whole “lifespan” can it change. It can either change from pending to fulfilled (yay!), or from pending to rejected (boo!). Once our promise state has switched, it cannot become pending again. It also can’t go from fulfilled to rejected, or from rejected to fulfilled. We only get one shot at mutating each promise. Which is a good thing! The state of a promise is going to determine which, if any, sets of callback functions we run (those we tag as error-case, or those that we tag as success-case). Once a promise has a non-pending state, that’s a fact on which we can rely for the entire future of our code.</p><p>3. A promise has a value. This value in a success case will be the data we want, or an error (or a “reason”) if things go wrong. The internal state of a promise will always resolve in tandem with ETIHER an error or the data as the promise’s value, and once that state has changed, not only is the state immutable, but the promise’s value is too. The value can’t change once we get it (at least, in relation to the promise itself). Which again, is a desirable state of affairs — we don’t want things shifting under our feet.</p><p>4. Finally, for a promise to be a promise, it has to have access to a “then” method (and we’re going to talk about this in more depth in a sec). This is what will take the place of nesting callbacks — it’s where we’ll handle the results of our asynchronous action.</p><p><strong>Part III: Making Promises</strong></p><p>There are two main ways we’ll encounter promises in the wild. In JavaScript, we do have access to the promise constructor, so we can instantiate a new Promise, and pass it our executor and callbacks ourselves. It’s a little weird, but still way easier than vanilla sync, because it is, and will remain, flat, no matter how many things we chain off of it, and any weirdness is pretty front-loaded. It also means that our code is portable — we can make a promise in one place, and attach a handler to it anywhere else in our code (we can even attach multiple, non-chained handlers to the same promise).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oy4tWj7cg0GdtxKJQnVWHw.png" /><figcaption>making promises, willy-nilly</figcaption></figure><p>More frequently, however, we’ll see that promises are supported and baked into other libraries that our application uses. Sequelize, for example, which helps us set up our database schema and saves us from the terrifying task of writing our own SQL queries, supports promises with its database actions, so we can just treat any of those actions as though they are variables representing a promise (because they are). Which is pretty great.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y3D3YZLE2auj7tsyhJ8Q2g.png" /><figcaption>look at how neat and pretty this is!</figcaption></figure><p>And we’re only just getting up to the real magic of Promises. Every promise has a method on it called “then.” And it’s easiest to understand what then does in very plain, english-language terms. If you have a promise, it will settle (that is, resolve or reject), and THEN run the code that is passed as a callback to the then function. And even more handily, the function that we pass to then automatically receives as an argument the resulting data or error.</p><p>But it doesn’t just stop there! Having only one then available to us isn’t much good. We talked earlier about how inter-reliant different operations might be, and so, for promises to be really helpful, they need to be chainable from one another. The return value of a then function <em>is itself a new promise</em>, so the following then will receive the resolution or error from <em>that</em> upstream promise as its argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gjbH0wC-huEB3y3_PNGbug.png" /><figcaption>Bam!</figcaption></figure><p>Suddenly, we can control both when our functions run (or at least, we can guarantee that reliantNewPromise won’t run until somePromise resolves and passes on its value, and that weCouldDoThisAllDayPromise won’t run until <em>that</em> resolves, and so forth and so on) and guarantee that each will have the information which they need in order to run effectively. And again — it’s pretty easy on the eyes, isn’t it?</p><p><strong>Part IV: We all make mistakes. Or, at least, errors.</strong></p><p>One of the most annoying things about our old frenemies, vanilla async callbacks, is that PITA error-first format. Error management with promises is much, much simpler. First of all, promises have a success-first format. So one way to handle errors in a promise chain is to pass our then a second function argument, so that our program knows what to do in any possible outcome.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euPzQAX6uHUTuiUDjiR8xA.png" /><figcaption>A perfectly fine way to handle errors that pop up in your promise chain</figcaption></figure><p>But promises give us something that async callbacks don’t — they give us bubbling. If one promise rejects, and the then it is currently in does not have an error case callback, it will move to the next then, and so on, until it finds the first then that does have an error case callback. So, another, more readable way to manage errors in promises is to have two separate thens, with the error handling then following the success handling one, where we would just pass “null” as the first argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NMEbp387RvyoDHqOje-ZNw.png" /><figcaption>A better, but still a bit clunky way of handling promise chain errors</figcaption></figure><p>But…it gets better still! There are usually a fairly limited number of things that we want to do when errors get thrown, right? (Like, log them to the console, or send them to the browser to tell our client that they’ve screwed something up.) Wouldn’t it be even slicker if we could just handle all of those errors in one place? Because of that bubbling capability, we can actually make all of our thens success-only, and let any errors slide right on down to this super useful promise method “catch.” This works a bit like JavaScript’s try/catch set up — any errors that get thrown upstream will be “caught” by our catch block, and handled in its callback, obviating the need for any other error handling clogging up our code. And of course, the fewer places we have to implement something, the fewer opportunities we have for error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zX62H06f0L-W-5gQAay5AA.png" /><figcaption>Ta-Da! In most cases, this will be the best way to set up your error handling</figcaption></figure><p>Just to be clear — a promise “decides” which case to run based on its internal state. While the state is “pending” (forever, if the promise never resolves for some reason), no callbacks of any kind will be run. Once the state has settled, EITHER the success handlers will fire, OR the error ones will. There’s no middle ground, here, no circumstances under which both success and error handlers will execute. This is why it’s so important that the promise state can only change once, and only in certain predictable ways. For beginners in JavaScript, the <a href="https://blog.coursesity.com/popular-javascript-frameworks/">best JavaScript frameworks</a> are the best way to excel.</p><p><strong>Part V: The Bottom Line</strong></p><p>If you look at the chains from these examples, you can start to see that promises let us control our code more functionally, and allow us to have success and error bubbling in something like the form we have in a synchronous context. Better yet, it’s become much easier to manage and understand what data we have access to when. And we’re not just restricted to this pipeline of impenetrable bubbles where we get one piece of data, and move on to the next in a use it or lose it sort of style. We also have methods like Promise.all(), where we can aggregate the results of multiple promises, and handle all the data they return together — meaning, we can access them all at once, if we want to.</p><p>Let’s take a look at a quick example here:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OlEy2z4fuwS_g-Y_p8MFNQ.png" /><figcaption>Promise.all(yourPromisesAtOnce);</figcaption></figure><p>Here we have a series of promises that we’re containing in an array. They’re not reliant on one another’s success, but we do want them to all succeed or fail together. By passing this array to the JavaScript Promise’s all method, we will return a <strong>single promise </strong>that will either resolve when every promise has resolved, or reject with the reason of the first value in the array that reject. If, as we hope, our promise array resolves completely, the resulting values will be an array of values whose results are ordered by the order of the promises in the original array — <strong>regardless of which promises resolve first. </strong>Isn’t that frankly rad?</p><p>Let’s tie this up with a nice bow. Promises give us simple chaining in the place of endless nesting — our code becomes linear again, the way we like it. They give us simple, unified error handling. They make our asynchronous actions portable — we can set them up in one place, and manage what to do when they complete in another, and they’re timing ambivalent, so we can even attach more handlers (or handler chains!) to them whenever or wherever we want, still confident that every appropriate success or error handler function will run.</p><p>If it seems like the promise-y meat of this went by more quickly than the build up, if promises seem less weighty than using vanilla async callbacks, then that’s good! That’s a sign of success here, because they <em>are </em>simpler, from a user standpoint. That’s why we generally will want to use them wherever we can in place of vanilla async.</p><p>Unfortunately, promises don’t solve all of our problems. They still keep our slow-gotten data in this sort of separate funnel within our program. We don’t have a simple way of making the information from a resolved promise available globally in our application, or of guaranteeing that code <em>not</em> in the promise chain won’t try to use our promise-y data before it’s settled. For that, you’re gonna have to wait until I get around to writing an article on async await!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3aac5b65b887" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quick-code/javascript-promises-in-twenty-minutes-3aac5b65b887">JavaScript Promises in Sixteen Minutes</a> was originally published in <a href="https://medium.com/quick-code">Quick Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Console Frogger: JavaScript Debugging 101]]></title>
            <link>https://codeburst.io/the-console-frogger-javascript-debugging-101-7f2268662777?source=rss-a48494e6a2ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f2268662777</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[debugging]]></category>
            <dc:creator><![CDATA[Leigh Steiner]]></dc:creator>
            <pubDate>Fri, 02 Feb 2018 23:39:13 GMT</pubDate>
            <atom:updated>2018-02-05T20:38:46.390Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/810/1*HiwBessNBihM_xFfIlhmeg.png" /><figcaption>The Console Frogger</figcaption></figure><p>Bugs don’t appear out of nowhere. We make each and every one of them. But they can be pretty nerve-wracking when they appear. Having a systematic approach for what to do when you see one will help you fix them faster and more effectively, and will help you learn more about your code.</p><p>What we’re going to do now is talk about some things that we can try for any and every sort of bug in our code, and then break down different kinds of bugs we might see, and the more unique approaches for dealing with each of them.</p><p><strong>To-Do’s For All Sorts of Bugs</strong></p><ol><li>Remain Calm. We’re going to get through this.</li><li>Get help! Aren’t you happy when someone else asks you for help with their coding problems? Someone else will be just as happy to unpick yours. And it doesn’t have to be someone who knows more than you do, either. Just a pair of fresh eyes can go a long way to spotting mistakes.</li><li>Take a break! When in doubt, freshen your own damn eyes. If you can’t take an actual break, go work on something other project, or some other part of your application.</li><li>Google the error you’re getting. Google the error message. List the language you’re writing in. List the tools that you’re using to write it. In the results, look for people who have generated that error in the same context, or in similar ones. Especially when you’re just starting out, it’s reasonable to assume that someone, somewhere has fucked up this particular fuck up before. Learn from them.</li><li>If you’re having trouble pinpointing either where the error is, or what mistake is causing it, try this: comment out a wide swath of your code, until you disappear the error. Piece by piece, comment the code back in, until you’ve broken it again — hopefully you can isolate exactly what’s causing you’re problem. If you really can’t spot it, trying writing out the code fresh, sometimes you’ll overwrite a small error that your eyes just couldn’t spot from looking at the code for too long. Copy-editing is hard, and it’s a whole different skill!</li><li>Check the docs. Check them again. Find someone explaining the docs.</li><li>Don’t fear the error message! It’s here to help!</li></ol><p><strong>An Incomplete Checklist for Avoiding Bugs In The First Place</strong></p><ol><li>Test your code as you write it. Write a route, see if you can hit it and get the expected response. Write a react component, see if it renders the way you want it to.</li><li>In fact, consider writing tests for your code (better yet, write them <em>before</em> you write the code!) — this way, if you get your code in one part of the application working, and then something you write elsewhere breaks it later, you can always just run your tests to make sure your specs are passing (rather than hand testing every feature over and over again).</li><li>Practice good Git hygiene! Commit early and commit often. Commit with fantastic, descriptive commit messages too.</li><li>Related: work out tricky features on their own branches. That way, you can always revert to your last-working-version if you break everything and destroy the universe.</li><li>Get in the habit of writing beautifully formatted code. (5a: install a linter). If you’re consistent in your spacing, indenting and semi-colon habits, you’re a) more likely to be able to spot errors and b) less likely to make them in the first place.</li></ol><p><strong>Loud Errors</strong></p><p>This is the first broad category of error. This is when our code <em>literally</em> breaks — stops running in the first the first place, and gives us some sort of error message. This might sound bad, but don’t be fooled. These are the good times. The happy times. You will miss them when they are gone.</p><p><strong>To-Do’s for All Loud Errors:</strong></p><ol><li>Read. The. Error. Message. R E A D I T.</li><li>Read the stack trace to figure out where the error is being thrown. You should be able to find the file name and the exact line number where your code is breaking.</li><li>If the error is being thrown by your node modules, keep going down the stack trace to hopefully find the bit that is being thrown by your code (express probably does not have a bug in it). 3a) if you go through the WHOLE thing and none of it is your code, check what modules are throwing the error, and start checking the places where you use them.</li></ol><p><strong>Types Of Error Messages (In JavaScript)</strong></p><p>There are six types of JS error message. The first three, you’ll see pretty often, the rest you probably won’t see as much.</p><ol><li><strong>Syntax Error</strong>: Your code won’t parse. Translation: You have a typo. <br>Solutions: <br> i) go check that line number. (see also: your linter)<br>ii) know that a syntax error will be generated by the line where the code itself breaks — often the actual typo might be in the lines above (or below, if you have a brackets problem)</li><li><strong>TypeError</strong>: your code expects a variable to be one *kind* of thing, but it is in fact another. This is one that you’ll see a lot, because it can be caused by lots of different kinds of screw ups. error messages like “cannot read {property} of undefined” or “{such and such} is not a function” are generally type errors. This is a very non-exhuastive list of solutions, to give you an idea of where to start looking. <br> i ) console.log(typeof offendingVariable) to see if it’s what you expect/need.<br>ii) check the formatting of your function — is it being called *on* what it should be called on, is it structured correctly?<br>iii) is your data moving where it should? (console.log your function arguments and maybe their types?)<br>iv) if this error is being thrown by your use of a library, check the docs to see if you’re using it right. <br> ivA) try to find examples of other people using that tool!</li><li><strong>ReferenceError</strong>: You’re referencing a variable that does not exist. Solution: look for where you think you’ve defined it, or where you should have defined it. you will likely find that you have either a) made a typo, b) imported/exported incorrectly c) not actually declared it at all or d) made a scoping error (eg, using “let” inside an “if” block, and then referencing that variable outside the code block). Solution: look for where you think you’ve defined it, or where you should have defined it. you will likely find that you have either a) made a typo, b) imported/exported incorrectly c) not actually declared it at all or d) made a scoping error (eg, using “let” inside an “if” block, and then referencing that variable outside the code block).</li><li><strong>RangeError</strong>: Raised when a numeric variable exceeds its allowed range (solution: don’t do complicated math in javascript. or at least, use a special math-y library for it. alternately: fix your callstack.)</li><li><strong>EvalError</strong>: you’re using eval() wrong. but if you get this error, you <em>know </em>you’re using eval() wrong, because you’ve decided to use eval(). Don’t do that.</li><li><strong>URIError</strong>: Raised when the encodeURI() or decodeURI() functions are used in an incorrect manner. Lots of cool libraries exist just so that you never have to make this error. Like Express. Or Koa. Or Hapi. Consider using one.</li></ol><p><strong>Silent Errors</strong></p><p>This is for the rest of the time. Our code is running, it’s not breaking, but it is not giving us the output we expect or want. These are the sad times. The dark times. The lonely times.</p><p><strong>To-Do’s For Silent Errors</strong></p><ol><li>Diagram out our desired data flow with a pen and paper. Start tracing it out with console.logs, and try to find the point where we go from having the right outputs to the wrong ones.</li><li>Check to make sure that we’re actually executing the code we’re expecting to: console.log just to make sure we’re getting through to the blocks we should be.</li><li>Talk through what should be happening, with a teammate or fresh pair of eyes. see if anyone can spot a logic-error.</li><li>Check the docs for the technologies you’re using — do built in functions return the data you expect, in the format you expect?</li><li>Brainstorm alternate ways to solve your problem. What is the goal of your code? If the approach you’re debugging just isn’t unfucking itself, could there be other ways of achieving the same goal?</li></ol><p>These are just some very basic kinds of errors, and ways of looking at solving them. Especially as you start to use more JS tools and libraries, you’ll encounter all kinds of new and exciting bugs, but these same principles will at least give you a place to start.</p><p>If you’d like the meat of this in super-short, light markdown, check out my github repo here: <a href="https://github.com/LeighSteiner/deBuggerChecklist">https://github.com/LeighSteiner/deBuggerChecklist</a>. If you think I’ve made any terrible mistakes that you want to yell at me about, or if you want to add some more tools and trips, feel free to send me a pull request!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f2268662777" width="1" height="1" alt=""><hr><p><a href="https://codeburst.io/the-console-frogger-javascript-debugging-101-7f2268662777">The Console Frogger: JavaScript Debugging 101</a> was originally published in <a href="https://codeburst.io/">codeburst</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>