<?xml version="1.0" encoding="UTF-8"?>
<?xml-stylesheet type="text/xsl" media="screen" href="/~d/styles/atom10full.xsl"?><?xml-stylesheet type="text/css" media="screen" href="http://feeds.feedburner.com/~d/styles/itemcontent.css"?><feed xmlns="http://www.w3.org/2005/Atom">

  <title><![CDATA[Terse Systems]]></title>
  
  <link href="http://tersesystems.com/" />
  <updated>2013-05-13T23:20:00-07:00</updated>
  <id>http://tersesystems.com/</id>
  <author>
    <name><![CDATA[Will Sargent]]></name>
    <email><![CDATA[will.sargent@gmail.com]]></email>
  </author>
  <generator uri="http://octopress.org/">Octopress</generator>

  
  <atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="self" type="application/atom+xml" href="http://feeds.feedburner.com/tersesystems/JkwO" /><feedburner:info xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0" uri="tersesystems/jkwo" /><atom10:link xmlns:atom10="http://www.w3.org/2005/Atom" rel="hub" href="http://pubsubhubbub.appspot.com/" /><feedburner:emailServiceId xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">tersesystems/JkwO</feedburner:emailServiceId><feedburner:feedburnerHostname xmlns:feedburner="http://rssnamespace.org/feedburner/ext/1.0">http://feedburner.google.com</feedburner:feedburnerHostname><entry>
    <title type="html"><![CDATA[Play in Practice]]></title>
    <link href="http://tersesystems.com/2013/04/20/play-in-practice" />
    <updated>2013-04-20T14:20:00-07:00</updated>
    <id>http://tersesystems.com/2013/04/20/play-in-practice</id>
    <content type="html"><![CDATA[<p>I gave a talk on Play in Practice at the <a href="http://www.meetup.com/SF-Scala/events/111419142/">SF Scala meetup</a> recently.
Thanks to <a href="http://stackmob.com">Stackmob</a> for hosting us and providing pizza.</p>

<p>I went into describing how to implementing <a href="http://martinfowler.com/bliki/CQRS.html">Command Query Responsibility Segregation</a>
in <a href="http://www.playframework.com/">Play</a>, but there was a fairly long question and answer section about Play as well.
I couldn&#8217;t go into detail on some of the answers and missed some others, so I&#8217;ll fill in the details here.</p>

<h2>Video</h2>

<iframe width="560" height="315" src="http://www.youtube.com/embed/s2GOZpzBwVE?rel=0" frameborder="0" allowfullscreen></iframe>


<h2>Slides</h2>

<iframe src="http://www.slideshare.net/slideshow/embed_code/19312123" width="597" height="486" frameborder="0" marginwidth="0" marginheight="0" scrolling="no" style="border:1px solid #CCC;border-width:1px 1px 0;margin-bottom:5px" allowfullscreen webkitallowfullscreen mozallowfullscreen> </iframe>


<h2>Core API</h2>

<p>The core API is <a href="http://www.playframework.com/documentation/2.1.1/ScalaActions">Action</a>, which take in a
<code>Request</code> and return a <code>Result</code>.  The <code>Request</code> is immutable, but you can
<a href="http://stackoverflow.com/questions/9629250/how-to-avoid-passing-parameters-everywhere-in-play2">wrap it</a> with extra
information, which you&#8217;ll typically do with <a href="http://www.playframework.com/documentation/2.1.1/ScalaActionsComposition">action composition</a>.
2.1.1 introduced EssentialAction, which uses <code>(RequestHeader =&gt; Iteratee[Array[Byte], Result])</code> instead of Action&#8217;s
<code>(Request =&gt; Result)</code> and makes building Filters <a href="http://jazzy.id.au/default/2013/02/16/understanding_the_play_filter_api.html">easier</a>.</p>

<p>Again, Play&#8217;s core is simple.  <a href="http://sadache.tumblr%0A.com/post/26258782102/bitsbout-play2-architecture">About as simple as you can get</a>.</p>

<h2>Streaming</h2>

<p>Streaming is handled by <a href="http://www.playframework.com/documentation/2.1.1/Iteratees">Iteratees</a>, which can be a
confusing topic for many people.  There are good writeups
<a href="http://mandubian.com/2012/08/27/understanding-play2-iteratees-for-normal-humans/">here</a>
and <a href="http://jazzy.id.au/default/2012/11/06/iteratees_for_imperative_programmers.html">here</a>.  <a href="https://github.com/ornicar/lila">lila</a>
is the best application to look at for streaming, especially for sockets and hubs.</p>

<p>Also worth nothing: the Streaming API has changed <a href="http://stackoverflow%0A.com/questions/14141408/playframework-2-0-x-2-1-rc-migration">repeatedly</a>, and is probably still under active
development.  Somehow lila is typically ahead of any mailing list or documentation, so if something breaks in a new
version of Play, then check if lila changed the API interaction recently.</p>

<p>Having good streaming primitives is something that I didn&#8217;t get into that much in the talk, but is still vitally
important to &#8221;<a href="http://arstechnica.com/business/2012/05/say-hello-to-the-real-real-time-web/">real time web</a>&#8221; stuff.</p>

<h2>Templating</h2>

<p>Play comes packaged with its own template language, <a href="https://github.com/spray/twirl">Twirl</a>, but you&#8217;re not required to
use it.  There is an integration into <a href="https://github.com/adetante/play2-scalate">Scalate</a> that gives you Mustache,
Jade, Scaml and SSP.  There&#8217;s also an <a href="https://github.com/guillaumebort/play2-freemarker-demo">example project</a> that
shows how to integrate Play with Freemarker.</p>

<p>One thing that Play doesn&#8217;t address directly is how to set up a structure for page layouts.  Play provides you with index.scala.html and main.scala.html, but
doesn&#8217;t provide you with any more structure than that.  If you set up a header and footer and allow for subdirectories to use their own templates, you can minimize the amount of confusion in the views.</p>

<p>There&#8217;s an example in <a href="https://github.com/wsargent/play20-rememberme/tree/master/app/views/base">RememberMe</a>, and this is the approach that <a href="https://github.com/ornicar/lila">lila</a> takes as well.</p>

<p>Another thing is that Play&#8217;s default project template is intentionally minimal.  If you use Backbone and HTML5 templates,
then a custom <a href="https://github.com/n8han/giter8">giter8</a> template like
<a href="http://prihoda.net/blog/2012/6/17/play-scala-template-with-html5-boilerplate-and-backbonejs.html">mprihoda/play-scala</a> may suit you better.</p>

<h2>JSON</h2>

<p>Play&#8217;s JSON API is very well done, and is a great way to pass data around without getting into the weeds or having to
resort to XML.  It goes very well with case classes.</p>

<p>The documentation isn&#8217;t bad, but Pascal Voitot (the author of play-json) has a series of blog posts that go
the extra mile: <a href="http://mandubian%0A.com/2012/09/08/unveiling-play-2-dot-1-json-api-part1-jspath-reads%0A-combinators/">reading JSON with JsPath</a>, <a href="http://mandubian%0A.com/2012/10/01/unveiling-play-2-dot-1-json-api-part2-writes-format-combinators/">writing JSON formats</a>,
<a href="http://mandubian.com/2012/10/29/unveiling-play-2-dot-1-json-api-part3-json-transformers/">transforming JSON</a>, and
even defining <a href="http://mandubian.com/2012/11/11/JSON-inception/">JSON macros</a>.</p>

<h2>Forms</h2>

<p>Form handling is always painful.  The documentation helps, but really if you want to know how to do validation, using the <a href="https://github.com/playframework/Play20/tree/master/samples/scala/forms">sample forms application</a> is the best way to pick things up.  There are many useful nuggets that aren&#8217;t explicitly discussed in the documentation.  In particular, the ability to make custom constraints is <a href="https://github.com/wsargent/play20-rememberme/blob/master/app/controllers/BaseConstraints.scala">extremely useful</a>.</p>

<h2>Routing</h2>

<p>There&#8217;s only one routing API replacement that I know of, <a href="https://github.com/teamon/play-navigator">Play Navigator</a>, a
routing DSL for <a href="http://codetunes.com/2012/scala-dsl-tutorial-writing-web-framework-router">REST services</a>.  However, you can use
custom data types in the routing table using <a href="http://www.playframework.com/documentation/api/2.1.0/scala/index.html#play.api.mvc.QueryStringBindable">QueryStringBindable</a> and <a href="http://julien.richard-foy.fr/blog/2012/04/09/how-to-implement-a-custom-pathbindable-with-play-2/">PathBindable</a>, and save yourself some &#8220;string2foo&#8221; conversion.</p>

<h2>Optimization</h2>

<p>Optimizing Play can be tricky, for a couple of reasons.</p>

<p>The first reason is that it&#8217;s easy to think you&#8217;re optimizing something that you&#8217;re not.  Sadek Drobi gives a nice
<a href="http://sadache.tumblr.com/post/42351000773/async-reactive-nonblocking-threads-futures-executioncont">overview</a>,
and there&#8217;s an exhaustive <a href="https://groups.google.com/d/topic/play-framework-dev/30MqnKDp0Fs/discussion">mailing list discussion</a> about asynchronous code in Play.</p>

<p>The second bit of trickiness is that Play 2.0 and Play 2.1 do not use Akka in the same way.</p>

<p>Play 2.0 uses Akka for <a href="http://www.playframework.com/documentation/2.0/AkkaCore">almost everything</a> internally.</p>

<p>Play 2.1 does <em>not</em> use Akka to handle incoming requests, or iteratees, or internal code.  It uses <code>scala.concurrent.Future</code> instead with its own <a href="http://www.playframework.com/documentation/2.1.0/ThreadPools">thread pools</a>.</p>

<p>Play 2.1 also uses a default thread pool, which <em>is</em> Akka backed &#8211; <code>ActorSystem("play")</code> &#8211;
and is used for the application code, i.e. the stuff inside <code>Action</code>.</p>

<p>This is important, because blog posts like James Ward&#8217;s <a href="http://www.jamesward.com/2012/06/25/optimizing-play-2-for-database-driven-apps">Optimizing Play 2 for Database Driven Apps</a> are <em>only</em> applicable to Play 2.0,
not 2.1.  For 2.1, use the <a href="http://www.playframework.com/documentation/2.1.0/ThreadPools">thread pools</a> documentation.</p>

<p>In addition to the &#8220;play&#8221; actor system, there&#8217;s a Play Akka plugin.  The Akka plugin is actually packaged with
Play itself, and you can find it under <code>play.api.libs.concurrent.Akka</code>.</p>

<p>So, if Play already uses Akka, then why define an Akka plugin?</p>

<p>I believe it&#8217;s because the Akka plugin defines a distinct <code>ActorSystem("application")</code> that can be used for backend
tasks like sending email, and can be configured without impacting the &#8220;play&#8221; ActorSystem.  The Akka plugin provides a
useful default and enforces seperation between Play&#8217;s actors and the application&#8217;s actors.</p>

<h2>CQRS</h2>

<p>Given that most of the CQRS talks I&#8217;ve read have been from the enterprise perspective, it was nice to talk about CQRS
in the context of functional programming and statelessness.</p>

<p><a href="http://en.wikipedia.org/wiki/Message_passing">Message passing</a>
is something that is typically mentioned in inter process communication, or in message oriented middleware.
Akka &#8211; a message passing architecture on the thread level &#8211; allows us to build &#8220;zero coupling&#8221; systems
.  As message passing patterns, CQRS and DDD are a good set of idioms to think about domain logic together,
especially since they already assume eventual consistency and indeterminate time.</p>

<h2>Authentication</h2>

<p>If you&#8217;re using Scala, there are two good authentication options, <a href="https://github.com/wsargent/play20-rememberme">RememberMe</a>
(ahem) and <a href="https://github.com/jaliss/securesocial">SecureSocial</a>.  SecureSocial has better documentation and has been
around longer, but RememberMe has better security resistance to some attacks.  I&#8217;m working to integrate RememberMe&#8217;s
functionality into SecureSocial, but you&#8217;ll want to check out both of them.</p>

<p>There&#8217;s also a pure Java authentication option: <a href="http://joscha.github.io/play-authenticate/">Play Authenticate</a>.  I haven&#8217;t used this, but the code looks reasonable.</p>

<p>If you&#8217;d rather go it alone or need a basic starter application, you may find <a href="https://github.com/yesnault/Play20StartApp">Play20StartApp</a> useful (password reset, account confirmation, etc.)</p>

<h2>Authorization</h2>

<p><a href="https://github.com/schaloner/deadbolt-2">Deadbolt 2</a> is the best known authorization framework.  You can use things like <a href="https://github.com/wsargent/play-shiro/">Shiro</a>, but you&#8217;re better off with something specifically designed for Play.</p>

<h2>Security</h2>

<p>Play does fairly well on security compared to other frameworks.  For example, it will set a <a href="https://github.com/playframework/Play20/pull/336">CORS header</a> to protect against <a href="http://webapp-hardening.heroku.com/clickjacking">clickjacking</a>, will sign the session cookie with an HMAC to protect against <a href="http://webapp-hardening.heroku.com/broken_auth">broken authentication</a>, supports SSL, etc.</p>

<p>However, there are some things that Play doesn&#8217;t do.</p>

<p>Play doesn&#8217;t encrypt the session cookie, so you shouldn&#8217;t store any sensitive information in there.</p>

<p>Play won&#8217;t protect you from <a href="http://en.wikipedia.org/wiki/Replay_attack">replay attacks</a>, as Play is stateless by default.  You can specify a nonce or request counter to counteract this, and <a href="https://github.com/wsargent/play20-rememberme">RememberMe</a> uses a <a href="http://atyantik.com/blog/improved-persistent-login-cookie-best-practice/">token based</a> approach for persistent login cookies.</p>

<p>Play won&#8217;t protect you against <a href="http://www.troyhunt.com/2010/05/owasp-top-10-for-net-developers-part-1.html">injection attacks</a>.  You can specify <a href="http://tersesystems.com/2012/12/16/problems-scala-fixes">value classes</a> to validate your input against raw strings.</p>

<p>Play won&#8217;t protect you against <a href="http://webapp-hardening.heroku.com/security_misconfig">security misconfiguration</a>.  You should have a <a href="http://webdevchecklist.com/play-framework/">release checklist</a>.</p>

<p>Play won&#8217;t protect you from <a href="http://webapp-hardening.heroku.com/insecure_crypto">insecure cryptography practices</a>.  Education helps, but there&#8217;s a lot of misinformation out there as well; watch <a href="https://www.youtube.com/watch?v=ySQl0NhW1J0">this video</a> (and <a href="http://rdist.root.org/2009/06/10/when-crypto-attacks-slides-posted/">slides</a>) and be wary of things you read on Stack Overflow and Hacker News.</p>

<p>Play won&#8217;t protect you from <a href="http://webapp-hardening.heroku.com/unrestricted_access">failure to restrict URL access</a>; that&#8217;s up to the authorization framework.</p>

<p>Play does have <a href="http://webapp-hardening.heroku.com/csrf">cross site request forgery</a>
protection, but it will only be effective if you enable the filter and explicitly pass the CSRF helper function in through
<a href="http://nickcarroll.me/2013/02/11/protect-your-play-application-with-the-csrf-filter/">every single form</a>.  There is an <a href="https://github.com/orefalo/play2-authenticitytoken">authenticity token</a> approach as well, though I haven&#8217;t used it.</p>

<p>Most importantly, Play won&#8217;t tell you about how web application security fails.  I recommend <a href="http://www.amazon.com/Tangled-Web-Securing-Modern-Applications/dp/1593273886">The Tangled Web</a> as an excellent overview on how web applications are stitched together out of different technologies, and how to secure them.</p>

<h2>Logging</h2>

<p>The underlying logger for Play is <a href="http://logback.qos.ch/">Logback</a>. Logback is one of the few hardcoded dependencies
 in Play, which has caused some <a href="https://github.com/typesafehub/play2-mini/issues/7">issues</a>.  Fortunately, Play uses
Logback through the SLF4J logging API, but there&#8217;s no option built into Play to allow Logback to be swapped out easily.
There are reports of people swapping out Logback for <a href="http://osdir.com/ml/play-framework/2013-02/msg00881.html">other logging frameworks</a>, but I haven&#8217;t tried them.</p>

<p>There have also been issues with the logging configuration conflicting in places or being unclear.  One thing that has
tripped people up repeatedly is that all the logging configuration
<a href="http://blog.mograbi.info/2013/03/setting-logback-with-playframework-20.html">must be done in one place</a>.  You can&#8217;t
have some logging configuration in <code>application.conf</code> and some configuration in logger.xml.</p>

<p>While Play uses SLF4J under the hood, it doesn&#8217;t expose SLF4J functionality in <code>play.api.Logger</code>.  In fact,
there are only two method signatures for logging:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="nc">String</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="nc">String</span><span class="o">,</span> <span class="n">error</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="nc">Throwable</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Unit</span>
</span></code></pre></td></tr></table></div></figure>


<p>This doesn&#8217;t really cover the way I like to log, and it doesn&#8217;t provide even the features that are available in
SLF4J, such as parameterized logging.  My own answer was to ignore the Play logging API entirely and write a
Logging wrapper directly against SLF4J (with
<a href="http://debasishg.blogspot.com/2009/09/side-effects-with-kestrel-in-scala.html">kestrel combinators</a>, natch), but you
may want to use something out of the box.</p>

<p>For example, <a href="https://github.com/typesafehub/scalalogging">Typesafe Logging</a>, uses SLF4J and provides you with this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">params</span><span class="k">:</span> <span class="kt">AnyRef*</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">t</span><span class="k">:</span> <span class="kt">Throwable</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">marker</span><span class="k">:</span> <span class="kt">Marker</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">marker</span><span class="k">:</span> <span class="kt">Marker</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">params</span><span class="k">:</span> <span class="kt">AnyRef*</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">marker</span><span class="k">:</span> <span class="kt">Marker</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span> <span class="n">t</span><span class="k">:</span> <span class="kt">Throwable</span><span class="o">)</span><span class="k">:</span> <span class="kt">Unit</span>
</span></code></pre></td></tr></table></div></figure>


<p>Or you can use <a href="https://github.com/dln/loglady/">loglady</a>, which uses the Python API style with printf syntax:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>  <span class="n">params</span><span class="k">:</span> <span class="kt">Any*</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Unit</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">error</span><span class="o">(</span><span class="n">thrown</span><span class="k">:</span> <span class="kt">Throwable</span><span class="o">,</span> <span class="n">message</span><span class="k">:</span> <span class="kt">String</span><span class="o">,</span>  <span class="n">params</span><span class="k">:</span> <span class="kt">Any*</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Unit</span>
</span></code></pre></td></tr></table></div></figure>


<h2>WAR packaging</h2>

<p>I said in the Q&amp;A that I didn&#8217;t think you could package Play 2 applications as WAR files.  Well, it turns out that
there is a <a href="https://github.com/dlecan/play2-war-plugin">plugin available</a>, and it works with Servlet 3.0 and 2.5
containers (Tomcat 6/7, Jetty 7/8/9, JBoss 5/6/7, etc).  You may need to
<a href="https://github.com/dlecan/redirect-playlogger">tweak the logger</a> to work in the container correctly.</p>

<p>I don&#8217;t know how Play&#8217;s performance is affected by running inside a servlet container; let me know if it works for you.</p>

<h2>Email</h2>

<p>Email is one of those things that I think should be divorced as much as possible from Play.  It&#8217;s backend and async by
nature, and this makes it something that is best handled through Akka.</p>

<p><a href="http://blog.eigengo.com/blog_posts/akka-extras-email">akka-email</a> is available on <a href="https://github.com/eigengo/akka-extras/tree/master/javamail">Github</a> and
gives you a starting place to build up a message passing infrastructure for email.</p>

<h2>Metrics</h2>

<p>Instrumenting applications is important.  The
<a href="http://typesafe.com/products/console">Typesafe Console</a> is the best thing to use, but that depends on having a
<a href="http://typesafe.com/products/typesafe-subscription">Typesafe subscription</a> if you want to use it in production.</p>

<p>However, there are other options:</p>

<ul>
<li><a href="https://github.com/twitter/ostrich">Ostrich</a>, the Twitter metrics library.</li>
<li><a href="http://metrics.codahale.com/">Metrics</a>, with the <a href="https://github.com/erikvanoosten/metrics-scala">metrics-scala</a> from
Erik Van Oosten, cross-compiled for multiple versions.  This is what I use.</li>
<li><a href="https://github.com/Ticketfly/pillage">Pillage</a>, which has a Scala option (I have not tried this).</li>
<li><a href="https://github.com/typesafehub/play-plugins/tree/master/statsd">statsd</a> module for Play 2.</li>
</ul>


<h2>Profiling</h2>

<p>When you&#8217;re load testing, it helps to be able to profile the application as well.  I usually use
<a href="http://jmeter.apache.org/">Apache JMeter</a> to load the system, and then use
<a href="http://docs.oracle.com/javase/6/docs/technotes/guides/management/jconsole.html">jconsole</a> to connect to Play through
JMX.  <a href="http://www.yourkit.com/overview/index.jsp">YourKit</a> is apparently a good option for profiling as well.</p>

<h2>Deployment</h2>

<p>There are a number of different ways to deploy Play projects.  Using <code>play dist</code> gets you most of the way, but you may want to deploy with <a href="http://www.perevillega.com/post/2013/04/01/28/using-ansible-to-deploy-play-framework-apps-in-ec2-instances#.UYBlNyt4YkZ">Ansible</a> or <a href="https://github.com/njin-fr/application_play2">Chef</a> or <a href="https://groups.google.com/d/msg/play-framework/iIbKXtBlo9k/mjxp5ZWYZ6AJ">Fabric</a>.  Or you can use <a href="http://agileand.me/content/deploying-play-application-rackspace-cloud-vps">upstart</a> or even <a href="http://justinholmes.co.uk/50cbc7281223262b001ca08e">git hooks</a>.</p>

<p>If you just want to push changes to a staging server as they happen, you can do this with <code>rsync -avz --delete -e ssh $deployed_code staging:/opt/play-app</code>, although this isn&#8217;t so great for production.</p>

<h2>More?</h2>

<p>If you have suggestions or want to point something out, please email me at <a href="mailto:will.sargent@gmail.com" title="Play in Practice">will.sargent@gmail.com</a>, and I&#8217;ll fill out this post with more details.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Error Handling in Scala]]></title>
    <link href="http://tersesystems.com/2012/12/27/error-handling-in-scala" />
    <updated>2012-12-27T15:38:00-08:00</updated>
    <id>http://tersesystems.com/2012/12/27/error-handling-in-scala</id>
    <content type="html"><![CDATA[<p>The <a href="http://tersesystems.com/2012/12/16/problems-scala-fixes">previous post</a> was mostly about programming &#8220;in the small&#8221; where the primary concern is making sure the body of code in the method does what it&#8217;s supposed to and doesn&#8217;t do anything else.  This blog post is about what to do when code doesn&#8217;t work &#8211; how Scala signals failure and how to recover from it, based on <a href="http://aboutwhichmorelater.tumblr.com/post/30409572482/scala-util-try">some</a> <a href="http://grokbase.com/t/gg/scala-debate/128ssy8tkd/design-improvement-for-success-failure/128svrykfq#128svrykfq">insightful</a> <a href="http://grokbase.com/t/gg/scala-user/129w1rkfar/more-about-try-catching-handling">discussions</a>.</p>

<p>First, let&#8217;s define what we mean by failure.</p>

<ul>
<li><em>Unexpected internal failure</em>: the operation fails as the result of an unfulfilled expectation, such as a null pointer reference, violated assertions, or simply bad state.</li>
<li><em>Expected internal failure</em>: the operation fails deliberately as a result of internal state, i.e. a blacklist or <a href="https://github.com/erikvanoosten/sentries">circuit breaker</a>.</li>
<li><em>Expected external failure</em>: the operation fails because it is told to process some raw input, and will fail if the raw input cannot be processed.</li>
<li><em>Unexpected external failure</em>: the operation fails because a resource that the system depends on is not there: there&#8217;s a loose file handle, the database connection fails, or the network is down.</li>
</ul>


<p>Java has one explicit construct for handling failure: <code>Exception</code>.  There&#8217;s some difference of usage in Java throughout the years &#8211; IO and JDBC use checked exceptions throughout, while other API like <code>org.w3c.dom</code> rely on unchecked exceptions.  According to <a href="http://www.amazon.com/Clean-Code-Handbook-Software-Craftsmanship/dp/0132350882">Clean Code</a>, the best practice is to use unchecked exceptions in preference to checked exceptions, but there&#8217;s <a href="http://www.ibm.com/developerworks/java/library/j-jtp05254/index.html">still debate</a> over whether unchecked exceptions are always appropriate.</p>

<h2>Exceptions</h2>

<p>Scala makes &#8220;checked vs unchecked&#8221; very simple: it doesn&#8217;t have checked exceptions.  All exceptions are unchecked in Scala, even <code>SQLException</code> and <code>IOException</code>.</p>

<p>The way you catch an exception in Scala is by defining a <code>PartialFunction</code> on it:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">input</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileReader</span><span class="o">(</span><span class="n">file</span><span class="o">))</span>
</span><span class='line'><span class="k">try</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">try</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">for</span> <span class="o">(</span><span class="n">line</span> <span class="k">&lt;-</span> <span class="nc">Iterator</span><span class="o">.</span><span class="n">continually</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="n">readLine</span><span class="o">()).</span><span class="n">takeWhile</span><span class="o">(</span><span class="k">_</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>      <span class="nc">Console</span><span class="o">.</span><span class="n">println</span><span class="o">(</span><span class="n">line</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">finally</span> <span class="o">{</span>
</span><span class='line'>    <span class="n">input</span><span class="o">.</span><span class="n">close</span><span class="o">()</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span> <span class="k">catch</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="n">e</span><span class="k">:</span><span class="kt">IOException</span> <span class="o">=&gt;</span> <span class="n">errorHandler</span><span class="o">(</span><span class="n">e</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Or you can use <a href="http://www.scala-lang.org/api/current/scala/util/control/Exception$.html">control.Exception</a>, which provides <a href="http://stackoverflow.com/questions/2903481/using-scala-util-control-exception">some interesting building blocks</a>.  The docs say &#8220;focuses on composing exception handlers&#8221;, which means that this set of classes supplies most of the logic you would put into a catch or finally block.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="nc">Exception</span><span class="o">.</span><span class="n">handling</span><span class="o">(</span><span class="n">classOf</span><span class="o">[</span><span class="kt">RuntimeException</span><span class="o">],</span> <span class="n">classOf</span><span class="o">[</span><span class="kt">IOException</span><span class="o">])</span> <span class="n">by</span> <span class="n">println</span> <span class="n">apply</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">throw</span> <span class="k">new</span> <span class="nc">IOException</span><span class="o">(</span><span class="s">&quot;foo&quot;</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Using the <code>control.Exception</code> methods is fun and you can string together exception handling logic to create <a href="http://stackoverflow.com/a/1646480/5266">automatic resource management</a>, or an automated exception logger.  On the other hand, it&#8217;s full of sharp things like <code>allCatch</code>.  Leave it alone unless you really need it.</p>

<p>Exceptions don&#8217;t get mentioned very much in Scala, but they&#8217;re still the bedrock for dealing with unexpected failure.  For unexpected internal failure, there&#8217;s a set of <a href="http://daily-scala.blogspot.com/2010/03/assert-require-assume.html">assertion methods</a> called <code>require</code>, <code>assert</code>, and <code>assume</code>, which all use throwables under the hood.</p>

<h2>Option</h2>

<p><a href="http://www.scala-lang.org/api/current/scala/Option.html">Option</a> represents optional values, returning an instance of <code>Some(A)</code> if A exists, or <code>None</code> if it does not.  It&#8217;s ubiquitous in Scala code, to the point where it fades into invisibility.  The <a href="http://blog.tmorris.net/scalaoption-cheat-sheet/">cheat sheet</a> is the best way to get a handle on it.</p>

<p>It&#8217;s almost impossible to use <code>Option</code> incorrectly, but there is one caveat: <code>Some(null)</code> is valid.  If you have code that returns null, wrap it in <code>Option()</code> to convert it:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">optionResult</span> <span class="k">=</span> <span class="nc">Option</span><span class="o">(</span><span class="kc">null</span><span class="o">)</span> <span class="c1">// optionResult is None.</span>
</span></code></pre></td></tr></table></div></figure>


<h2>Either</h2>

<p><a href="http://www.scala-lang.org/api/rc/index.html#scala.util.Either">Either</a> is a disjoint union construct.  It returns either an instance of <code>Left[L]</code> or an instance of <code>Right[R]</code>.  It&#8217;s commonly used for error handling, where by convention <code>Left</code> is used to represent failure and <code>Right</code> is used to represent success.  It&#8217;s perfect for dealing with expected external failures such as parsing or validation.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">FailResult</span><span class="o">(</span><span class="n">reason</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span>
</span><span class='line'>
</span><span class='line'><span class="k">def</span> <span class="n">parse</span><span class="o">(</span><span class="n">input</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">FailResult</span>, <span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">val</span> <span class="n">r</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">StringTokenizer</span><span class="o">(</span><span class="n">input</span><span class="o">)</span>
</span><span class='line'>  <span class="k">if</span> <span class="o">(</span><span class="n">r</span><span class="o">.</span><span class="n">countTokens</span><span class="o">()</span> <span class="o">==</span> <span class="mi">1</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>    <span class="nc">Right</span><span class="o">(</span><span class="n">r</span><span class="o">.</span><span class="n">nextToken</span><span class="o">())</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">else</span> <span class="o">{</span>
</span><span class='line'>    <span class="nc">Left</span><span class="o">(</span><span class="nc">FailResult</span><span class="o">(</span><span class="s">&quot;Could not parse string: &quot;</span> <span class="o">+</span> <span class="n">input</span><span class="o">))</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><code>Either</code> is like <code>Option</code> in that it makes an abstract idea explicit by introducing an intermediate object.  Unlike <code>Option</code>, it does not have a <code>flatMap</code> method, so you can&#8217;t use it in <a href="http://www.scala-lang.org/node/111">for comprehensions</a> &#8211; not safely at any rate. You can use a left or right projection if you&#8217;re not interested in handling failure:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">rightFoo</span> <span class="k">=</span> <span class="k">for</span> <span class="o">(</span><span class="n">outputFoo</span> <span class="k">&lt;-</span> <span class="n">parse</span><span class="o">(</span><span class="n">input</span><span class="o">).</span><span class="n">right</span><span class="o">)</span> <span class="k">yield</span> <span class="n">outputFoo</span>
</span></code></pre></td></tr></table></div></figure>


<p>More typically, you&#8217;ll use <code>fold</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="n">parse</span><span class="o">(</span><span class="n">input</span><span class="o">).</span><span class="n">fold</span><span class="o">(</span>
</span><span class='line'>  <span class="n">error</span> <span class="k">=&gt;</span> <span class="n">errorHandler</span><span class="o">(</span><span class="n">error</span><span class="o">),</span>
</span><span class='line'>  <span class="n">success</span> <span class="k">=&gt;</span> <span class="o">{</span> <span class="o">...</span> <span class="o">}</span>
</span><span class='line'><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>You&#8217;re not limited to using <code>Either</code> for parsing or validation, of course.  You can use it for <a href="http://martinfowler.com/bliki/CQRS.html">CQRS</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">UserFault</span>
</span><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">UserCreatedEvent</span>
</span><span class='line'>
</span><span class='line'><span class="k">def</span> <span class="n">createUser</span><span class="o">(</span><span class="n">user</span><span class="k">:</span><span class="kt">User</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">UserFault</span>, <span class="kt">UserCreatedEvent</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>or arbitary binary choices:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">whatShape</span><span class="o">(</span><span class="n">shape</span><span class="k">:</span><span class="kt">Shape</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">Square</span>, <span class="kt">Circle</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p><code>Either</code> is powerful, but it&#8217;s trickier than <code>Option</code>.  In particular, it can lead to <a href="http://stackoverflow.com/questions/13105020/calling-external-services-in-scala-code-with-dependencies">deeply nested code</a>.  It can also be misunderstood.  Take the following Java lookup method:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='java'><span class='line'><span class="kd">public</span> <span class="n">Foo</span> <span class="nf">lookup</span><span class="o">(</span><span class="n">String</span> <span class="n">id</span><span class="o">)</span> <span class="kd">throws</span> <span class="n">FooException</span> <span class="c1">// throw if not found or db exception</span>
</span></code></pre></td></tr></table></div></figure>


<p>Scala has <code>Option</code>, so we can use that.  But what if the database goes down?  Using the error reporting convention of <code>Either</code> might suggest the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">lookup</span><span class="o">()</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">FooException</span>,<span class="kt">Option</span><span class="o">[</span><span class="kt">Foo</span><span class="o">]]</span>
</span></code></pre></td></tr></table></div></figure>


<p>But this is awkward.  If you return <code>Either</code> because something might fail unexpectedly, then immediately half your API becomes littered with <code>Either[Throwable, T]</code>.</p>

<p>Ah, but what if you&#8217;re modifying a new object?</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">modify</span><span class="o">(</span><span class="n">inputFoo</span><span class="k">:</span><span class="kt">Foo</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">FooException</span>,<span class="kt">Foo</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you&#8217;re dealing with expected failure and there&#8217;s good odds that the operation will fail, then returning <code>Either</code> is fine: create a case class representing failure <code>FailResult</code> and use <code>Either[FailResult,Foo]</code>.</p>

<p>Don&#8217;t return exceptions through Either.  If you want a construct to return exceptions, use Try.</p>

<h2>Try</h2>

<p><a href="http://www.scala-lang.org/api/rc/index.html#scala.util.Try">Try</a> is similar to <code>Either</code>, but instead of returning any class in a <code>Left</code> or <code>Right</code> wrapper, it returns <code>Failure[Throwable]</code> or <code>Success[T]</code>.  It&#8217;s an analogue for the try-catch block: it replaces try-catch&#8217;s stack based error handling with heap based error handling.  Instead of having an exception thrown and having to deal with it immediately in the same thread, it disconnects the error handling and recovery.</p>

<p><code>Try</code> can be used in for comprehensions: unlike <code>Either</code>, it implements <code>flatMap</code>.  This means you can do the following:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">sumTry</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;1&quot;</span><span class="o">))</span>
</span><span class='line'>  <span class="n">int2</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;2&quot;</span><span class="o">))</span>
</span><span class='line'><span class="o">}</span> <span class="k">yield</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="o">+</span> <span class="n">int2</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>and if there&#8217;s an exception returned from the first <code>Try</code>, then the for comprehension will terminate early and return the <code>Failure</code>.</p>

<p>You can get access to the exception through pattern matching:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="n">sumTry</span> <span class="k">match</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Failure</span><span class="o">(</span><span class="n">thrown</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span>
</span><span class='line'>    <span class="nc">Console</span><span class="o">.</span><span class="n">println</span><span class="o">(</span><span class="s">&quot;Failure: &quot;</span> <span class="o">+</span> <span class="n">thrown</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Success</span><span class="o">(</span><span class="n">s</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span>
</span><span class='line'>    <span class="nc">Console</span><span class="o">.</span><span class="n">println</span><span class="o">(</span><span class="n">s</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Or through <code>failed</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">if</span> <span class="o">(</span><span class="n">sumTry</span><span class="o">.</span><span class="n">isFailure</span><span class="o">)</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">val</span> <span class="n">thrown</span> <span class="k">=</span> <span class="n">sumTry</span><span class="o">.</span><span class="n">failed</span><span class="o">.</span><span class="n">get</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p><code>Try</code> will let you recover from exceptions at any point in the chain, so you can defer recovery to the end:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">sum</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;one&quot;</span><span class="o">))</span>
</span><span class='line'>  <span class="n">int2</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;two&quot;</span><span class="o">))</span>
</span><span class='line'><span class="o">}</span> <span class="k">yield</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="o">+</span> <span class="n">int2</span>
</span><span class='line'><span class="o">}</span> <span class="n">recover</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="n">e</span> <span class="k">=&gt;</span> <span class="mi">0</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Or <code>recover</code> in the middle:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">sum</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;one&quot;</span><span class="o">)).</span><span class="n">recover</span> <span class="o">{</span> <span class="k">case</span> <span class="n">e</span> <span class="k">=&gt;</span> <span class="mi">0</span> <span class="o">}</span>
</span><span class='line'>  <span class="n">int2</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;two&quot;</span><span class="o">))</span>
</span><span class='line'><span class="o">}</span> <span class="k">yield</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="o">+</span> <span class="n">int2</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>There&#8217;s also a <code>recoverWith</code> method that will let you swap out a <code>Failure</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">sum</span> <span class="k">=</span> <span class="k">for</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;one&quot;</span><span class="o">)).</span><span class="n">recoverWith</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">case</span> <span class="n">e</span><span class="k">:</span> <span class="kt">NumberFormatException</span> <span class="o">=&gt;</span> <span class="nc">Failure</span><span class="o">(</span><span class="k">new</span> <span class="nc">IllegalArgumentException</span><span class="o">(</span><span class="s">&quot;Try 1 next time&quot;</span><span class="o">))</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>  <span class="n">int2</span> <span class="k">&lt;-</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;2&quot;</span><span class="o">))</span>
</span><span class='line'><span class="o">}</span> <span class="k">yield</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">int1</span> <span class="o">+</span> <span class="n">int2</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can mix <code>Either</code> and <code>Try</code> together to coerce methods that throw exceptions internally:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">either</span> <span class="k">:</span> <span class="kt">Either</span><span class="o">[</span><span class="kt">String</span>, <span class="kt">Int</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Try</span><span class="o">(</span><span class="nc">Integer</span><span class="o">.</span><span class="n">parseInt</span><span class="o">(</span><span class="s">&quot;1&quot;</span><span class="o">)).</span><span class="n">transform</span><span class="o">({</span> <span class="n">i</span> <span class="k">=&gt;</span> <span class="nc">Success</span><span class="o">(</span><span class="nc">Right</span><span class="o">(</span><span class="n">i</span><span class="o">))</span> <span class="o">},</span> <span class="o">{</span> <span class="n">e</span> <span class="k">=&gt;</span> <span class="nc">Success</span><span class="o">(</span><span class="nc">Left</span><span class="o">(</span><span class="s">&quot;FAIL&quot;</span><span class="o">))</span> <span class="o">}).</span><span class="n">get</span>
</span><span class='line'><span class="nc">Console</span><span class="o">.</span><span class="n">println</span><span class="o">(</span><span class="s">&quot;either is &quot;</span> <span class="o">+</span> <span class="n">either</span><span class="o">.</span><span class="n">fold</span><span class="o">(</span><span class="n">l</span> <span class="k">=&gt;</span> <span class="n">l</span><span class="o">,</span> <span class="n">r</span> <span class="k">=&gt;</span> <span class="n">r</span><span class="o">))</span>
</span></code></pre></td></tr></table></div></figure>


<p><code>Try</code> isn&#8217;t always appropriate.  If we go back to the first exception example, this is the <code>Try</code> analogue:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
<span class='line-number'>9</span>
<span class='line-number'>10</span>
<span class='line-number'>11</span>
<span class='line-number'>12</span>
<span class='line-number'>13</span>
<span class='line-number'>14</span>
<span class='line-number'>15</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">input</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">BufferedReader</span><span class="o">(</span><span class="k">new</span> <span class="nc">FileReader</span><span class="o">(</span><span class="n">file</span><span class="o">))</span>
</span><span class='line'><span class="k">val</span> <span class="n">results</span> <span class="k">=</span> <span class="nc">Seq</span><span class="o">(</span>
</span><span class='line'>  <span class="nc">Try</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">for</span> <span class="o">(</span><span class="n">line</span> <span class="k">&lt;-</span> <span class="nc">Iterator</span><span class="o">.</span><span class="n">continually</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="n">readLine</span><span class="o">()).</span><span class="n">takeWhile</span><span class="o">(</span><span class="k">_</span> <span class="o">!=</span> <span class="kc">null</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>      <span class="nc">Console</span><span class="o">.</span><span class="n">println</span><span class="o">(</span><span class="n">line</span><span class="o">)</span>
</span><span class='line'>    <span class="o">}</span>
</span><span class='line'>  <span class="o">},</span>
</span><span class='line'>  <span class="nc">Try</span><span class="o">(</span><span class="n">input</span><span class="o">.</span><span class="n">close</span><span class="o">())</span>
</span><span class='line'><span class="o">)</span>
</span><span class='line'>
</span><span class='line'><span class="n">results</span><span class="o">.</span><span class="n">foreach</span> <span class="o">{</span> <span class="n">result</span> <span class="k">=&gt;</span>
</span><span class='line'>  <span class="n">result</span><span class="o">.</span><span class="n">recover</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">case</span> <span class="n">e</span><span class="k">:</span><span class="kt">IOException</span> <span class="o">=&gt;</span> <span class="n">errorHandler</span><span class="o">(</span><span class="n">e</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Note the kludge to get around the lack of a <code>finally</code> block to close the stream.  Victor Klang and Som Snytt suggested using a value class and <code>transform</code> to pimp <code>Try</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">implicit</span> <span class="k">class</span> <span class="nc">TryOps</span><span class="o">[</span><span class="kt">T</span><span class="o">](</span><span class="k">val</span> <span class="n">t</span><span class="k">:</span> <span class="kt">Try</span><span class="o">[</span><span class="kt">T</span><span class="o">])</span> <span class="k">extends</span> <span class="nc">AnyVal</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">eventually</span><span class="o">[</span><span class="kt">Ignore</span><span class="o">](</span><span class="n">effect</span><span class="k">:</span> <span class="o">=&gt;</span> <span class="nc">Ignore</span><span class="o">)</span><span class="k">:</span> <span class="kt">Try</span><span class="o">[</span><span class="kt">T</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">val</span> <span class="n">ignoring</span> <span class="k">=</span> <span class="o">(</span><span class="k">_:</span> <span class="kt">Any</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span> <span class="n">effect</span><span class="o">;</span> <span class="n">t</span> <span class="o">}</span>
</span><span class='line'>    <span class="n">t</span> <span class="n">transform</span> <span class="o">(</span><span class="n">ignoring</span><span class="o">,</span> <span class="n">ignoring</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span><span class='line'>
</span><span class='line'><span class="nc">Try</span><span class="o">(</span><span class="mi">1</span> <span class="o">/</span> <span class="mi">0</span><span class="o">).</span><span class="n">map</span><span class="o">(</span><span class="k">_</span> <span class="o">+</span> <span class="mi">1</span><span class="o">)</span> <span class="n">eventually</span> <span class="o">{</span> <span class="n">println</span><span class="o">(</span><span class="s">&quot;Oppa Gangnam Style&quot;</span><span class="o">)</span> <span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Which is cleaner, at the cost of some magic.</p>

<p><code>Try</code> was originally invented at Twitter to solve a specific problem: when using Future, the exception may be thrown on a different thread than the caller, and so can&#8217;t be returned through the stack.  By returning an exception instead of throwing it, the system is able to <a href="http://grokbase.com/t/gg/scala-user/129w1rkfar/more-about-try-catching-handling#20120930akr7hvezngsw5xhrwztjpx7smq">reify the bottom type</a> and let it cross thread boundaries to the calling context.</p>

<p><code>Try</code> is new enough that people are still getting comfortable with it.  I think that it&#8217;s a useful addition when try-catch blocks aren&#8217;t flexible enough, but it does have a snag: returning <code>Try</code> in a public API means exceptions must be dealt with by the caller.  Using <code>Try</code> also implies to the caller that the method has captured all non fatal exceptions itself.  If you&#8217;re doing this in your trait:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">modify</span><span class="o">(</span><span class="n">foo</span><span class="k">:</span><span class="kt">Foo</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Try</span><span class="o">[</span><span class="kt">Foo</span><span class="o">]</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then <code>Try</code> should be at the top to ensure exception capture:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">modify</span><span class="o">(</span><span class="n">foo</span><span class="k">:</span><span class="kt">Foo</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Try</span><span class="o">[</span><span class="kt">Foo</span><span class="o">]</span> <span class="k">=</span> <span class="nc">Try</span> <span class="o">{</span>
</span><span class='line'>  <span class="nc">Foo</span><span class="o">()</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Because exceptions must be dealt with the caller, you are placing more trust in the caller to handle or delegate a failure appropriately.  With try-catch blocks, doing nothing means that the exception can pass up the stack to a top level exception handler.  With <code>Try</code>, exceptions must be either returned or handled by each method in the chain, just like checked exceptions.</p>

<p>To pass the exception along, use <code>map</code>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">fooToString</span><span class="o">(</span><span class="n">foo</span><span class="k">:</span><span class="kt">Foo</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Try</span><span class="o">[</span><span class="kt">String</span><span class="o">]</span> <span class="k">=</span> <span class="o">{</span>
</span><span class='line'>  <span class="n">modify</span><span class="o">(</span><span class="n">foo</span><span class="o">).</span><span class="n">map</span> <span class="o">{</span> <span class="n">outFoo</span> <span class="k">=&gt;</span>
</span><span class='line'>   <span class="n">outFoo</span><span class="o">.</span><span class="n">toString</span><span class="o">()</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Or to rethrow the exception up the stack if the return type is Unit:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">doStuff</span> <span class="k">:</span> <span class="kt">Unit</span> <span class="o">=</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">val</span> <span class="n">modifiedFoo</span> <span class="k">=</span> <span class="n">modify</span><span class="o">(</span><span class="n">foo</span><span class="o">).</span><span class="n">get</span> <span class="c1">// throws the exception if failure</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>And you want to avoid this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
<span class='line-number'>5</span>
<span class='line-number'>6</span>
<span class='line-number'>7</span>
<span class='line-number'>8</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="n">modify</span><span class="o">(</span><span class="n">foo</span><span class="o">)</span> <span class="k">match</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Failure</span><span class="o">(</span><span class="n">f</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span>
</span><span class='line'>    <span class="c1">// database failure?  don&#39;t care, swallow exception.</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Success</span><span class="o">(</span><span class="n">s</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span>
</span><span class='line'>    <span class="o">...</span>
</span><span class='line'>  <span class="o">}</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>If you have a system that needs specific error logging or error recovery, it&#8217;s probably safer to stick to unchecked exceptions.</p>

<h2>TL;DR</h2>

<ul>
<li>Use <code>Exception</code> to signal unexpected failure.</li>
<li>Use <code>Option</code> to return optional values.</li>
<li>Use <code>Option(possiblyNull)</code> to avoid instances of <code>Some(null)</code>.</li>
<li>Use <code>Either</code> to report expected failure.</li>
<li>Use <code>Try</code> over <code>Either</code> to return exceptions.</li>
<li>Use <code>Try</code> for handling unexpected failure.</li>
<li>Use <code>Try</code> when working with <code>Future</code>.</li>
<li>In a public API, throwing an exception is probably safer than returning <code>Try</code>.</li>
</ul>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Problems Scala Fixes]]></title>
    <link href="http://tersesystems.com/2012/12/16/problems-scala-fixes" />
    <updated>2012-12-16T14:47:00-08:00</updated>
    <id>http://tersesystems.com/2012/12/16/problems-scala-fixes</id>
    <content type="html"><![CDATA[<p>When I tell people I write code in Scala, a typical question is well, why?  When it comes to writing code, most of my work is straightforward: SQL database on the backend, some architectural glue, CRUD, some exception handling, transactions handlers and an HTML or JSON front end. The tools have changed, but the problems are usually the same: you could get a website up in 5 minutes with <a href="http://rubyonrails.org/">Rails</a> or <a href="http://dropwizard.codahale.com/">Dropwizard</a>.  So why pick Scala?</p>

<p>It&#8217;s a tough question to answer off the bat. If I point to the language features, it doesn&#8217;t get the experience across. It&#8217;s like explaining why I like English by reading from a grammar book.  I don&#8217;t like Scala because of its functional aspects or its higher kinded type system.  I like Scala because it solves practical, real world problems for me.</p>

<p>You can think of Scala as Java with all the rough edges filed off, with new features that make it easier to write correct code and harder to create bugs.  Scala is not a purist&#8217;s language &#8211; it goes out of its way to make it easy for Java programmers to dip their toes in the pool.  You can literally take your Java code and <a href="http://stackoverflow.com/a/5489232/5266">hit a key</a> to create working Scala code.</p>

<p>So what problems does Scala solve?</p>

<p>Let&#8217;s start with the single biggest problem in programming, the design flaw that&#8217;s caused more errors than anything else combined. <a href="http://qconlondon.com/london-2009/presentation/Null+References:+The+Billion+Dollar+Mistake">Null references</a>.</p>

<h2>Solving for Null</h2>

<p>Scala avoids null pointer references by providing a special type called <a href="http://www.naildrivin5.com/scalatour/wiki_pages/OptionType">Option</a>. Methods that return Option[A] (where A is the type that you want, i.e. Option[String]) will give you an object that is either a wrapper object called &#8216;Some&#8217; around your type, or None. There are a number of <a href="http://blog.tmorris.net/scalaoption-cheat-sheet/">different ways</a> you can use Option, but I&#8217;ll just mention the ones I use most. You can chain Options together in Scala using <a href="http://www.naildrivin5.com/scalatour/wiki_pages/ForComprehensions">for comprehensions</a>:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">for</span> <span class="o">{</span>
</span><span class='line'>     <span class="n">foo</span> <span class="k">&lt;-</span> <span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">(</span><span class="-Symbol">&#39;foo</span><span class="err">&#39;</span><span class="o">)</span>
</span><span class='line'>     <span class="n">bar</span> <span class="k">&lt;-</span> <span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">(</span><span class="-Symbol">&#39;bar</span><span class="err">&#39;</span><span class="o">)</span>
</span><span class='line'>  <span class="o">}</span> <span class="k">yield</span> <span class="n">myService</span><span class="o">.</span><span class="n">process</span><span class="o">(</span><span class="n">foo</span><span class="o">,</span> <span class="n">bar</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>or through a map:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">(</span><span class="-Symbol">&#39;foo</span><span class="err">&#39;</span><span class="o">).</span><span class="n">map</span> <span class="o">{</span> <span class="n">foo</span> <span class="k">=&gt;</span> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="o">(</span><span class="n">foo</span><span class="o">)</span> <span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>or through pattern matching.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">(</span><span class="-Symbol">&#39;foo</span><span class="err">&#39;</span><span class="o">)</span> <span class="k">match</span> <span class="o">{</span>
</span><span class='line'>    <span class="k">case</span> <span class="nc">Some</span><span class="o">(</span><span class="n">foo</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="o">{</span> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="o">(</span><span class="n">foo</span><span class="o">)</span> <span class="o">}</span>
</span><span class='line'>    <span class="k">case</span> <span class="nc">None</span> <span class="k">=&gt;</span> <span class="o">{</span> <span class="n">logger</span><span class="o">.</span><span class="n">debug</span><span class="o">(</span><span class="-Symbol">&#39;no</span> <span class="n">foo</span> <span class="o">:-(</span><span class="err">&#39;</span><span class="o">)</span> <span class="o">}</span>
</span><span class='line'>  <span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>Not only is this easy, but it&#8217;s also safer. You can flirt with NPE saying myOption.get, but if you do that, you deserve what you get. Not having to deal with NPE is a pleasure.</p>

<h2>Right Type in the Right Place</h2>

<p>What&#8217;s the second biggest problem in programming? It&#8217;s a huge issue in security and in proving program correctness: <a href="http://en.wikipedia.org/wiki/Garbage_in,_garbage_out">invalid, unchecked input</a>.</p>

<p>Take the humble String. The work of manipulating strings is one of the biggest hairballs in programming &#8211; they&#8217;re pulled in from the environment or embedded in the code itself, and then programs try to figure out how best to deal with them. In one case, a string is displayed to the user and it&#8217;s done. In another case, an SQL query is embedded as a query parameter on a web page and passed straight through to the database. To the compiler, they&#8217;re just strings and there is no difference between them.  But there are some types of strings that are suitable to pass to databases, and some which are not. Ideally, we&#8217;d like to tell the compiler that SQL and query parameters have different types. Scala makes this easy.</p>

<p>With the <a href="https://github.com/milessabin/shapeless">Shapeless library</a>, you can add distinguishing type information to objects and ensure that you can&#8217;t pass random input in:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">import</span> <span class="nn">shapeless.TypeOperators._</span>
</span><span class='line'><span class="k">type</span> <span class="kt">SqlString</span> <span class="o">=</span> <span class="nc">Newtype</span><span class="o">[</span><span class="kt">String</span>, <span class="kt">Any</span><span class="o">]</span>
</span><span class='line'><span class="k">val</span> <span class="n">x</span><span class="k">:</span> <span class="kt">SqlString</span> <span class="o">=</span> <span class="n">newtype</span><span class="o">(</span><span class="s">&quot;SELECT * FROM USER&quot;</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>I&#8217;ve called out strings because it&#8217;s a good example, but you can also do this for <a href="http://chemikadze.blogspot.com/2012/11/full-typed-approach-to-data-objects-in.html">repository IDs</a>.  No more this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">case</span> <span class="k">class</span> <span class="nc">User</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Int</span><span class="o">,</span> <span class="n">firstName</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">lookup</span><span class="o">(</span><span class="n">id</span><span class="k">:</span><span class="kt">Int</span><span class="o">)</span> <span class="k">:</span> <span class="kt">User</span>
</span></code></pre></td></tr></table></div></figure>


<p>When you can have this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">case</span> <span class="k">class</span> <span class="nc">User</span><span class="o">(</span><span class="n">id</span><span class="k">:</span> <span class="kt">Id</span><span class="o">[</span><span class="kt">User</span><span class="o">],</span> <span class="n">firstName</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span>
</span><span class='line'>  <span class="k">def</span> <span class="n">lookup</span><span class="o">(</span><span class="n">id</span><span class="k">:</span><span class="kt">Id</span><span class="o">[</span><span class="kt">User</span><span class="o">])</span> <span class="k">:</span> <span class="kt">User</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can also use this to validate input on the front end. One of the big problems with regular expressions is that when you parse a random string for certain kinds of input, you get back&#8230; more strings. You may be validating a string as a username (no spaces, no odd characters), but what you&#8217;ve got at the end is a string that says it&#8217;s a username.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">val</span> <span class="n">rawInput</span> <span class="k">=</span> <span class="n">request</span><span class="o">.</span><span class="n">params</span><span class="o">(</span><span class="-Symbol">&#39;foo</span><span class="err">&#39;</span><span class="o">)</span>
</span><span class='line'><span class="k">if</span> <span class="o">(</span><span class="n">isUsername</span><span class="o">(</span><span class="n">rawInput</span><span class="o">))</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">val</span> <span class="n">username</span> <span class="k">=</span> <span class="n">rawInput</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>You can replace that with something nicer.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>   <span class="k">val</span> <span class="n">email</span> <span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Username</span><span class="o">]</span> <span class="k">=</span> <span class="n">parseUsername</span><span class="o">(</span><span class="n">rawInput</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>This embeds the constraint in the type itself.  You can design your API to accept Username instead of String, and so enforce a kind of whitelisting.</p>

<p>Can you do this in Java? Yes, but it&#8217;s inconvenient. Scala&#8217;s type system makes it easy for you, and in 2.10 there will be <a href="http://docs.scala-lang.org/overviews/core/value-classes.html">Value Classes</a>, which will provide this functionality in the core language itself.</p>

<h2>Doing the gruntwork for you</h2>

<p>The previous example can be improved though. Really, we just want a Username at the end &#8211; we don&#8217;t want to have to call parseUsername on it. Fortunately, Scala rewards the lazy with <a href="http://www.naildrivin5.com/scalatour/wiki_pages/ImplicitConversions">implicit conversions</a>.
If you define a method like this and use the implicit keyword:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">implicit</span> <span class="k">def</span> <span class="n">string2username</span><span class="o">(</span><span class="n">input</span> <span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Username</span><span class="o">]</span> <span class="k">=</span> <span class="n">parseUsername</span><span class="o">(</span><span class="n">input</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>And do this:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>  <span class="k">val</span> <span class="n">email</span> <span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Username</span><span class="o">]</span> <span class="k">=</span> <span class="n">rawInput</span><span class="o">;</span>
</span></code></pre></td></tr></table></div></figure>


<p>Then the compiler is smart enough to see that a String isn&#8217;t an Option[Username], and looks through any implicit methods available to do the conversion.</p>

<p>There is an element of &#8216;magic&#8217; to implicit conversions, especially when you&#8217;re reading someone else&#8217;s code and trying to figure out where the conversion is happening. You can find the appropriate implicit through the REPL, or through <a href="http://devnet.jetbrains.net/message/5265499">IDEA</a>.</p>

<h2>Providing Context</h2>

<p>There are many cases in programming where everything depends on a <a href="http://www.corej2eepatterns.com/Patterns2ndEd/ContextObject.htm">Context object</a> in some way: either you&#8217;re using a database connection, or you rely on a security principal, or you&#8217;re resolving objects from a request or JAAS / LDAP / Spring context&#8230; the list goes on. Whatever it is, it&#8217;s passed in by the system, it&#8217;s absolutely essential, and you can count on most of your API to depend on it in some way. A typical Java way to deal with this is to make it part of the parameter list, or try to ignore it and make it a <a href="http://www.adam-bien.com/roller/abien/entry/how_to_pass_context_with">ThreadLocal object</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>   <span class="n">public</span> <span class="n">void</span> <span class="n">doStuff</span><span class="o">(</span><span class="nc">Context</span> <span class="n">context</span><span class="o">);</span>
</span></code></pre></td></tr></table></div></figure>


<p>Scala has a better way to deal with this: you can specify <a href="http://www.naildrivin5.com/scalatour/wiki_pages/ImplicitParameters">implicit parameters</a> on a method.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>   <span class="k">def</span> <span class="n">doStuff</span><span class="o">(</span><span class="k">implicit</span> <span class="n">context</span><span class="k">:</span><span class="kt">Context</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>which means that anything marked as implicit that is in scope will be applied:</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'>   <span class="k">implicit</span> <span class="k">val</span> <span class="n">context</span> <span class="k">=</span> <span class="k">new</span> <span class="nc">Context</span><span class="o">()</span>
</span><span class='line'>   <span class="n">doStuff</span>  <span class="c1">// uses val context automatically.</span>
</span></code></pre></td></tr></table></div></figure>


<p>This is all handled by the compiler: just set up the implicits and Scala will do the rest.</p>

<h2>A place for everything</h2>

<p>So now you have a number of implicit methods, value classes and type definitions and wotnot.  In Scala, there&#8217;s a place to keep all this stuff that is so intuitive, you may not think of it as a place at all. It&#8217;s the <a href="http://www.naildrivin5.com/scalatour/wiki_pages/PackageObjects">package object</a>.</p>

<p>Package objects are supremely useful. You define a file called package.scala, then in the file you put</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">package</span> <span class="nn">object</span> <span class="n">mypackagename</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">implicit</span> <span class="k">def</span> <span class="n">string2username</span><span class="o">(</span><span class="n">input</span> <span class="k">:</span> <span class="kt">String</span><span class="o">)</span> <span class="k">:</span> <span class="kt">Option</span><span class="o">[</span><span class="kt">Username</span><span class="o">]</span> <span class="k">=</span> <span class="n">parseUsername</span><span class="o">(</span><span class="n">input</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>and after that point, anything with &#8216;import mypackagename._&#8217; will import the package object as well. One less thing to think about.</p>

<h2>Free Data Transfer Objects</h2>

<p><a href="http://www.naildrivin5.com/scalatour/wiki_pages/CaseClasses">Case classes</a>.  So called because they&#8217;re used in case statements (see below).</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">Data</span><span class="o">(</span><span class="n">propertyOne</span><span class="k">:</span><span class="kt">String</span><span class="o">,</span> <span class="n">propertyTwo</span><span class="k">:</span><span class="kt">Int</span><span class="o">)</span>
</span></code></pre></td></tr></table></div></figure>


<p>Immutable, convenient, and packed with functionality.  They make creating data types or DTOs trivial.  <a href="http://www.codecommit.com/blog/scala/case-classes-are-cool">They&#8217;re cool</a>.</p>

<h2>Free Range (Organic) Checking</h2>

<p>Scala contains a powerful <a href="http://www.naildrivin5.com/scalatour/wiki_pages/PatternMatching">pattern matching</a> feature.  You can think of it as a <a href="http://thecodegeneral.wordpress.com/2012/03/25/switch-statements-on-steroids-scala-pattern-matching/">switch statement on steroids</a>.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="n">a</span> <span class="k">match</span> <span class="o">{</span>
</span><span class='line'>   <span class="k">case</span> <span class="nc">Something</span> <span class="k">=&gt;</span> <span class="n">doThis</span>
</span><span class='line'>   <span class="k">case</span> <span class="nc">SomethingElse</span> <span class="k">=&gt;</span> <span class="n">doThat</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<p>There are so many things that feed into pattern matching &#8211; <a href="http://www.scala-lang.org/node/112">extractor objects</a>, <a href="https://coderwall.com/p/m1bnlq">aliases</a>, matching on types, regular expressions and wildcards &#8211; it&#8217;s the &#8216;regexp&#8217; of Scala.  It takes in an object as input, filters it, and manipulates it in exactly the way you want.</p>

<p>But the thing I really like about pattern matching is what it doesn&#8217;t let you do. It doesn&#8217;t let you miss something.</p>

<p>There&#8217;s a feature called <a href="http://www.naildrivin5.com/scalatour/wiki_pages/SealedClasses">sealed classes</a> which lets you define all the valid types in a file. If you define a trait with the sealed keyword inside a file, then any classes you define inside that file that extend that trait are the ONLY classes that will extend that trait.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">sealed</span> <span class="k">trait</span> <span class="nc">Message</span> <span class="o">{</span> <span class="k">def</span> <span class="n">msg</span><span class="k">:</span> <span class="kt">String</span> <span class="o">}</span>
</span><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">Success</span><span class="o">(</span><span class="n">msg</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span>
</span><span class='line'><span class="k">case</span> <span class="k">class</span> <span class="nc">Failure</span><span class="o">(</span><span class="n">msg</span><span class="k">:</span><span class="kt">String</span><span class="o">)</span> <span class="k">extends</span> <span class="nc">Message</span>
</span></code></pre></td></tr></table></div></figure>


<p>The compiler knows this, and so when you write use pattern matching against that trait, it knows that it must be one of the case classes defined. If not all of the case classes are defined in the match, it will print out a warning method saying that you don&#8217;t have an exhaustive match.</p>

<figure class='code'><figcaption><span></span></figcaption><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class='scala'><span class='line'><span class="k">def</span> <span class="n">log</span><span class="o">(</span><span class="n">msg</span><span class="k">:</span> <span class="kt">Message</span><span class="o">)</span> <span class="k">=</span> <span class="n">msg</span> <span class="k">match</span> <span class="o">{</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Success</span><span class="o">(</span><span class="n">str</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">println</span><span class="o">(</span><span class="s">&quot;Success: &quot;</span> <span class="o">+</span> <span class="n">str</span><span class="o">)</span>
</span><span class='line'>  <span class="k">case</span> <span class="nc">Failure</span><span class="o">(</span><span class="n">str</span><span class="o">)</span> <span class="k">=&gt;</span> <span class="n">println</span><span class="o">(</span><span class="s">&quot;Failure: &quot;</span> <span class="o">+</span> <span class="n">str</span><span class="o">)</span>
</span><span class='line'><span class="o">}</span>
</span></code></pre></td></tr></table></div></figure>


<h2>And More</h2>

<p>But that&#8217;s enough for now.  I hope this gives you an idea of why I like Scala.  If you have any features dear to your heart, add them to the comments and let me know what makes you happy.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Remember Me Cookies for Play 2.0]]></title>
    <link href="http://tersesystems.com/2012/07/07/remember-me-cookies-for-play-2-dot-0" />
    <updated>2012-07-07T15:19:00-07:00</updated>
    <id>http://tersesystems.com/2012/07/07/remember-me-cookies-for-play-2-dot-0</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been working with <a href="http://www.playframework.org/">Play 2.0</a> for a while now, and in many ways it&#8217;s the ideal web
framework for me: it&#8217;s a light framework that gets a request, puts together a result (either at once or in chunks using
an iteree pattern), and provides some HTML templates and form processors for ease of use.  It lets you change code and
templates while the server is running, and gives you an asset pipeline for compressing LESS and Coffeescript into minified
CSS and Javascript out of the box.</p>

<p>That being said, it&#8217;s a new web framework, and the biggest issue right now is all the boring infrastructure that goes
on top of it to make a framework deal with authentication, authorization, and even boring things like resetting a password.</p>

<p>On the Java side, Yvonnick Esnault has a good <a href="https://github.com/yesnault/Play20StartApp">starter application</a>
(disclaimer; I contributed some code), or you can use <a href="http://joscha.github.com/play-authenticate/">Play Authenticate</a>.</p>

<p>On the Scala side, <a href="https://github.com/t2v/play20-auth">play20-auth</a> is a good starting point for an authentication
system.  However, it didn&#8217;t do token based authentication, aka &#8220;Remember Me&#8221; cookies.  Adding this feature turns out to
be tricky if you&#8217;re new to Scala, because extending the request pipeline in Play 2.0 Scala requires that you know a functional style
of programming called &#8221;<a href="https://github.com/playframework/Play20/wiki/ScalaActionsComposition">action composition</a>&#8221;.</p>

<p>So here&#8217;s a boilerplate project <a href="https://github.com/wsargent/play20-rememberme">play20-rememberme</a> that does authentication
with remember me functionality (although it doesn&#8217;t have the password reset or confirm features added to Play20StartApp).</p>

<p>UPDATE: Now works with Play 2.1.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How to surf from a public wifi]]></title>
    <link href="http://tersesystems.com/2012/05/28/how-to-surf-from-a-public-wifi" />
    <updated>2012-05-28T12:04:00-07:00</updated>
    <id>http://tersesystems.com/2012/05/28/how-to-surf-from-a-public-wifi</id>
    <content type="html"><![CDATA[<p>I&#8217;ve been working from home or from public wireless points for about two years now.  Here&#8217;s how I make things work for me.</p>

<h2>Issue #1: Public wireless networks are not secure.</h2>

<p>The biggest risk is that someone steals your login credentials while you&#8217;re surfing the web.  There are a number of ways I deal with this:</p>

<ul>
<li>I have a VPN service, which will encrypt all my traffic.  Here&#8217;s a <a href="http://torrentfreak.com/which-vpn-providers-really-take-anonymity-seriously-111007/">list</a>.</li>
<li>I use HTTPS, backed up with <a href="https://www.eff.org/https-everywhere">HTTPS Everywhere</a> and <a href="http://convergence.io/">Convergence</a>.</li>
<li>I use <a href="http://www.privoxy.org/">Privoxy</a>, an HTTP proxy that blocks tracking websites&#8230; or all websites.</li>
</ul>


<p>This last one is worth noting if you have a tendency to procrastinate: using a whitelist is be far more effective for me than using Freedom or SelfControl. When I go to a coffeeshop, I&#8217;m going to work; there&#8217;s no point in randomly browsing websites, so I block everything with Privoxy, and then set up a whitelist.action file.</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>{ +block{WORK MOAR} }
</span><span class='line'>
</span><span class='line'>{ -block }
</span><span class='line'>  .turntable.fm # Add whitelisted domain names here</span></code></pre></td></tr></table></div></figure>


<p>You can install Privoxy using <a href="http://mxcl.github.com/homebrew/">Homebrew</a> and it&#8217;s good to go.  Set up a custom location in Network Preferences, and set up the HTTPS and HTTP proxy to localhost:8118 to pass it through.</p>

<h2>Issue #2: Public Wireless networks are flakey.</h2>

<p>I still can&#8217;t quite believe how terrible open networks can get.  So:</p>

<ul>
<li>I have a <a href="http://www.verizonwireless.com/b2c/store/controller?item=phoneFirst&amp;action=viewPhoneDetail&amp;selectedPhoneId=5633">Verizon Mifi mobile hotspot</a>.  I don&#8217;t typically need it, but it&#8217;s worthwhile when I do.</li>
<li>I use another HTTP proxy, <a href="http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/">Polipo</a>, that caches content for me.</li>
<li>I use a DNS proxy, <a href="http://members.home.nl/p.a.rombouts/pdnsd/">pdnsd</a>, that caches IP addresses from DNS, and Google DNS.</li>
</ul>


<p>I used the instructions from <a href="https://plus.google.com/104111751954651277535/posts/TjuN1nA6YQM">Yesudeep Mangalapilly</a> to set these up, with the modification to chain Privoxy to Polipo.  See &#8220;Is it possible to run Polipo together with Privoxy?&#8221; in the <a href="http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/faq.html">FAQ</a>.</p>

<p>Polipo is extremely useful, but the version on Homebrew is out of date.  The trunk version is recommended if you run into any bugs.  The pdnsd install on Homebrew is almost totally seamless, and Polipo <a href="http://www.pps.univ-paris-diderot.fr/~jch/software/polipo/manual/DNS.html">recommends</a> it.</p>

<p>Using Polipo and pdnsd means my exposure to the network is somewhat limited, and browsing is somewhat faster.  Minimizing network traffic is important when I&#8217;m using the mobile hotspot &#8211; it&#8217;s limited to 5 GB a month, which is very easy to blow through if you&#8217;re not careful.  There is some duplication of effort as browsers will typically cache content internally&#8230; but then again, if I&#8217;m checking the same page in Chrome &amp; Firefox, they&#8217;re not sharing their internal caches.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The User Illusion]]></title>
    <link href="http://tersesystems.com/2012/05/26/the-user-illusion" />
    <updated>2012-05-26T15:51:00-07:00</updated>
    <id>http://tersesystems.com/2012/05/26/the-user-illusion</id>
    <content type="html"><![CDATA[<p>Slides from the May 17th <a href="https://5mof.net/">Five Minutes of Fame</a>.  This one is on consciousness and a book called <a href="http://www.amazon.com/The-User-Illusion-Cutting-Consciousness/dp/0140230122">The User Illusion</a>.  I read the book and thought it interesting, but it was only after reading <a href="http://www.rifters.com/real/Blindsight.htm">Blindsight</a> and following Peter Watts&#8217;s <a href="http://www.rifters.com/crawl/">blog</a> that it clicked as something that happened outside of science experiments.</p>

<p>That, and I&#8217;d really been hankering for a good science talk.  There&#8217;s nothing quite like science; even when it comes to something as wishy-washy as consciousness, it can still give you surprising answers.</p>

<div style="width:425px" id="__ss_13089132"><object id="__sse13089132" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=userillusion-120526180356-phpapp02&amp;stripped_title=user-illusion&amp;userName=wsargent" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><embed name="__sse13089132" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=userillusion-120526180356-phpapp02&amp;stripped_title=user-illusion&amp;userName=wsargent" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="425" height="355"></embed></object></div>


<p>And video!</p>

<iframe width="560" height="315" src="http://www.youtube.com/embed/TYXKN0DSOdg" frameborder="0" allowfullscreen></iframe>


<p>The short version of the slides:</p>

<p>When you see, you see what&#8217;s already been processed and filtered.  Illusions are when the system doesn&#8217;t work; you don&#8217;t see when it does work.  In other words, we see &#8220;car accident&#8221; as presented to our consciousness &#8211; we don&#8217;t consciously put it together from our visual input.  I&#8217;ll spare you the customary link to the &#8220;You wouldn&#8217;t know if a Gorilla showed up&#8221; study, but it&#8217;s fairly clear the brain only passes on the Cliff Notes version to the executive layer.</p>

<p>Consciousness lags well behind.  When scientists measure the movement of a finger, the electrical potential rises a full second before the finger moves.  But we report making the decision to move half a second before the finger moves (<a href="https://en.wikipedia.org/wiki/Benjamin_Libet">Libet</a>).  We become aware of making the decision after it&#8217;s already happened.</p>

<p>Some scientists conjecture that consciousness may simply be unnecessary (<a href="http://rifters.com/real/articles/Neuropsychologia_Rosenthal_2008.pdf">Rosenthal</a>).  Others think that consciousness may be a result of conflicting subconscious systems (<a href="http://bss.sfsu.edu/emorsella/images/MorsellaPsychRev.pdf">Morsella</a>, <a href="http://www.amazon.com/Am-Strange-Loop-Douglas-Hofstadter/dp/0465030793">Hofstader</a>, <a href="http://www.amazon.com/Being-No-One-Self-Model-Subjectivity/dp/0262633086">Metzinger</a>), and the <a href="http://www.rifters.com/crawl/?p=791">Watts commentary</a> points out that consciousness seems to be strongly associated with inner conflict and/or pain, although I&#8217;m not spoiling his punchline.</p>

<p>Despite what <a href="http://h3ph.com/">Heph</a> says, I don&#8217;t think the talk is depressing.  When you think about consciousness, you assume that it&#8217;s a good thing, but realistically we&#8217;re far happier and productive in flow, without that <a href="http://www.lastwordonnothing.com/2012/02/09/better-living-through-electrochemistry/">nagging voice inside our heads</a>.  Rather than life being suffering, suffering itself is the act of consciousness.</p>

<p>The talk itself went down well, with the coveted  seal of approval. The 5MoF itself was surprisingly wide ranging &#8211; <a href="http://www.artsology.com/blog/2012/01/eclair-acuda-bandersnatch/">Eclair Bandersnatch</a> showed up in a barbie mask and wig to talk about art, <a href="http://www.oblomovka.com/">Danny O&#8217;Brien</a> gave a talk on The Cosmopolitan Anarchist and recapped the news on <a href="http://freebyron.org/index.php/Main_Page">Byron Sonne</a>, <a href="http://bookmaniac.org">Liz Henry</a> read poetry from her <a href="http://bookmaniac.org/unruly-islands-will-blow-your-mind-so-buy-it/">new book</a>, and Josh Juran presented <a href="http://www.metamage.com/code/forge/">FORGE</a>, a GUI based on manipulating what appeared to be symbolic files on the filesystem &#8211; a programming paradigm that apparently came from Plan 9 and hurts my brain every time I think about it.</p>

<p>We&#8217;re doing the same thing next month, and I&#8217;ll probably be talking about <a href="https://noisebridge.net/wiki/TDCS">Transcranial Direct Current Stimulation</a> (if I&#8217;m not, y&#8217;know, drooling in a corner).  So!  If you have a thought that&#8217;s been burning a hole in some mental sidepocket, you should <a href="https://5mof.net/signup">sign up</a>.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Web Security Class at Noisebridge]]></title>
    <link href="http://tersesystems.com/2012/03/27/web-security-class-at-noisebridge" />
    <updated>2012-03-27T09:07:00-07:00</updated>
    <id>http://tersesystems.com/2012/03/27/web-security-class-at-noisebridge</id>
    <content type="html"><![CDATA[<p>Just a quick note to say I&#8217;ll be giving a <a href="https://noisebridge.net/wiki/Frontend_Web_Development">special class</a> with Carl Sue on hardening web applications at Noisebridge (2169 Mission) on April 2nd.</p>

<p>UPDATE: Class went well.  I&#8217;ve put a website up at <a href="http://webapp-hardening.heroku.com/">http://webapp-hardening.heroku.com/</a> and will be updating it as I go.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Systemantics]]></title>
    <link href="http://tersesystems.com/2012/03/17/systemantics" />
    <updated>2012-03-17T12:29:00-07:00</updated>
    <id>http://tersesystems.com/2012/03/17/systemantics</id>
    <content type="html"><![CDATA[<p>New Five Minutes of Fame presentation.  This one&#8217;s a presentation about a little known book called <a href="http://en.wikipedia.org/wiki/Systemantics">Systemantics</a> (a.k.a. The Systems Bible).</p>

<div style="width:425px" id="__ss_12048768"><strong style="display:block;margin:12px 0 4px"><a href="http://www.slideshare.net/wsargent/systemantics" title="Systemantics">Systemantics</a></strong><object id="__sse12048768" width="425" height="355"><param name="movie" value="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=systemantics-120317142231-phpapp01&stripped_title=systemantics&userName=wsargent" /><param name="allowFullScreen" value="true"/><param name="allowScriptAccess" value="always"/><param name="wmode" value="transparent"/><embed name="__sse12048768" src="http://static.slidesharecdn.com/swf/ssplayer2.swf?doc=systemantics-120317142231-phpapp01&stripped_title=systemantics&userName=wsargent" type="application/x-shockwave-flash" allowscriptaccess="always" allowfullscreen="true" wmode="transparent" width="425" height="355"></embed></object></div>


<p>This is a hard book to get hold of, but a worthwhile one.  Systemantics doesn&#8217;t make a lot of sense without the context of <a href="http://en.wikipedia.org/wiki/Systems_theory">Systems Theory</a>, which is responsible for the word &#8220;cybernetics&#8221; and a whole bunch else, mostly talking about systems in the context of the complex feedback loop of a nuclear power plant.</p>

<p>Systemantics is a little bit different: it talks about the feedback loop involved in organizations, and how the system has an independent life (and will to live) outside of any of its participants.  It&#8217;s a book about how systems actually behave, and how what an observer may consider to be a bug looks like appropriate behavior to the system.  It&#8217;s about the system as you know it at 2 am, the system complete unto itself in all its ineffable complexity.</p>

<p>That being said, much of it is applicable to complex computer systems as well &#8211;  in fact I&#8217;d say that Systems Theory is far more applicable to my day job than most CS Theory is, and if there&#8217;s ever going to be a Software Engineering curriculum then I&#8217;d want it to include this book.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Interviews without Puzzles]]></title>
    <link href="http://tersesystems.com/2012/02/22/interviews-without-puzzles" />
    <updated>2012-02-22T19:12:00-08:00</updated>
    <id>http://tersesystems.com/2012/02/22/interviews-without-puzzles</id>
    <content type="html"><![CDATA[<p>Technical interviews have their own particular lore, and their own history.  Over the years, there are some interview practices that have sunk into the group subconscious of engineers, to the point where they&#8217;re used so commonly we don&#8217;t even question why.  Puzzles, for example.</p>

<p>There are a few famous interview puzzles out there.  Microsoft has &#8220;Why are Manhole Covers Round?&#8221; Google has &#8220;You are shrunk to the height of a nickel and your mass is proportionally reduced so as to maintain your original density. You are then thrown into an empty glass blender. The blades will start moving in 60 seconds. What do you do?&#8221;</p>

<p>The standard answer to the first puzzle is &#8220;So they don&#8217;t fall in.&#8221;  The answer to the second is that assuming you have the same proportionate strength, you can <a href="http://online.wsj.com/article/SB10001424052970204552304577112522982505222.html?google_editors_picks=true">jump out</a>. (There&#8217;s an inverse square root effect between muscle and body length, so density is not a factor.)</p>

<p>But here&#8217;s the thing.  The first answer is <em>incorrect</em>.  Manhole covers are round because they <a href="http://www.joblossguide.com/2009/02/why-are-manhole-covers-round_10.html?showComment=1293805783516#c1734354851346190815"><em>can</em> be round</a>.  They could be square or triangular just as easily.</p>

<p>So as an interviewer, if you pick random interview puzzles out of a book and you think you know the &#8220;right answer&#8221; to the puzzle, you run the chance of not hiring someone because the answer he gave was actually the correct one.</p>

<p>A more common problem is that a clever interview puzzle is usually well-known.  As soon as you figure it out, you&#8217;ll tell all your friends, and they tell their friends.  Eventually, you can google for the answer.</p>

<p>Back in the day, Zen Schools had the same problem.  They were looking for insight and flashes of realization, initially, and wanted a way to test for this.  Some people thought up excellent questions that could test the subtle understanding of self, reality and perception required of Zen students.  More and more, the koans were used as the standard by which students&#8217; understanding could be measured. Eventually, someone had the bright idea to put together a book of koans &#8211; complete with &#8220;acceptable responses&#8221; &#8211; and through years of formalization, the age old question &#8220;What is the sound of one hand clapping&#8221; turned into a <a href="http://web.archive.org/web/20070125230458sh_re_/www3.tky.3web.ne.jp/~edjacob/koan.html">meaningless ritual</a>.</p>

<p>Even if you don&#8217;t use well known puzzles, interviewing with logic puzzles in the long run optimizes for them. Through discussion, shared experiences and research, people will generally know that they should study for a general class of <a href="http://amzn.com/098478280X">logic puzzle</a>. And the company will start getting more people that will do well at those puzzles&#8230; but that doesn&#8217;t mean they know programming any better.</p>

<p>Fermi questions, those &#8221;<a href="http://www.vendian.org/envelope/dir0/fermi_questions.html">How many elevators are in New York City?</a>&#8221; questions that are popular in interviews, have a clearer structural weakness. They have no right answer at all, and can be completely circumvented with the right training.  Once you know the rules, you can come up with completely the wrong answer and still be &#8220;correct&#8221; according to the law of the game.</p>

<p>I also have a philosophical problem with Fermi questions.  Yes, they&#8217;re pointless, but it&#8217;s not just that they&#8217;re pointless.  Asking a Fermi question says that you don&#8217;t really care what the answer is.  Asking a Fermi question tells your candidate that you want them to guess.</p>

<p>Engineers are trained out of guessing.  Engineers are trained to nail down as much as they can <a href="http://programmers.stackexchange.com/questions/45259/is-premature-optimization-always-bad">before</a> solving any problem, because invalid assumptions and requirements are <a href="http://courses.cs.vt.edu/~cs3604/lib/Therac_25/Therac_1.html">dangerous</a> and <a href="http://www.doc.ic.ac.uk/~ban/pubs/ariane5.pdf">expensive</a>.  But that&#8217;s not why engineers don&#8217;t like to guess.</p>

<p><em>Why</em> is because most engineers remember vividly what happened the last time someone came up to them and said &#8220;When do you think we can go live?  <a href="http://gigamonkeys.wordpress.com/2007/04/26/estimation-considered-harmful/">Just make a guess</a>.&#8221;  When it comes to Fermi questions, a cagey and hesitant engineer isn&#8217;t a bad candidate, but an experienced one.</p>

<p>So what do I recommend? <a href="http://amzn.com/0932633595">This book</a> is good to get a broader sense of what interviews are supposed to do, and you can ask spot questions about <a href="http://www.bestcode.com/html/interview_questions.html">language and system knowledge</a>, then rate them on the <a href="http://www.starling-software.com/employment/programmer-competency-matrix.html">Programmer Competency Matrix</a>.  But the best way to figure out how someone attacks code is to bring out some buggy code and ask for help debugging it, or bring out a design and talk about how you&#8217;d implement it, talk about the engineer&#8217;s background, print out the engineer&#8217;s github project and ask about it.  They&#8217;ll appreciate it, and so will you.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Setting up ATG with Vagrant]]></title>
    <link href="http://tersesystems.com/2012/02/18/setting-up-atg-with-vagrant" />
    <updated>2012-02-18T16:32:00-08:00</updated>
    <id>http://tersesystems.com/2012/02/18/setting-up-atg-with-vagrant</id>
    <content type="html"><![CDATA[<p>I do ATG development.  ATG&#8217;s a big system with lots of moving parts &#8211; assumes you have several machines to play with, and some bits don&#8217;t take well to running on a Macbook Pro.</p>

<p>So, I cheat.  Here&#8217;s how I set it up with Vagrant and VirtualBox so I can carry several different development environments around.  Warning: severe nerdery and technical detail below.</p>

<!-- more -->


<p>ATG has some very specific requirements.  If you’re developing on a different platform, you can be bitten by unexpected bugs when you test in a different environment.  However, if you’re running an upgrade, you need to a) have fresh environments configured exactly to spec.  You have a bit of wiggle room on the OS.  You have very little wiggle room when it comes to the JDK and JBoss versions: the EA version of JBoss will NOT serve as an acceptable substitute, and ATG will stress out the JDK in some very specific ways that are painful to debug given the wrong patch version.</p>

<p>Here’s what you can do with VMs:</p>

<ul>
<li>Package up your project-specific VMs as boxes (basically templates), then distribute them to your team for an immediately runnable system.</li>
<li>Create automated boxes from your VMs as &#8220;snapshots&#8221; of the system at various points in time.</li>
<li>Create disposible, run-once  instances of your project to try out destructive changes and upgrades to the system.</li>
<li>Create a snapshot of the system in a broken or buggy state and it make available for debugging.</li>
<li>Move a box over to a big iron server with lots of memory / CPUs when you want to run batch processes.</li>
</ul>


<p>I use VirtualBox as my VM platform, but you can get the same effect by using VMWare or Parallels.  I prefer VirtualBox as it’s free and (with the addition of Vagrant) easy to configure in scripts and on the command line, and works the same in Windows, MacOS and Linux.</p>

<p>Here’s how you do it:</p>

<ul>
<li>Install VirtualBox.</li>
<li>Install Vagrant.</li>
<li>Review your target ATG platform.</li>
<li>Download (preferably) or build (not so preferably) your vagrant box.</li>
<li>Create an instance from your box that you’ll add more stuff onto.</li>
<li>Package up your instance as another ATG box.</li>
</ul>


<p>The first step is to make sure you have VirtualBox installed and you feel comfy with it. <a href="http://michaelhallsmoore.com/blog/Running-A-Local-Web-Development-Environment-With-VirtualBox">Read through this.</a></p>

<p>So notice how you had to install the OS by hand, starting with the ISO and walk through everything right from the very beginning, ending with a system that has a bunch of stuff that you don’t care about.  Vagrant short-circuits that by providing you with &#8220;boxes&#8221; that have already been through the OS install and let you hit the ground running.  <a href="http://www.jedi.be/blog/2011/03/28/using-vagrant-as-a-team/">This will teach you about Vagrant.</a>  You will also want the <a href="http://vagrantup.com">vagrant docs</a>.</p>

<p>So the next step is to install Vagrant.  Once you’ve installed Ruby (I use RVM, you may want something else), this is simple:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>$ gem install vagrant
</span><span class='line'>$ vagrant box add base http://files.vagrantup.com/lucid32.box
</span><span class='line'>$ vagrant init
</span><span class='line'>$ vagrant up</span></code></pre></td></tr></table></div></figure>


<p>The important bit to note here is the second command: we told Vagrant to add a box called &#8220;base&#8221; to its library, from the URL http://files.vagrantup.com/lucid32.box.  When we typed &#8220;vagrant init&#8221; then that created a Vagrantfile with some default options, and then &#8220;vagrant up&#8221; started up the VM.  Vagrant has far more features than that, of course, but it’s a good place to start.</p>

<p>The next step is to make sure you have the files you need for your environment, as close as possible.</p>

<p>The dependency matrix for ATG (not counting the various patches, hotfixes, etc.):</p>

<h3>ATG 2007</h3>

<ul>
<li>JBoss EAP 4.0.5,</li>
<li>RHEL 4.0update2 (32 bit),</li>
<li>Oracle 10g,</li>
<li>Sun JDK 5.0u11</li>
</ul>


<h3>ATG 9.3</h3>

<ul>
<li>JBoss EAP 4.3.0 CP09,</li>
<li>RHEL 5.1 (32 or 64 bit),</li>
<li>Oracle 10g/11g,</li>
<li>Sun JDK 1.6_22,</li>
<li>Oracle Thin 11.2.0.x XA (for all versions).</li>
</ul>


<h3>ATG 10.2</h3>

<ul>
<li>JBoss 5.1.0 EAP,</li>
<li>RHEL 5.4 (64 bit),</li>
<li>Oracle 10.2.0.2 / 11.2.0.1.0,</li>
<li>Oracle Thin 11.2.0.1 XA (for all versions),</li>
<li>Sun JDK 1.6.0_22</li>
</ul>


<p>If you are doing this for development or want to try it out, you may find it easier to download a CentOS box from http://www.vagrantbox.es/search/?q=centos</p>

<p>If you’re hardcore, then you’ll be downloading RHEL 4 or RHEL 5, which aren’t publically available.  If so, you’re going to want to know the details of building a box with Vagrant.</p>

<h2>Building a base box</h2>

<p>Your first Vagrant box is always going to be a bit wonky.  Get comfortable and knock out a few before you think about putting together a base box you&#8217;re going to settle down with.</p>

<p>Once you have your box, then you’ll want to do the following:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>mkdir my_instance; cd my_instance
</span><span class='line'>vagrant init
</span><span class='line'>vi Vagrantbox</span></code></pre></td></tr></table></div></figure>


<ul>
<li>Set up a vagrant instance with memory / CPU (see the <a href="http://vagrantup.com">vagrant docs</a> for this.</li>
<li>Provision your vagrant box with basic packages and port forwarding.</li>
</ul>


<p>Because you’re using CentOS, you’ll need some extra settings.</p>

<p>Note that you may run into a problem with CentOS being <a href="https://github.com/jedi4ever/veewee/issues/14">slow</a> but this will fix it:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>config.ssh.max_tries = 50
</span><span class='line'> config.ssh.timeout   = 300
</span><span class='line'>vagrant up
</span><span class='line'>vagrant ssh</span></code></pre></td></tr></table></div></figure>


<p>Now you have a vagrant instance up and you can connect to it.  Start installing packages.  NOTE: If you&#8217;re doing this all from scratch, you may want to look at <a href="https://gist.github.com/354734">this</a>.</p>

<script src="https://gist.github.com/1258637.js"> </script>


<h2>Installing ATG 10:</h2>

<ul>
<li>Create ATG user.</li>
<li>Install Sun JDK.</li>
<li>Install the version of JBoss.</li>
<li>Copy all your ATG files into the VM, and then install them.</li>
<li>Install the licenses into $DYNAMO_HOME/localconfig</li>
<li>Install any patches and hotfixes for JBoss and ATG.</li>
</ul>


<h2>Packaging your base ATG Commerce box</h2>

<p>Once you’ve got a base ATG install, you can package your instance up as another box:</p>

<figure class='code'><div class="highlight"><table><tr><td class="gutter"><pre class="line-numbers"><span class='line-number'>1</span>
<span class='line-number'>2</span>
<span class='line-number'>3</span>
<span class='line-number'>4</span>
</pre></td><td class='code'><pre><code class=''><span class='line'>mkdir atg10_box; cd atg10_box;
</span><span class='line'>vagrant package --base atg10
</span><span class='line'># vagrant box remove atg10
</span><span class='line'>vagrant box add atg10 package.box</span></code></pre></td></tr></table></div></figure>


<p>You now have a correct, well known ATG template that you can take with you and install on any project.</p>

<h2>Installing Oracle</h2>

<p>In addition, you’ll also need Oracle installed.  Installing Oracle is enough of a pain that I’ve seen bumper stickers about it.  You will want to do this on a different VM than your ATG install, just for ease of use, not least because Oracle has its own specific memory and disk space requirements and it’s easier not to have to manage them.  <a href="https://www.oratoolkit.ch/">oraToolkit</a> is a godsend here, and I can only imagine the work it took to make this all pan out.</p>

<p>Do not use Express Edition.  It only takes 2GB databases.  If someone hands you a 20GB dump of their database, you’re out of luck.</p>

<p>You may want to increase maximum number of sessions, or add more memory to the VM to the Oracle instance, but for right now we won&#8217;t worry about it.</p>

<script src="https://gist.github.com/1258640.js"> </script>


<h2>Setting up and running new project</h2>

<ul>
<li>Create a new vagrant instance using your ATG base box</li>
<li>Create a new vagrant instance using your Oracle instance</li>
<li>Set up all the ATG tables in Oracle</li>
<li>Set up your project to have deployment sftp the EAR file to the ATG box</li>
<li>Set up your project to have an rsync daemon send JSP files to the ATG box</li>
</ul>


<h2>Notes</h2>

<p>Use Vagrant for making snapshots.  Do not use VirtualBox’s snapshot facility unless you really, really know what you’re doing.</p>

<p>If you cannot connect to a shared folder, make sure that your user is in the vboxsf group.</p>

<p>I am aware that a) this is a mess and b) it will probably be rendered out of date shortly.  Email me with improvements and new gists.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Failing with Passwords]]></title>
    <link href="http://tersesystems.com/2012/02/17/failing-with-passwords" />
    <updated>2012-02-17T11:08:00-08:00</updated>
    <id>http://tersesystems.com/2012/02/17/failing-with-passwords</id>
    <content type="html"><![CDATA[<p>Did a talk about implementing password security right last night at Five Minutes of Fame.</p>

<iframe src="https://docs.google.com/presentation/embed?id=1PMGgO_bjMhPaCdE5MrcF-6lwuLY1lNvgsS-dx62flKY&start=false&loop=false&delayms=3000" frameborder="0" width="529" height="426" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>


<p>If you don&#8217;t want to go through the slides, here&#8217;s the TL;DR version:</p>

<h2>TL;DR User Security</h2>

<ul>
<li>Use a <a href="http://arstechnica.com/security/guides/2011/03/ask-ars-where-should-i-store-my-passwords.ars">password manager</a> like <a href="https://lastpass.com/">LastPass</a> or <a href="https://agilebits.com/onepassword">1Password</a> (with Dropbox) and use their password generation.</li>
<li>If no manager available (routers, OS logins, etc), use pass phrases with non-English words or acronyms (see <a href="http://xkcd.com/936/">xkcd</a>)</li>
<li>Assume sites get compromised all the time and you never hear about it.  NEVER reuse a password.</li>
<li>If you&#8217;re at a coffee shop or hackerspace, use a <a href="http://mashable.com/2010/10/28/firesheep-vpns/">public VPN service</a>.</li>
<li>OAuth / Twitter / Facebook based authentication is putting your auth credentials in their hands.</li>
</ul>


<h2>TL;DR Encryption Security</h2>

<ul>
<li>Use <a href="http://chargen.matasano.com/chargen/2007/9/7/enough-with-the-rainbow-tables-what-you-need-to-know-about-s.html">bcrypt</a>.  Bounce up the factor every few years.</li>
<li>Do not limit password field length. (bcrypt takes up to 55 bytes of input.)</li>
<li>Run a <a href="http://howsecureismypassword.net/">JS password tester</a> to reject weak passwords.</li>
<li>Run a <a href="http://www.openwall.com/john/">password cracker</a> regularly to test your security.</li>
<li>Suggest to your users that they use passphrases with acronyms, punctuation or LOLspeak.</li>
<li>Generate random passwords for your users.</li>
<li>Consider removing <a href="http://www.useit.com/alertbox/passwords.html">password masking</a>.</li>
</ul>


<h2>TL;DR Operational Security</h2>

<ul>
<li>Use HTTPS for both <a href="https://www.owasp.org/index.php/Transport_Layer_Protection_Cheat_Sheet#Rule_-_Use_TLS_for_All_Login_Pages_and_All_Authenticated_Pages">rendering and submitting</a> login page.</li>
<li>Show <a href="http://www.ethicalhacker.net/content/view/182/1/">Cain and Abel</a> video to everyone you work with.</li>
<li>Use <a href="http://en.wikipedia.org/wiki/HTTP_Strict_Transport_Security">HSTS</a> headers with HTTPS.</li>
<li>Use <a href="http://www.corej2eepatterns.com/Design/PresoDesign.htm">Synchronizer Token</a> to prevent <a href="http://guides.rubyonrails.org/security.html#cross-site-request-forgery-csrf">CSRF attacks</a> (or use a decent web framework).</li>
<li>Use a <a href="http://en.wikipedia.org/wiki/CAPTCHA">captcha</a> / <a href="http://datagraph.rubyforge.org/rack-throttle/">throttle</a> on password attempts.</li>
<li>Use double validation for registering accounts (register sends email, clicking email link heads back to site).</li>
<li>Use one time use password reset links.</li>
<li>Send email notifications on password change attempts.</li>
</ul>


<h2>Extra Credit</h2>

<ul>
<li>Add Honeypot Logins.</li>
<li>Use login token IDs with hidden check bits and math invariants that indicate tampering.</li>
<li>Implement a secret in the session management system to keep state on the client and verify it on server interaction for better session authentication.</li>
</ul>


<p>OWASP also has <a href="https://www.owasp.org/index.php/Cheat_Sheets">cheat sheets</a> which look useful if you&#8217;re putting a site together.  It still disturbs me how freaking MANUAL so much of this is, but I suppose web frameworks can&#8217;t do everything for you.  There are <a href="http://everydayrails.com/2011/09/21/rails-authentication.html">some options</a> if you&#8217;re on Rails.</p>

<p>It was a surprisingly tough talk to give.  At first I was like, &#8221;<a href="http://www.troyhunt.com/2011/01/whos-who-of-bad-password-practices.html">lol, look at all the companies with crappy security</a>&#8221;, but it&#8217;s a murky field in general. For example, the <a href="http://xkcd.com/936/">XKCD cartoon about passphrases</a> is missing the problem that most people type passphrases in standard English, and only use about two thousand words in general conversation.  It may look like there&#8217;s more entropy generated, but if your attackers know that your customers use passphrases, you may have just made their jobs <a href="http://technet.microsoft.com/en-us/library/cc512613.aspx">much easier</a>.</p>

<p>Also, brute force cracking is surprisingly effective.  MD5 and the SHA-* algorithms are inappropriate because GPUs chew through them <a href="http://blog.duosecurity.com/2010/12/brief-analysis-of-the-gawker-password-dump/">very quickly</a>, but the newer FPGA chips can do a reasonable implementation of bcrypt in hardware.  It&#8217;s an issue that computers are fast, but a bigger problem is that they just keep getting faster.</p>

<p>The biggest thing has to be to not let your users pick <a href="http://howsecureismypassword.net/">crappy passwords</a>.  Even if you have bcrypt with all the factors, if your users are <a href="http://www.rawstory.com/rs/2012/02/08/anonymous-hacks-syrian-presidents-email-with-12345-password/">entering &#8220;12345&#8221; as the password</a>, it&#8217;s not going to make a difference.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Exporting Typo to Disqus]]></title>
    <link href="http://tersesystems.com/2012/02/16/exporting_typo_to_disqus" />
    <updated>2012-02-16T11:33:00-08:00</updated>
    <id>http://tersesystems.com/2012/02/16/exporting_typo_to_disqus</id>
    <content type="html"><![CDATA[<p>The blog&#8217;s been moved over to <a href="http://octopress.com/">Octopress</a> and most of the comments have been imported.  I had to do some tweaks to get the lists to <a href="https://github.com/imathis/octopress/issues/417">inline properly</a> but other than that it&#8217;s good.</p>

<p>Exporting from <a href="blog.typosphere.org">Typo</a> to <a href="http://disqus.com">Disqus</a> turned out to be a much bigger deal than I anticipated: the initial Typo -> Disqus export didn&#8217;t work because the Disqus gem would drop comments on the floor, and the various WXP export scripts I found on the web either used XML::Builder (which didn&#8217;t format / escape things correctly) or just plain had bugs in them.</p>

<p>On top of that, WXR is actually not valid XML itself (there&#8217;s no default namespace defined) so even if you do it correctly, it won&#8217;t validate.  You just have to check it matches the import format exactly.  So here&#8217;s my version.</p>

<!-- more -->




<script src="https://gist.github.com/1847244.js"></script>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Heuristics in Mate Search]]></title>
    <link href="http://tersesystems.com/2012/01/17/heuristics-in-mate-search" />
    <updated>2012-01-17T15:00:00-08:00</updated>
    <id>http://tersesystems.com/2012/01/17/heuristics-in-mate-search</id>
    <content type="html"><![CDATA[<p>Five Minutes of Fame talk about dating heuristics.  This went much better than expected because the pictures and subject matter helped balance out the math.</p>

<iframe src="https://docs.google.com/presentation/embed?id=1vywPmRpHKE6QwjaLvyXKBINzOAbZ1fiZZ3Bxpw5LFYQ&start=false&loop=false&delayms=3000" frameborder="0" width="529" height="426" allowfullscreen="true" webkitallowfullscreen="true"></iframe>


<p>Although there were a number of people afterwards who were like &#8220;too unrealistic&#8221; and I was like &#8220;yeah, this works better for interviews and college placement but whatchagonnado.&#8221;</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Five Minutes of Web Frameworks]]></title>
    <link href="http://tersesystems.com/2011/11/18/five-minutes-of-web-frameworks" />
    <updated>2011-11-18T15:00:00-08:00</updated>
    <id>http://tersesystems.com/2011/11/18/five-minutes-of-web-frameworks</id>
    <content type="html"><![CDATA[<p>New 5MOF presentation, wherein I talk about why web applications are complicated.  In five minutes.</p>

<p>I really need to write this up as an essay, as I think presentation objects vs domain objects are a much bigger detail than we realize.</p>

<iframe src="https://docs.google.com/presentation/embed?id=1GWA93mRUbzX2x-uC5CluojrFsoMu4Awha5OgFflvhkc&start=false&loop=false&delayms=3000"
frameborder="0" width="529" height="426" allowfullscreen="true" webkitallowfullscreen="true"></iframe>

]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[How We Make Decisions]]></title>
    <link href="http://tersesystems.com/2011/10/21/how-we-make-decisions" />
    <updated>2011-10-21T14:04:00-07:00</updated>
    <id>http://tersesystems.com/2011/10/21/how-we-make-decisions</id>
    <content type="html"><![CDATA[<p>
  Five Minutes of Fame presentation on how we make decisions.  This one was a lot more dry and technical, but it was a nice change of pace after bronies melted my brain.
</p>

<iframe src="https://docs.google.com/presentation/embed?id=1pNN9NHaAMCuCKyxfMVpe58vIgcSwOT_gpt4FP1r-nFU&start=false&loop=false&delayms=3000" frameborder="0" width="529" height="426" allowfullscreen="true" webkitallowfullscreen="true"></iframe>

<p>
  Part of what makes this so fascinating to me is that you can actually see the algorithm that tells us &#8220;hey, we should do more of this.&#8221;  That&#8217;s a huge step in knowing our blind spots.
</p>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Bronies]]></title>
    <link href="http://tersesystems.com/2011/09/15/bronies" />
    <updated>2011-09-15T15:00:00-07:00</updated>
    <id>http://tersesystems.com/2011/09/15/bronies</id>
    <content type="html"><![CDATA[<p>5MoF talk about Bronies.  This one was fun &#8211; before starting the presentation, I showed the video below to everyone:</p>

<iframe width="560" height="315" src="http://www.youtube.com/embed/mHIMs7UKTSg" frameborder="0" allowfullscreen></iframe>

<p>After that (and I really wish I&#8217;d videoed everyone&#8217;s faces), it was onto the presentation itself, which is about how the Bronies beat down 4chan.</p>

<iframe src="https://docs.google.com/presentation/embed?id=1EEY2BVEOiRL4fxCpUnpKYYP_yhWEMuHHabYHWh7YVLc&start=false&loop=false&delayms=3000" frameborder="0" width="529" height="426" allowfullscreen="true" webkitallowfullscreen="true"></iframe>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Kittehs]]></title>
    <link href="http://tersesystems.com/2011/08/20/kittehs" />
    <updated>2011-08-20T15:11:00-07:00</updated>
    <id>http://tersesystems.com/2011/08/20/kittehs</id>
    <content type="html"><![CDATA[<p>Five Minutes of Fame talk, all about my new kittens.  It was kind of amazing to see everyone&#8217;s faces light up.  Mostly consisted of the videos below.</p>

<p>
  <a href="http://twitpic.com/5vdxbu" title="It is a happy purring kitty named Asha"><img src="http://twitpic.com/show/thumb/5vdxbu.mp4" width="450" height="450" alt="It is a happy purring kitty named Asha."></a>  
</p>

<p>
<iframe width="560" height="315" src="http://www.youtube.com/embed/47D9-U8hn5I" frameborder="0" allowfullscreen></iframe>
</p>

<p><iframe width="420" height="315" src="http://www.youtube.com/embed/9AVG8odajpA" frameborder="0" allowfullscreen></iframe></p>

<p><iframe width="420" height="315" src="http://www.youtube.com/embed/aFztjgfDWDA" frameborder="0" allowfullscreen></iframe></p>

<p>
  I was told my talks were too technical and depressing.  WHO&#8217;S LAUGHING NOW, HUH.  Oh right, EVERYONE.
</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[Happiness Lecture at Noisebridge]]></title>
    <link href="http://tersesystems.com/2011/07/15/happiness-lecture-at-noisebridge" />
    <updated>2011-07-15T15:11:00-07:00</updated>
    <id>http://tersesystems.com/2011/07/15/happiness-lecture-at-noisebridge</id>
    <content type="html"><![CDATA[<p>Ty put up a video of me presenting Happiness @ Noisebridge.</p>

<p>It has kittens.</p>

<iframe src="http://www.youtube.com/embed/MCjiCvG1DuY" frameborder="0"
width="529" height="426" allowfullscreen="true" webkitallowfullscreen="true"></iframe>

<p>Updated: Now with slides!</p>

<iframe src="https://docs.google.com/presentation/embed?id=16IiPcJKEoDi-_0d3IMcC7MR_Vx-092NZA3Ep5igoF1E&start=false&loop=false&delayms=3000" frameborder="0" width="529" height="426" allowfullscreen="true" mozallowfullscreen="true" webkitallowfullscreen="true"></iframe>]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Core of Agile]]></title>
    <link href="http://tersesystems.com/2011/06/12/the-core-of-agile" />
    <updated>2011-06-12T00:00:00-07:00</updated>
    <id>http://tersesystems.com/2011/06/12/the-core-of-agile</id>
    <content type="html"><![CDATA[<p>
	I&#39;ve been thinking lately about Agile. &nbsp;Again.</p>
<p>
	The first thing I&#39;ve been thinking about is the people who say &quot;You&#39;re doing Agile Wrong.&quot;</p>
<p>
	There&#39;s always been a dichotomy for me between the theory of Agile, and the practice. &nbsp;It&#39;s a common problem with any dream; it&#39;s always cleaner, brighter, simpler, better than the reality. &nbsp;Reality is messy. &nbsp;It is imprecise. &nbsp;It is never seen directly, always filtered through recollections to make each participant the protagonist of their own play. &nbsp;</p>
<p>
	If you try pair programming, then you&#39;re going to find that &quot;you should never pair program 100% of the time.&quot; &nbsp;Or that &quot;you should only pair program between people with equal skill sets.&quot; &nbsp;Or that &quot;you should practice pair programming ping pong&quot;. &nbsp;There will always be a special case. There will always be something that works for you that doesn&#39;t work for someone else. &nbsp; There will always be something that doesn&#39;t work for you that works for someone else.</p>
<p>
	Not only do we do Agile &quot;wrong&quot;, but we will always do Agile &quot;wrong&quot;. &nbsp;We won&#39;t ever do anything &quot;right&quot; &#8211; we will do imperfect jobs, come home to imperfect relationships, have imperfect children and live imperfect lives. &nbsp; This is what happens when you measure yourself against an ideal.</p>
<p>
	But why believe in Agile then, if the only way you can do it is wrong? &nbsp;Something that came to mind about that statement. &nbsp;</p>
<p>
	If you&#39;re trying to do Agile, and it&#39;s not working for you&#8230; then you&#39;re doing it wrong.</p>
<p>
	Another way of phrasing that statement is that Agile is Doing It Right. &nbsp;</p>
<p>
	In fact, almost by definition, Agile is Doing It Right.</p>
<p >
	&quot;Agile teams produce a continuous stream of value, at a sustainable pace, while adapting to the changing needs of business.&quot; &#8211; <a href="http://testobsessed.com/2010/12/14/the-agile-acid-test/">Elizabeth Hendrickson</a>.</p>
<p >
	&quot;Agile development uses feedback to make constant adjustments in a highly collaborative environment.&quot; &#8211; <a href="http://pragprog.com/titles/pad/practices-of-an-agile-developer">Practices of an Agile Developer</a>.</p>
<p>
	&quot;Agile has no definition. [&#8230;] There&#39;s no standards board, there&#39;s no test, there&#39;s no approved workbook, there&#39;s no checklist. &nbsp;[&#8230;] It&#39;s based on three things: 1) principles not practices, 2) attention to people, and 3) always be adapting.&quot; &#8211; <a href="http://www.whattofix.com/blog/archives/2010/09/agile-ruined-my.php">Daniel Markham</a>.</p>
<p>
	Three definitions of Agile. &nbsp;Nothing about practices, or even methodology. &nbsp;What they agree on is a feedback cycle that can respond to changing input and produce useful output. &nbsp;</p>
<p>
	It&#39;s <a href="http://tersesystems.com/2011/06/10/the-logic-of-failure">Dorner&#39;s model of problem solving</a>. &nbsp;Or Deming&#39;s <a href="http://en.wikipedia.org/wiki/PDCA">PDCA cycle</a>. &nbsp;Or the Military&#39;s&nbsp;<a href="http://en.wikipedia.org/wiki/OODA_loop">OODA cycle</a>. &nbsp; Or the <a href="http://en.wikipedia.org/wiki/Scientific_method">Scientific Method</a>. &nbsp;Or <a href="http://en.wikipedia.org/wiki/Kaizen">Kaizen</a>. &nbsp;It&#39;s continous process improvement, in all its forms.</p>
<p>
	If you&#39;re following a &quot;best practice&quot; and that &quot;best practice&quot; isn&#39;t working for you, then it&#39;s not a case of &quot;You&#39;re Doing Agile Wrong.&quot; &nbsp;You&#39;re doing something that isn&#39;t providing a benefit for you. &nbsp; By following that &quot;best practice&quot;, you&#39;re not doing Agile at all. Agile is the ability to plan something new, throw out something old, and challenge preconceived beliefs.</p>
<p>
	That&#39;s the core of Agile for me: it&#39;s not about Wrong or Right. &nbsp;It&#39;s the idea of saying &quot;We can do better.&quot; &nbsp;And then doing it.</p>
]]></content>
  </entry>
  
  <entry>
    <title type="html"><![CDATA[The Logic of Failure]]></title>
    <link href="http://tersesystems.com/2011/06/10/the-logic-of-failure" />
    <updated>2011-06-10T00:00:00-07:00</updated>
    <id>http://tersesystems.com/2011/06/10/the-logic-of-failure</id>
    <content type="html"><![CDATA[<p>
	Another talk, this time on <a href="http://www.amazon.com/Logic-Failure-Recognizing-Avoiding-Situations/dp/0201479486">The Logic of Failure: Recognizing and Avoiding Error in Complex Situations</a>, a book by <a href="http://www.uni-bamberg.de/allgpsych/team/dietrich-doerner/">Dietrich Dorner</a>.</p>
<p>
	The book&rsquo;s been a favorite of mine for years, not just for the set up, but for the detailed, unsparing look it provides on how human beings fail to get things right. &nbsp;Too often in psychology, there&rsquo;s an emphasis on either seeing how people feel about a situation, or how well or how poorly they perform at a given task. &nbsp;Dorner goes further, and tries to understand not just how, but why they fail.</p>
<h4>
	The Slides</h4>
<p>
<iframe src="https://docs.google.com/present/embed?id=dcxrsgwk_137cncdckf4&size=m" frameborder="0" width="555" height="451"></iframe>
</p>
<h4>
	The Setup</h4>
<p>
	The setup was simple. &nbsp;Dorner set up a computer simulation of an African village called Tanaland. &nbsp;This book was written in 1990, and so Sim City was not widely known, but it&rsquo;s the same concept. &nbsp;The players were given dictatorial powers, given the goal to &ldquo;improve the wellbeing of the people&rdquo; and had six opportunities over 10 years to review (and possibly change) their policies.</p>
<h4>
	The Experiment</h4>
<p>
	Given the tools the players had at hand, they went to improving what they could. &nbsp;They improved the food supply (using artifical fertilizer) and increased medical care. &nbsp;There were more children and fewer deaths, and lif expectancy was higher. &nbsp;For the first three sessions, everything went well. &nbsp;But unknown to the players, they&rsquo;d set up an unsustainable situation.</p>
<p>
	Famine typically broke out in the 88th month. &nbsp;The agarian population dropped dramatically, below what they had been initially. &nbsp;Sheep, goats and cows died off in their herds, and the land was left barren by the end. &nbsp;Given a free hand, most players engineered a wasteland.</p>
<p>
	One player, by the end of the simulation, had a stable population and had significantly better quality of life for the villagers. &nbsp;Failure was the rule, but somehow he had found an exception.</p>
<h4>
	The Breakdown</h4>
<p>
	The litany of possible errors was a long one, and so immediately recognisable that it&#39;s hard to suppress a wince of empathy on reading.</p>
<p>
	The players who did badly tended not to ask &quot;why&quot; things happened. &nbsp;They tended to jump from one subject to another, switching aimlessly, without focus. &nbsp;They proposed hypotheses without testing them. &nbsp;If they did test their hypotheses, they did so on an adhoc basis, testing success cases without testing possible failure cases. &nbsp;In some cases they had tunnel vision: focussing on irrelevancies at the expence of the larger picture. &nbsp;In other cases, they attempted to &quot;delegate&quot; intractable problems to the villagers themselves or refused to deal with the issue at all. &nbsp;Finally, and most tellingly, most players dealt with the problems that they saw &quot;on the spot&quot; without thinking of the larger, longer term problems that they were setting up with that immediate short term solution.</p>
<p>
	These results were not a surprise. &nbsp;They were just what Dorner&#39;s team was looking for. &nbsp;Where many scientists would have looked at the successes and determined the optimal &quot;working strategy&quot; &#8211; Dorner was just as interested in the range of failures in the experiment. &nbsp; Dorner&#39;s team had specifically designed the simulation so that most people would fail at it, precisely aiming at the weak points of human decision making. &nbsp;</p>
<p>
	Not all players failed in the same way. &nbsp;Even amongst the players who failed the same way, many players had different reasons for their particular mode of failure. &nbsp;And yet, there were strong commonalities among the failing players, both in their reactions to incipient failure, and in their attempts at recovery.</p>
<h4>
	The Reasons</h4>
<p>
	The reason why most people failed was that they did not understand the nature of Tanaland. &nbsp;Despite being a simulation, Tanaland was no game, and Dorner&#39;s team programmed in as accurate a simulation of an African village as the hardware would allow. &nbsp;The watertable under the village had a limited amount of water available. &nbsp;The population grew at an exponential rate given the available food and healthcare. &nbsp;Even the topsoil was modelled accurately, so that overgrazing caused by massive herds would erode the topsoil over time. &nbsp;All of this data was available to the players &#8211; had they thought to look. &nbsp;But most players didn&#39;t. &nbsp;The experiment ended in three predictable failure modes: either the cattle starved and died, or the groundwater was exhausted, or the population exceeded the available food. &nbsp;Far from being a bundle of independent subsystems, all of Tanaland was deeply intertwingled.</p>
<h4>
	The Weaknesses</h4>
<p>
	The deeper reason why Tanaland was so successful at bamboozling players is partly due to the incredible success of the human brain&#39;s pattern recognition system. &nbsp;Human beings are capable of driving in heavy traffic, understanding language, and recognizing patterns in almost random data, feats far beyond most computers. &nbsp;But there are some problems which defeat human intuition. &nbsp;</p>
<p>
	<strong>Linear extrapolation.&nbsp;</strong>Human beings have a tendency to assume change itself is static. &nbsp;Even when shown exponential growth, we&#39;re not good at internalizing that knowledge. &nbsp;This may be why calculus is so hard for many people, because we don&#39;t think about the rate of growth itself growing.</p>
<p>
	<strong>Delayed Feedback.&nbsp;</strong>Human beings tend to assume that an action will yield a response immediately, or not at all. &nbsp;This is the way that we interact with the world on a daily basis, and we can become very confused when there&#39;s a significant delay in the system&#39;s response. &nbsp;Even when we recognize intellectually that a change is &quot;in the pipeline&quot;, we may struggle against the instinct to do more and oversteer rather than correctly &quot;sitting on our hands.&quot;</p>
<p>
	<strong>Contradicting goals.&nbsp;</strong>Part of the failure of players was inherent in the vague goals that they had. &nbsp;What, exactly does &quot;improve the wellbeing of the people&quot; really mean? &nbsp;Does it mean providing the best quality of life to all the villagers? &nbsp;Growing the village as a whole to be more prosperous? &nbsp;In many cases, the top level goal ended up being broken down into goals that conflicted with each other. &nbsp;In other cases, players tried to find concrete problems to fix. &nbsp;One player, deciding that the village needed irrigation, set out building an irrigation system and quickly became fixated on that one problem, becoming &quot;addicted&quot; to his experience of flow. &nbsp;In such cases, &nbsp;players were unable to clearly form goals at all.</p>
<p>
	<strong>Priorities</strong>.&nbsp;Even when the players had clearly defined goals, they had another problem to contend with: they would be stymied by cases where actions which furthered one goal would thwart another. &nbsp;The complex interdependencies in the system did not allow for a full optimization of every variable, and players would either flail uselessly or be paralysed by their inability to cover every base.</p>
<p>
	<strong>Information overload.&nbsp;</strong>In many cases, the players used too little information to know how to make the best decisions. &nbsp;However, some players had the opposite problem; given access to all data of a complex system, they tried to see the entire system at once. &nbsp;These players found themselves paralysed by complexity, and unable to interpret the results of the data. &nbsp;Interestingly, the problem the players had was not that they did not see the correct chart. &nbsp;They were literally unable to recognize the charts and the changes in data as relevant &#8211; having looked at all the data available, their abilities to see a pattern was exhausted well before they stumbled on the correct chart.</p>
<p>
	<strong>Reductive Hypotheses.&nbsp;</strong>By far the worst problem that players had, above all others, was that the first hypotheses they formed about the system were not changed in response to the data. &nbsp;If anything, the players were apt to be the most sure in their beliefs when the hypotheses were completely wrong. &nbsp;Part of this came from uncertainty and cognitive dissonance. &nbsp;Uncertainty produced fear and doubt. &nbsp;Asserting the hypothesis helped quell this fear and doubt. &nbsp;Over time, the players learned that the more they believed in the hypothesis, the better they felt. &nbsp;This reduced their ability to develop new hypotheses, as they were already &quot;wedded&quot; to their existing ideas.</p>
<h4>
	The Successes</h4>
<p>
	There were also commonalities amongst the players who did well. &nbsp;The players who did well were the ones who could tolerate uncertainty. &nbsp;They defined clear goals and priorities. &nbsp;They made many small decisions in different areas, and followed up on the expected vs actual results of most, if not all of those decisions. &nbsp;They kept an eye on the overall processes of the system, and did not succumb to flow experiences.</p>
<p>
	Adding to this, Dorner&#39;s team ran an experiment with two groups of fifteen players each. &nbsp;One group was drawn from the student population. &nbsp;The other group was made of senior managers from large industrial and commercial firms. &nbsp;The managers did significantly better than the students on every possible metric; given several different challenges, they responded appropriately to each one. &nbsp;Dorner&#39;s team was unable to determine if this was innate talent or the benefit of years of experience.</p>
<h4>
	A Decision Making Model</h4>
<p>
	So what is the right thing to do when faced with a complex situation? Dorner presents a possible schema for problem solving, intended more as a helpful aid than as a representation of how people&nbsp;actually solve problems. &nbsp;&nbsp;</p>
<ol>
	<li>
		Formulation of Goals - deciding what it is that needed fixing, and putting priorities on those goals.</li>
	<li>
		Formulation of Models - determining the internal workings of the system.</li>
	<li>
		Prediction and Extrapolation - determining the eventual output of the system.</li>
	<li>
		Planning of Actions; decision making, and execution of actions - feeding input into the system.</li>
	<li>
		Review of effects of actions and revision of strategy - determining the expected model vs the actual model.</li>
</ol>
<p>
	Interestingly, this is very close to the <a href="http://en.wikipedia.org/wiki/PDCA">Plan/Do/Check/Act cycle</a> proposed by&nbsp;Deming&nbsp;&#8211; it assumes incomplete knowledge of a complex system and tries to improve understanding of the underlying model through repeated iterations of the cycle.</p>
<p>
	Dorner also notes that being simply told of a decision making strategy did no good at all to players; when given instruction on dealing with complex systems, the players thought that they had been helped and were better able to discuss their failures with better terminology&#8230; but their actual performance was the same as the control group. &nbsp;What really helped players, overall, was repeated exposure to complex systems. &nbsp;Showing was not enough; they had to experience their own reactions and build up their tolerance to decision making in the face of uncertainty and emotional stress.</p>
]]></content>
  </entry>
  
</feed>
