<?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 Matt Clarke on Medium]]></title>
        <description><![CDATA[Stories by Matt Clarke on Medium]]></description>
        <link>https://medium.com/@kiwiandroiddev?source=rss-7b3a2c1f2f16------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*JApyKI_yJ21s6EOi25rjfw.jpeg</url>
            <title>Stories by Matt Clarke on Medium</title>
            <link>https://medium.com/@kiwiandroiddev?source=rss-7b3a2c1f2f16------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 02 Dec 2026 00:54:02 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kiwiandroiddev/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[Improve Your Tests by being an Evil Coder]]></title>
            <link>https://medium.com/@kiwiandroiddev/improve-your-tests-by-being-an-evil-coder-e3d4090cde6c?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d4090cde6c</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-testing]]></category>
            <category><![CDATA[tdd]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Thu, 15 Aug 2019 05:18:25 GMT</pubDate>
            <atom:updated>2019-08-22T10:09:14.654Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zUK3ZrTIQp0ANOuc-6L0Pg.jpeg" /><figcaption>Literal example of an upwards spiral. Photo by <a href="https://www.flickr.com/photos/7906253@N03">Alicia-Lee-07</a>, licensed under <a href="https://creativecommons.org/licenses/by-sa/2.0/?ref=ccsearch&amp;atype=rich">CC BY-SA 2.0</a></figcaption></figure><p><em>Note: this article assumes you’re somewhat familiar with the idea of </em><a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd"><em>Test-Driven Development</em></a><em>.</em></p><p>Automated tests improve the quality of your code by (at minimum) revealing some of its defects. If one of your tests fails, in theory this points to a defect in your code. You make a fix, the test passes, and the quality of your software has improved by some small amount as a result.</p><p>Another way to think about this is that the tests apply evolutionary selection pressure to your code. Your software needs to continually adapt to the harsh and changing conditions imposed by your test suite. Versions of the code that don’t pass the selection criteria don’t survive (read: make it into production).</p><p>There’s something missing from this picture though. So far the selection pressure only applies in one direction — from the tests onto the production code. What about the <em>tests themselves</em>? Chances are they have defects of their own, just like any other code. Not to mention the possibility of big gaps in the business requirements they cover. What, if anything, keeps the tests up-to-scratch?</p><p>If tests are actually an important tool for maintaining code quality, then this is an important question to get right. Low-quality tests can’t be expected to bring about higher quality software. In order to extract the most value out of automated tests, we need a way to keep them up to a high standard.</p><p>What could provide this corrective feedback? You could write tests for your original tests. But this quickly leads to the problem of <a href="https://en.wikipedia.org/wiki/Infinite_regress">infinite regress</a>. Now you need tests for those tests, and tests for <em>those</em> tests, and so on. For all eternity.</p><p>What if the production code itself could somehow apply selection pressure <em>back onto</em> the tests? What if you could set up an adversarial process, where the tests force the production code to improve and the production code, in turn, forces the tests to improve? This avoids the infinite regress problem.</p><p>It turns out this kind of thing is built into the TDD process. Here are the <a href="http://butunclebob.com/ArticleS.UncleBob.TheThreeRulesOfTdd">“3 laws of TDD”</a> (emphasis added):</p><ol><li>You must write a failing test before you write any production code.</li><li>You must not write more of a test than is sufficient to fail, or fail to compile.</li><li><strong>You must not write more production code than is sufficient to make the currently failing test pass.</strong></li></ol><p>It’s following rule 3 that applies selection pressure back onto the tests. By only writing the bare minimum code in order to make a test pass, you’re forced to write another test to show that your code is actually half-baked. You then write just enough production code in order to address the newly failing test, and so on. It’s a positive feedback loop.</p><p>You end up jumping between two roles that are pitted against each other: the laziest developer on the planet, and a test engineer that’s constantly try to show the developer up with failing tests.</p><p>Another benefit to being lazy is that it produces lean code. At some point, there are no more tests to write; you’ve implemented to complete specification as it’s currently understood. When this happens, you will often find that you’ve written far less code than expected. This is a win because all else being equal, <a href="https://martinfowler.com/bliki/BeckDesignRules.html">less code is easier to understand</a>.</p><p>Reading about this is one thing, but it needs to be tried out to really grasp its benefits. It turns out there is a exercise/game called <a href="https://software-carpentry.org/blog/2015/09/code-retreat.html">“Evil Coder”</a> created to practise this part of TDD. You pair up with another developer, with one person writing tests and the other taking the Evil Coder role:</p><blockquote><strong><em>Evil mute A/B pairing</em></strong><em>: pairs are not allowed to talk. One person writes tests. The other person is a “lazy evil” programmer who writes the minimal code to pass the tests (but the code doesn’t need to actually implement the specification).</em></blockquote><p>You can try this out by heading along to the next <a href="https://www.coderetreat.org/">Global Day of Code Retreat</a> event in your city — it’s a lot of fun.</p><p><strong>TLDR:</strong> improve your tests, and your production code as a result, by being lazy and evil.</p><p><em>Thanks to Ali and Xiao for proofreading and providing feedback on a draft of this essay.</em></p><p><em>Originally published at </em><a href="https://coderefinery.wordpress.com/2019/08/15/an-adversarial-process-to-improve-your-tests/"><em>http://coderefinery.wordpress.com</em></a><em> on August 15, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d4090cde6c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[“Business needs vs. Customer needs” is a False Dichotomy]]></title>
            <link>https://medium.com/@kiwiandroiddev/business-needs-vs-customer-needs-is-a-false-dichotomy-e4c093daf079?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/e4c093daf079</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[business]]></category>
            <category><![CDATA[app-development]]></category>
            <category><![CDATA[lean-startup]]></category>
            <category><![CDATA[ux]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Mon, 10 Jun 2019 06:32:21 GMT</pubDate>
            <atom:updated>2019-08-20T23:13:03.714Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*YnSgVsqhdJuPdw4J" /></figure><p><em>“We have to balance the customer’s needs with the business needs”.</em></p><p>How many times have you heard this while working in a software development team?</p><p>I’ve worked as a mobile developer at a number of large companies. In enterprise environments like these, typically the mobile app is “the storefront of the business”, and brings together a number of features paid for by other departments.</p><p>Often the initial requirements from the other department will come with a suggestion to make their feature more prominent in the app. For example, “add it to the top of the dashboard”, “just add a new tab for it” or “send a push notification to our users about it”.</p><p>This is understandable. The job of the people from the other department is firstly to improve the area of the business they are responsible for. Their job is not to work out how to nicely integrate their feature into the app so it plays nicely with every other feature. That’s the app team’s job.</p><p>When members of the app team point out that adding a new top-level tab or push-notification for every new feature requested by every department isn’t a sustainable long-term strategy, and will lead to a poor user experience, the protest that often comes back is something like:</p><blockquote>Well, we have to remember to balance the customer’s needs with the business needs.</blockquote><p>I was never comfortable with this statement. It’s taken me a while to think through exactly why this is. What I eventually concluded is that while it seems reasonable on the surface, buried in it is a wrong assumption.</p><p>It’s not that you should always prioritize the customer’s needs over business needs, or vice versa. Rather, the assumption underlying the statement — that these two things are at odds — is wrong. It’s a false dichotomy.</p><p>To believe that “balancing the user’s needs with business needs” makes sense, you need to be engaged in short-term thinking of one kind or another.</p><p><strong>If you want your business to survive in the long term, there can be no distinction between the interests of your customer and those of your business.</strong></p><p>Your business exists to serve a customer, in a sustainable way. In the final analysis (assuming a free market where your customers can leave), business needs and customer needs must be aligned. Promoting one at the expense of the other actually harms both.</p><p>In the long term, building a system that helps the business at the expense of your customers is actually harming both the business and your customers<em>. </em>( <a href="https://clevertap.com/blog/uninstall-apps/">Spamming them with notifications in an attempt to boost engagement</a>, for example).</p><p>Likewise, building a system that helps your customers at the expense of the business is actually harming both your customers and the business.</p><p>How does this second point make sense? I.e. how is that helping your customers at the expense of the business actually harms them?</p><p>Here’s how: <strong><em>presumably, your customers would rather your business continues to exist than not</em>.</strong> For example, bribing customers with giveaways and subsidized prices isn’t sustainable. If you “spend 1 dollar to make 80 cents”, you will eventually go out of business.</p><p>When this happens, you will (at the very least) inconvenience your customers, leaving them bereft or forced against their wishes to switch to a competitor. Or if you offer something unique, you deprive them of that unique offering altogether.</p><p>Is it idealistic or wishful thinking to see the success of your customer and business as inextricably linked? Jeff Bezos, the CEO of Amazon, doesn’t seem to think so. The top 3 of his <a href="https://myemail.constantcontact.com/The-4-Pillars-of-Amazon-s-Success--According-to-CEO-Jeff-Bezos.html?soid=1124597373777&amp;aid=RHPNXLDxhMc">4 pillars of Amazon’s success</a> are:</p><ol><li><strong>Customer Obsession</strong></li><li><strong>Eagerness to Invent to Please the Customer</strong></li><li><strong>Long-term Orientation</strong></li></ol><p>So next time you hear that the “needs of customer need to be balanced with the needs of the business” remember that to successful businesses, there is really no distinction.</p><p><em>Thanks to Xiao and Arun for their feedback and suggestions. Liked this article? Please consider sharing it with your friends and colleagues with one of the buttons below.</em></p><p><em>Originally published at </em><a href="https://coderefinery.wordpress.com/2019/06/10/business-vs-customer-needs/"><em>http://coderefinery.wordpress.com</em></a><em> on June 10, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e4c093daf079" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beyond DRY — Why Redundancy Makes Your Code More Robust and Less Fragile]]></title>
            <link>https://medium.com/@kiwiandroiddev/beyond-dry-why-redundancy-makes-your-code-more-robust-and-less-fragile-6a64d0172a57?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a64d0172a57</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[antifragile]]></category>
            <category><![CDATA[redundancy]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Mon, 28 Jan 2019 00:02:17 GMT</pubDate>
            <atom:updated>2019-01-29T18:58:27.198Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beyond DRY — Why Redundancy Makes Your Code More Robust and Less Fragile</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/710/0*_FjCkXQcGDhmM1-t" /></figure><p><a href="https://www.amazon.com/gp/product/0812979680/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0812979680&amp;linkCode=as2&amp;tag=coderefinery-20&amp;linkId=1f7d5955a136972100127a9c17413981">Anti-Fragile</a> by Nassim Nicholas Taleb is a goldmine of practical ideas for software developers, despite it not being a software development book.</p><p>Redundancy is one example of such an idea that is explored. Taleb explains how having some redundancy reduces fragility, and means we don’t need to predict the future so well. Think of food stored in your basement, or cash under your mattress.</p><p>Taleb notes how nature’s designs frequently employ redundancy (“Nature likes to overinsure itself”):</p><blockquote><em>“Layers of redundancy are the central risk management property of natural systems. We humans have two kidneys […] extra spare parts, and extra capacity in many, many things (say, lungs, neural system, arterial apparatus), while human design tends to be spare and inversely redundant, so to speak — we have a historical track record of engaging in debt, which is the opposite of redundancy”</em></blockquote><p>Software source code is a good example of human design that tends to be “spare” (having no excess fat) and “inversely redundant”. Redundancy in code is traditionally avoided at all costs. In fact, one of the first principles that junior developers are often taught is the <a href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a> — Don’t Repeat Yourself. As far as DRY is concerned, redundant code is a blight that should be eliminated wherever it shows up.</p><p>There are good reasons for the DRY principle. Duplicate code adds noise to the project, making it harder to understand without adding any obvious value. It makes the project harder to modify because the same code must be maintained separately at each place it is duplicated. Each of these locations is also another opportunity to introduce bugs. Duplicate code feels like waste.</p><p>However, as Taleb states:</p><blockquote><em>“Redundancy is ambiguous because it </em><strong><em>seems like a waste if nothing unusual happens</em></strong><em>. Except that something unusual happens — usually.” [emphasis added]</em></blockquote><p>What are these “unusual things that usually happen” in software development? And how could duplicate code possibly help protect us against them?</p><h3>The Wrong Abstraction</h3><p>Firstly, remember that duplication is eliminated by introducing abstractions, such as a function or class. The problem with abstractions is that it is difficult to know ahead of time whether a chosen abstraction is actually a good fit for your project. And the cost of getting this wrong is high. Poorly-chosen abstractions add friction to making the kinds of changes that are actually needed for the project, while still exacting an ongoing cost in terms of complexity. There’s also the risk that by the time poor abstractions have been recognised as such, they have already spread throughout the project. Rooting them out at this point will likewise impact code all throughout the project, potentially with unintended consequences.</p><p>The “unusual things that usually happen” in software development are unexpected, unpredictable (and unavoidable) changes in business requirements. These have the annoying effect of revealing the shortcomings of your abstractions, abstractions that you perhaps added while faithfully following the DRY principle.</p><p>Too-eager abstraction and a lack of redundancy mirrors the problems of centralisation, another idea explored in Anti-Fragile. Centralisation, while efficient in the short-term (read: less code), makes systems fragile. When blow-ups happen, they can take down (or at least damage) the entire system. NNT outlines in Anti-Fragile how such fragility and lack of redundancy was the cause of the banking system collapse of 2008.</p><p>Redundancy in the form of duplicated code, on the other hand, makes code more robust. It does this by avoiding the worse evil of introducing the wrong abstraction. In this way, it limits the impact of unexpected changes in business requirements. As Sandi Metz states: <a href="https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction">“Duplication is far cheaper than the wrong abstraction”</a></p><h3>The Rule of Three</h3><p>As it turns out, there is another software development principle (or rule of thumb) which does recognise the risks of poor abstractions, and seeks to mitigate them through some redundancy. It’s called the <a href="https://en.wikipedia.org/wiki/Rule_of_three_(computer_programming)">“Rule of Three”</a>. It states that you should wait until a piece of code appears three times before abstracting it out. (Note that this appears to contradict the DRY principle). This minimises the chances that the abstraction is premature, and increases the chances that it addresses a real, recurring feature of the problem domain that is worth the cost of abstraction.</p><p>Introducing an abstraction is in some sense a prediction of the future. Abstractions make a certain class of future changes easier, at the cost of some extra complexity and fragility. They are worth this cost if and only if the types of changes they make easier actually turn out to be reasonably common. Following The Rule of Three means deliberately holding off on making a prediction until more evidence has come in. The assumption built into the Rule of Three is that <strong>past changes are the best predictor of future changes</strong>.</p><h3>Back to Nature</h3><p>Now to return to Taleb’s observation of widespread redundancy in nature’s designs. An interesting implication of this is that despite all of the apparent “waste” involved, evolutionary processes have nonetheless converged onto it as the best strategy for dealing with unpredictability — a permanent feature of the real world (or at least, a better strategy than no redundancy — having one kidney, for instance).</p><p>At a high level, our software projects and teams are similar in the sense that they exist in a challenging, competitive environment punctuated by unpredictable changes. If meaningful parallels can be made between complex systems, it’s worth considering the possibility that despite the apparent “waste” involved, some redundancy is likewise the best strategy for dealing with the unpredictability in our environment too.</p><p>This is all to say: go forth and fearlessly copy-paste more code 🙂</p><h3>References and Further Reading</h3><p><a href="https://www.sandimetz.com/blog/2016/1/20/the-wrong-abstraction">The Wrong Abstraction</a></p><p><a href="https://programmingisterrible.com/post/139222674273/write-code-that-is-easy-to-delete-not-easy-to">Write code that is easy to delete, not easy to extend</a></p><p><a href="https://www.amazon.com/gp/product/0812979680/ref=as_li_tl?ie=UTF8&amp;camp=1789&amp;creative=9325&amp;creativeASIN=0812979680&amp;linkCode=as2&amp;tag=coderefinery-20&amp;linkId=e4615d0788f69e0bacef8f9c935d324c">Antifragile: Things That Gain from Disorder (Incerto)</a></p><p><em>Originally published at </em><a href="https://coderefinery.wordpress.com/2019/01/28/beyond-dry-why-redundancy-makes-your-code-more-robust-and-less-fragile/"><em>coderefinery.wordpress.com</em></a><em> on January 28, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a64d0172a57" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How Google’s Halo Effect is affecting the Android community]]></title>
            <link>https://medium.com/@kiwiandroiddev/how-googles-halo-effect-is-affecting-the-android-community-2f76a109b0fd?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/2f76a109b0fd</guid>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[google]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[psychology]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Thu, 05 Jul 2018 09:06:29 GMT</pubDate>
            <atom:updated>2018-07-05T09:21:11.659Z</atom:updated>
            <content:encoded><![CDATA[<p>If you work in the tech industry, you might have heard of the term “HiPPO” — the “Highest Paid Person’s Opinion”. The retail store chain <a href="https://www.forbes.com/sites/derosetichy/2013/04/15/what-happens-when-a-hippo-runs-your-company/#2eb7e03e40cf">JCPenny serves as a cautionary tale</a> of what can happen when your company is run by HiPPOs rather than by data. Their new CEO relentlessly implemented his vision for the stores, overriding any contradicting data or opinions. The company lost nearly $1 billion in the process.</p><p>It’s worth asking why a Hippo’s opinion carries so much weight in the company. <strong><em>Safety</em></strong> might be one reason. Agreeing with your boss’s opinion without question might seem like a safe option for your job security, at least in the short term.</p><p>More charitably, there are probably some good reasons as to why the Hippo is paid so well (assuming your company isn’t entirely corrupt, that is). They probably <em>are</em> very competent, at least in certain areas. Maybe they have insight that you don’t. Maybe you <em>should</em> just keep quiet and go along with their ideas.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*KwDRMB8Ygw16fZ7RphMI3w.jpeg" /><figcaption>“The fallacy is that the best way of deciding what to do within a business or a government is to take the Hippo’s opinion, rather than testing with hard data.” — <a href="https://www.standard.co.uk/lifestyle/london-life/why-you-shouldnt-listen-to-the-office-hippo-thats-highestpaid-persons-opinion-a3540571.html">Evening Standard</a></figcaption></figure><p>The major problem with being a Hippo-driven company (as the people at JCPenny found out) is that <strong>rank is no guarantee of the quality of one’s ideas</strong>. This is particularly true in newer industries, that are highly complex and rapidly-evolving, such as I.T.</p><h4>Google is like a Hippo</h4><p><strong>To Android developers, Google’s offerings — their tools, libraries and services — are somewhat like HiPPOs.</strong> They come with an inordinate amount of weight behind them from birth. As with your boss’s opinion, it’s not that they’re bad or wrong, or even that they’re not right most of time. It’s just that they are too often <em>assumed</em> to be the best way to go just because they “came from Google”.</p><blockquote><strong>To Android developers, Google’s offerings — their tools, libraries and services — are like HiPPOs.</strong> They come with an inordinate amount of weight behind them from birth.</blockquote><h3>Google’s Halo Effect</h3><p>This tendency to assume that the Google Way is best is an example of what psychologists call the <a href="https://en.wikipedia.org/wiki/Halo_effect">Halo Effect</a>. The Halo Effect is a cognitive bias whereby positive qualities are assumed about something on the basis of other, unrelated qualities. It applies to people, brands, organisations and ideas. Brands like and aim for the halo effect — it’s why the <a href="https://www.investopedia.com/terms/h/halo-effect.asp">success of the iPod</a> made the success of the iPhone and iPad more likely.</p><p>The Halo Effect means that developer tools and libraries from Google are naturally bathed in glow of Google’s brand name, gaining some positive attributes automatically, before any solid evidence is available.</p><h4>The case for Google’s Halo</h4><p>The Halo Effect is a heuristic — a mental shortcut used to make decisions in situations of uncertainty. Heuristics “<a href="https://en.wikipedia.org/wiki/Heuristic">ease the cognitive load of making a decision</a>”. They’re quick, easy and often better than nothing when you don’t have any hard data to rely on.</p><p>You could argue that it’s not unreasonable to assume that something from Google will be of a high quality. After all, Google is one of the most profitable companies in the world and have their pick of top engineers. They also have every reason to help developers succeed in building for their platform.</p><p>And, even if you <em>were</em> to grant that something from Google might not be the best tool for the job, there’s another reason why you might choose to adopt it anyway: <strong>widespread familiarity</strong>. The mere fact of it being from Google means you can bet a lot of Android developers will try it out, or at least know about it. This has real value all on its own. For one thing, it means less time on-boarding new Android developers, which is money saved for the business. All else being equal, going with Google’s offering is a safer bet.</p><p><em>(Ironically, widespread familiarity was one of the reasons for </em><a href="https://softwareengineering.stackexchange.com/questions/140848/why-was-java-chosen-for-android"><em>Java being chosen as the language for Android development</em></a><em>…)</em></p><h4>The Halo Effect in Software development</h4><p>Let’s dig into this further to see why the Halo Effect can cause problems (particularly in software).</p><p>First is that building something new in a complex, rapidly-changing domain is always difficult to get right. Complex domains are somewhat unpredictable by their nature - it’s impossible to know for sure what will succeed in them prior to gathering hard data from real-world testing.</p><p>Software is a complex field, and the challenge of complexity applies not only to software products but to libraries, APIs, tools and patterns. Tech companies with money to burn and every motivation to succeed still regularly launch products that go down in flames (e.g. Apple Maps, Apple Music, Amazons’ Fire Phone, Facebook Home…)</p><p>Google is no exception. Some notable failures they’ve had at the product-level are Google Wave, Google+, Google Glass and Allo.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*FT9UaRLNQeou10foTNwURw.png" /><figcaption>The Google+ social network didn’t quite catch on</figcaption></figure><p>Some examples of libraries and tools that might come to mind for Android developers are Volley, Instant Run, Data Binding, Fragments, Loaders and Agera. (These examples could be debated of course; they’re all still around. The point is more that they failed to match up with the overly high expectations one might have of Google.)</p><p><em>(Side-note: ‘failure’ as such is not the real problem here. In complex environments, ‘failure’ can be thought of as nothing other than ‘learning’ or ‘experimentation’. The problem is that the Halo Effect means the downsides of this learning can be much bigger than they need to be).</em></p><p>So the first problem with Google’s Halo is that it paints an unrealistically rosy picture of their new offerings. <strong>Google’s engineers make mistakes, like everyone else, because building software is an intractably hard problem.</strong> This might be far more often than you’d think as a new Android developer or someone who is positively inclined towards Google.</p><h4>The Dark Side of Google’s Halo</h4><p>You might protest that, so far, none of this is specific to Google, and that this problem applies to <em>any</em> software vendor with a good reputation, whether it’s another large corporation or a well-known open source developer. Fair point.</p><p>However, the problem with Google’s Halo is somewhat special due to their unique position in the Android ecosystem. It becomes clear when you start to shift your perspective from that of an individual developer to looking at the Android ecosystem as a whole.</p><p>As the owner and main contributor to the Android platform, Google naturally has an unparalleled influence on the Android community. It’s possible that an Android developer has never heard of <a href="https://github.com/square">Square, Inc.</a>, it’s not possible that they haven’t heard of Google. Add to this the fact that someone who chose to develop for Android over iOS is likely to be positive towards Google. <strong>From this it follows that the cumulative harm caused by Google’s Halo Effect to the Android community is also unparalleled compared to that of any other single company or developer.</strong></p><p>Google’s dominant position in the Android ecosystem means their offerings to developers are like <a href="https://en.wikipedia.org/wiki/Leverage_(finance)">highly-leveraged investments</a>: the total impact to the community if things go wrong is multiplied massively compared to any other source.</p><p>Consequences to Android developers matter not least because they ultimately affect Android users. Time spent tracking down bugs, delving into the source code to investigate why something isn’t working as expected and working around clunky APIs is time that could be better spent solving your user’s problems.</p><p>There’s a <a href="https://www.folklore.org/StoryView.py?story=Saving_Lives.txt">nice quote from Steve Jobs</a> about how small inefficiencies really add up when they apply across an entire ecosystem:</p><blockquote>“Well, let’s say you can shave 10 seconds off of the boot time. Multiply that by five million users and thats 50 million seconds, every single day. Over a year, that’s probably dozens of lifetimes. So if you make it boot ten seconds faster, you’ve saved a dozen lives. That’s really worth it, don’t you think?”</blockquote><h4>Warnings from the community</h4><p>Jake Wharton, author of many popular open source Android libraries, has rightly warned us about the risk of trusting Google too blindly — of our susceptibility to Google’s halo.</p><p>In <a href="http://fragmentedpodcast.com/2015/04/">an episode of the Fragmented podcast</a>, Jake was asked about what things Android developers could do to get better. Here’s how he responded:</p><blockquote>I think one of the biggest ones that we see now […] in the community there’s this sense that the fact that every engineer… everything that comes out of Google is the canonical way and the only way of doing something. Now that’s not to say that some of the smartest people in the world don’t work there and some of the best ideas and libraries for Android actually *do* come out of there... <strong>it’s just the problem is the blind acceptance of anything that comes out of Google as the way of doing something </strong>[emphasis mine]<strong>.</strong></blockquote><p>To his credit, his message has stayed the same even since joining Google in 2016:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SlrGYBPJV4BYP7PY8-LEhQ.png" /><figcaption><a href="https://twitter.com/JakeWharton/status/982836324075016192">https://twitter.com/JakeWharton/status/982836324075016192</a></figcaption></figure><h4>Agera and RxJava</h4><p>Jake is by no means the only prominent member in the development community to warn developers about the dangers of Google’s halo. The <a href="https://github.com/google/agera">Agera</a> project gave rise to another interesting example.</p><p>In 2016, the Google Play Movies team open-sourced a reactive library they’d developed internally. It was advertised as “a super lightweight Android library” for writing reactive apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*qGEkTPDSBEZU_uE--QhfQA.png" /></figure><p>Reactive programming was not new to the Android community as RxJava was already rising in adoption in 2016. However, RxJava was (and rightly still is) known to have a steep learning curve. A lightweight reactive library from Google designed just for Android sounded very promising.</p><p>David Karnok, lead maintainer of RxJava, did not waste any time in <a href="https://akarnokd.blogspot.com/2016/04/google-agera-vs-reactivex.html">providing a detailed analysis</a> of Agera from his experience working in the async/reactive domain. He reported on its level of sophistication compared to other reactive libraries, concluding that <a href="https://github.com/google/agera/issues/20#issuecomment-212007539">“Agera is almost a 1st generation reactive library with strong 0th generation ties”</a>.</p><p>More to the point is that David’s swift and public response to Agera was a <strong>conscious effort on his part to reduce the impact of Google’s halo on the community</strong>. From his blog post (emphasis added):</p><blockquote><strong>It doesn’t really matter who released it, all that matters what they released</strong> and how it relates to the well established reactive libraries, RxJava, Reactor and Akka-Streams, altogether.</blockquote><p>He concludes (emphasis added):</p><blockquote>You may ask, why do I care what Google/Agera does? Aren’t I confident in RxJava? Of course I am confident and Agera’s existence doesn’t really strike me.</blockquote><blockquote>However, my experience shows, <strong>if you have big name banner over your head, unchallenged self-confidence and sub-par outcome may be forced upon an entire community</strong>. I don’t really want to give out ideas here but imagine the next Android version would mandate Agera, in its current form, to be <strong>the</strong> standard for asynchrous programming!</blockquote><h3>Moving Forward</h3><p>So what can be done to limit the downsides of Google’s Halo Effect?</p><p>Here are a few guidelines you could consider as an individual developer. These might also be things you’ve heard from senior technical people in your company who been bitten enough times (thanks Peter!). Note that these apply to all third-party tools and libraries, not just those from Google:</p><ul><li><strong>Resist the urge to adopt the shiny new thing straight away.</strong> Wait a while for the initial hype to die down and for feedback from the wider community to come in. Check Reddit and monitor the issues page if the project has one.</li><li><strong>Try out new tools in a small, low-risk project first.</strong> Maybe this could be one of your personal side-projects or a less-critical app at work.</li><li>Remember that <strong>sample apps bundled with libraries typically only show the “happy path”</strong> — the type of problem <em>for which they are most suited</em>. Real-world projects, with all of their complexity and awkwardness, are much more likely to reveal a library’s shortcomings.</li></ul><p>This all boils down to the same advice for taming Hippos — prefer concrete data over subjective opinion and feelings:</p><blockquote>“If we have data, let’s look at data. If all we have are opinions, let’s go with mine.” — Dan Barksdale, Netscape CEO</blockquote><p>What about from Google’s end? What can they do to <a href="https://en.wikipedia.org/wiki/Iatrogenesis">protect their platform from themselves</a>? This is an interesting topic that could be explored in a future article, but in short I believe the Android teams at Google have made significant strides towards mitigating this problem in recent years. This was particularly evident in the content and general spirit of the last two I/O conferences. There seems to be a move away from “big bang” style releases and towards tenuous announcements of libraries, emphasising that they are in alpha, may change at any time, and that they will be refined over time through feedback from the community (Architecture Components and Android KTX, for example).</p><p>Hopefully the movement continues, for the benefit of the Android developers, users and the sustainability of the ecosystem as a whole.</p><p><em>If you liked this article, please let me know by hitting the applause button. Feedback, good or bad, is welcome.</em></p><p><em>Thanks to Daniel O., David K., Gyurme D. and Peter H. for feedback and suggestions. Special thanks to Daniel for the title.</em></p><h3>Bibliography/Further Reading</h3><ul><li><a href="https://www.standard.co.uk/lifestyle/london-life/why-you-shouldnt-listen-to-the-office-hippo-thats-highestpaid-persons-opinion-a3540571.html">Why you shouldn&#39;t always listen to the highest-paid person&#39;s opinion</a></li><li><a href="http://whatusersdo.com/blog/why-hippos-are-the-enemy-of-ux/">Enemies of UX and how to kill them: #1 HiPPOs | Be Good To Your Users</a></li><li><a href="https://www.investopedia.com/terms/h/halo-effect.asp">Halo Effect</a></li><li><a href="https://en.wikipedia.org/wiki/Halo_effect">Halo effect</a></li><li><a href="https://en.wikipedia.org/wiki/Thinking,_Fast_and_Slow">Thinking, Fast and Slow - Wikipedia</a></li><li><a href="http://fragmentedpodcast.com/episodes/6/">006: Jake Wharton on Becoming a Better Developer and Creating Successful Open Source Projects (Part 1)</a></li><li><a href="https://akarnokd.blogspot.com/2016/04/google-agera-vs-reactivex.html">Google Agera vs. ReactiveX</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2f76a109b0fd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Case for Constraint: Why Fewer Options Mean Less Procrastination and More Creativity]]></title>
            <link>https://medium.com/@kiwiandroiddev/the-case-for-constraint-why-fewer-options-mean-less-procrastination-and-more-creativity-d11dc0f4e741?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/d11dc0f4e741</guid>
            <category><![CDATA[creativity]]></category>
            <category><![CDATA[procrastination]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[psychology]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Thu, 04 Jan 2018 19:48:49 GMT</pubDate>
            <atom:updated>2018-01-04T19:48:49.198Z</atom:updated>
            <content:encoded><![CDATA[<p>I don’t know about you, but I waste more time on weekends than I would like. Despite having a rough idea of some meaningful or productive things I’d like to do, I often end up sitting on the couch watching something on YouTube or scrolling through Twitter.</p><p>On weekdays, when there’s little time for anything unrelated to work, I imagine all of the great, interesting things I could be doing <em>if I only had more free time</em>.</p><p>“Not to worry”, I tell myself. “When the weekend comes along I’ll do everything I’ve been thinking about and wanting to do during the week”.</p><p><strong>But it never</strong> (well, rarely) <strong>works out this way</strong>.</p><p>Why is this? And what, if anything, can be done about it?</p><p>I’ve been mulling over this question for a while. This article is an attempt to answer it by bringing together some research and ideas from psychology. None of these ideas are my own (and please let me know if you see anything needing correction) but I’ve found them to be fascinating and useful in providing some explanations for this problem, especially once linked together.</p><p>If procrastination on weekends is a problem you suffer from, perhaps they’ll be useful — or at least thought-provoking — to you too.</p><h3>Scarcity</h3><p>One psychological explanation for the problem of weekend procrastination could be that it’s in our nature to place more value on those things that are rare and limited — in this case, <em>time</em>.</p><p>In the midst of the work week, free time is rare and therefore more valuable and desired. However, when holidays and weekends come along, suddenly free time is a plentiful commodity, and not nearly as valuable. So we squander it and take it for granted.</p><p>This is known as the <a href="https://en.wikipedia.org/wiki/Scarcity_(social_psychology)">Scarcity</a> principle in social psychology:</p><blockquote>Simply put, humans place a higher value on an object that is scarce, and a lower value on those that are in abundance. For example diamonds are more valuable than rocks because diamonds are not as abundant.</blockquote><p>Our tendency to place relatively higher value on those things we perceive to be scarce has long been understood and exploited by advertisers. Sales, “limited time offers”, and limits on the number of items per customer are all examples of the scarcity principle in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*eO6fK1g1_RvROrMuCM5QLQ.jpeg" /><figcaption>The scarcity principle in action</figcaption></figure><p>While I believe the scarcity principle plays a part in weekend procrastination, I’ve also come to believe that there is more to the problem than just this.</p><h3>The Paradox of Choice</h3><p>At times I’ve become aware of my procrastination as it’s happening. During these times I’ve made an effort to pay attention to my thoughts in an attempt to better understand what’s going on. What characterises these thoughts is something like <strong>debate and indecision. </strong>I’m cycling over all of the possible things that I could do and attempting to prioritise them according to which are most important right now, <em>all things considered</em>.</p><p>The feeling associated with this pattern of thinking is not exactly pleasant. It could best be described as low-grade anxiety. Apparently my response to this is to revert to relatively mindless activities like watching YouTube videos, which provide some short-term relief. This temporarily suppresses (but ultimately, seems to worsen) a vague, dissatisfied, guilty feeling in the back of my mind. The feeling that <em>I’m not doing all that I could be doing</em>.</p><p>So it’s not exactly that I’m devaluing the greater amount of free time available on the weekend. What seems to be happening is that I’m getting <strong>overwhelmed by the number of possibilities it offers</strong>.</p><p>This is a strange idea. More possibilities and greater freedom is always a <em>good</em> thing, right? Who, if asked, would say they would prefer fewer choices in life?</p><p>Reality isn’t this simple it seems. There is evidence that <a href="https://www.pbs.org/newshour/economy/is-the-famous-paradox-of-choic">excessive choice is paralysing and counter-productive</a>.</p><p>This is from Barry Schwartz, author of a book called <strong><em>The Paradox of Choice — Why More is Less:</em></strong></p><blockquote>… there is evidence in the real world that reducing options increases sales. […] First, a large retailer of office supplies reduced the number of options offered in its print catalog in many product categories. It did this not because of the research on too much choice, but to save money on production and postage. It assumed that the change would lead to reduced sales, but hoped that production and distribution savings would outpace sales losses. What the company found was that <strong>in virtually every category in which options had been reduced, sales increased</strong>. [emphasis added]</blockquote><p>Here’s <a href="http://www.bemanaged.com/the-surprising-paradox-of-choice-in-401k-plan/">another study</a> showing that the more retirement plan options you offer employees, the less likely they are to participate in any of them:</p><blockquote>Sheena and her team found that as more choices are made available to the consumer (and perhaps you could relate to this) three things happen:</blockquote><blockquote>1. Folks procrastinate even when it goes against their best self-interest</blockquote><blockquote>2. They’re more likely to make worse choices (worse medical choices, financial choices, et cetera)</blockquote><blockquote>3. They’re more likely to make choices that leave them less satisfied</blockquote><p>What seems to happen is that as the number of the choices being offered ramps up, people increasingly choose to <em>avoid making a decision altogether</em>, despite this not being in their best interest.</p><p>This seems to me to bear a striking resemblance to the problem of procrastination on weekends.</p><p>To avoid the paralysing anxiety of choosing between so many possibilities, I frequently avoid making a decision altogether, and revert to comparatively easy, mindless activities. The irony of course is that by being unwilling to exclude <em>some</em> possibilities (i.e. to make a <a href="https://think-legacy.com/2013/10/14/root-word-decision/">decision</a>, technically speaking), <em>all</em> possibilities are effectively excluded.</p><p>So, if too much choice is paralysing and anxiety-inducing, it seems like a reasonable strategy could be to bring about the opposite. That is, to <strong>intentionally limit the choices available</strong>.</p><h3>Combatting Chaos</h3><p>This strategy seems to be in line with advice given by Jordan B. Peterson, a professor of psychology at the University of Toronto, to <a href="https://www.youtube.com/watch?v=OoA4017M7WU">people attempting to discipline themselves</a>. One of his suggestions is to start to use a calendar to plan out your days, and not to tyrannise yourself with it, but use it to schedule the kind of day that would be good for you and that you could realistically follow through with.</p><p>In other words, Dr. Peterson’s suggestion is to <strong>combat overwhelming chaos, complexity and possibility </strong>with<strong> voluntarily-imposed structure and constraint</strong>. Constraint and structure are the opposite of freedom and possibility — they restrict what you can do. Which, somewhat counter-intuitively, is the right response <em>when your problem is too much freedom</em>.</p><p>When your options are relatively limited by your environment, it’s easier to see which one is best, given the circumstances.</p><h3>Constraints in Coding</h3><p>When I was at university studying for a Computer Science degree, I was given an assignment to create a program using assembly language. Assembly language is a very low-level programming language, meaning it is much easier for machines to “read” than for humans. I’d never used assembly language before, and found it to be incredibly constraining compared to the modern programming languages I was used to, like Java and Python.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/492/1*2ErCwn816HX_FoEUuR6kgA.png" /><figcaption>An example of assembly code</figcaption></figure><p>However, rather than being frustrated by this, I found the challenge of building the required program to be liberating and engaging. It felt as though it unlocked the best of my problem-solving abilities. It was enormously satisfying.</p><p>(As an aside I would imagine this is the same feeling “inquisitive computer programmers” get when finding creative ways to bypass software and hardware security measures that have been specifically designed to keep them out.)</p><p>I still remember the surprise I felt by this realisation at the time, despite it being almost ten years ago. How could it be that the task of writing a program in such a primitive language was so enjoyable? How did that make sense?</p><p>It seemed to be a paradox:<strong> operating under more limitations was liberating rather than stifling</strong>.</p><h3>The Effect of Constraints on Creativity</h3><p>An explanation of this paradox that seems to fit is that <em>creativity itself requires a constrained problem space in order to completely manifest.</em></p><p>That is, in order for one’s creative potential to reveal itself, it first needs to be presented with a problem that is “worthy of it”, one that <em>requires</em> it.</p><p>This same phenomenon can be seen in any number of creative pursuits. Artists, it seems, produce some of their best work when placed under harsh constraints. Michelangelo’s famous statue of David falls into this category. His contract required that it be finished in two years and specified both how it should look and how it should be positioned.</p><p>Interestingly, artists also frequently <em>place restrictions on themselves voluntarily.</em> Presumably they too find such additional constraints liberating.</p><p>Some examples of deliberately restrictive mediums that come to mind (and I’m sure you can think of others): haiku, song lyrics, poetry in general, short stories, 48 hour film challenges, single-take films (<a href="https://en.wikipedia.org/wiki/Victoria_(2015_film)"><em>Victoria</em></a><em> </em>is one I’d recommend), “found-footage” films and modern pixel-art video games.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*nx-jQCWDm21zD-Om-qf3og.gif" /><figcaption>Isometric pixel art, another example of a constrained format — By Propeterson (Own work) [<a href="https://creativecommons.org/licenses/by-sa/4.0">CC BY-SA 4.0</a>], via Wikimedia Commons</figcaption></figure><p>Bob Sutton, Professor of Organizational Behavior at Stanford business school, writes with regards to the research into <a href="https://medium.com/stanford-d-school/want-some-creativity-crank-up-the-constraints-5728a988a635">constraints and creativity</a>:</p><blockquote>Research on creativity and constraint demonstrates that, when options are limited, people generate more, rather than less, varied solutions — <strong>apparently because their attention is less scattered</strong>. [emphasis added]</blockquote><h4>Imaginative Play</h4><p>In a similar vein, it has been demonstrated that toddlers are more creative in their play sessions when the number of toys available to them is limited.</p><p>Michelle Imwalle from the University of Toledo in Ohio <a href="http://utdr.utoledo.edu/cgi/viewcontent.cgi?article=1566&amp;context=graduate-projects">conducted a study</a> where toddlers were allowed to play with either four or sixteen toys for up to 30 minutes. Their quality of play was then measured for each session, defined in terms of incidences, duration and variety of play.</p><p>The results were as follows:</p><blockquote>RESULTS: When presented with fewer toys in their environment, participants had fewer incidences of toy play, longer durations of toy play, and more manners of play with each toy. Only the latter was statistically significant.</blockquote><blockquote>CONCLUSIONS: The findings from this study suggest that the number of toys present in the environment can affect a toddler’s quality of play. This study shows that <strong>by providing fewer toys in the environment</strong>, toddlers are able to engage in longer periods of toy play with a single toy, <strong>which allows them to focus on the toy at hand to explore and play more creatively with the toy</strong>.</blockquote><blockquote>[emphasis added]</blockquote><p>The results of this study are noteworthy, I think, because they’re <strong>counter-intuitive, </strong>much like the “Paradox of Choice” examples from earlier. That is, you would be forgiven for thinking that the variety and creativity of toddlers’ play would be increased by providing them with <em>more</em> toys, not fewer.</p><h4>Brain Drain</h4><p>In the same study, the author makes reference to another important contributing factor to the quality of toddler’s play: the impact of distractions in their environment.</p><blockquote>[A study] conducted by Schmidt and colleagues (2008) examined the attention to play in 12-, 24-, and 36–month-old children. These children played with toys for 30 minutes while the television game show Jeopardy! played in the background and for 30 minutes with the television off. <strong>In the television condition, there was less play in general, shorter play episodes, and shorter episodes of focused attention to the toys.</strong> Researchers found that background television disrupted toy play <strong>even when children paid little attention to it</strong>.</blockquote><blockquote>[emphasis added]</blockquote><p>What’s particularly surprising here is that even the <em>mere presence</em> of the distracting stimuli (a television in this case) was enough to impact the quality of play. This was the case <em>even when the children appeared to be successfully resisting it</em>.</p><p>Although toddler’s ability to maintain selective attention is still under development (as the author points out), it’s interesting to consider the possibility that adults, too, could be affected in much the same way.</p><p>Could it be that the mere existence of attractive distractions in your environment affects your quality of work - even when you apparently succeed in resisting them?</p><p>Recent research indicates that this is indeed the case.</p><p>Here’s an excerpt from a 2017 study titled “<strong>Brain Drain: The Mere Presence of One’s Own Smartphone Reduces Available Cognitive Capacity</strong>” (the <a href="http://www.journals.uchicago.edu/doi/full/10.1086/691462">full text</a> of which is freely available online and I would highly recommend):</p><blockquote>In this research, we test the “brain drain” hypothesis that the <strong>mere presence of one’s own smartphone may occupy limited-capacity cognitive resources</strong>, thereby leaving fewer resources available for other tasks and undercutting cognitive performance. Results from two experiments indicate that even when people are successful at maintaining sustained attention — as when avoiding the temptation to check their phones — the mere presence of these devices reduces available cognitive capacity. [emphasis added]</blockquote><p>The researchers tested if simply varying the prominence of participant’s smartphones (a common source of distractions, as we all know) would affect their cognitive ability.</p><p>Participant’s performance on cognitively demanding tasks was tested under three conditions:</p><ol><li>With their smartphone visible on their desk</li><li>With their smartphone out of sight in their pocket or bag</li><li>With their smartphone in a separate room</li></ol><p>In all three cases the smartphones were set to be completely silent — i.e. no sounds or vibrations.</p><p>The results indicated that the <em>mere presence</em> of the participant’s smartphones impaired their working memory and fluid intelligence. This was the case even when the participants didn’t use or report thinking about their phone during the test.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5rJXZA7s56o20TLnd55ScA.png" /><figcaption>Source: <a href="http://www.journals.uchicago.edu/doi/full/10.1086/691462">http://www.journals.uchicago.edu/doi/full/10.1086/691462</a></figcaption></figure><p>Consequently, what this experiment suggests is that if you’re someone who typically has your smartphone within reach (so, basically all of us), you can effectively boost your creativity and problem solving ability <em>simply by physically separating yourself from it!</em></p><p>More generally, this study seems to suggest that by <strong>consciously designing and placing yourself in a suitably constrained, distraction-free environment (i.e. a structured environment), you will see a measurable increase in your creativity and problem solving abilities</strong>.</p><h3>The Dark Side of Structure</h3><p>The general theme that is emerging is that constraints and structure have a lot of benefits to offer us. If this is the case, why do we typically have such an aversion to them? Why is it that more freedom and choice are seen as unconditionally and self-evidently good, when there is substantial evidence that this is not always the case? Is this an attitude that’s more characteristic of Western culture?</p><p>These are important questions that are somewhat beyond the scope of this article. Personally, I think my long-held (but hopefully changing) negative attitude towards structure stems partly from my experience at school. Simply put, <em>school felt like prison</em>. Most of the time, I didn’t feel like I was learning anything valuable, and I resented having no choice in the matter.</p><p>This is illustrative of the <strong>dark side of structure in general</strong>. As Dr. Jordan Peterson points out, structure (and process, and culture) has a dual nature. In its positive sense, it offers security, predictability and simplicity. In its negative sense it alienates, oppresses and tyrannises. (If you’re interested in a deep dive into this topic from a psychological and mythological perspective, I would recommend checking out Dr. Peterson’s book <a href="https://www.amazon.com/Maps-Meaning-Architecture-Jordan-Peterson/dp/0415922224">Maps of Meaning</a>).</p><p>Whether or not a particular structure is beneficial overall then depends on whether the ways in which it restricts you are <strong>in line with your goals</strong>. It needs to <em>restrict you in the right ways</em>, providing a more clearly-delineated path for you to follow that takes you closer to where you’d like to be.</p><p>School felt like prison because I couldn’t see how it was helping me achieve anything worthwhile. On top of that, it was externally imposed and completely rigid. I couldn’t change it nor choose to leave. This is not to say that in reality it didn’t offer any value, nor that as a child I was in any way equipped to design a better educational system! Rather, this example is to demonstrate how structure can come to be seen as nothing but tyrannical and oppressive, and more importantly, <em>that these negative aspects of structure need not apply to the ones you create for yourself.</em></p><p>While rejecting all structure is an understandable reaction to painful experiences with oppressive structures, this is not an optimal strategy. It would amount to throwing yourself into a sea of overwhelming possibility, and all of the anxiety that will follow. Rather, there’s more utility in adopting a <em>more comprehensive view of structure</em>, one that acknowledges its positive aspects — and can therefore take advantage of them.</p><p>As an independent adult, you have a large amount of freedom to design and inhabit structures that are aligned with your goals, and to modify them when necessary. With some care it’s possible to take advantage of the many benefits structure can offer you without having their negative aspects manifest.</p><h3>Goals and Values</h3><p>There is another topic that can’t be meaningfully separated from any discussion about structure that has only been mentioned in passing so far. This is the question of your goals and values. With this article I’ve made the assumption that you already have some goals, it’s just that you’re struggling to make much progress with them. However, I will touch on this topic briefly here because clarifying your goals is so important for putting these ideas into practise effectively.</p><p>The reason why goals and values can’t be separated from structure is because any structure, by its nature, <em>values some things over others</em>, and promotes the achievement of <em>some goals over others</em>. It might not be immediately obvious what these are but you can infer them by looking at <em>what the structure leaves out</em>.</p><p>For example, tennis lessons don’t typically include any instruction on how to ride a motorbike. From this we can reasonably infer that someone attending tennis lessons places higher value on improving their tennis game over learning to ride a motorbike (or an infinite number of other activities) — at least while they’re at the tennis lesson.</p><p>Likewise, tennis lessons promote the attainment of some goals over others. For example, they promote improved physical fitness, better coordination and better chances of winning in games against friends over furthering your education, becoming a better golfer, or doing charitable work.</p><p>What this means when it comes to designing structures for your life is that it’s first necessary to carefully think through (and ideally <em>write down</em>) what it is you value and what important goals you would like to achieve. This is because the degree to which the structures you inhabit are out of alignment with these goals and values will determine <em>how oppressive they feel. </em>This will in turn determine how likely you are to resist them or discard them entirely.</p><p>There are many resources available on effective goal setting, some of which I have included as recommendations at the end of the article. Even if you already have some goals it can still be worthwhile to review them and flesh them out further. This might also result in you coming up with new ones entirely. This is okay and will naturally provide you with additional motivation.</p><h3>Putting it all Together</h3><p>So what does all of this research mean for procrastination? Let’s recap:</p><ul><li>The Paradox of Choice suggests that too many options will result in either no decisions (paralysis) or poor decisions.</li><li>Research into the link between constraint and creativity shows that creativity is maximised and attention is most focused when options are relatively limited. This seems to be as true for artists as it is for toddlers.</li><li>Finally, the mere presence of attractive distractions (such as smartphones) measurably impacts working memory and fluid intelligence, even when these distractions are successfully resisted.</li></ul><p>Given all of this, it starts to become clear why free time at home on the weekend presents such a challenge to getting any kind of creative work done. This environment—both in terms of its location and the time available — comes with an almost unlimited number of possibilities and distractions built-in. To the degree to which these are a factor in procrastination, it seems reasonable to think that <strong>consciously designing and placing yourself into a more constrained environment will have massive benefits on your productivity</strong>.</p><p>Or to put it differently:</p><blockquote>Inhabiting an environment containing fewer options and distractions, that is aligned with one or more of your goals, will maximise your creativity, fluid intelligence and focus while reducing your anxiety and tendency to procrastinate.</blockquote><p>This is useful to know but still somewhat abstract. How might this translate down into <strong>concrete actions</strong>?</p><p>One example has already been mentioned. That is Dr. Jordan Peterson’s suggestion to <strong>use a calendar</strong> (e.g. the Google or Apple Calendar app on your phone) to schedule the kind of day you would like to have and that would be good for you — and then to stick to it. As Dr. Peterson points out, it’s necessary to <em>negotiate with yourself </em>to find out what percentage of your time you could reasonably devote to necessary commitments (e.g. chores) such that you’ll still follow your schedule. This might not be much time at first, and that’s okay. It will increase over time with practise.</p><p>Another example straight from the “Brain Drain” experiments is to <strong>physically separate yourself from attractive distractions</strong> (such as your smartphone and the TV) during the blocks of time you have dedicated to your important creative work. One form this could take is to work from a cafe, leaving your smartphone at home or temporarily swapping it for a basic feature phone for use in emergencies.</p><p>This separation can also take a more digital form. If your creative work takes place on your laptop and you find yourself tempted to browse social media or news sites, there are ways of temporarily blocking these distracting sites altogether. A quick search revealed <a href="https://chrome.google.com/webstore/detail/stayfocusd/laankejkbhbdhmipfmgcngdelahlfoji?hl=en">this site-blocking extension</a> for the Chrome browser.</p><p>Another way to put this into action is to book meaningful social activities in advance, such as attending events with friends, attending a <a href="https://www.meetup.com/">meet-up</a> based on one of your interests or joining a sports team. These have the added bonus of having <em>social constraints </em>built-in. Leveraging peer pressure can be powerful.</p><h4>Preliminary Results</h4><p>In any case, putting these ideas into practise will be an ongoing journey. Here’s a report of some of the results I’ve had so far.</p><p>I have had mostly positive results from scheduling my time with a calendar. I have found that at the very least it has been helpful for providing me with a decent plan to fall back on when my willpower is fading, as an alternative to more impulsive activities (e.g. watching TV).</p><p>It is much easier to do healthier activities when I’m not faced with the daunting task of coming up with an ideal plan “in real time”, but have one prepared ahead of time. I’ve found the best time to do this preparation is when willpower and clarity is highest. For me this is early in the morning or right before bed.</p><p>The calendar hasn’t been a silver bullet however.</p><p>There are times when just the fact of having scheduled activities hasn’t been <em>sufficiently constraining</em> — they have been too easy to rationalise away or endlessly delay. This is more often the case on weekends; I find them much easier to follow during the work week. On weekends, the best results I have gotten from the calendar are from scheduling things with other people — i.e. commitments that <em>aren’t so easily broken</em>.</p><p>Interestingly, having even one of these “unbreakable” activities scheduled seems to have a positive effect on my weekend productivity overall. I don’t exactly know why this is. I suspect it is for the same reason that following a schedule is easier on work days, with their built-in constraints and relatively limited free time.</p><p>To recap, if there’s one concrete action I’ve discovered so far for putting weekends to better use it’s this: <strong>schedule activities in advance that you know will be meaningful to you, ideally with other people, that will incur personal consequences if broken off</strong>.</p><p>Once you are in that constrained environment that you have set up for yourself ahead of time, things become easy. The meaningful/productive activity will be natural and automatic.</p><p>That’s all for now.</p><p>If this article struck a chord with you, or you have further ideas or feedback, I’d love to hear about it. Drop me a comment below.</p><h3>Resources and References</h3><h4>“The Paradox of Choice”</h4><p><a href="https://www.ted.com/talks/barry_schwartz_on_the_paradox_of_choice">TED Talk — Barry Schwartz: The paradox of choice</a></p><p><a href="https://en.wikipedia.org/wiki/The_Paradox_of_Choice">The Paradox of Choice — Why More Is Less</a></p><p><a href="http://www.bemanaged.com/the-surprising-paradox-of-choice-in-401k-plan/">The Surprising Paradox of Choice in 401k Plans</a></p><p><a href="http://freakonomics.com/2009/12/02/is-the-paradox-of-choice-not-so-paradoxical-after-all/">Is the Paradox of Choice Not So Paradoxical After All?</a></p><p><a href="http://www.swarthmore.edu/SocSci/bschwar1/self-determination.pdf">Self-Determination — The Tyranny of Freedom by Barry Schwartz</a> (not directly referenced here but a remarkable essay with similar themes nonetheless)</p><h4>Constraints and Creativity</h4><p><a href="https://medium.com/stanford-d-school/want-some-creativity-crank-up-the-constraints-5728a988a635">Want Some Creativity? Crank-up the Constraints</a></p><p><a href="https://www.fastcompany.com/3027379/the-psychology-of-limitations-how-and-why-constraints-can-make-you-more-creative">Proof That Constraints Can Actually Make You More Creative</a></p><p><a href="http://utdr.utoledo.edu/cgi/viewcontent.cgi?article=1566&amp;context=graduate-projects">Does the number of toys in the environment influence play in toddlers? Michelle L. Phlipot</a></p><h4>Distractions and Cognitive Ability</h4><p><a href="http://www.journals.uchicago.edu/doi/full/10.1086/691462">Brain Drain: The Mere Presence of One’s Own Smartphone Reduces Available Cognitive Capacity</a></p><h4>Goal Setting</h4><p><a href="https://www.wikihow.com/Set-Goals">How to Set Goals — WikiHow</a></p><p><a href="https://www.amazon.com/Create-Your-Own-Future-Unlimited/dp/0471718521">Create Your Own Future — Brian Tracy</a></p><p><a href="https://selfauthoring.com/future-authoring.html">Future Authoring programme (paid but affordable)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d11dc0f4e741" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Distraction-Free Reading for your Android app — Part I]]></title>
            <link>https://medium.com/@kiwiandroiddev/distraction-free-reading-for-your-android-app-part-i-242f77466175?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/242f77466175</guid>
            <category><![CDATA[pocket]]></category>
            <category><![CDATA[material-design]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[android]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Wed, 05 Jul 2017 10:04:18 GMT</pubDate>
            <atom:updated>2017-07-05T10:07:56.063Z</atom:updated>
            <content:encoded><![CDATA[<p>One app that I’ve had on every phone I’ve owned since 2013 is <a href="https://play.google.com/store/apps/details?id=com.ideashower.readitlater.pro&amp;hl=en">Pocket</a>. If you haven’t heard of it, it lets you save any articles you come across online and read them later in the app, only with all distracting elements and visual noise (like popups, navigation and ads) removed, and with nicely-formatted text.</p><p>On top of that, all non-essential in-app UI elements, such as the status and navigation bars, fade away as you start reading. It’s basically the closest you’ll get to a paper book on your phone in terms of a focused reading experience:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*lve-9lJnTIEWPLT8GrHHTQ.gif" /><figcaption>Pocket’s Auto-Fullscreen mode in action</figcaption></figure><p>Recently I’ve starting working on an app for StarCraft II strategies. The app is relatively text-heavy and seemed to be a good match for this kind of feature, so I thought I’d have a go at building it.</p><p>Although definitely doable, getting everything to work seamlessly involved a decent amount of reading (and re-reading) of different blog posts and documentation, and a fair bit of trial-and-error. It took a while until certain parts “clicked” — particularly how <a href="http://developer.android.com/reference/android/view/View.html#attr_android:fitsSystemWindows">android:fitsSystemWindows</a> works.</p><h3>Outline</h3><p>This guide aims to make all of that more accessible, and hopefully save you time and frustration if you’re looking to build something similar. It’ll assume no more than a mid-beginner level of experience with Android development.</p><p>We’ll build a Pocket-like distraction-free reading experience with an iterative approach, starting with a basic activity layout, and adding distraction-free features, one at a time.</p><p>Part I (this article) will set up an app with some basic distraction-free features; if you’re an experienced developer with an existing app you might want to jump straight to Part II where we look into <strong>fitsSystemWindows</strong> to implement the more advanced features.</p><p>If you get stuck, there’s a link to the full source code for this part at the end of the article.</p><p>Onward…</p><h3>What we’re going to build</h3><ul><li>A basic article view with a <a href="https://developer.android.com/reference/android/widget/Toolbar.html">Toolbar</a> on top, a translucent system navigation bar and a <a href="https://developer.android.com/reference/android/support/design/widget/FloatingActionButton.html">Floating Action Button</a> (FAB) to make things a bit more interesting.</li><li>When the user scrolls down the article, the Toolbar, system bars and FAB (“<a href="https://www.nngroup.com/articles/browser-and-gui-chrome/">chrome</a>” collectively) will animate away all at once.</li><li>Scrolling up will animate the chrome back in.</li></ul><p><strong>Additional constraints to further reduce distractability:</strong></p><ol><li>The text content should not jump or snap in any way when the chrome animates in or out. Chrome should fade away seamlessly, without disrupting the user.</li><li>It should never be necessary for the user to trigger auto-hiding of chrome in order to read all parts of the article. In other words, it should still be possible to read the entire article even if chrome happened to get stuck in a permanently-visible state (this is actually related to the previous constraint — more on that later).</li></ol><h3>Getting Started</h3><p>Let’s dive in. Open up Android Studio and create a new project with a blank activity.</p><h4>Theme</h4><p>By default your app’s theme will inherit from Theme.AppCompat.Light.DarkActionBar which will automatically add an Action bar/Toolbar to your activity windows. We’re going to want to add the Toolbar to our Activity layout manually to precisely control its placement, so this isn’t what we want. Change your AppTheme to inherit from AppCompat’s <strong>NoActionBar</strong> theme instead:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97fb2fdae922e7e7a66f0a5ea9cd6524/href">https://medium.com/media/97fb2fdae922e7e7a66f0a5ea9cd6524/href</a></iframe><h4>Build Dependencies</h4><p>Since we want a FAB we’ll need to add a dependency on Google’s <a href="https://developer.android.com/training/material/design-library.html">Design Support Library</a>. Add this to the dependencies section of your app module’s build script:</p><p>app/build.gradle:</p><pre>compile <strong>&#39;com.android.support:design:25.3.1&#39;</strong></pre><p>(Where 25.3.1 is the same version as the other support libraries in your build script — this might differ in your generated project)</p><h4>Strings</h4><p>We’ll need some dummy article content for our reader activity, and enough of it to extend outside of the screen to make the view scrollable.</p><p>Grab some <a href="http://www.lipsum.com/feed/html">Lorem ipsum text</a> and paste it into your strings file as a new string resource:</p><p>app/src/main/res/strings.xml:</p><pre>&lt;<strong>string name=&quot;lorem&quot;</strong>&gt;Lorem ipsum dolor sit amet ... <strong>&lt;/string&gt;</strong></pre><p>(This is also a good time to change your app_name string to something else if you feel so inclined).</p><h3>Initial Activity Layout</h3><p>Open up activity_main.xml and replace whatever’s in there with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b2f2ed3ae7107908dab5bbc15783114/href">https://medium.com/media/1b2f2ed3ae7107908dab5bbc15783114/href</a></iframe><h4>A quick refresher on FrameLayout</h4><p>So what’s going on here is we have two full-size (i.e. width and height set to match_parent) view groups stacked on top of each other inside a root <a href="https://developer.android.com/reference/android/widget/FrameLayout.html">FrameLayout</a>. The first view group is for the article text (the NestedScrollView) and the second is for the UI chrome (the inner FrameLayout).</p><p>Due to their order in the root FrameLayout, the UI chrome layer will always be drawn over the text layer. One way to remember how FrameLayout works is to imagine it painting Views in the order they’re listed— the last-mentioned View will always be painted last, over top of everything else.</p><p>Now you might be thinking this setup would result in the TextView being obscured by the Toolbar, violating constraint #2 from earlier. You would be right. To avoid that, the TextView’s top margin has been set to the default actionbar height, ensuring it will appear just below the bottom of the Toolbar when the activity first opens.</p><h4>Initial Activity Code</h4><p>There isn’t much code to write at the point, all we need to do is ensure some text is displayed in the Toolbar.</p><p>Open up MainActivity.java and replace the default code with this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14852edb230a13009d88575623736230/href">https://medium.com/media/14852edb230a13009d88575623736230/href</a></iframe><p>This will cause the Toolbar’s title to be whatever you chose for the app_name string.</p><p>If you go ahead and Run (Ctrl+R on Mac) the app now you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*W0FWfRfiPbnq0lG49c4_Lw.png" /><figcaption>Our inappropriately-titled first version</figcaption></figure><p>This isn’t exactly the embodiment of a distraction-free reading experience yet. Let’s start fixing that.</p><h3>Removing Distractions, One Step at a Time</h3><h4>Disappearing FAB</h4><p>It turns out hiding the FAB when the user scrolls is straightforward enough, so let’s start there. Jump back into editing MainActivity in Android Studio and add a new field for the FAB:</p><pre><strong>private </strong>FloatingActionButton <strong>actionButton</strong>;</pre><p>The FAB has an id assigned in the activity’s layout XML, we can use that to find and save a reference to it in onCreate():</p><pre>@Override<br>protected<strong> </strong>void<strong> </strong>onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);<br>    <strong>actionButton = (FloatingActionButton) findViewById(R.id.<em>fab</em>);</strong><br>    setupToolbar();<br>}</pre><p>We can use this reference to hide and show the FAB when needed in code. The next step is to actually do that at the correct times, namely, when the NestedScrollView is scrolled up or down.</p><h4>Listening out for Scroll direction changes</h4><p>NestedScrollView can have an <a href="https://developer.android.com/reference/android/view/View.OnScrollChangeListener.html">OnScrollChangeListener</a> set on it via its aptly-named setOnScrollChangeListener() method. This listener gives us all of the info we need (and then some!) to know whether to hide or show the FAB via its single callback method:</p><pre>void onScrollChange (NestedScrollView v, <br>                int scrollX, <br>                int scrollY, <br>                int oldScrollX, <br>                int oldScrollY)</pre><p>We happen to know that horizontal scrolling isn’t possible in our layout, so we can ignore scrollX and oldScrollX.</p><p>scrollY and oldScrollY contain the absolute scroll positions for the view. What we’re interested in is not so much absolute values, but when the scroll <strong>direction</strong> changes. I.e. when the user begins scrolling down initially, and when they go from scrolling down (possibly intermittently) to scrolling up.</p><p>In other words, we’re interested in when scrollY - oldScrollY (let’s call this yDelta) goes from zero or negative, to something positive, and vice versa.</p><p>This implies storing an oldYDelta somewhere, and then comparing a newly-calculated yDelta against it each time there’s a scroll event. We <em>could </em>store this state in a field in the activity, but activities have a way of accumulating more and more variables and code until they become a confusing mess.</p><p>This is a good opportunity to create a small, reusable class. In Android Studio, create a new abstract class called OnScrollDirectionChangedListener:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9d9367e21ba6bb2e2848b40b890a18ac/href">https://medium.com/media/9d9367e21ba6bb2e2848b40b890a18ac/href</a></iframe><p>This class encapsulates all of the logic and state needed to calculate scroll direction changes and surfaces it through a higher-level, easier-to-use interface — its onStartScrollingDown() and onStartScrollingUp() callback methods.</p><p>Let’s make use of this in MainActivity and see how it looks. Jump back into MainActivity and add a new method called setupScrollView():</p><pre><strong>private void </strong>setupScrollView() {<br>    NestedScrollView scrollView =<br>            (NestedScrollView) findViewById(R.id.<strong><em>nested_scrollview</em></strong>);<br>    <br>    scrollView.setOnScrollChangeListener(<br>            <strong>new </strong>OnScrollDirectionChangedListener() {<br>                @Override<br>                <strong>public void </strong>onStartScrollingDown() {<br>                    <strong>actionButton</strong>.hide();<br>                }<br><br>                @Override<br>                <strong>public void </strong>onStartScrollingUp() {<br>                    <strong>actionButton</strong>.show();<br>                }<br>            });<br>}</pre><p>Add a call to it in onCreate():</p><pre>@Override<br>protected void<strong> </strong>onCreate(Bundle savedInstanceState) {<br>    super.onCreate(savedInstanceState);<br>    setContentView(R.layout.<em>activity_main</em>);<br>    actionButton<strong> </strong>= (FloatingActionButton) findViewById(R.id.<em>fab</em>);<br>    setupToolbar();<br>    <strong>setupScrollView();</strong><br>}</pre><p>That’s all for the FAB. If you run the app (Ctrl+R) now you should find that the FAB shrinks away to nothing when you scroll down, and zooms back into existence when you scroll up. FloatingActionButton is unusual in that it comes with these animations out of the box — a nice touch by the library developers.</p><h4>Disappearing Toolbar</h4><p>Since we have a scroll listener set up, it’s not too much extra work to get the Toolbar to appear and re-appear as well.</p><p>Now we <em>could </em>just set the Toolbar’s visibility to GONE on scroll down, and back to VISIBLE on scroll up, but having visuals instantly pop in and out isn’t a great user experience. Also, it would violate that part in constraint #1 about “chrome fading away seamlessly”.</p><p>No, we can do better. Let’s actually animate it.</p><p>The Toolbar class doesn’t come with built-in animations like FloatingActionButton, so we’ll add our own.</p><p>We will create two new animation XML files in app/src/main/res/anim (create the directory first if it doesn’t exist) — one for animating the Toolbar out of view, and one for bringing it back in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9647fa17c2b0e47e16687202611c127/href">https://medium.com/media/d9647fa17c2b0e47e16687202611c127/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d46d303e79cb6229774e5f9289d1663f/href">https://medium.com/media/d46d303e79cb6229774e5f9289d1663f/href</a></iframe><p>Now jump back to MainActivity and create two new methods for hiding and showing the Toolbar using these animations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc52292252da004884f3d995ff03c971/href">https://medium.com/media/bc52292252da004884f3d995ff03c971/href</a></iframe><p>Note that we have to change the Toolbar’s visibility at the end and beginning of these animations via AnimationListeners. If we don’t do this, they will immediately return to their pre-animation states when the animations end. Remember: just because an animation causes a View to fade out, doesn’t mean the View will <em>stay</em> faded-out :)</p><p>Add calls to these new methods from the same scroll direction callbacks we used earlier for the FAB:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/101a6c34cbda7d6beb7e2c7d84b3e38b/href">https://medium.com/media/101a6c34cbda7d6beb7e2c7d84b3e38b/href</a></iframe><p>Let’s see how it looks now:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*n5iQKUiFzkHFrIcFtIBtBg.gif" /></figure><p>Progress! We’re halfway to building a respectable Pocket clone (well… kindof).</p><p>All that’s left are the system bars — the status bar on top and navigation bar on the bottom.</p><p>We’ll tackle that in Part II by learning about fitsSystemWindows, window flags, decor views and other dark corners of the Android SDK.</p><p>You can find the <a href="https://github.com/kiwiandroiddev/distraction-free-reading-part-1">source code for Part 1 on github</a>.</p><p>Hope this helped, stayed tuned for Part II in this series!</p><h4>Further Discussion</h4><h4>Q: Why not use CoordinatorLayout + AppBarLayout from the design support library to hide the toolbar on scrolls?</h4><p><strong>A:</strong> This is a valid question — the design support library provides an alternative way to do everything we’ve seen in the sample until now with a combination of <a href="http://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.html?utm_campaign=adp_series_coordinatorlayoutbehavior_021716&amp;utm_source=medium&amp;utm_medium=blog">CoordinatorLayout</a>, <a href="https://developer.android.com/reference/android/support/design/widget/AppBarLayout.html">AppBarLayout</a>, <a href="https://developer.android.com/reference/android/support/v4/widget/NestedScrollView.html">NestedScrollView</a> and custom <a href="https://developer.android.com/reference/android/support/design/widget/CoordinatorLayout.Behavior.html">Behaviors</a>. It’s good to use existing solutions where possible to avoid reinventing the wheel, and in fact this is where I started. Ultimately however, I moved away from using CoordinatorLayout for a number of reasons.</p><p>CoordinatorLayout + AppBarLayout gives you a lot of power and options for animating the Toolbar in response to scroll events. This includes having it scroll out of view in direct relation to scrolls on the text, rather than hiding with a fixed-duration animation. This is a nice effect, and if you want this it does probably make sense to use the library.</p><p>However, you’ll notice that Pocket opts for a fixed-duration Toolbar animation. I think this makes sense given the goals for their app: if you want to hide all non-essential UI elements in an non-distracting way, it makes sense to have them <strong>all hide together at the same speed</strong>. In addition, for reading apps like this it makes sense to <strong><em>hide chrome as soon as possible once the user has indicated their interest in the text via scrolling</em></strong>, rather than letting it linger.</p><p>As we’ve seen, setting up a scroll listener to run a fixed-duration animation on the Toolbar yourself is straightforward and requires very little code. It’s easy to see what’s going on, even to developers new to the platform.</p><p>I don’t believe the same can be said about the CoordinatorLayout Behavior approach. If you’re anything like me and other Android developers I’ve worked with, you’ll find yourself referring back to documentation to understand the effect of the different app bar layout behaviors each time you encounter them. The names aren’t self-documenting.</p><p>If and when you need to implement more complex animations in your layout in response to scroll events, the extra power offered by the library might be exactly what you need. For simple cases like this however, the trade-off in complexity and readability probably isn’t worth it.</p><p>Remember the <a href="https://en.wikipedia.org/wiki/KISS_principle">KISS</a> and <a href="https://en.wikipedia.org/wiki/You_aren%27t_gonna_need_it">YAGNI</a> principles.</p><h4>Q: What about just using a custom CoordinatorLayout Behavior to hide the FAB?</h4><p>Yes that can be done — the recommended approach was to use CoordinatorLayout as your root layout, create a new <a href="https://github.com/ianhanniballake/cheesesquare/blob/92bcf7c8b57459051424cd512a032c12d24a41b3/app/src/main/java/com/support/android/designlibdemo/ScrollAwareFABBehavior.java">ScrollAwareFABBehavior</a> class that extends FloatingActionButton.Behavior, setting it as the FAB’s layout_behavior in XML, and this will work fine.</p><p>That is, it <em>did</em> work fine until v25.1.0 of the Design Support Library. This version <a href="https://issuetracker.google.com/issues/37130108">introduced a breaking change</a> whereby Views whose visibility is GONE would no longer received nested scroll events. This is true for FABs after hide() is called, meaning your FAB would hide once and never reappear.</p><p>The <a href="https://github.com/chrisbanes/cheesesquare/compare/master...ianhanniballake:scroll_aware_fab">recommended solution/workaround</a> was to create a new Behavior for the scrolling view itself to iterate through all of the CoordinatorLayout’s child Views, checking if they’re FABs via runtime type-checking, and then animating them if they are.</p><p>Even ignoring potential performance issues of this approach, I found this to be a needlessly complex and opaque solution when contrasted with simply calling hide() or show() on the FAB in a scroll listener.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=242f77466175" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit testing HAPI-FHIR — how to compare model objects]]></title>
            <link>https://medium.com/@kiwiandroiddev/unit-testing-hapi-fhir-how-to-compare-model-objects-5066cf7a701?source=rss-7b3a2c1f2f16------2</link>
            <guid isPermaLink="false">https://medium.com/p/5066cf7a701</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[fhir]]></category>
            <category><![CDATA[jvm]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Matt Clarke]]></dc:creator>
            <pubDate>Tue, 01 Nov 2016 06:14:00 GMT</pubDate>
            <atom:updated>2016-11-01T22:11:31.544Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re a Java/JVM developer working in the healthcare domain today, chances are you’re using the popular open-source <a href="https://github.com/jamesagnew/hapi-fhir">HAPI-FHIR</a> library to work with <a href="https://www.hl7.org/fhir/overview.html">FHIR</a> resources (domain objects such as Patient, Medication, AllergyIntolerance etc.)</p><p>Say you have some code that builds a FHIR model based on some input. To test this code, you might write a unit test that compares its output to an expected FHIR model that you create in your test. Like this (note: incoming <a href="https://kotlinlang.org/">Kotlin</a> code samples):</p><pre>val actualObservation = Observation().setValue(QuantityDt(5.0))<br>val expectedObservation = Observation().setValue(QuantityDt(5.0))<br><br>assertThat(actualObservation).isEqualTo(expectedObservation)</pre><p>If so, you might have been surprised by the output:</p><pre><em>java.lang.AssertionError: <br>Expecting:<br> &lt;”Observation[id=null] (Observation@6b54655f)”&gt;<br>to be equal to:<br> &lt;”Observation[id=null] (Observation@69637b10)”&gt;<br>but was not.</em></pre><p>This is because FHIR resource classes don’t override the equals() method, so equals() performs an identity comparison — typically not what you want in your unit tests.</p><p>One way to get around this could be to compare fields manually. This isn’t <em>too</em><strong> </strong>bad if the fields are primitive types, but a lot of FHIR resources have other FHIR resources as fields, resulting in this kind of abomination:</p><pre>val actualObservation =   Observation().setValue(QuantityDt(5.0).setUnit(&quot;kgs&quot;))<br>val expectedObservation = Observation().setValue(QuantityDt(5.0).setUnit(&quot;kg&quot;))<br><br>assertThat((actualObservation.<em>value </em>as QuantityDt).<em>value</em>).isEqualTo(<br>        (expectedObservation.<em>value </em>as QuantityDt).<em>value</em>)<br>assertThat((actualObservation.<em>value </em>as QuantityDt).<em>unit</em>).isEqualTo(<br>        (expectedObservation.<em>value </em>as QuantityDt).<em>unit</em>)</pre><p>This isn’t exactly scalable and has a lot of problems, not least of which it doesn’t check that all fields match (what if your production code is incorrectly setting a value for an unexpected field?)</p><h3>There is a Better Way (kind of…)</h3><p>We can create a pseudo-equals function that can compare all of the fields of any two FHIR resources by leveraging HAPI-FHIR’s JSON encoding functionality:</p><pre>fun assertFhirResourcesAreEqual(expected : IBaseResource,<br>                                actual : IBaseResource) {<br>    val jsonParser = FhirContext.forDstu2().newJsonParser()<br>    val actualAsJson = jsonParser.encodeResourceToString(actual)<br>    val expectedAsJson = jsonParser.encodeResourceToString(expected)</pre><pre>    assertThat(actualAsJson).isEqualTo(expectedAsJson)<br>}</pre><p>(Side-note: FhirContext is a heavy-weight object and should definitely <strong>not</strong> be recreated each time this function is run — I put it in here for demonstration purposes. You will want to move it to the constructor of your test class, or some other central location)</p><p>Updated unit test:</p><pre>val actualObservation =   Observation().setValue(QuantityDt(5.0).setUnit(&quot;kgs&quot;))<br>val expectedObservation = Observation().setValue(QuantityDt(5.0).setUnit(&quot;kg&quot;))<br><br>assertFhirResourcesAreEqual(expectedObservation, actualObservation)</pre><p>And output for the new test:</p><pre>org.junit.ComparisonFailure: <br>Expected :”{“resourceType”:”Observation”,”valueQuantity”:{“value”:5.0,”unit”:”kg”}}”<br>Actual :”{“resourceType”:”Observation”,”valueQuantity”:{“value”:5.0,”unit”:”kgs”}}”<br> &lt;Click to see difference&gt;</pre><p>(As a bonus, IntelliJ will give you a nice visual diff, highlighting the offending field values)</p><p>Happy FHIR unit-testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5066cf7a701" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>