<?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 Jason on Medium]]></title>
        <description><![CDATA[Stories by Jason on Medium]]></description>
        <link>https://medium.com/@ImJasonH?source=rss-4a0637341451------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*ytWC1zorC-uIkVbo.jpeg</url>
            <title>Stories by Jason on Medium</title>
            <link>https://medium.com/@ImJasonH?source=rss-4a0637341451------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 12:20:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ImJasonH/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[Dim Your iPhone Screen with Three Clicks]]></title>
            <link>https://medium.com/@ImJasonH/dim-your-iphone-screen-with-three-clicks-4a01deb79f71?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a01deb79f71</guid>
            <category><![CDATA[iphone]]></category>
            <category><![CDATA[apple]]></category>
            <category><![CDATA[tech]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 06 Apr 2017 17:13:57 GMT</pubDate>
            <atom:updated>2017-04-06T17:14:15.251Z</atom:updated>
            <content:encoded><![CDATA[<p>When you’re trying to take a picture outside with the sun shining bright, your iPhone screen’s brightness is a godsend. When you’re trying to lull yourself to sleep by mindlessly scrolling through Twitter, your iPhone screen’s brightness is an unholy curse.</p><p><a href="http://www.imore.com/night-shift">Night Shift</a> exists, sure, but sometimes it’s just not enough. I’m going to unlock a dimmer dim than you’ve ever seen.</p><h3><strong>Part 1: Dimming your screen using “Zoom”</strong></h3><ol><li>Open Settings</li><li>Swipe down to show the Search bar</li></ol><p>First, can we talk about how great it is to search through Settings? I didn’t know about this for a long time, and let’s just say I wasted a lot of time stumbling through the twisty maze of iPhone settings. It was terrible. Open Settings, swipe down and Search, it’s how Steve Jobs intended you to muck with your settings. Anyway.</p><p>3. Search for “<strong>Zoom</strong>” — it’s the one under General → Accessibility → Vision</p><p>4. Down at the bottom, select “Zoom Filter” then select “Low Light”</p><p>Now, when you enable “Zoom” your phone screen will dim. Disabling brightens. You are half way there.</p><h3><strong>Part 2: Now, with three clicks!</strong></h3><p>But wait! There’s more!</p><p>If you’re (totally real-life example) handling a screaming infant at 4 AM and you’re in a rush to turn on your white noise app, you don’t have time to fumble through your phone’s settings to avoid blinding yourself and your offspring, no matter how transformative searching through Settings is.</p><ol><li>Back to Settings, search for “<strong>Accessibility Shortcut</strong>”</li><li>Select “Zoom”</li></ol><p>That’s it. Now, triple-clicking the Home button will enable/disable Zoom and dim/brighten your display.</p><p>If you select more than one option, triple-clicking will let you select which feature to enable. I only use Zoom.</p><p><strong>Caveat:</strong> Sometimes enabling Zoom will actually zoom the screen for some silly reason. If that happens, you can unzoom (without undimming) by double-tapping the screen with three fingers — I call this maneuver a “sextap.”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a01deb79f71" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[More Powerful Synchronization in Go, using Channels]]></title>
            <link>https://medium.com/stupid-gopher-tricks/more-powerful-synchronization-in-go-using-channels-f4a1c3242ed0?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4a1c3242ed0</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 12 Jan 2017 20:38:09 GMT</pubDate>
            <atom:updated>2017-01-13T01:25:43.108Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a common predicament: you have a value, e.g., some string or number or struct, that can be read and written by many goroutines, and you want to make sure readers and writers don’t collide — that readers get the most recently written value, and no other, and that writers don’t write the value while a reader is reading it.</p><p>You may have an idea in your head about how you would approach this problem, and your idea may be completely correct. But I want to try to level up your Go-fu and see what it looks like to solve this problem using channels, Go’s powerful concurrency primitive.</p><p>First, let’s imagine a simple interface which we’ll implement below. This example guards reads and writes of a string, but it could easily guard any other value:</p><pre>// Holder holds a string value in a concurrency-safe manner.<br>type Holder interface {<br>  Get() string<br>  Set(string)<br>}</pre><p>The canonical solution is to use a Mutex. In Go these are provided by <a href="https://golang.org/pkg/sync#Mutex">sync.Mutex</a>. Here’s an example using a sync.Mutex to provide concurrency safety.</p><pre>type mutexHolder struct {<br>  val string<br>  mu sync.Mutex<br>}</pre><pre>// NewMutexHolder returns a Holder backed by a sync.Mutex.<br>func NewMutexHolder() Holder {<br> return &amp;mutexHolder{}<br>}</pre><pre>func (h *mutexHolder) Get() string {<br>  h.mu.Lock()<br>  defer h.mu.Unlock()<br>  return h.val<br>}</pre><pre>func (h *mutexHolder) Set(s string) {<br>  h.mu.Lock()<br>  defer h.mu.Unlock()<br>  h.val = s<br>}</pre><p>This is very simple, and in many cases it may give you exactly what you want. If that’s the case, you should just use a Mutex and get back to solving the real problem.</p><p>But sometimes, you want additional logic and flexibility around your synchronization, and using a Mutex, while easy, doesn’t make it easy to add more synchronization features. Mutexes are simple, but can also be limiting.</p><p>Here’s an alternative solution, which guards reading from happening concurrently with writing, using Channels instead of Mutexes.</p><pre>type chanHolder struct {<br>  setValCh chan string<br>  getValCh chan string<br>}</pre><pre>// NewChanHolder returns a new Holder backed by Channels.<br>func NewChanHolder() Holder {<br>  h := chanHolder {<br>    setValCh: make(chan string),<br>    getValCh: make(chan string),<br>  }<br>  go h.mux()<br>  return h<br>}</pre><pre>func (h chanHolder) mux() {<br>  var value string<br>  for {<br>    select {<br>    case value = &lt;-h.setValCh: // set the current value.<br>    case h.getValCh &lt;- value: // send the current value.<br>    }<br>  }<br>}</pre><pre>func (h chanHolder) Get() string {<br>  return &lt;-h.getValCh<br>}</pre><pre>func (h chanHolder) Set(s string) {<br>  h.setValCh &lt;- s<br>}</pre><p>This is a bit more code than the Mutex-based solution, but at its heart it’s not magic. The key is in the mux method, which is spawned in a goroutine in NewChanHolder.</p><p>mux runs an infinite loop with a select statement inside it, which will block until either a value is received from setValCh or sent to getValCh. This ensures that either the value is read or written each time through the for loop. This is where the synchronization comes from, the select statement ensures that value is only being written to or read from at a given time.</p><p>The implementation of Set sends the new value to the setter channel, and Get receives from the getter channel.</p><p>The value is local to mux’s loop, which means that it’s impossible for another method on Holder to modify it. This is a useful contrast to the Mutex-based solution, where a new method on mutexHolder can modify the value and forget to acquire the lock first.</p><p>But let’s imagine a scenario where you want to guarantee to callers that Get <em>always</em> returns a non-empty string, even if you have to wait for it. The value it’s holding might be an auth token, and callers requesting the token should be able to guarantee that they’ve gotten a valid non-empty token before proceeding. In this case, callers to Get should block until a value can be provided by some other goroutine’s call to Set.</p><p>To do this, we need to handle the empty string as a special value. This is not so simple to implement if all you’re using is a Mutex. But with the channel-backed implementation, this isn’t terribly difficult at all, it’s just another special case in mux:</p><pre>func (h chanHolder) mux() {<br>  var value string<br>  for {<br>    // if the value is empty, only accept setting.<br>    if value == &quot;&quot;{<br>      value = &lt;- h.setValCh<br>      continue<br>    }<br>    // once the value is non-empty, it can be set or gotten<br>    // as normal.<br>    select {<br>    case value = &lt;-h.setValCh: // set the current value.<br>    case h.getValCh &lt;- value: // send the current value.<br>    }<br>  }<br>}</pre><p>With this simple tweak to mux, calls to Get will block until a value has been previously Set. Callers can call Set(&quot;&quot;) to clear the value and force callers of Get to block until Set is called with a non-empty string.</p><p><strong>NB:</strong> The continue in the above code is important; if a caller calls Set(&quot;&quot;) while the value is already empty, we want to start over with the for loop, and not proceed down to the select statement, which might provide values to callers of Get.</p><p>Some callers of Get might not want to their call to block <em>forever</em>. In the case of an auth token, you may want to just fail if you can’t acquire the token after some amount of time. This is also pretty easy to implement with our channel-backed Holder, with another select statement and <a href="https://godoc.org/time#After">time.After</a>.</p><pre>// ErrTimeout is the error returned by GetWithTimeout if the value<br>// was not provided before the given timeout.<br>var ErrTimeout = errors.New(&quot;timeout waiting for value&quot;)</pre><pre>// GetWithTimeout attempts to get the value, or returns ErrTimeout<br>// if getting it takes too long.<br>func (h chanHolder) GetWithTimeout(d time.Duration) (string, error) {<br>  select {<br>  case &lt;-time.After(d):<br>    return &quot;&quot;, ErrTimeout<br>  case v := &lt;-h.getValCh:<br>    return v, nil<br>  }<br>}</pre><p>This sort of feature is not so easy to add if you’ve only got a Mutex guarding your value.</p><p>But wait! Eagle-eyed readers might notice that this implementation keeps a goroutine running indefinitely, forever. In doing so, we have committed a cardinal sin of Go: we <a href="https://dave.cheney.net/2016/12/22/never-start-a-goroutine-without-knowing-how-it-will-stop">started a goroutine without knowing how it will stop</a>.</p><p>If you expect the Holder to live for the duration of your program, then the goroutine will stop when the program stops, and we don’t need to do anything more. On the other hand, if you expect your program to stop setting and getting values at some point, you will want to clean up the Holder when it’s not needed anymore. Let’s add a Close method to clean up.</p><pre>type chanHolder struct {<br>  setValCh chan string<br>  getValCh chan string<br>  closeCh chan struct{}<br>}</pre><pre>// NewChanHolder returns a new Holder backed by Channels.<br>func NewChanHolder() Holder {<br>  h := chanHolder {<br>    setValCh: make(chan string),<br>    getValCh: make(chan string),<br>    closeCh: make(chan struct{}),<br>  }<br>  go h.mux()<br>  return h<br>}</pre><pre>func (h chanHolder) mux() {<br>  val value string<br>  for {<br>    // if the value is empty, only accept setting, or closing.<br>    if value == “” {<br>      select {<br>      case &lt;-h.closeCh: // we also need to handle closing here!<br>        close(h.setValCh)<br>        close(h.getValCh)<br>        return<br>      case value = &lt;- h.setValCh:<br>        continue<br>      }<br>    }<br>    select {<br>    case value = &lt;-h.setValCh: // set the current value.<br>    case h.getValCh &lt;- value: // send the current value.<br>    case &lt;-h.closeCh: // closing, time to clean up!<br>      close(h.setValCh)<br>      close(h.getValCh)<br>      return<br>    }<br>  }<br>}</pre><pre>func (h chanHolder) Close() {<br>  close(h.closeCh)<br>}</pre><p>This version adds a third channel, which is used to signal to mux that it’s time to clean up. This channel doesn’t need to pass any information, it just needs to signal a single event, which we can do just by closing the channel. Because it doesn’t need to carry any information, it can be a chan struct{}.</p><p>mux’s select statement receives from closeCh in addition to getValCh and setValCh, and when it sees the channel is closed, it closes the other two channels and returns from mux.</p><p>With this implementation, if any callers call Set after Close, it will panic (“send on closed channel”). If any callers call Get after Close, it will return an empty string, because they’re receiving from a closed channel. If any callers call Close multiple times, it will panic (“close of a closed channel”). With a little more code you can change this behavior however you want.</p><p>Using channels to synchronize data access can unlock a new level of power and control, but obviously also requires a fair bit of care to make sure you’re not leaking resources. With great power comes great responsibility.</p><h3>Future Work</h3><p>Using channels for synchronization opens up even more possibilities than those described here. Consider how you might implement these features:</p><ul><li>Don’t panic if Set is called after Close, return an error instead, or do nothing.</li><li>Don’t return an empty string if Get is called after Close, return an error instead, or return the last value that was set.</li><li>Don’t panic if Close is called multiple times, return an error instead, or do nothing.</li><li>Implement SetWithExpiry(s string, d time.Duration), which sets the value and clears it after the duration, unless another value is Set in the meantime. If the same value is set again before the value expires, just update the expiration time. What kinds of cases might such a Holder be useful?</li><li>Implement chanHolder using only one internal channel. What would the channel communicate, and how would mux use it? How might this change make other future changes easier?</li><li>Consider the difference in the performance of the Mutex-based solution and the channel-based solution. Write a benchmark to determine which is faster under which use cases. If you plan to use this pattern in a hot code path, the flexibility of the channel-based solution may not be worth the performance penalty. As usual, you should profile your code to determine hotspots before optimizing code, especially if it makes the code harder to understand.</li></ul><p>Full code, with tests, available <a href="https://gist.github.com/ImJasonH/6713e855b431a0c067afea4b74cbf504">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4a1c3242ed0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stupid-gopher-tricks/more-powerful-synchronization-in-go-using-channels-f4a1c3242ed0">More Powerful Synchronization in Go, using Channels</a> was originally published in <a href="https://medium.com/stupid-gopher-tricks">Stupid Gopher Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Natality data with BigQuery]]></title>
            <link>https://medium.com/@ImJasonH/exploring-natality-data-with-bigquery-ed9b7fc6478a?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed9b7fc6478a</guid>
            <category><![CDATA[pregnancy]]></category>
            <category><![CDATA[bigquery]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 10 Mar 2016 11:43:28 GMT</pubDate>
            <atom:updated>2016-03-10T11:43:28.887Z</atom:updated>
            <content:encoded><![CDATA[<h4>Big Data for the Big Day</h4><p>My wife and I found out we were pregnant in July. Since then I think I’ve had about 20,000 questions that I honestly never cared at all about before. Most of them can boil down to, “what’s a normal pregnancy?”</p><p>If I could just ask every person who has ever given birth how theirs went, I think it would make me feel better, and give me an idea of what to expect. I guess I could start cold-calling people at random, that sounds like fun…</p><h4>Enter BigQuery</h4><p>Fortunately, <a href="https://cloud.google.com/bigquery/what-is-bigquery">BigQuery</a> has this information readily available in its <a href="https://cloud.google.com/bigquery/sample-tables">sample datasets</a>. The data comes from from the CDC and covers U.S. birth records from 1969 to 2008. The dataset includes information about the baby’s weight, sex, race, gestational age, <a href="https://en.wikipedia.org/wiki/Apgar_score">Apgar scores</a>, and information about the mother like her age, previous births, cigarette and alcohol use, and whether she was married at the time of the birth.</p><p>It’s really easy to use BigQuery to sift through this pile of data. The query language is basically just SQL, and it only takes a few seconds to run through 40+ years of birth records. The first terabyte of data processed per month is free, so it doesn’t even cost anything to play around and run some queries.</p><p>Of course, you don’t <em>need</em> to actually crunch the numbers to get a lot of useful information; Google has plenty of search results for [<a href="http://lmgtfy.com/?q=pregnancy+week+histogram">pregnancy week histogram</a>] for instance, if you’re willing to <a href="http://spacefem.com/pregnant/due.php">cheat</a>. But I wanted to check their work, and besides, it’s not like I was sleeping anyway.</p><p>Some caveats about this dataset, before we get started:</p><ul><li><a href="http://www.cdc.gov/nchs/data_access/vitalstatsonline.htm#Births">The CDC provides data beyond 2008</a>, they’re just not in the sample table. I briefly looked into loading it in, but the format required just enough work that I decided against it. There’s a ton of other datasets available from the CDC too, if you’re interested.</li><li>Due to what was probably an attempt to anonymize data, there’s a column for “record_weight” which means that the record describes two very similar births, and should be counted twice. If you find yourself doing a COUNT(*), what you actually want is a SUM(record_weight).</li><li>The information the CDC provides changes over time, so some years’ data might include the child’s race or the mother’s reported number of cigarettes per day, and some years they might not. This makes it hard to compare data across years for anything but the more basic facts.</li><li>Like any data source generated by millions of hard-working nurses and public servants, there will be some “anomalous” data. It looks like it was standard practice in the 60s to mark the birth year as “1998” when the birth year was unknown, because who would ever use <em>that</em> number for real data at any time in the future? It’s important to filter out obviously insane data points, like the 40-year term.</li><li>I am not a professional data scientist or medical expert or epidemiologist or person who knows statistics good. Consult your doctor before planning your life around this Medium post.</li></ul><p>With that out of the way, let’s run some queries.</p><h4>Births by day of week</h4><p>One interesting birth fact I kept hearing was that births are much more common on weekdays. This makes some sense when you consider that many births are induced, either due to concerns about <a href="https://en.wikipedia.org/wiki/Postterm_pregnancy">post-term pregnancy</a>, or out of sheer convenience for the mother or doctor.</p><p>Looking at the data, we can see that there is indeed a noticeable decrease in births on weekends, about a third fewer on the least popular day (Sunday) as the most popular (Tuesday):</p><pre>SELECT wday, SUM(record_weight) c<br>FROM [publicdata:samples.natality]<br>GROUP BY wday<br>HAVING wday &gt; 0<br>ORDER BY wday</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*wb5Qh-EZLlh-SiXW8ptuiQ.png" /><figcaption>Loverboy was right, Everybody’s <em>is</em> Working for the Weekend</figcaption></figure><h4>Distribution of pregnancy term length</h4><p>My wife is 36 weeks today. At least for me, now’s the time when it’s all becoming eerily real. We’re meeting with the midwife weekly now. The nursery looks a lot like a real room where a human could live. This baby could happen at any moment.</p><p>But how common is it to give birth at this point? The dataset has a column gestation_weeks, which gives us this information:</p><pre>SELECT gestation_weeks, SUM(record_weight) c<br>FROM [publicdata:samples.natality]<br>GROUP BY gestation_weeks<br>HAVING gestation_weeks &gt; 30 AND gestation_weeks &lt; 45<br>ORDER BY gestation_weeks</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*S6gtC4HxMn3WEOJZ4P_RPw.png" /></figure><p>That’s kind of useful, but at this point I’m not so much interested in the likelihood it’ll happen this week as I am about it happening <em>today. </em>Ohgoditcouldhappentoday.</p><p>Fortunately, the dataset also includes a column “lmp” for last menstrual period. Unfortunately, it’s given in the form “MMDDYYYY” while the birth date is given as three separate columns. To poorly paraphrase Mark Watney: We’re going to have to formula the shit out of this.</p><p>Here’s what I came up with to give us a day-by-day breakdown:</p><pre>SELECT<br> DATEDIFF(<br>  USEC_TO_TIMESTAMP(PARSE_UTC_USEC(<br>CONCAT(STRING(year),&#39;-&#39;,STRING(month),&#39;-&#39;,STRING(day),&#39;00:00:00&#39;))),<br>  USEC_TO_TIMESTAMP(PARSE_UTC_USEC(<br>CONCAT(SUBSTR(lmp,5,4),&#39;-&#39;,SUBSTR(lmp, 0, 2),&#39;-&#39;,SUBSTR(lmp, 3, 2),<br>&#39; 00:00:00&#39;)))) diff,<br> SUM(record_weight) c,<br>FROM [publicdata:samples.natality]<br>GROUP BY diff<br>HAVING diff &lt; 7*45 AND diff &gt; 7*30<br>ORDER BY diff</pre><p><em>Phew</em>! Okay, so basically what this does is string together the birth date into a timestamp, and the lmp date into a timestamp, and get the difference between them using DATEDIFF. That gives us the gestational period in days.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EwCjfSO97CZxomTIsSxfYw.png" /><figcaption>That’s smooooth.</figcaption></figure><p>With this chart it’s pretty easy to see another sign of induced labors: the pronounced peak right at 40 weeks. To the best of my understanding, births used to be induced much more often, and used to be induced at pretty much exactly 40 weeks. These days it’s not uncommon to let the kid bake a little longer if there are no signs of distress. Unfortunately the “lmp” column isn’t populated after 1988.</p><p>The BigQuery natality dataset has a lot more information buried inside it than just these simple queries can answer. Is cigarette use correlated with low birth weight or pre-term birth? Have women started getting pregnant later over the last 40 years? Has the rate of multiple births (twins, triplets) increased, and does it correlate with mother’s age?</p><p>If I have time I can try to answer these questions too, but I probably won’t. After all, there’s a <em>ton</em> of stuff to get done around here.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed9b7fc6478a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ensuring Go interface satisfaction at compile-time]]></title>
            <link>https://medium.com/stupid-gopher-tricks/ensuring-go-interface-satisfaction-at-compile-time-1ed158e8fa17?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ed158e8fa17</guid>
            <category><![CDATA[golang]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 22 Oct 2015 17:36:07 GMT</pubDate>
            <atom:updated>2015-11-02T21:56:45.977Z</atom:updated>
            <content:encoded><![CDATA[<p>In <a href="https://medium.com/stupid-gopher-tricks/stubbing-out-interfaces-in-go-e85afc200aa8">my last post</a>, I described a technique to ensure that a test implementation satisfies an interface, without having to implement every method of the interface. If you haven’t read it, do that now, I’ll wait.</p><p>That technique is great for tests. Your test implementations only have to stub out the methods you care about for that particular test scenario, and they’ll continue to work if the interface changes in ways unrelated to your test.</p><p>But, as the post mentions, it’s not suitable for production code. If an unimplemented method does manage to get called, you get a nasty panic.</p><p>There’s another technique for ensuring that your production implementations satisfy their interfaces at compile-time:</p><pre>type Interface interface {<br>    Foo()<br>}</pre><pre>type Implementation struct {}</pre><pre>func (*Implementation) Foo() { fmt.Println(&quot;foo!&quot;) }</pre><pre>var _ Interface = (*Implementation)(nil) // &lt;---</pre><p>This last line will ensure that your Implementation satisfies your Interface, and will fail to compile if Interface adds methods that the Implementation fails to satisfy.</p><p>Let’s dig into that line a little more. It says, define a global unnamed var (“_”) of type Interface, whose value is a nil pointer, cast as a *Implementation.</p><p>If that nil pointer cast as a *Implementation doesn’t satisfy Interface, the var is invalid, and you’ll get a compiler error:</p><pre>prog.go:16 cannot use (*Implementation)(nil) (type (Implementation) as type Interface in assignment:<br> *Implementation does not implement Interface (missing Foo method)</pre><p>Try it out in the Playground: <a href="http://play.golang.org/p/yxdU-F1tWm">http://play.golang.org/p/yxdU-F1tWm</a></p><p>And, because it’s just an unnamed global var, it will be compiled out after it passes the type check, so it won’t have any impact at all on runtime.</p><h4>Two approaches to changing interfaces</h4><p>So now we’ve got two complimentary techniques for dealing with changing interfaces.</p><ol><li>Embed the Interface inside the Implementation, ensuring the Implementation satisfies the Interface, but only vacuously — unimplemented methods will panic, making this a useful hack for tests, where you don’t care about methods you don’t call.</li><li>Declare a var stating that Implementation satisfies the Interface, ensuring that your code will fail to compile if it doesn’t satisfy. This is useful for production code, where you’ll fail to compile without satisfaction.</li></ol><p>Each have their ups and downs, and each are useful in their own ways. But each are very useful when you find yourself dealing with interfaces outside your control.</p><p>And even if you do control the interface, declaring definitively that an implementation <em>must</em> satisfy the interface can be a nice piece of compiler-enforced documentation for your teammates.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ed158e8fa17" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stupid-gopher-tricks/ensuring-go-interface-satisfaction-at-compile-time-1ed158e8fa17">Ensuring Go interface satisfaction at compile-time</a> was originally published in <a href="https://medium.com/stupid-gopher-tricks">Stupid Gopher Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stubbing Out Interfaces in Go]]></title>
            <link>https://medium.com/stupid-gopher-tricks/stubbing-out-interfaces-in-go-e85afc200aa8?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/e85afc200aa8</guid>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 16 Jul 2015 20:14:08 GMT</pubDate>
            <atom:updated>2015-11-02T21:57:22.603Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a situation in which you may find yourself. You have a service that exposes a lot of functionality. Because you’re a good software engineer, you want to define an interface so you can stub out some of those calls in your tests.</p><pre>type doesEverything interface {<br>  countChickens() int<br>  hatch()<br>  checkWeather(lat, lng float64) string<br>  checkScores(home, away team) (int, int)<br>  checkYourself() bool<br>  wreckYourself()<br>}</pre><pre>func countChickensAndHatch(de doesEverything) error {<br>  c := de.countChickens()<br>  if c &gt; 10 {<br>    de.hatch(c)<br>    return nil<br>  }<br>  return errors.New(&quot;not enough chickens!&quot;)<br>}</pre><p>And your test code:</p><pre>// TestCountChickensAndHatch tests that various inputs to<br>// countChickensAndHatch produce expected errors.<br>func TestCountChickensAndHatch(t *testing.T) {<br>  cases := []struct {<br>    numChickens int<br>    exp         error<br>  }{<br>    {1, errNotEnoughChickens},<br>    {10, errNotEnoughChickens},<br>    {11, nil},<br>    {1000, nil},<br>  }<br>  for _, c := range cases {<br>    s := stub{numChickens: c.numChickens}<br>    got := countChickensAndHatch(s)<br>    if got != c.exp {<br>      t.Errorf(&quot;countChickensAndHatch(%d); got %v, want %v&quot;, got, c.exp)<br>    }<br>  }<br>}</pre><pre>type stub struct {<br>  numChickens int<br>}</pre><pre>func (s stub) countChickens() int { return s.numChickens }</pre><p>Obviously this is a pretty contrived example — this interface is terrible — and that’s a pretty meaningless test. That’s not what I want to demonstrate. This test also doesn’t compile:</p><pre>cannot use stub literal (type stub) as type doesEverything in argument to countChickensAndHatch:<br>  stub does not implement doesEverything (missing checkWeather method)</pre><p>Yep. Our stub implementation doesn’t implement all the necessary methods, namely checkWeather.</p><p>A lot of people would just start throwing in all the necessary methods into the stub implementation to get it to compile:</p><pre>func (s stub) checkWeather(float64, float64) string { return &quot;&quot; }<br>func (s stub) checkScores(team, team) (int, int) { return 0, 0}<br>func (s stub) checkYourself() bool { return true }<br>func (s stub) wreckYourself() { panic(&quot;wrecked&quot;) }<br>func (s stub) hatch(int) {}</pre><p>And there we go, we’ve satisfied the interface, we’re compiling, and we’re off to the races.</p><p>But what if the interface adds another method? What if it adds a <em>dozen</em> more? You don’t want to have to update your stub for each and every one of them, do you? <em>Do you?!</em></p><p>Of course not, you’re better than that. You know <em>the trick!</em></p><p>Instead of writing a bunch of nonsense stub methods, we can just tell the Go compiler that the stub implements the doesEverything interface, by embedding the interface in the struct:</p><pre>type stub struct {<br>  doesEverything<br>  numChickens int<br>}</pre><pre>// Define the stub implementation of countChickens, as before<br>func (s stub) countChickens() int { return s.numChickens }</pre><p>That’s enough to tell the Go compiler that stub has all the methods that the interface defines, without having to write all those methods out yourself. If new methods are added to the interface, the stub will get them too.</p><p>But <em>beware!</em> Lest you think this is a fancy tricky way to ensure that a struct satisfies an interface and use this trick in production: even though stub <em>has</em> those methods, <em>they will panic if called:</em></p><pre>panic: runtime error: invalid memory address or nil pointer dereference</pre><p>So in the above test, since countChickensAndHatch calls hatch, we’ll also need to stub out that method as well:</p><pre>func (s stub) hatch(i int) { fmt.Printf(&quot;hatching %d...\n&quot;, i) }</pre><p>But at least we don’t have to stub out each and every method on the interface.</p><p>Because unimplemented methods panic, this technique is not meant to be used outside of test code, where you can ensure that no code path will ever end up calling an unimplemented method. And if your tests panic, that’s a heck of a lot less serious than your production code panicking.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e85afc200aa8" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stupid-gopher-tricks/stubbing-out-interfaces-in-go-e85afc200aa8">Stubbing Out Interfaces in Go</a> was originally published in <a href="https://medium.com/stupid-gopher-tricks">Stupid Gopher Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Streaming data in Go, without bytes.Buffer]]></title>
            <link>https://medium.com/stupid-gopher-tricks/streaming-data-in-go-without-buffering-3285ddd2a1e5?source=rss-4a0637341451------2</link>
            <guid isPermaLink="false">https://medium.com/p/3285ddd2a1e5</guid>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[stupidgophertricks]]></category>
            <category><![CDATA[golang]]></category>
            <dc:creator><![CDATA[Jason]]></dc:creator>
            <pubDate>Thu, 25 Jun 2015 13:52:59 GMT</pubDate>
            <atom:updated>2017-07-21T14:41:09.055Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>Here’s a common problem I find myself encountering often when writing a program in <a href="https://golang.org/">Go</a>: I have a value that I’d like to encode as JSON and pass to some method that will read it. Usually this is an HTTP request that I’m sending.</p><p>Go’s <a href="http://golang.org/pkg/encoding/json">encoding/json</a> and <a href="http://golang.org/pkg/net/http/">net/http</a> packages are fantastic examples of idiomatic Go, but JSON encoding writes to an <a href="http://golang.org/pkg/io/#Writer">io.Writer</a>, and HTTP requests operate with <a href="http://golang.org/pkg/io/#Reader">io.Readers</a>. I feel a bit like the engineers in <a href="http://www.imdb.com/title/tt0112384/"><em>Apollo 13</em></a>, faced with the task of <a href="https://www.youtube.com/watch?v=C2YZnTL596Q">making a square peg fit into a round hole</a>. Only, y’know, with much less stress because nobody’s lives are at stake. But I digress.</p><p>The general case of this problem is that I want to write some data to a stream (encoded JSON), and give another piece of code a handle to read from that stream (an HTTP request). I’ll use this as an example for this post, but the same solution can be used in lots of situations.</p><h3>Encoding into a Buffer</h3><p>In a lot of cases, the problem can be solved by writing the data to a buffer, then reading from it:</p><pre>// Set up a buffer to temporarily hold the encoded data.<br><strong>var buf bytes.Buffer</strong></pre><pre>// Write JSON-encoded data to a buffer of bytes.<br>// This buffer will grow to whatever size necessary to<br>// hold the buffered data.<br><strong>err := json.NewEncoder(&amp;buf).Encode(&amp;v)</strong></pre><pre>// Send the HTTP request. Whatever is read from the Reader<br>// will be sent in the request body.<br>// The buffer is also a Reader, so it can be passed in here.<br>// Its data will be read out until the buffer is complete.<br><strong>resp, err := http.Post(“example.com”, “application/json”, &amp;buf)</strong></pre><p>A <a href="http://golang.org/pkg/bytes/#Buffer">bytes.Buffer</a> satisfies both the Writer and Reader interfaces, which makes sense, because a buffer can be both written to and read from.</p><p>This works just fine in most cases, when you have small enough data that the memory overhead isn’t that onerous, a couple hundred bytes or so, up to a few KB.</p><p>That bytes.Buffer starts off small (64 bytes), and grows as needed as data is written to it, possibly allocating a whole new slice and copying your data into it, then discarding the original byte slice to be garbage collected.</p><p>You could specify the size of the buffer with <a href="http://golang.org/pkg/bytes/#NewBuffer">bytes.NewBuffer</a>, but even then you won’t know exactly how many bytes you’ll end up writing, and you may overallocate or underallocate.</p><p>Let’s skip buffering altogether.</p><h3>Encoding with a Pipe</h3><p>If the data you’re encoding is huge, or you just want to avoid unnecessary allocations, Go has you covered. In the io package, there is a pair of types called <a href="http://golang.org/pkg/io/#PipeReader">PipeReader</a> and <a href="http://golang.org/pkg/io/#PipeWriter">PipeWriter</a>. These are created with a call to <a href="http://golang.org/pkg/io/#Pipe">io.Pipe</a>, and the Reader and Writer it returns are paired together, such that whatever is written to the PipeWriter is read from the PipeReader.</p><p>It’s like a portal from <a href="https://en.wikipedia.org/wiki/Portal_(video_game)">Portal</a>, whatever goes in the Writer end, immediately goes out the Reader end. Here’s a new version of the code to demonstrate:</p><pre>// Set up the pipe to write data directly into the Reader.<br><strong>pr, pw := io.Pipe()</strong></pre><pre>// Write JSON-encoded data to the Writer end of the pipe.<br><strong>err := json.NewEncoder(pw).Encode(&amp;v)</strong></pre><pre>// Send the HTTP request. Whatever is read from the Reader<br>// will be sent in the request body.<br>// As data is written to the Writer, it will be available<br>// to read from the Reader.<br><strong>resp, err := http.Post(“example.com”, “application/json”, pr)</strong></pre><p>Note that I haven’t used a bytes.Buffer here (or a []byte, or string, etc.) — this code does <em>zero unnecessary buffering. </em>It may do some small amount of buffering internally as data is written faster than it’s read, but it’s negligible. As data is written to the Writer, it can immediately be read from the paired Reader.</p><p><strong>But wait</strong>! This code also includes a serious bug! Because we’re writing to the Writer, then reading from it afterwards, and because the Writer explicitly <em>will not buffer anything</em>, we have a deadlock on our hands! Calls to Write will block until that data can be read, which we’re not doing until <em>after</em> we’ve written. That’s a deadlock.💩</p><p>To solve this problem, we can use a <a href="https://golang.org/doc/effective_go.html#goroutines">goroutine</a> to <em>concurrently</em> write while data is being read.</p><pre>// Set up the pipe to write data directly into the Reader.<br><strong>pr, pw := io.Pipe()</strong></pre><pre>// Write JSON-encoded data to the Writer end of the pipe.<br>// Write in a separate concurrent goroutine, and remember<br>// to Close the PipeWriter, to signal to the paired PipeReader<br>// that we’re done writing.<br><strong>go func() {<br>  err := json.NewEncoder(pw).Encode(&amp;v)<br>  pw.Close()<br>}()</strong></pre><pre>// Send the HTTP request. Whatever is read from the Reader<br>// will be sent in the request body.<br>// As data is written to the Writer, it will be available<br>// to read from the Reader.<br><strong>resp, err := http.Post(“example.com”, “application/json”, pr)</strong></pre><p>In this version, we spawn a goroutine to write to the pipe. This goroutine will not block execution of the next line of code, which passes the Reader to <a href="https://golang.org/pkg/net/http/#Post">http.Post</a> to be read.</p><p>The writing goroutine will write one chunk of data as before, then block until that data can be read from the Reader. When code backing the POST request reads the request body from the Reader, the writing goroutine will become unblocked and be able to write another chunk. And so on, until the writer is done and pw.Close is called. Closing the Writer signals to its paired Reader that there’s no more data, which in turn returns io.EOF, signalling to http.Post that the request body is complete.</p><p>And that’s that. We have JSON-encoded a value into an HTTP request, without unnecessary buffering, using a pipe.</p><h3>Summary</h3><p>This has demonstrated how you can use <a href="http://golang.org/pkg/io/#Pipe">io.Pipe</a> to avoid unnecessary buffering and memory allocations.</p><p>In most cases, it probably won’t be necessary; buffering is just fine for small enough data. But if you find that you’re using more memory than you’d like, or if you know you’ll be working with really huge data, a pipe can be a useful weapon in your arsenal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*48QPJSgyL20PE_RMhRSIwA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3285ddd2a1e5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/stupid-gopher-tricks/streaming-data-in-go-without-buffering-3285ddd2a1e5">Streaming data in Go, without bytes.Buffer</a> was originally published in <a href="https://medium.com/stupid-gopher-tricks">Stupid Gopher Tricks</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>