<?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 Brandon Duffany on Medium]]></title>
        <description><![CDATA[Stories by Brandon Duffany on Medium]]></description>
        <link>https://medium.com/@bduffany?source=rss-f8186d96ec61------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*6QDezoF_GwCXkEOT4a_v5w.jpeg</url>
            <title>Stories by Brandon Duffany on Medium</title>
            <link>https://medium.com/@bduffany?source=rss-f8186d96ec61------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 01 Dec 2026 20:25:18 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@bduffany/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[Python code golf for Advent of Code 2022, Day 10]]></title>
            <link>https://bduffany.medium.com/python-code-golf-for-advent-of-code-2022-day-10-b31154257ce3?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/b31154257ce3</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code-golf]]></category>
            <category><![CDATA[advent-of-code-2022]]></category>
            <category><![CDATA[python]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Sat, 10 Dec 2022 23:10:31 GMT</pubDate>
            <atom:updated>2022-12-11T04:43:15.781Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*__rX9u0LuQJ9bw1QjG8-Yg.png" /></figure><p>This December, I’m participating in <a href="https://adventofcode.com/2022">Advent of Code</a>, which is a daily coding puzzle from December 1 through December 25.</p><p>Today’s puzzle (December 10) was a lot of fun. I had so much fun with it, that I decided to try my hand at <a href="https://en.wikipedia.org/wiki/Code_golf">golfing</a> my Python solution, whittling it down to as few characters as possible.</p><p>Here’s the tiniest solution I could come up with:</p><pre>x=1;c=0<br>for l in open(0).read().replace(&#39;a&#39;,&#39;\na&#39;).splitlines():a=int(l[4:]or 0);p=&#39;.#&#39;[abs(x-c)&lt;=1];c=(c+1)%40;print(p,end=&#39;\n&#39;[c:]);x+=a</pre><p>In this article, I’ll explain step-by-step how that abomination came to be. It was quite a journey, and I’m hoping that you’ll learn a thing or two from it, even if you aren’t interested in code golf or Advent of Code. I learned some new things about Python even as I was writing out this article!</p><p><em>This article contains spoilers, so don’t read it if you want to try the problem yourself and haven’t gotten a chance yet!</em></p><p>Today’s problem (if you haven’t seen it and don’t plan on solving it) is the following:</p><p><strong>As output, the program writes a series of “pixels” to a “CRT display:”</strong></p><ul><li>Every “CPU cycle,” the program prints either # (a bright “pixel”) or . (a dark “pixel”).</li><li>Every 40 pixels, it prints a newline character (\n) to begin the next row of “pixels.”</li><li>Before each cycle, to decide whether to print a bright or dark pixel, the program reads from a CPU register called <strong>X</strong>. If the current value of X is within one pixel of the CRT’s current position, then it prints a bright pixel; otherwise it prints a dark pixel.</li></ul><p><strong>As input, the program reads a series of “instructions” that determine what pixel should be drawn at the current CRT position:</strong></p><ul><li>The program input file contains a list of <strong>CPU instructions</strong>, one per line.</li><li>The CPU instructions determine what the value of X will be during each CPU cycle. The value X starts at one.</li><li>Each CPU instruction is either the string <strong>noop</strong> or <strong>addx N</strong>, where N is an integer (like -1 or 15)</li><li>noop instructions have no effect, and require 1 CPU cycle to execute.</li><li>addx N instructions have the effect of adding N to the CPU register X, and require 2 CPU cycles to execute. The register is not updated until <em>after</em> the 2 required CPU cycles.</li></ul><p><strong>The solution to the program is found by looking at the pixels drawn to the display.</strong></p><p>For example, the program output for the input that I was assigned looks like this:</p><pre>####..##....##..##..###....##.###..####.<br>#....#..#....#.#..#.#..#....#.#..#.#....<br>###..#.......#.#..#.#..#....#.#..#.###..<br>#....#.......#.####.###.....#.###..#....<br>#....#..#.#..#.#..#.#....#..#.#.#..#....<br>#.....##...##..#..#.#.....##..#..#.####.</pre><p>Interpreting this image (a bit of a challenge on its own!) leads us to a solution of FCJAPJRE.</p><p>So, with all that said, here was my original solution to this problem:</p><pre>lines = open(&#39;input.txt&#39;).read().splitlines()<br># Initialize the X register and CRT_X position.<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    # If the line has a noop instruction, we&#39;ll spend<br>    # 1 CPU cycle and leave X unchanged.<br>    cycle_duration = 1<br>    addx = 0<br>    # Otherwise if the line has an addx N instruction,<br>    # we&#39;ll spend 2 CPU cycles and add N to x afterwards.<br>    if line.startswith(&#39;addx &#39;):<br>        cycle_duration = 2<br>        addx = int(line.split()[1])<br>    # For each cycle, if CRT_X is within 1 pixel of X,<br>    # print &#39;#&#39;, otherwise print &#39;.&#39;<br>    for _ in range(cycle_duration):<br>        if x in (crt_x - 1, crt_x, crt_x + 1):<br>            print(&#39;#&#39;, end=&#39;&#39;)<br>        else:<br>            print(&#39;.&#39;, end=&#39;&#39;)<br>        crt_x += 1<br>        # Once we reach the end of the row, wrap CRT_X<br>        # back around to 0, printing a blank line.<br>        if crt_x == 40:<br>            print()<br>            crt_x = 0<br>    # Note, addx instructions only apply *after* the<br>    # CPU cycles have elapsed for the instruction.<br>    x += addx</pre><h3>Golfing strategy</h3><p>In order to golf this code, my overall strategy was to try to rewrite the main for loop as a single <a href="http://docs.python.org/reference/compound_stmts.html">Compound statement</a>, like this:</p><pre>for line in lines:statement_1;statement_2; # more statements...</pre><p>The benefit of doing it this way is that we save one byte per statement. With a compound for loop, we only need a single character ; as a separator, which requires only one byte. For a “normal” for loop, the best we can do is a newline character followed by a tab character (\n\t), which requires two bytes (twice as many per statement!).</p><p>The challenge is that Python only allows certain types of compound statements. For example, the following is <strong>invalid</strong> syntax:</p><pre>for line in lines: if some_condition: do_something()</pre><p>To get a valid compound statement, all of the statements in the loop body need to be either variable assignments like x=1, or simple function calls like print(x).</p><h3>Removing block statements in the main loop</h3><p>Here’s our original code again, this time with comments removed:</p><pre>lines = open(&#39;input.txt&#39;).read().splitlines()<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    cycle_duration = 1<br>    addx = 0<br>    if line.startswith(&#39;addx &#39;):<br>        cycle_duration = 2<br>        addx = int(line.split()[1])<br>    for _ in range(cycle_duration):<br>        if x in (crt_x - 1, crt_x, crt_x + 1):<br>            print(&#39;#&#39;, end=&#39;&#39;)<br>        else:<br>            print(&#39;.&#39;, end=&#39;&#39;)<br>        crt_x += 1<br>        if crt_x == 40:<br>            print()<br>            crt_x = 0<br>    x += addx</pre><p>As the first major simplification, let’s try to get rid of the inner nested for loop.</p><p>The reason we had the nested for loop in the original implementation is that we have to deal with the differing CPU cycle requirements for each instruction: noop instructions take 1 cycle, and addx instructions take 2 cycles. The inner loop would execute once for each cycle, printing one pixel each time.</p><p>The key observation is that if we <em>artificially </em>insert a noop instruction before each addx instruction, then we can pretend that addx instructions only take 1 CPU cycle, and our program should behave exactly the same without needing the inner loop!</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         # Artificially insert a<br>         # noop line before each addx:<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = 0<br>    if line.startswith(&#39;addx &#39;):<br>        addx = int(line.split()[1])<br>    if x in (crt_x - 1, crt_x, crt_x + 1):<br>        print(&#39;#&#39;, end=&#39;&#39;)<br>    else:<br>        print(&#39;.&#39;, end=&#39;&#39;)<br>    crt_x += 1<br>    if crt_x == 40:<br>        print()<br>        crt_x = 0<br>    x += addx</pre><p>Now that we’re treating all instructions as taking only 1 cycle, we can simplify even further by replacing all noop lines with addx 0, which are now equivalent. The benefit of doing that is that it lets us parse all lines as addx instructions, rather than needing a conditional to deal with the possibility of noop instructions:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         # Make all noops look like adds:<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    # All instructions are now &quot;addx n&quot;,<br>    # so we can trim to get just &quot; n&quot;.<br>    # Note that int() strips whitespace.<br>    addx = int(line[4:])<br>    if x in (crt_x - 1, crt_x, crt_x + 1):<br>        print(&#39;#&#39;, end=&#39;&#39;)<br>    else:<br>        print(&#39;.&#39;, end=&#39;&#39;)<br>    crt_x += 1<br>    if crt_x == 40:<br>        print()<br>        crt_x = 0<br>    x += addx</pre><p>Now, we also want to get rid of those if-else statements, since they are not allowed in compound for-loops.</p><p>For the first one, let’s make a variable p for the text we want to print, then print it once:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    # Using an &quot;if ... else&quot; expression here:<br>    p = &#39;#&#39; if x in (crt_x - 1, crt_x, crt_x + 1) else &#39;.&#39;<br>    print(p, end=&#39;&#39;)<br>    crt_x += 1<br>    if crt_x == 40:<br>        print()<br>        crt_x = 0<br>    x += addx</pre><p>Note, in this new code, we’re still using if and else, but now we&#39;re using an if-else <em>expression</em>, not an if-else <em>statement</em>.</p><p>Next, there’s still another if statement we need to get rid of. Let&#39;s use the % operator to implement the wrap-around logic, and append &#39;\n&#39; to the printed text only when p wraps around to 0:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    p = &#39;#&#39; if x in (crt_x - 1, crt_x, crt_x + 1) else &#39;.&#39;<br>    print(p, end=&#39;&#39;)<br>    # Using % here:<br>    crt_x = (crt_x + 1) % 40<br>    # Using &quot;if ... else&quot; here:<br>    print(&#39;\n&#39; if crt_x == 0 else &#39;&#39;, end=&#39;&#39;)<br>    x += addx</pre><p>OK! Now, we can condense our code into a single compound statement, since each line is either an assignment or a single function call.</p><p>That will make the code super hard to read, though, so let’s do a few more optimizations while our loop body is still nice and indented.</p><p>The lowest hanging fruit is to replace the crt_x computation with a shorter expression. Instead of explicitly checking each possible x position, we can check whether the CRT&#39;s x position is within distance 1 of the sprite&#39;s x position:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    # Using a distance formula here:<br>    p = &#39;#&#39; if abs(x - crt_x) &lt;= 1 else &#39;.&#39;<br>    print(p, end=&#39;&#39;)<br>    crt_x = (crt_x + 1) % 40<br>    print(&#39;\n&#39; if crt_x == 0 else &#39;&#39;, end=&#39;&#39;)<br>    x += addx</pre><p>Another low-hanging fruit is to combine the two print statements:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    p = &#39;#&#39; if abs(x - crt_x) &lt;= 1 else &#39;.&#39;<br>    crt_x = (crt_x + 1) % 40<br>    # Combining both print() statements:<br>    print(p + (&#39;\n&#39; if crt_x == 0 else &#39;&#39;), end=&#39;&#39;)<br>    x += addx</pre><h3>Golfing the if-else expressions</h3><p>We’ve simplified quite a bit so far, but one thing to notice is that the if-else expressions require quite a lot of bytes to represent.</p><p>A neat way to get rid of if-else expressions is to group the two possible outcomes into an array, where the first array element contains the False branch&#39;s expression, and the second array element contains the True branch&#39;s expression. Then, you can index into that array using the conditional bool result, since array[False] works the same as array[0] and array[True] works the same as array[1] due to type conversion.</p><p>So, if we have some code that looks like this:</p><pre>true_branch if condition else false_branch</pre><p>We can rewrite it like this:</p><pre>[false_branch,true_branch][condition]</pre><p>But wait — there’s more! If false_branch and true_branch are both single-character strings, we can write a compact string literal containing the two characters, instead of an array with two separate strings. So instead of writing [&#39;A&#39;,&#39;B&#39;][condition] we can write &#39;AB&#39;[condition].</p><p>In our case, the optimization looks like this:</p><pre>&#39;#&#39;if abs(x-crt_x)&lt;=1 else&#39;.&#39;<br>&#39;.#&#39;[abs(x-crt_x)&lt;=1]######## 8 bytes saved!</pre><p>Note, we even applied a trick here in the first line: the &#39;#&#39;if and else&#39;.&#39; in the first line are omitting an optional space. But we still save 8 bytes by rewriting using array indexing.</p><p>So, let’s apply that trick to our code so far:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    # Condensing &quot;if ... else&quot;:<br>    p = &#39;.#&#39;[abs(x-crt_x)&lt;=1]<br>    crt_x = (crt_x + 1) % 40<br>    print(p + (&#39;\n&#39; if crt_x == 0 else &#39;&#39;), end=&#39;&#39;)<br>    x += addx</pre><p>So, can we apply this to the second if-else as well?</p><p>Turns out, we can’t, because we’re dealing with an empty string in the else case 😕 So we’d be stuck using a list like [&#39;&#39;,&#39;\n&#39;] instead of just &#39;\n&#39; .</p><p>But we can apply an even more interesting trick here: we can take a <em>slice</em> into the string.</p><p>The idea is that if the crt_x value is zero, then we want to take a slice starting with index 0, like &#39;\n[0:], which is just &#39;\n&#39;. Otherwise, we know that crt_x is greater than or equal to 1 (since it can&#39;t be negative). In that case, taking a slice starting anywhere greater than or equal to 1 will yield an empty string. So the pattern is that \n[0:] evaluates to &#39;\n&#39;, but then &#39;\n&#39;[1:] and &#39;\n&#39;[2:] (and so on) evaluate to &#39;&#39;.</p><p>Check out the byte savings:</p><pre>&#39;&#39;if crt_x else&#39;\n&#39;<br>&#39;\n&#39;[crt_x:]####### 7 bytes saved!</pre><p>Here’s the whole program again so far:</p><pre>lines = (open(&#39;input.txt&#39;).read()<br>         .replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>         .replace(&#39;noop&#39;, &#39;addx 0&#39;)<br>         .splitlines())<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:])<br>    p = &#39;.#&#39;[abs(x-crt_x)&lt;=1]<br>    crt_x = (crt_x + 1) % 40<br>    # Condensing &quot;if ... else&quot;:<br>    print(p + &#39;\n&#39;[crt_x:], end=&#39;&#39;)<br>    x += addx</pre><p>OK, now before we start making the code even harder to read, lets zoom out a bit and look for some bigger-picture optimizations we can make.</p><h3>More input transformations</h3><p>Recall that earlier, we transformed the input so that it consists of only addx instructions. But that came at a cost of some verbose replace() calls. Can we shorten those?</p><p>Well, one observation is that the letter ‘a’ only appears in ‘addx’, so the following are equivalent:</p><pre>replace(&#39;addx&#39;, &#39;noop\naddx&#39;)<br>replace(&#39;a&#39;, &#39;noop\na&#39;)###### 6 bytes saved!</pre><p>Another observation is that our code right now only works if all of the instructions look like &#39;addx N&#39; where N is a number. But we&#39;re spending quite a bit of code on making sure all lines adhere to that pattern.</p><p>To reduce the amount of code here, we need an important insight: if a number appears in the current line, it will always appear after index 4. This is because the strings “addx” and “noop” both have lengths of at most 4.</p><p>So, this means we can delete the call to replace(&#39;noop&#39;, &#39;addx 0&#39;) entirely! We just need to handle the possibility of the number being an empty string (&#39;&#39;), so our conversion int(line[4:]) now becomes int(line[4:] or 0). So we’ve added some code, but it’s a net win overall:</p><pre># Removing &quot;replace(&#39;noop&#39;, &#39;addx 0&#39;)&quot;:<br>lines = open(&#39;input.txt&#39;).read().replace(&#39;a&#39;, &#39;noop\na&#39;).splitlines()<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    # Adding &quot;or 0&quot; to allow noops:<br>    addx = int(line[4:] or 0)<br>    p = &#39;.#&#39;[abs(x-crt_x)&lt;=1]<br>    crt_x = (crt_x + 1) % 40<br>    print(p + &#39;\n&#39;[crt_x:], end=&#39;&#39;)<br>    x += addx</pre><p>One thing to note is that Python allows referencing out-of-bounds indexes when taking a slice and it will return an empty string. This means that line[4:] will return an empty string whether the line is &quot;noop&quot; or if the line is blank. So we actually don&#39;t even need to replace &#39;a&#39; with &#39;noop\na&#39;. We can just replace it with &#39;\na&#39;:</p><pre># Removing &quot;noop&quot; here:<br>lines = open(&#39;input.txt&#39;).read().replace(&#39;a&#39;, &#39;\na&#39;).splitlines()<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:] or 0)<br>    p = &#39;.#&#39;[abs(x-crt_x)&lt;=1]<br>    crt_x = (crt_x + 1) % 40<br>    print(p + &#39;\n&#39;[crt_x:], end=&#39;&#39;)<br>    x += addx</pre><p>The last interesting observation is that we can remove the + in the print() statement by taking advantage of the fact that the print() statement already concatenates the end argument onto the first argument that we&#39;re printing:</p><pre>lines = open(&#39;input.txt&#39;).read().replace(&#39;a&#39;, &#39;\na&#39;).splitlines()<br>x = 1<br>crt_x = 0<br>for line in lines:<br>    addx = int(line[4:] or 0)<br>    p = &#39;.#&#39;[abs(x-crt_x)&lt;=1]<br>    crt_x = (crt_x + 1) % 40<br>    # Letting print() concatenate<br>    # via the &quot;end&quot; arg:<br>    print(p, end=&#39;\n&#39;[crt_x:])<br>    x += addx</pre><p>Now the remaining optimizations are all pretty mechanical.</p><h3>Minifying the result</h3><p>Next up, we’ll do a speed round of easy minifications, which are all very mechanical and could probably be done using some sort of minification tool.</p><p>Our solution so far is 234 bytes.</p><p>Shortening variable names to onecharacter brings this to 194 bytes (-40):</p><pre>s = open(&#39;input.txt&#39;).read().replace(&#39;a&#39;, &#39;\na&#39;).splitlines()<br>x = 1<br>c = 0<br>for l in s:<br>    a = int(l[4:] or 0)<br>    p = &#39;.#&#39;[abs(x-c)&lt;=1]<br>    c = (c + 1) % 40<br>    print(p, end=&#39;\n&#39;[c:])<br>    x += a</pre><p>Inlining s reduces this further to 188 bytes (-6):</p><pre>x = 1<br>c = 0<br>for l in open(&#39;input.txt&#39;).read().replace(&#39;a&#39;, &#39;\na&#39;).splitlines():<br>    a = int(l[4:] or 0)<br>    p = &#39;.#&#39;[abs(x-c)&lt;=1]<br>    c = (c + 1) % 40<br>    print(p, end=&#39;\n&#39;[c:])<br>    x += a</pre><p>Trimming whitespace within each line brings us down to 159 bytes (-29):</p><pre>x=1<br>c=0<br>for l in open(&#39;input.txt&#39;).read().replace(&#39;a&#39;,&#39;\na&#39;).splitlines():<br>  a=int(l[4:]or 0)<br>  p=&#39;.#&#39;[abs(x-c)&lt;=1]<br>  c=(c+1)%40<br>  print(p,end=&#39;\n&#39;[c:])<br>  x+=a</pre><p>Converting to compound statements gets us to 148 bytes (-11):</p><pre>x=1;c=0<br>for l in open(&#39;input.txt&#39;).read().replace(&#39;a&#39;,&#39;\na&#39;).splitlines():a=int(l[4:]or 0);p=&#39;.#&#39;[abs(x-c)&lt;=1];c=(c+1)%40;print(p,end=&#39;\n&#39;[c:]);x+=a</pre><h3>Cheating a bit!</h3><p>As a finishing touch, we can shorten open(&#39;input.txt&#39;) by changing how we read the input. Instead of reading from the input.txt file, we can read the file contents from stdin, which on Unix-like systems is <a href="https://man7.org/linux/man-pages/man3/stdin.3.html">file descriptor 0</a>. Python&#39;s open() API treats integer values as file descriptor numbers, so we can write open(0) here:</p><pre>x=1;c=0<br>for l in open(0).read().replace(&#39;a&#39;,&#39;\na&#39;).splitlines():a=int(l[4:]or 0);p=&#39;.#&#39;[abs(x-c)&lt;=1];c=(c+1)%40;print(p,end=&#39;\n&#39;[c:]);x+=a</pre><p>(This one was arguably cheating, since it’s sort of an OS-specific trick 😅)</p><h3>Drum roll please…</h3><p>The final program is only <strong>138 bytes in length! </strong>🎉</p><p>There are probably even more optimizations that can be made, maybe even using a totally different high-level approach. But this is what I came up with, and I hope you learned something from this example!</p><p>I also recommend checking out the <a href="https://www.reddit.com/r/adventofcode/comments/zhjfo4/2022_day_10_solutions/">Reddit thread</a> for Day 10, which has lots of other cool solutions. I wouldn’t be surprised if there are Python solutions in that thread that are even shorter than mine.</p><p>My favorite from the thread is the Python solution <a href="https://www.reddit.com/r/adventofcode/comments/zhjfo4/comment/izoox4w">here</a> which implements <a href="https://en.wikipedia.org/wiki/Optical_character_recognition">OCR</a> on the output so that it prints the letters in plain text rather than ASCII art. Super cool!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b31154257ce3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stuff I Wish I’d Known Sooner About Golang — Part 1: Variables and Constants]]></title>
            <link>https://medium.com/swlh/stuff-i-wish-id-known-sooner-about-variable-assignments-in-golang-f00317b57bcb?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/f00317b57bcb</guid>
            <category><![CDATA[go]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Sun, 21 Feb 2021 04:55:39 GMT</pubDate>
            <atom:updated>2021-10-04T14:16:11.101Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stuff I Wish I’d Known Sooner About Go — Part 1: Variables and Constants</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pm4zrkg3g3RDR8B783uIpw.png" /></figure><p>Go is a nice, simple language that looks very familiar at first glance if you’ve used other programming languages before.</p><p>But it has a bit of a learning curve, since it does introduce a few novel concepts.</p><p>So I’m writing a few articles which would have saved me some time sifting through documentation and going through several rounds of trial-and-error on the <a href="https://play.golang.org/">Go playground</a>.</p><p>In this first article, I’ll be talking about the basics, which are surprisingly subtle in some cases: <em>variables</em>. You’ll probably learn a thing or two even if you’ve already been using Go for a few weeks.</p><h4>When to use var</h4><p>Most of the Go code I have worked with avoids using var unless it is either required or if it makes the code clearer.</p><p>Here are the only cases where I think var makes sense to use:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/873a71d9804700e4c48c4a86078d4395/href">https://medium.com/media/873a71d9804700e4c48c4a86078d4395/href</a></iframe><h4>When to use short-declare (colon equals)</h4><p>The short-declare operator (:=) gives you a way to declare a variable and assign its value in a single statement, <em>without</em> needing to specify the type. Instead, the type is assigned based on the value you’re assigning.</p><p>You should use :=if:</p><ol><li>you’re declaring one or more new variables (and the equivalent var declaration would be more verbose), or</li><li>you’re in a block initializer, such as if, for, select, or switch, and you want to declare a new variable — var isn’t allowed there.</li></ol><p><strong>Note:</strong> := is only possible when you’re introducing at least one <strong>new </strong>variable declaration into the current scope. If you’re trying to <em>re-assign</em> a variable in the current scope, use the plain old = operator.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3cbfd557adc1a5d1a6401304bb59093a/href">https://medium.com/media/3cbfd557adc1a5d1a6401304bb59093a/href</a></iframe><p>Side note: when I first saw this short-declare syntax, my reaction was: “this feels a little confusing — why can’t we just use = everywhere when assigning, like Python?”</p><p>But the problem with using = everywhere is that it becomes hard to know which scope you’re targeting — do you want to declare a new local variable, or do you want to overwrite the one in the surrounding function? Or even a global? To solve this problem, Python uses nonlocal and global keywords when assigning to something that’s not in the local scope. Personally, these feel a bit clunky, and it’s easy to forget to specify them.</p><p>In Go, = always assigns to the value in the current scope, and you can use := to explicitly “shadow” declarations in outer scopes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NwdtU3PXaGkZrHB6faByhw.png" /></figure><p>Here are some interesting examples where:= is used to shadow a variable declared in an outer scope (the second example requires some knowledge of functional programming and <a href="https://stackoverflow.com/a/7464475/828709">closures</a>):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd63c93b96dd52c7dea21894df919131/href">https://medium.com/media/dd63c93b96dd52c7dea21894df919131/href</a></iframe><h4>When to cast</h4><p>Let’s look at the definition of time.Duration (from the “time” package):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/850b94fcbb71f1db5a4c2c3d399909bf/href">https://medium.com/media/850b94fcbb71f1db5a4c2c3d399909bf/href</a></iframe><p>What kinds of values can we assign to a variable of type time.Duration?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e77a64f99f0263e947ba8604e6ef955/href">https://medium.com/media/4e77a64f99f0263e947ba8604e6ef955/href</a></iframe><p>Check out this <a href="https://play.golang.org/p/Fj7PJOkyxB6">Go playground</a> if you want to see some of the default types that go assigns to untyped literals.</p><p>That’s all I’ve got for this article! Please comment if you’ve got any tips you’d like to share which are useful for understanding how variables work in golang. Looking forward to sharing more Go tips!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f00317b57bcb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/stuff-i-wish-id-known-sooner-about-variable-assignments-in-golang-f00317b57bcb">Stuff I Wish I’d Known Sooner About Golang — Part 1: Variables and Constants</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Hitchhiker’s Guide to Next.js]]></title>
            <link>https://medium.com/swlh/the-hitchhikers-guide-to-next-js-fd7aa14ae8d0?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd7aa14ae8d0</guid>
            <category><![CDATA[nextjs]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Tue, 16 Jun 2020 23:01:31 GMT</pubDate>
            <atom:updated>2020-06-18T16:32:39.623Z</atom:updated>
            <content:encoded><![CDATA[<h4>How Next.js evolved, and why it’s one of the best React frameworks on the market</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/744/1*T473Fn0k_Hqe69TFqZJDGw.png" /></figure><p>Recently, there has been a lot of hype around Next.js — a Web framework based on React. But is the hype warranted? What improvements does Next.js provide over the existing tools, like the feature-rich, developer-friendly create-react-app? or the simple, tried-and-true, static site generation tool — <a href="https://jekyllrb.com/">Jekyll</a>?</p><p>Is Next.js just going to add more bloat to your app? Is it really the future of frontend development, or is it just a fad? What problems is it really solving?</p><p>In this article, I’ll try to answer all of these questions and more.</p><p><em>In this article, I don’t draw a direct comparison between Next.js and its main competitor, Gatsby. These frameworks both have very similar features and have their own strengths. They are both evolving rapidly and have thriving ecosystems surrounding them, so it’s too difficult to make a comparison that will still be relevant even a month from now.</em></p><h3>What Next.js is, and what it isn’t</h3><p>Many people have heard that Next.js is basically just a “static site generator” that allows writing your code in React. Some React developers I have talked to in the past have followed the rule of thumb that if they want to create a static site, they should use a tool like Next.js or Gatsby, but if they want a dynamic site with more features, they should stick with the tried and true create-react-app.</p><p>But Next.js is a lot more than just a static site generator. It’s much more powerful than Jekyll, which is primarily designed to host simple, static sites. Next.js supports the same static-site generation features as Jekyll, <em>in addition</em> to all the features of create-react-app, and much, much more. And if you deploy Next.js on Vercel, you get an incredibly smooth, no-nonsense, “zero-config” developer experience.</p><p>In other words, static site generation is <em>just one thing </em>that Next.js is great at, but it is by far its main selling point. I wouldn’t call Next.js a static site generator, but rather an <strong>automatic static optimization</strong> framework, which is opinionated about embracing React at its core.</p><p>When a Next.js app is deployed on Vercel, it is also an excellent <strong>serverless </strong>framework, ideal for building a JAMstack application.</p><p>But what do these things mean? How does “automatic static optimization” differ from static site generation? And what do I mean by “serverless?”</p><p>On top of this, Next.js uses an opinionated <a href="https://nextjs.org/docs/routing/introduction"><strong>file-system based routing</strong></a> approach, instead of requiring you to configure all the routes yourself through JavaScript, or using something like React Router. But is it flexible enough? Is this approach the right fit for a serious enterprise app that can have many complex routing scenarios, or even a medium-sized app with some dynamic functionality?</p><p>Lastly, should you use Vercel to deploy your Next.js app, or something else?</p><p>Once again, I’ll try to answer or at least touch on all of these questions in this article, and more.</p><h3>How Next.js came to be: a brief history of Web development</h3><p>Before I start raving about Next.js, let’s try to understand how Next.js evolved as a technology.</p><p><em>If you have been developing Web apps since the early days, you can skip this part without really missing out on anything.</em></p><p>In the early 1990s, when the Web was first introduced, most of the Web consisted of a bunch of HTML files stored on a bunch of computers in different places.</p><p>You’d make a request to a specific Web server using a <a href="https://en.wikipedia.org/wiki/URL">URL</a>. The request would ultimately get delivered to a Web server, which would then respond back with an HTML file. Finally, your browser would display the HTML document to you.</p><p>This was pretty slow in those days, mainly because computers were slower, and Internet infrastructure was not as advanced as it is today. But all in all, this was a pretty solid system. It was simple, and it worked. Life was good.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*r8j0RdnK_YEVjLMqsA4rYA.png" /><figcaption>There are a lot of pieces missing here, like DNS servers and Internet routers, but this is the basic idea.</figcaption></figure><p>This “static file” approach was very limited, though — what about pages that need to display some data from a database, which is changing all the time? What about pages that contain information that contains info which should only be rendered some of the time? Do we have to create separate HTML files for every possible page that the user might see?</p><h4>Server-side rendering</h4><p>To enable more dynamic Web pages, technologies like <a href="https://en.wikipedia.org/wiki/PHP">PHP</a> were introduced, which made it easy to return different HTML responses for the same URL, dependent on different conditions. This approach is called <strong>server-side rendering, </strong>because the server “renders” (generates) the HTML page on-the-fly for each request, and then sends it back to the user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*j2Hz-uq9qNfNCd3L0OzxnA.png" /><figcaption>In reality it’s a lot more complicated than this… but hopefully you get the basic idea!</figcaption></figure><p>PHP was a fantastic idea. It allowed you to write some code in HTML, but then as soon as you realized that a section of the HTML you were writing had to be dynamically computed, you just switch into PHP mode and then start writing the logic that decides what belongs in the current chunk of HTML. Then, you could switch back to HTML mode, and carry on with plain old HTML.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1161f095cb4705ef79fbe6fb74906e5a/href">https://medium.com/media/1161f095cb4705ef79fbe6fb74906e5a/href</a></iframe><p>The server-side rendering approach enabled tons of great Web page features (like email, online banking, and more)<em>, but at the cost of page load time. </em>Every time the server needed to read some data from a database, data could be traveling hundreds or even thousands of miles across the globe.</p><p>Even if data were transmitted at the speed of light, downloading an HTML page could take several seconds, especially as more requests are added and the amount of data loaded into the page increases.</p><p>But despite these drawbacks, this approach worked well, and people were happy.</p><h4>JavaScript and AJAX</h4><p>Server-side rendering was only one way that the Web became more interactive and interesting.</p><p>As browsers improved and computers got more powerful, more interactive Web pages became more common, all thanks to <strong>JavaScript</strong>. Drop-down menus, popups, date range pickers, interactive charts, and even interactive maps became possible.</p><p>Using <strong>AJAX</strong>, Web pages could update themselves with fresh data without the user needing to fully reload the page. This made Web pages feel even more like desktop apps, which let you update your data and see the result almost immediately without the screen going blank and being rendered from scratch.</p><h4>Client-side rendering and SPAs</h4><p>As computers started getting faster and JavaScript became more and more central to Web page functionality, Web developers became sick of writing JavaScript code and PHP code and HTML code and CSS code…and having to make sure all these languages played nicely together, and having to mentor all of their team members on so many different technologies…</p><p>So they thought, “what if we ditched PHP, and rendered the <em>entire </em>page using only JavaScript, running right in the Web browser? Then we’d have one less programming language to worry about!”</p><p>And that is exactly what they did! Libraries like jQuery were introduced, which made it even more convenient to update a Web page dynamically using JavaScript and fetch data using AJAX, and many people thought that jQuery was the best thing since sliced bread.</p><p>Later, JavaScript frameworks like <a href="https://web.archive.org/web/20130115043630/http://emberjs.com/">Ember.js</a> and <a href="https://web.archive.org/web/20120413024916/http://angularjs.org/#/">Angular.js</a> evolved. (Those links point to snapshots of those sites from the early 2010s — check them out!) These frameworks were a bit more complex than jQuery, but they allowed people to be very productive when writing Web apps. They made Web development simpler by encouraging people to write most of their code on the client side, instead of worrying so much about the server side.</p><p>Around this time, the concept of a “single page application” (<strong>SPA</strong>) took shape, in which a Web page only sent one request to the server to fetch the initial HTML, and then every update to the page afterwards was done with JavaScript and AJAX, instead of completely reloading the page.</p><p>The “new world” of client-side rendering, JS frameworks, and SPAs looked something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/995/1*vAdq4daIBs0FdfjRmNEduQ.png" /><figcaption>With client-side rendering, the Web gets even more complex.</figcaption></figure><p>Client-side rendering made Web developers and tech companies very happy. They could save on computing costs by having the user execute code on their own machines, and it was much easier to write and maintain code that ran mostly on the client side, rather than writing the code in both PHP and JavaScript.</p><p>As libraries like jQuery, Ember, Angular, React, and Vue were introduced, and tools like create-react-app and <a href="https://bower.io/">bower</a> made it even easier to use these libraries, it became even more convenient and trendy to do 100% of the rendering right in the Web browser.</p><h4>Problems with client side rendering</h4><p>Client-side rendering is great for productivity, because it enables developers to focus mostly on JavaScript. But it’s not necessarily better for the user.</p><p>Why? Because downloading and executing JavaScript and making DOM manipulations through JavaScript is <em>costly</em>.</p><p>Before, with server-side rendering, the browser just requested the final HTML response directly from the server, and maybe a few scripts would load to add a few more things to the page.</p><p>Now, with client-side rendering, the browser receives a mostly blank HTML page, then starts downloading JavaScript, then parses, compiles, and executes the JavaScript, which then generates HTML, and then the page is finally rendered.</p><p>This all takes time.</p><p>Loading time is made even worse when many scripts and other files (like images and CSS) are loaded at the same time, which is often the case for modern Web apps.</p><p>Now, you might be thinking that browsers, data centers, CPUs, disk drives, network infrastructure, caching, RAM, are all getting better and faster as time goes on, so is this extra cost even noticeable?</p><p>Well, these advancements don’t happen fast enough to keep up with the demands of modern Web apps. Worse yet, users in countries with fewer resources (where the average computer is older and less powerful, and Internet infrastructure is not upgraded as frequently), are stuck with a worse experience, with Web pages that load painfully slowly.</p><p>And there was an even more pressing issue: the mobile Web. More people were using their mobile devices to access Web pages. When smartphones and laptops first came out, they had only a fraction of the power of desktop computers, and client-rendered pages built with frameworks like Angular.js were simply too slow — the phones themselves were not powerful enough, and wireless network speeds were not as great as they are today.</p><p>In addition to being slower than server-side rendering, client-side rendering introduced another huge problem: Search Engine Optimization (<strong>SEO</strong>).</p><p>If you don’t know how SEO works, here’s a brief summary. Search engines like Google have special programs called “crawlers,” which “crawl” the Web by starting with a curated list Web pages (e.g. wikipedia.org), then following all the clickable links from those pages, and then following the links from <em>those</em> pages, and so on. Eventually, they will reach every part of the “public Web.”</p><p>With client-side rendering, recall that the server sends back a mostly blank initial HTML response, which then gets updated by JavaScript. This is a problem, because search engines started getting empty pages back from servers, which now just had &lt;script&gt; tags in them that needed to be run in order to see the final page! So, client-side rendered pages were said to have “poor SEO.”</p><p>Naturally, search engines solved this problem by simulating a real browser and actually running all the JavaScript on the page, then scanning the final page after all the scripts were run and the page was fully “visible.”</p><p>However, this solution introduced many problems of its own. It is slower and costlier for search engines to simulate a Web browser when scanning your page, and often more error-prone. Google has even written a <a href="https://developers.google.com/search/docs/guides/javascript-seo-basics">comprehensive guide</a> on how to write your Web page to be SEO-friendly.</p><p>“Fantastic,” thought developers everywhere. “Even <em>more</em> problems for us to worry about when developing Web apps!”</p><h4>The return of server-side rendering</h4><p>Many Web developers who had gotten on board with client-side rendering ultimately took a step back and did some thinking when they realized their pages were too slow.</p><p>They realized that ultimately, they had to make the switch back to server-side rendering. But at the same time, they wanted to stay free of <a href="https://eev.ee/blog/2012/04/09/php-a-fractal-of-bad-design/">the perils of PHP</a>.</p><p>Fortunately, <strong>Node.js </strong>was created — a technology which allows writing a Web server in JavaScript!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5541962a2fe55028c7f381552b22c67e/href">https://medium.com/media/5541962a2fe55028c7f381552b22c67e/href</a></iframe><p>Many people were skeptical about Node at first — after all, JavaScript was <em>slow, </em>even when run on a powerful Web server. But at least it was faster to run JavaScript on the server than it was to run it on a tiny mobile device! Plus, as JavaScript got better and faster, Node-based servers got faster and faster, just by installing software updates! The performance problem with Node.js was becoming less and less of an issue, and many developers started to embrace JavaScript on the server.</p><p>At the same time, the <a href="https://www.npmjs.com/"><strong>npm</strong></a> ecosystem was thriving. More and more powerful open source JavaScript libraries became easily usable in both the browser and the server. Node.js frameworks like <a href="https://www.meteor.com/">Meteor</a> were created, blurring the line even more between client-side and server-side development.</p><p>Node.js and JavaScript were booming.</p><p>Meanwhile, people did not want to ditch their Web frameworks like Angular and React. Libraries like <a href="https://reactjs.org/docs/react-dom-server.html">ReactDOMServer</a>, <a href="https://ssr.vuejs.org/">vue-server-renderer</a>, and <a href="https://angular.io/guide/universal">Angular Universal</a> made it even easier to render the app on a Node.js server using the same code that the client would have used, if the page were client-side rendered instead.</p><p>These frameworks introduced a <a href="https://ssr.vuejs.org/guide/hydration.html"><strong>hydration</strong></a> step to the initial page load, which allows client-side JavaScript to pick up where the server-rendered JavaScript left off. This approach allows the client to get the important parts of the HTML page sooner, and then <a href="https://en.wikipedia.org/wiki/Progressive_enhancement"><strong>progressively enhance</strong></a><strong> </strong>the page<strong> </strong>with<strong> </strong>more<strong> </strong>interactivity later on, with minimal effort from the developer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/979/1*ItdkK9AjjHOt39o9KiBDZg.png" /></figure><p>At this point, life is pretty good. We’re now back to server-rendered pages which are much lighter on the client, and much smarter, in the sense that they deliver the initial HTML response to the client sooner.</p><p>When combined with techniques like <a href="https://github.com/ModuleLoader/es-module-loader">lazy module loading</a>, <a href="https://webpack.js.org/guides/code-splitting/">code splitting</a>, and <a href="https://webpack.js.org/concepts/">bundling</a>, this new world can result in a page that loads much faster than a fully client-rendered page.</p><h3>Introducing Next.js</h3><p>So, at this point, it might seem like we’ve solved most of our problems, and we have a pretty good system going on.</p><p>We can write all of our code in JavaScript. The page is mostly rendered on the server. We still get to use our much-loved Web frameworks like Angular and React.</p><p>In reality, though, there were a few big problems that needed addressing:</p><ol><li>Server-side rendering with client-side hydration was not easy to set up! Even with frameworks like Meteor and modern React tools (like create-react-app), developers had to read lots of documentation to understand how server-side rendering works, why they need it, and how to wire it up. For most people trying to get something done, it was just too much work.</li><li>Not all pages contain dynamic data that requires a Web server to read from a database. In fact, a huge fraction of Web pages can just be static HTML files, like they were in the very, very early days of the Web. Landing pages, help pages, contact forms, terms of service/privacy policy pages, career directories, sitemaps, and blogs are all examples of pages that could be static.</li><li>Taking #2 a step further, even the pages which read from a database can still be represented as static pages! The app’s “skeleton” HTML can be sent straight to the client, and then the client can make AJAX requests to fetch data. So ideally, we don’t need a complicated Web server to host our pages! We just need a separate API server that the static HTML file can make its requests to.</li></ol><p>With these optimizations, loading a Web page might look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*GNPDqDpo-W9b50xHZ3Yfpw.png" /></figure><p><em>“But why would we want all of our HTML files to be static? Won’t that mean that we will have less feature-rich apps?”</em></p><p>Well, “static” does <em>not</em> mean “motionless!” Static pages can load scripts of their own, containing complex JavaScript and CSS. The scripts can then do “dynamic” stuff to the page. You can even use React to create a static page. (Spoiler alert: that’s what Next.js does!)</p><p><em>“How does this static file approach improve anything? We still have to make a Web server in order to get the static file anyway, right? So why not just request the file directly from our cool Node.js server that will do our server-side rendering on the fly?”</em></p><p>Well, the answer to this is a bit complicated.</p><p>The first thing to understand is that when you visit a Website, your Web browser cannot do <em>anything</em> until it gets a response back from the Web server. As a result, this initial HTML request is the single biggest bottleneck in the entire page load sequence. Even if your page loads dozens of scripts and stylesheets and you have done tons of optimizations to make them all load super fast, <em>none</em> of that can happen until the initial HTML comes back!</p><p>So, we really<strong> </strong>want to make sure that the browser gets back the initial HTML response for our site as quickly as possible.</p><p><em>“So, what do static files have to do with the initial HTML response coming back quickly? Can’t we just run a bunch of copies of our server around the globe, close to where users are located? That way, requests to our servers would come back super fast.”</em></p><p>Sure, that’s one way to do it. But that would also be super expensive! Most people can’t afford to pay for so many servers to be running around the globe at all times.</p><p>Fortunately, we have <strong>CDNs</strong>, which are cheap, global networks of machines that are heavily optimized for storing <em>static</em> files around the world. If we could somehow make sure that all of our Web pages were just static HTML files, then we could leverage CDNs to cheaply distribute our app around the world, making it readily available to users.</p><p><em>Side note: In the latest Web jargon, you might hear that a file is served from “</em><a href="https://www.cloudflare.com/learning/cdn/glossary/edge-server/"><em>the edge</em></a><em>” — that’s pretty much what this is referring to. You might have also heard of Google’s “AMP” pages — </em><a href="https://developers.google.com/amp/cache/"><em>AMP</em></a><em> leverages Google’s CDN to store and serve special types of HTML files (called AMP files), which place tight restrictions on the HTML in order to prevent it from doing anything that would slow down the initial page load.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*Lq4TC3fwSPEbObvZfQF3nw.png" /></figure><p>So, with static HTML served from a CDN, we get the initial HTML to the user <em>super</em> quickly, and the page loads almost immediately if they are close enough to a CDN edge.</p><p>But it gets even better. If a user has already visited a page, then the HTML file might already be stored in their browser’s cache. If the cached HTML is already up to date, then the CDN server responds with304 Not Modified, and the browser knows to serve up the HTML directly from disk. The CDN doesn’t even have to send the HTML file back to the browser!</p><p>With caching and CDNs, a Web page’s loading sequence now looks more like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/916/1*9F3Yfr-8tSVvvHbCfasJ7g.png" /></figure><p>…but can we optimize this <em>even more?</em></p><p>Yes! The initial page load sequence can be optimized using <em>tons</em> of ingenious techniques like <a href="https://medium.com/reloading/preload-prefetch-and-priorities-in-chrome-776165961bbf">prefetching, preloading, preconnecting,</a> <a href="https://swr.now.sh/">SWR</a>, <a href="https://stackoverflow.com/a/43465666/828709">font</a> and stylesheet inlining, <a href="https://developers.google.com/web/ilt/pwa/caching-files-with-service-worker">service worker caching</a>, and much more — but I won’t go into all of those techniques here. The main speedup I want to focus on is the one gained by serving up a static HTML page so that it can be cached by CDN servers, because this single speedup has the biggest positive impact on page load time.</p><p>So, now we know that CDN technology is the primary tool at our disposal for ensuring that the initial HTML response is returned as quickly as possible.</p><p>With this in mind, here’s our new strategy for making sure our site loads as quickly as possible:</p><ol><li>If a particular page on our site is 100% static (contains no dynamic content whatsoever), then we should make sure it is available on a CDN as a static HTML file. Otherwise, the user would have to make an unnecessary request to our server, which may be far away from them and will incur unnecessary costs by recomputing the same exact HTML output for every single request.</li><li>If a Web page <em>does</em> have dynamic functionality, then we should try to make as much of the page static as possible, so that the static parts can load almost instantly, and <em>then</em> we should enhance the page by fetching the data that we need from our server.</li></ol><p>OK, this seems like a great strategy. But how do we actually implement this? What code do we need to write? Do we have to maintain separate code bases for our static pages and our dynamic pages? Do we have to write the static parts in pure HTML/CSS and then use plain old JavaScript and AJAX to update the HTML (the old, inconvenient way of doing things?)</p><p><em>Is there a better way?</em></p><h4>Next.js to the rescue: automatic static optimization!</h4><p>So, I mentioned near the start of the article that Next.js’s killer feature is <em>automatic static optimization</em>. It exactly implements this strategy that we talked about above, making as much of the site static as possible, and producing CDN-friendly static output for pages that are 100% static.</p><p>And it does all of this <em>automatically!</em></p><p>At the same time, Next.js is not overly restrictive, like AMP — it lets you write your app in the same JavaScript and React that you’re used to, so you can make use of state-of-the-art UI libraries like <a href="https://material-ui.com/">material-ui</a> and <a href="https://github.com/final-form/react-final-form">react-final-form</a>. Next.js also provides a built-in way to implement a REST API, so you can implement endpoints for the UI to fetch data (if needed).</p><p><em>Okay, that sounds amazing. But how is it possible?</em></p><p>It’s actually pretty simple! Next.js works like this:</p><ul><li>Each <strong>page</strong> (“route”) in your application is associated with a single React component. For example, /home is associated with HomeComponent.</li><li>Pages can <em>optionally </em>fetch data asynchronously if they need to, using a special function called getServerSideProps, which gets attached to the component. These props are passed to the component as props when rendered.</li><li>If getServerSideProps is used, then the page is marked “dynamic.” Otherwise, it’s marked “static.”</li><li>Pages that are marked “static” are built <em>once</em> at compile time, and they are distributed to CDNs.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*df2ZHomhMGXjP126oaA7gw.png" /><figcaption>What it looks like when you build a Next.js app</figcaption></figure><p>To make a page static and still have dynamic functionality, all you have to do is avoid using getServerSideProps, and instead use a library like <a href="https://swr.now.sh/">SWR</a> that makes it easy to request data on the client side instead of the server side.</p><h4>Incremental static generation</h4><p>“<em>But what about pages like </em><em>/products/:productid? How can these types of pages be generated statically? Wouldn’t we have to generate static pages for all possible products at build time? What if we add more products?”</em></p><p>These are great questions, and Next.js has a great answer: <strong>incremental static generation</strong>.</p><p>The way this works is that the first time a page is requested, Next.js can make a request to your server to render the page, but also save a static copy of the response and distribute it to CDNs.</p><p>So, the first time someone views a product, it will be a bit slow, but then it will be super fast for everyone else that views that product afterwards.</p><p>Check out this <a href="https://static-tweet.now.sh/">demo</a> of incremental static regeneration to see it in action!</p><h4>The routing system — how flexible is it?</h4><p>I mentioned before that Next.js has a file-system based routing architecture, associating each route with a React component.</p><p>This architecture is somewhat controversial, and has caused many developers to stray away from Next.js entirely. Some developers wind up with the belief that requiring a file for each route is just an odd, inflexible design choice that doesn’t scale to larger apps. But how much merit is there to these kinds of claims?</p><p>Next.js’s page-based routing system is indeed very opinionated. But that’s because it is heavily optimized to make the most common use cases extremely fast. Specifically, Next.js performs <strong>automatic code splitting</strong> when it builds each page, so that the code for each page is only loaded when you request that page, and no sooner.</p><p>For those rare cases where you don’t want to deal with Next’s routing system, (which will probably only happen if you are migrating a legacy app to Next.js), there is a beautifully simple escape hatch: Next.js exposes a minimal API that lets you imperatively render any page from your Node.js server. Here’s an <a href="https://github.com/Maxvien/next-shopify-storefront/blob/master/server/index.ts">example</a>. But in my experience, there has been no need to use the imperative API. Even that linked example could be implemented using file-based routing by creating a file called /products/[handle].js.</p><h4>Next.js deployment: how easy is it?</h4><p>Next.js sounds fantastic. But how do you launch an app built with Next.js?</p><p>One option is to use <strong>Vercel</strong>, which allows you to launch a Next.js app and get the static files super close to your users in only a few minutes.</p><p>Vercel works like this:</p><ul><li>You push your code to GitHub, then grant Vercel access to the repository.</li><li>Vercel automatically builds your app and deploys it to a live domain ending with .now.sh. You can also purchase a domain through their site, if you want a custom domain. Vercel automatically rebuilds your app and deploys to this URL every time you push your code to Git.</li><li>Vercel distributes the statically generated HTML files to its CDN network, so you don’t have to worry about how the static pages will get close to your users.</li><li>Vercel automatically sets up a <strong>serverless</strong> cloud function for each page that uses getServerSideProps, as well as each API route in your app. If you’d like to learn more about serverless architecture, you can read more <a href="https://martinfowler.com/articles/serverless.html">here</a>. If you’ve ever worked with AWS Lambda or Google Cloud Functions, you’ll quickly realize that Vercel’s approach is <em>way</em> easier to deal with.</li></ul><p>For me, this experience was super smooth and saved loads of time. By contrast, I tried deploying a Next.js app on Google Cloud, and it was a hassle. I had to create a Dockerfile that builds the app and then listens on $PORT, set up a cloudbuild.yaml file to build a Docker image from the app, configure a build trigger to automatically build the app when it was pushed to GitHub, update my cloudbuild.yaml file to automatically clean up unused Docker images, and set up a billing alert to make sure I was always on the free tier.</p><p>After all that configuration, I still needed to get the CDN working, figure out whether it’s possible to get Google Cloud working with Next.js’s new incremental static generation, and figure out how to get pages and API routes set up as Firebase Cloud Functions. Overall, it doesn’t seem worth it. Services like Google Cloud and AWS are extremely flexible, but from what I have seen, they are not as optimized as Vercel is for deploying Next.js apps.</p><p>Services like Netlify and GatsbyCloud are other services that offer a similar, “zero-config” approach to launching a Next.js app, but it’s hard to give an opinion on those services that wouldn’t be outdated a month from now.</p><h4>Conclusion</h4><ul><li>Next.js is a powerful React framework optimized for super fast page load times that can handle <strong>both static and dynamic sites </strong>extremely well.</li><li>To fully leverage the power of Next.js, <strong>avoid using </strong><strong>getServerSideProps and </strong><strong>getInitialProps unless it is absolutely necessary</strong>, and make sure that you write your dynamic pages by fetching data on the client side using a library like SWR.</li><li>Even for pages that accept dynamic URL parameters like /products/1234, you can <strong>use Next.js’s incremental static generation feature</strong> to generate static pages at runtime.</li><li>When deployed on Vercel, Next.js “just works.” Your app is automatically distributed to servers around the globe so that it loads super fast everywhere. Since Vercel automatically manages servers for you, you never have to worry that you’re paying for servers that aren’t being used, or not paying for enough servers, making your app slow.</li></ul><p>Thanks for reading! Hopefully you enjoyed the article and have a better understanding of Next.js!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd7aa14ae8d0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-hitchhikers-guide-to-next-js-fd7aa14ae8d0">The Hitchhiker’s Guide to Next.js</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The code formatting problem, and how to solve it]]></title>
            <link>https://medium.com/swlh/the-code-formatting-problem-and-how-to-solve-it-20fdaa07ebca?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/20fdaa07ebca</guid>
            <category><![CDATA[code-style]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[code]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Sat, 04 Apr 2020 17:31:37 GMT</pubDate>
            <atom:updated>2020-04-24T23:28:40.139Z</atom:updated>
            <content:encoded><![CDATA[<p>I’d like to show you a short and sweet piece of code, and I want you to take note of whether you have any thoughts or feelings on what the code <em>looks</em> like.</p><p>Ready? Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bdd343b484d0c8eefe6fe00fb5542cbe/href">https://medium.com/media/bdd343b484d0c8eefe6fe00fb5542cbe/href</a></iframe><p>So, what were your reactions?</p><p>Overall, this is perfectly valid Java code — but did it seem properly formatted to you? Did the spacing and indentation seem off, or was it just right? Were you irked by String args[] instead of String[] args? Were you bugged by the { being on its own line?</p><p>If any of those things floated through your mind while reading the code, I’m about to say something that might come as a surprise:</p><p><strong>You shouldn’t have been thinking about <em>any</em> of those things while reading that code.</strong></p><p>…but it’s not your fault if you were.</p><p>Before you start booing, throwing tomatoes, or <a href="https://www.youtube.com/watch?v=FWBUl7oT9sA">farting in my general direction</a>, please allow me to explain!</p><p>If you’re already in the camp that a programming language is “just a tool” to get stuff done, and you don’t care about aesthetics… great! You probably don’t need any convincing. <em>(Also … why did you even click on this article?)</em></p><p>But if you’re like me, you treat code as an expressive art form. You appreciate a beautiful piece of code, and have your own opinions about “beautiful code” versus “crappy code.”</p><p><a href="https://www.youtube.com/watch?v=Pgd2w0SQEYI">Having said that</a>, I think there are more places we can be artful and creative than in the amount of white space we choose to sprinkle in, and in the amount of indentation we choose to apply.</p><p>Here are a few examples:</p><ul><li><a href="https://journal.stuffwithstuff.com/2016/06/16/long-names-are-long/">Choosing variable names that are concise, yet unambiguous</a></li><li><a href="https://refactoring.guru/replace-nested-conditional-with-guard-clauses">Using “guard clauses” to reduce nesting and make the code look “flat”</a></li><li><a href="http://wiki.c2.com/?ArrangeActAssert">Using the elegant “Arrange, Act, Assert (AAA)” pattern in unit tests</a></li></ul><p>Don’t get me wrong: I’m not saying that we shouldn’t care about how our code is formatted.</p><p>I’m saying that we shouldn’t <em>have</em> to.</p><h3>The solution to the code formatting problem is this: <em>every programming language should have one, and only one, valid way to format code.</em></h3><p>If there is only one valid way to format a piece of code, then formatting would be a non-issue! None of us would ever have to think about how the code is formatted. Hooray!</p><p>We would be able to focus our attention entirely on writing concise, readable, well-tested, efficient code that is error-free and does what it is supposed to.</p><p>Consider this piece of code. It’s exactly the same as the one from earlier, except it was run through an unofficial Java formatting tool:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4dc229049872005cfeeb4100fa338f/href">https://medium.com/media/3f4dc229049872005cfeeb4100fa338f/href</a></iframe><p>If there were only one, standardized way to format Java code, and this code formatter adhered to that standard, then the program above would pretty much be the <em>only</em> way to write a “hello world” program in Java that compiles and does what it is supposed to.</p><p>If you saw this code during a code review, you wouldn’t be thinking things like “ugh, I wish they were using 4 spaces,” or “I wish they would put each curly brace on its own line,” because you would be used to <em>all</em> Java programs being formatted like the one above!</p><p><strong>Ideally, it wouldn’t even be possible to compile a program that isn’t properly formatted according to the official language standard.</strong></p><p>This would guarantee that you would never see any poorly formatted code in any code that actually works, and you can instead focus on what the code is <em>doing</em>, not how it looks.</p><p>Many languages come with standard formatting tools, like gofmt and dartfmt. But even these languages do not treat formatting errors as compile-time errors.</p><p>The JavaScript ecosystem is an especially bad offender. The JS standard doesn’t specify whether lines should end with semicolons, whether let or const should be preferred to var, whether multi-line lists should end with trailing commas, whether parentheses are preferred when writing new Foo() … (the list goes on). There are various popular style guides and enforcement tools, like <a href="https://github.com/airbnb/javascript/tree/master/packages/eslint-config-airbnb">eslint-config-airbnb</a>, but none that are officially required by the standard.</p><p>In JavaScript and many other languages, simple formatting decisions are all left up to the programmer. But why should they be? Why can’t there be a standard way of doing things?</p><p>For JS, maybe the ECMAScript folks should vote on what should be considered the “official” JS format, and all JS code should start migrating towards that format. In the long run, all JS developers would greatly benefit from spending less time configuring tools like ESLint and Prettier and instead getting straight to work on their projects.</p><p>Of course, some exceptions would need to be made. JavaScript, for example, often gets compressed and minified, meaning that whitespace is stripped. The browser shouldn’t refuse to execute minified JS. But maybe the browser could require those files to end with .min.js.</p><p>Languages like TypeScript, which get compiled to JS, are still in a stage of development where they could introduce these kinds of standards without causing any problems. Languages like C++ could do the same, since they could just introduce the standard format in future major versions of the language.</p><p>I hope you agree that in an ideal world, all programming languages would have one — and only one — way to format a given piece of code.</p><p>Thanks for reading, and I’d love to hear what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=20fdaa07ebca" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/the-code-formatting-problem-and-how-to-solve-it-20fdaa07ebca">The code formatting problem, and how to solve it</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Essential tips for scripting in Bash and Python]]></title>
            <link>https://bduffany.medium.com/essential-tips-for-scripting-in-bash-and-python-f0288b3b2d6?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0288b3b2d6</guid>
            <category><![CDATA[python]]></category>
            <category><![CDATA[scripting]]></category>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[bash]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Wed, 25 Mar 2020 22:01:36 GMT</pubDate>
            <atom:updated>2020-03-27T14:34:02.245Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*oAxkmVvAiddqgtAmmMdGaA.png" /></figure><p>In my last article, <a href="https://medium.com/@brandonduffany_45528/developers-want-scripts-and-tools-not-how-to-guides-a47717b1afdc">Developers want scripts and tools — not “how-to” guides</a>, I wrote about the importance of providing <em>runnable script files</em> in your software-related technical writing, instead of just listing out a series of commands that the reader has to copy and paste in order to accomplish a task.</p><p>In this article, I’ll walk you through some tips that have been indispensable to me while writing Bash and Python scripts, and distributing those scripts to other engineers.</p><p><em>Note: this guide is targeted towards Linux users. In future articles, I’ll be writing about PowerShell scripting in Windows (and why it’s awesome).</em></p><h3>Bash scripts</h3><p>For simple scripts that only consist of a few commands and maybe a few optional inputs, I like to use Bash, since it requires very little boilerplate and the syntax is extremely minimal, requiring few keystrokes and therefore saving lots of time.</p><ul><li>To create a new Bash script, you can use the new-script tool that I mentioned in my previous article. After installing it, you can run new-script my-cool-utility to create an executable script named my-cool-utility with useful boilerplate already inserted, and immediately launch into your preferred editor to start authoring the script. Zero-friction! To install this tool, just run this one command:</li></ul><pre>sudo bash -c &#39;cd /usr/local/bin &amp;&amp; wget -qO-    <a href="https://gist.githubusercontent.com/bduffany/a0cb3a8be0364dae91804ac510670e81/raw/7717ce1911fff3ba19dabc7f4acbb03cd5beda1f/new-script.sh">https://gist.githubusercontent.com/bduffany/a0cb3a8be0364dae91804ac510670e81/raw/7717ce1911fff3ba19dabc7f4acbb03cd5beda1f/new-script.sh</a> &gt; new-script &amp;&amp; chmod +x new-script&#39;</pre><ul><li>If your script relies on packages installed using apt-get, just install those packages directly in your script instead of asking users to install it before running the script! It’s usually fine to just sudo apt install -y. A good recipe for detecting whether something is installed is to just run type $COMMAND || sudo apt install -y $PACKAGE.</li><li>If your script needs to update a file that the user might already have (such as .bashrc), make sure to use grep to check that the user hasn’t made that same modification to their file already. Otherwise, you may wind up writing duplicate data or messing with some setting that the user already wrote themselves.</li><li>Gather information from the user using read prompts, e.g. read -P &quot;Enter your API key: &quot; api_key. For more sensitive info like passwords, tack on the -s flag, which prevents the user’s input from being displayed on the console.</li><li>Make use of the <a href="https://www.tldp.org/LDP/abs/html/internalvariables.html">built-in environment variables</a>. Instead of asking the user for their username, just reference $USER. $HOME is also very useful.</li><li>To find and replace text in files or input text, my go to recipe isperl -p -i -e &#39;s@foo@foo_replacement@&#39; file_name.txt. You’ll often see s/foo/foo_replacement/ instead, but I prefer to use @ instead of / as the delimiter since I often find it useful to manipulate directory name patterns, which already contain /.</li><li>Instead of telling your readers to add things to their ~/.bashrc file, you can do it for them! For example, this simple script checks whether a particular alias is already defined in ~/.bashrc, and if not, it adds the alias:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c23cfbaa6d4e9752ff546f00c33af15/href">https://medium.com/media/3c23cfbaa6d4e9752ff546f00c33af15/href</a></iframe><ul><li>The mktemp command is a great way to quickly create temporary files or temporary working directories in the /tmp/directory, which will automatically be deleted on the next system reboot.</li><li>In some cases, your script might need to create some temporary files outside of /tmp/ or make temporary modifications to files. In those cases, use <a href="http://redsymbol.net/articles/bash-exit-traps/">cleanup traps</a> to undo any damage or clean up any garbage generated by your script.</li><li>Make sure to abort the script if any commands fail, using set -eo pipefail at the top of the script (just after the hashbang). (new-script does this for you!)</li><li>Use the rsync command to efficiently synchronize one directory’s contents with another (contents of the source or target directory can come from a server!). This is especially useful if your script needs to mirror some data to the user’s local filesystem, or create backups of data in a pre-determined directory.</li></ul><p>If your Bash script starts getting too complicated (you find yourself needing to use loops, arrays, maps, or command line argument parsing), it’s probably time to switch to Python!</p><h3>Python scripts</h3><p>I use Python scripts whenever I need to parse arguments (which is a terrible experience in Bash) or if I need to use complex data structures (the syntax for dealing with maps and arrays in Bash is atrocious!).</p><p>This article is not intended to be a complete guide to Python, but here are a few basic tips for writing command-line tools in Python:</p><ul><li>For starters, some things are much easier to do in Bash than in Python. Inevitably, you will want to intermix some Bash commands into your Python script to save time. For that, I always keep this nifty utility function in my toolbox:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/91361edf6aa48f076f55d8b4f77e0f14/href">https://medium.com/media/91361edf6aa48f076f55d8b4f77e0f14/href</a></iframe><ul><li>If your Python script is expecting to be run inside a particular directory, make sure that the script automatically changes to that directory! The recipe os.chdir(os.path.dirname(path)) is your friend if you want to change to the same directory as the file passed in as the input argument.</li><li>Use the argparse module to deal with command line arguments. The <a href="https://docs.python.org/3/library/argparse.html">official documentation</a> has some fantastic examples.</li><li>The tempfile module is your friend if you need to create temporary files that will get automatically cleaned up by the operating system. The <a href="https://docs.python.org/3/library/tempfile.html#examples">official documentation</a> includes some great examples.</li><li>Use <a href="https://docs.python.org/3/library/os.html#os.walk">os.walk</a> to recursively process directories and their children.</li><li>If your script needs dependencies that aren’t included in the Python standard library, you can include a wrapper script in Bash which automatically installs them, like the one below, which uses <a href="https://github.com/pantsbuild/pex">Pex</a> to run the Python script in an isolated virtual environment with your required dependencies:</li></ul><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5c558e0d053745fdc60d029cad002f5a/href">https://medium.com/media/5c558e0d053745fdc60d029cad002f5a/href</a></iframe><ul><li>Use <a href="https://joblib.readthedocs.io/en/latest/auto_examples/memory_basic_usage.html#without-joblib-memory">joblib.Memory</a> to cache the results of expensive operations. For example, if your script runs an expensive query against your database and you don’t want users to rack up your compute costs, you can save the returned result to disk for subsequent invocations.</li></ul><p>Hopefully you found these tips to be useful. If you have any other tips, I’d love to hear them. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0288b3b2d6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Developers want scripts and tools — not “how-to” guides]]></title>
            <link>https://bduffany.medium.com/developers-want-scripts-and-tools-not-how-to-guides-a47717b1afdc?source=rss-f8186d96ec61------2</link>
            <guid isPermaLink="false">https://medium.com/p/a47717b1afdc</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[technical-writing]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Brandon Duffany]]></dc:creator>
            <pubDate>Mon, 16 Mar 2020 21:18:22 GMT</pubDate>
            <atom:updated>2020-03-16T21:21:44.910Z</atom:updated>
            <content:encoded><![CDATA[<h3>Developers want scripts and tools — not “how-to” guides</h3><h4>Does this scenario sound familiar to you?</h4><p>You want to do X on the command line. You Google search for an article on “how to do X.”</p><p>The first result: “How to do X” from developers.x.com, last updated this year.</p><p>Perfect! The official docs, and they’re even up to date! Of course, you click on it.</p><p>You read through the article, and you copy and paste the commands into your terminal. Before each command, there’s a detailed explanation of what each command is supposed to do, so you feel confident that this article is not going to leave you with a bricked computer.</p><p>“Great!” you think to yourself. The commands worked flawlessly, and you got X done.</p><h4>Two months later…</h4><p>You want to do X again. But this time, you’re a bit more time pressured. You really want to do Y, but you need to get X done before you can do Y.</p><p>So, to refresh your memory, you Google search “how to do X.” You see the same article: “How to do X.”</p><p>It lists out the same commands.</p><p>You copy and paste each of the commands.</p><p>“Ugh, this is so tedious!” you think to yourself. “I don’t want to read all of this! I don’t care about how to do X! <em>I just want to do Y!</em>”</p><p>The moral is: if you’re writing some technical documentation or even a blog post on “how to do X” and it involves more than a few commands, your readers would <em>love</em> if you could include a script that runs all the commands automatically for them. They would really appreciate a TL;DR at the top of the article that says something like “Done this before? Get the script <em>here (link)</em>.”</p><h3>A philosophical note</h3><p>If you have some knowledge about a particular process, you should <em>codify</em> that knowledge. When you take your knowledge of a certain process and turn that process into a script, you are <em>automating</em> that process, creating value by providing a new tool that allows people to be more productive, saving them the time of having to run commands manually and make decisions about whether or not they need to run commands.</p><p>As the number of users of your script increases, the amount of time saved increases. This is how we make progress in the field of software engineering — by saving time for cool stuff and automating the boring stuff!</p><h3>Where to write scripts</h3><p>GitHub repositories or even Gists are a great choice for storing one-off scripts. In your article, you can instruct readers to run one command to execute your script: eval $(wget -qO- $url), where $url is the URL of the raw file.</p><p>If the script starts to get complicated, with lots of user inputs required, it’s probably better to create a full-on Command Line Interface (CLI) with proper flag parsing, and consider uploading it to a package repository like PyPI or NPM.</p><h3>Let’s get meta: a script that creates new scripts</h3><p>After writing this article, I realized that a lot of the information in this article could be encoded in a script!</p><p>So, I wrote a script called new-script, which creates a new executable Bash script at the path provided as an argument. The generated script contains some basic boilerplate, and is marked executable. Best of all, it gets automatically opened in your preferred editor!</p><p>To install it, use this command:</p><pre>sudo bash -c &#39;cd /usr/local/bin &amp;&amp; wget -qO-    <a href="https://gist.githubusercontent.com/bduffany/a0cb3a8be0364dae91804ac510670e81/raw/7717ce1911fff3ba19dabc7f4acbb03cd5beda1f/new-script.sh">https://gist.githubusercontent.com/bduffany/a0cb3a8be0364dae91804ac510670e81/raw/7717ce1911fff3ba19dabc7f4acbb03cd5beda1f/new-script.sh</a> &gt; new-script &amp;&amp; chmod +x new-script&#39;</pre><p>Then try running new-script foo.</p><h3>Making scripts convenient</h3><p>Scripts can be made even more accessible and usable by providing integrations into various developer workflows.</p><p>For example, if a script needs to operate on a particular file as part of the code editing workflow, it might be nice to build a lightweight IDE extension that just runs the script using the currently open file in the editor.</p><p>More lightweight alternatives to extensions exist for simple scripts, like <a href="https://code.visualstudio.com/docs/editor/tasks">Tasks</a> in VS Code or <a href="https://www.jetbrains.com/help/idea/settings-tools-external-tools.html">External Tools</a> in IntelliJ.</p><p>In my next article, I’ll discuss some useful tips for writing scripts in both Bash and Python.</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a47717b1afdc" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>