<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sam Facer on Medium]]></title>
        <description><![CDATA[Stories by Sam Facer on Medium]]></description>
        <link>https://medium.com/@SamPFacer?source=rss-e2539b7d4744------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*x0e5WAV_OGcLOby0xo0cCQ.jpeg</url>
            <title>Stories by Sam Facer on Medium</title>
            <link>https://medium.com/@SamPFacer?source=rss-e2539b7d4744------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 04 Dec 2026 02:08:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@SamPFacer/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Scala Days Berlin — 2018]]></title>
            <link>https://medium.com/@SamPFacer/scala-days-berlin-2018-822b4209c01b?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/822b4209c01b</guid>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Thu, 07 Jun 2018 10:23:15 GMT</pubDate>
            <atom:updated>2018-06-07T10:23:15.292Z</atom:updated>
            <content:encoded><![CDATA[<p>Scala Days Berlin is complete, and what a awesome event it was! Roughly 1000 people congregated at the Kosmos Cinema in Berlin to witness some fantastic presentations, network with their peers, and ultimately show their support for the Scala community.</p><p>We also brought along the team from <a href="http://www.standbyproductions.co.uk/">Standby Productions</a> to film the whole thing, so here’s what the team thought of Scala Days Berlin 2018.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Ffast.wistia.net%2Fembed%2Fiframe%2Fzg7l4m5eew%3FvideoFoam%3Dtrue&amp;url=https%3A%2F%2Ffast.wistia.net%2Fembed%2Fiframe%2Fzg7l4m5eew%3FvideoFoam%3Dtrue&amp;image=https%3A%2F%2Fembed-ssl.wistia.com%2Fdeliveries%2F37fdd8864990b88eebd32429650e9cc5f1f34a95.jpg%3Fimage_crop_resized%3D960x540&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=wistia" width="960" height="540" frameborder="0" scrolling="no"><a href="https://medium.com/media/8eddfd3cfe80921ec38015046d1d2a4c/href">https://medium.com/media/8eddfd3cfe80921ec38015046d1d2a4c/href</a></iframe><p>Having sponsored and supported Scala Days for 4 consecutive years, our 5th year was surprisingly new territory for Cake, as we announced ourselves as a <a href="https://www.bamtechmedia.com/">BAMTECH</a> Media company, and what a fantastic response we had. Everyone was fascinated to know what had happened to Cake since they last saw us, and how the work we are doing now will be enjoyed by millions of subscribers. Here’s the new look stands (along with swag for all).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/0*cx85LK9fMgWwhGsP" /><figcaption>Bamtech Media Scala Days Stand</figcaption></figure><p>It was also great to see how large the Scala community has grown over the past year, with new sponsors like <a href="https://www.linkedin.com/showcase/iot-fast-data-platform/">Audi</a>, <a href="https://www.evolutiongaming.com/">Evolution Gaming</a>, <a href="https://www.here.com/en">Here</a> and <a href="https://www.signifytechnology.com/">Signify</a> joining in with our friends from <a href="https://virtuslab.com/">Virtus Labs</a>, <a href="https://www.knoldus.com/home.knol">Knoldus</a>, <a href="https://www.47deg.com/">47 Degrees</a> and <a href="https://www.lunatech.com/">Lunatech</a>.</p><p><strong>Highlights</strong></p><p>Not surprisingly, <a href="https://eu.scaladays.org/">Martin Odersky’s</a> keynote got the conference off to a rapturous applause, and was a clear signal for the rest of the event!</p><h3>Martin Odersky on Twitter</h3><p>Having a great time at #ScalaDays. Lots of good discussions about the move to Scala-3, and a very positive vibe. Here are my slides of the opening keynote: https://t.co/lQkEQyIFwH</p><p>Our very own <a href="https://twitter.com/tamer_radi">Tamer</a> took to the main stage on Wednesday to deliver his expert talk <a href="https://eu.scaladays.org/lect-6907-literal-types%2C-what-they-are-good-for.html">“Literal types, what they are good for”</a> which went down a treat with the audience, and clearly created some envy/admiration across a few followers!</p><p><strong>Upcoming Events</strong></p><p>Up next is the New York edition of <a href="https://na.scaladays.org/">Scala Days</a>, which will be held at the New York Sheraton hotel in Times Square from Tuesday 19th to Thursday 21st June, and our friends from the New York <a href="https://www.bamtechmedia.com/">BAMTECH</a> office will out in full force to meet everyone!</p><p>We will be sponsoring the upcoming <a href="https://skillsmatter.com/conferences/10488-scala-exchange-2018">Scala eXchange</a> in London in December 2018, with more details to follow, and also support the monthly <a href="https://www.meetup.com/scala-developers/">Scala</a> and <a href="https://www.meetup.com/Reactive-New-York/">Reactive</a> meetups in Manchester and New York.</p><p><strong>Careers</strong></p><p>If you’re interested in <a href="https://www.bamtechmedia.com/careers">joining</a> a world class, distributed Scala team building streaming services for some of the most iconic brands globally, get in touch.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=822b4209c01b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Week in Scala (04/06/2018)]]></title>
            <link>https://medium.com/@SamPFacer/this-week-in-scala-04-06-2018-50f485f67ede?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/50f485f67ede</guid>
            <category><![CDATA[distributed-systems]]></category>
            <category><![CDATA[akka]]></category>
            <category><![CDATA[thisweekinscala]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[scala]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Mon, 04 Jun 2018 10:50:28 GMT</pubDate>
            <atom:updated>2018-06-25T10:05:04.842Z</atom:updated>
            <content:encoded><![CDATA[<p>Welcome to the new edition of #ThisWeekInScala!</p><p>This blog aims to keep you up to date with the latest news from the world of Scala and Reactive programming.</p><p>It has been a week since <a href="https://www.cakesolutions.net/teamblogs/this-week-in-scala-30/04/2017">last time</a>, so lets catch-up on the latest Scala &amp; Reactive happenings…</p><h3>New Content</h3><ul><li>Futures in Scala pro tips vol. <a href="https://viktorklang.com/blog/Futures-in-Scala-protips-5.html">5</a> and <a href="https://viktorklang.com/blog/Futures-in-Scala-protips-6.html">6</a> by Viktor Klang himself</li><li><a href="http://www.lihaoyi.com/post/ZeroOverheadTreeProcessingwiththeVisitorPattern.html">Zero-Overhead Tree Processing</a> with the Visitor Pattern</li><li>More <a href="https://mostafa-asg.github.io/post/more-readable-code-in-scala/">Readable Code</a> in Scala</li><li><a href="https://kubuszok.com/2018/relearn-your-sbt/">Relearn</a> your sbt!</li><li><a href="https://developer.lightbend.com/blog/2018-05-29-berlin-scala-spree-and-sbt-1-1-6/">Berlin Scala Spree and sbt 1.1.6</a></li><li>How <a href="https://mostafa-asg.github.io/post/more-readable-code-in-scala/">composing functions</a> lead to more readable code</li><li>Akka anti-patterns: <a href="https://manuel.bernhardt.io/2018/05/30/akka-anti-patterns-stateless-actors/">stateless actors</a></li><li>Incorporating <a href="https://blog.softwaremill.com/incorporating-facenet-into-play-framework-with-silhouette-authentication-4a8844849b62">FaceNet into Play framework</a> with Silhouette authentication</li><li><a href="https://underscore.io/blog/posts/2018/05/17/modelling-js.html">Modelling JavaScript in Scala</a> with Scala.js</li><li>Implicit Implications (part 1): <a href="https://functional.works-hub.com/learn/implicit-implications-part-1-implicit-parameters-098e0">Implicit Parameters</a></li><li>Functional Programming with <a href="https://medium.com/@joang/a-cqrs-approach-with-kafka-streams-and-scala-49bfa78e4295">Kafka Streams and Scala</a></li><li><a href="https://techblog.commercetools.com/scaladays-2018-berlin-takeaways-f4f40f2fe925">ScalaDays 2018 Berlin Takeaways</a></li><li>Scalar 2018 whiteboard <a href="https://blog.softwaremill.com/scalar-2018-whiteboard-voting-results-c6f50f8fb16d">voting results</a>!</li></ul><h3>Updated Software</h3><ul><li><a href="https://developer.lightbend.com/blog/2018-05-29-berlin-scala-spree-and-sbt-1-1-6/">sbt</a> 1.1.6</li><li><a href="https://github.com/lihaoyi/mill">Published</a> v0.2.3 of the Mill Scala build tool</li><li>Cats-Effect 1.0.0-RC2 is <a href="https://github.com/typelevel/cats-effect">out</a>, the last one before 1.0</li><li>Just <a href="https://t.co/F5XGBAwdzr">released</a> akka-http-json 1.21.0</li><li><a href="https://github.com/frees-io/freestyle-rpc/releases/tag/v0.13.5">freestyle-rpc</a> 0.13.5</li><li><a href="https://github.com/softwaremill/sttp/tree/v1.2.0-RC1">sttp</a> 1.2.0-RC1</li><li><a href="https://github.com/epfldata/squid/releases/tag/v0.3.0">squid</a> 0.3.0</li><li>xml-lens is <a href="https://mailchi.mp/softwaremill/scala-times-issue-2607917">out</a></li><li>Flink 1.5.0 is <a href="https://t.co/TjnjXqSE4U">out</a>! This release includes many significant features, such as a completely reworked deployment model supporting dynamic resource allocations, improved latency, faster recovery, broadcast state, more SQL joins</li></ul><p>In case you are looking for new challenges, pay attention, because Disney Streaming Services are <a href="https://jobs.disneycareers.com/search-jobs?k=Bamtech">hiring</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/560/1*bVTMq95jFTsSx9pHjXV7qA.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50f485f67ede" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fans demand access to content on their own terms on any device, anytime, anywhere.]]></title>
            <link>https://medium.com/@SamPFacer/careers-ab17a1731d28?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab17a1731d28</guid>
            <category><![CDATA[recruitment]]></category>
            <category><![CDATA[careers]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Wed, 16 May 2018 14:37:59 GMT</pubDate>
            <atom:updated>2018-05-16T15:26:20.530Z</atom:updated>
            <content:encoded><![CDATA[<p>We are those fans. As a result the BAMTECH team helped pioneer live event streaming over the Internet in 2002 for Major League Baseball. The passion to improve that experience led to many impressive firsts: the first 720p or “HD Ready” stream, the consecutive record for concurrent streams and the first stream in 8K ultra HD. Today BAMTECH has a proven, scalable platform that powers direct-to-consumer applications for leading entertainment brands; and is now a major player in sports and eSports rights acquisition.</p><p>Three reasons to join BAMTECH media …</p><p><strong>Challenging work to be proud of</strong></p><p>Working with the top sports, media and gaming brands in the world brings world class challenges. Go home everyday being proud for setting new standards and impacting millions of fans across the globe.</p><p><strong>Work with the best to create the best</strong></p><p>BAMTECH is full of smart creatives with interests ranging far beyond sports, media or gaming. We are a versatile bunch, bringing a different viewpoint to the industry. However, we all do have one thing in common: we are very good at what we do.</p><p><strong>We are all on the same team</strong></p><p>We all strive to push each other in the right direction. Whether it be for professional growth, personal enrichment or a good work-life balance, what’s good for our employees, is good for our work and our clients.</p><p>We’re seeking talent across disciplines to join our team. Whether in New York City, San Francisco, London, Manchester or Amsterdam</p><p><a href="https://jobs.disneycareers.com/search-jobs?k=Bamtech">Reach Out</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ovCTPB4ygtdteygBpji_uw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab17a1731d28" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Passing parameters in Gatling]]></title>
            <link>https://medium.com/@SamPFacer/passing-parameters-in-gatling-85d40c05b0fa?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/85d40c05b0fa</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[gatling]]></category>
            <category><![CDATA[bamtech]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Wed, 01 Mar 2017 08:00:00 GMT</pubDate>
            <atom:updated>2018-05-24T13:25:50.309Z</atom:updated>
            <content:encoded><![CDATA[<p>Parameters can be passed to a simulation from the command line or from the launch script <em>gatling.sh</em>.</p><p>Refer to <a href="http://gatling.io/docs/2.2.3/cookbook/passing_parameters.html">this page</a>.</p><p>Consider this simple simulation:</p><p>class A_AtOnceUsers_1000 extends Scenario2 {<br> setUp(scen(&quot;Example scenario&quot;)<br> .inject(<br> atOnceUsers(1000),<br> nothingFor(5 seconds),<br> atOnceUsers(1000))<br> .protocols(httpConf))<br> .assertions(global.responseTime.mean.lt(2000))<br>}</p><p>We could declare a variable with the value 1000 and insert it in the simulation, as it appears there twice.</p><p>First, declare it like this:</p><p>val A_AtOnce = Integer.getInteger(&quot;A_AOusers&quot;, 1)</p><p>Then, insert the val in the simulation:</p><p>atOnceUsers(A_AtOnce),<br>nothingFor(5 seconds),<br>atOnceUsers(A_AtOnce))</p><p>Finally, we have to define the value of <em>A_AOusers</em>. We can do it from the command line or we can put it in the launch script itself.</p><p>From the command line:</p><p>$ JAVA_OPTS=”-DA_AOusers=1000” ./gatling.sh</p><p>Alternatively, put <strong>JAVA_OPTS=”-DA_AOusers=1000”</strong> in <em>gatling.sh</em>.</p><p>Note that the script takes priority here, as it is executed last - if you add the line above to the script, but then run something like:</p><p>$ JAVA_OPTS=”-DA_AOusers=1234” ./gatling.sh</p><p>the simulation will run with <em>A_AOusers</em> having the value of 1000, not 1234.</p><p>Another thing to be aware of is that arguments:</p><p>rampUsersPerSec<br> constantUsersPerSec</p><p>take Double, not Integer. (Eg. <em>rampUsersPerSec(Double) to Double</em>)</p><p>A simple way to tackle this is this:</p><p>val nbUsers = Integer.getInteger(&quot;users&quot;).toDouble</p><p>not forgetting about <strong>JAVA_OPTS=”users=[Int]”</strong></p><p>By Adam Grzegorzewski</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85d40c05b0fa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A different way of writing Gatling scenarios]]></title>
            <link>https://medium.com/@SamPFacer/a-different-way-of-writing-gatling-scenarios-5d45168b6199?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/5d45168b6199</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[gatling]]></category>
            <category><![CDATA[bamtech]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Tue, 28 Feb 2017 08:00:00 GMT</pubDate>
            <atom:updated>2018-05-24T13:26:26.636Z</atom:updated>
            <content:encoded><![CDATA[<p>I’m new to Scala and too the Gatling framework in general, here is some of my observations when creating a test suite.</p><p>Gatling is an open-source load testing tool based on Scala. It is aimed to be easy to use, supports HTTP, WebSockets, JMS, and utilises a DSL when coding scenarios and simulations.</p><p>Gatling runs users as messages, rather than threads, allowing to simulate a large number of concurrent users in a resource-cheap way</p><p>Simulations can be modelled using an in-built <em>recorder</em> or can be written by hand.</p><p>Gatling documentation provides an example Gatling simulation in the Quickstart chapter, paragraph ‘<a href="http://gatling.io/docs/2.2.3/quickstart.html#gatling-scenario-explained"><em>Gatling scenario explained</em></a>’.</p><p>Let’s take a look:</p><pre>package computerdatabase</pre><pre>import io.gatling.core.Predef._</pre><pre>import io.gatling.http.Predef._<br>import scala.concurrent.duration._</pre><pre>class BasicSimulation extends Simulation {</pre><pre>val httpConf = http<br>   .baseURL(&quot;http://computer-database.gatling.io&quot;)</pre><pre>.acceptHeader(&quot;text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8&quot;)<br>   .doNotTrackHeader(&quot;1&quot;)<br>   .acceptLanguageHeader(&quot;en-US,en;q=0.5&quot;)<br>   .acceptEncodingHeader(&quot;gzip, deflate&quot;)<br>   .userAgentHeader(&quot;Mozilla/5.0 (Windows NT 5.1; rv:31.0) Gecko/20100101 Firefox/31.0&quot;)</pre><pre>val scn = scenario(&quot;BasicSimulation&quot;)<br>   .exec(http(&quot;request_1&quot;)</pre><pre>.get(&quot;/&quot;))<br>   .pause(5)</pre><pre>setUp( <br>   scn.inject(atOnceUsers(1)) <br> ).protocols(httpConf) <br>}</pre><p>The code above is the output from the Gatling recorder, but it can easily be written by hand.</p><p>What we have here is a Class BasicSimulation which contains all the required vals and the setUp in it.</p><p>If we wanted to add another simulation in the same file, we’d have to copy/paste a lot of the same information — basically create a new <em>simulation</em> class with the same values and variables declarations and the same scenario definition — only editing the <strong>setUp</strong> part. We could also opt to create a new file to do that. Either way, there is a lot of repeated code which we can avoid.</p><p>Solution:</p><p>1. Wrap the whole code inside a trait</p><p>2. Construct methods for clearer scenario setup.</p><p>Example:</p><pre>trait Scenario extends Simulation {</pre><pre>val httpConf = http<br>   .baseURL(&quot;Example URL&quot;)<br>   .acceptHeader(&quot;text/plain,text/html,application/xhtml+xml,application/json,application/xml;q=0.9,*/*;q=0.8&quot;)    .doNotTrackHeader(&quot;1&quot;)<br>   .acceptLanguageHeader(&quot;en-US,en;q=0.5&quot;)<br>   .acceptEncodingHeader(&quot;gzip, deflate&quot;)<br>   .userAgentHeader(&quot;Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:16.0) Gecko/20100101 Firefox/16.0&quot;)</pre><pre>val headers = Map(&quot;Content-Type&quot; -&gt; &quot;application/json&quot;)</pre><pre>def firstMethod(A: Int, B: Int) =<br>   http(&quot;Example Name&quot;)<br>     .post(&quot;Example endpoint&quot;)<br>     .headers(headers)<br>     .body(StringBody(s&quot;&quot;&quot;{<br>              &quot;exampleValue&quot;: {<br>                    &quot;numberOne&quot; : $A,<br>                    &quot;numberTwo&quot; : $B<br>                   }<br>              }<br>     }&quot;&quot;&quot;)).asJSON<br>     .check(jsonPath(&quot;$.ID&quot;).saveAs(&quot;yourVariable&quot;))</pre><pre>def secondMethod() =<br>   http(&quot;Example Name 2&quot;)<br>     .get(&quot;Some endpoint/$yourVariable&quot;)<br>     .headers(headers)<br>     .check(jsonPath(&quot;$.AplusB&quot;).saveAs(&quot;result&quot;))</pre><pre>// Here is the scenario definition.</pre><pre>// Because we are using functions it is concise and easy to read and edit.</pre><pre>def scen(name: String) = {<br>  scenario(name)<br>         .exec(firstMethod(10, 20))<br>         .exec(secondMethod())<br>         .exec(session =&gt; {</pre><pre>val aaa = session.get(&quot;result&quot;).as[Int]<br>println(&quot;RESULT ----&gt;    &quot; + aaa)<br>session<br> })</pre><pre>}<br>}</pre><pre>// Method scen takes one argument, allowing you to name the scenario.</pre><pre>class 01_Example_Simulation_1_User extends Scenario {<br> setUp(scen(&quot;Provide the name of the scenario here&quot;)<br>     .inject(atOnceUsers(1))<br>     .protocols(httpConf))<br>}</pre><pre>class 02_Example_Simulation_100_RampUp_Users extends Scenario {<br> setUp(scen(&quot;Provide the name of the scenario here&quot;)<br>     .inject(rampUsers(100) over (5.second))<br>     .protocols(httpConf))<br>}</pre><p>(It doesn’t really matter what this simulation does — let’s say it submits values A and B, receives an ID of the target, then queries the ID for, say, A + B. Then prints A + B to the console.)</p><p>Because we have wrapped the simulation in a <strong>trait</strong>, we are able to vary our scenarios as separate classes, easily adding new ones when we want to, without having to copy a bulk of our code.</p><p>The two scenario classes will appear as distinct choices when running gatling.sh, as if they were separate simulations or separate Gatling files.</p><p>Using methods makes it clearer to read and edit when defining the scenario.</p><p><strong>By Adam Grzegorzewski</strong></p><p>Resources:</p><p>[1] Gatling, main page: <a href="http://gatling.io/#/">http://gatling.io/#/</a></p><p>[2] Gatling, documentation: <a href="http://gatling.io/docs/2.2.3/">http://gatling.io/docs/2.2.3/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*GZU_d_ZpezTQmlgb.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5d45168b6199" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Enforcing invariants in Scala datatypes]]></title>
            <link>https://medium.com/@SamPFacer/enforcing-invariants-in-scala-datatypes-30509e066c3d?source=rss-e2539b7d4744------2</link>
            <guid isPermaLink="false">https://medium.com/p/30509e066c3d</guid>
            <category><![CDATA[scala]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bamtech]]></category>
            <dc:creator><![CDATA[Sam Facer]]></dc:creator>
            <pubDate>Tue, 03 Jan 2017 08:00:00 GMT</pubDate>
            <atom:updated>2018-05-24T13:27:07.688Z</atom:updated>
            <content:encoded><![CDATA[<p>Scala provides many tools to help us build programs with less runtime errors. Instead of relying on nulls, the recommended practice is to use the Option type. Instead of throwing exceptions, Try and Either types are used for representing potential error scenarios. What&#39;s common with these features is that they&#39;re used for capturing runtime features in the type system, thus lifting the runtime scenario handling to the compilation phase: your program doesn&#39;t compile until you&#39;ve explicitly handled nulls, exceptions, and other runtime features in your code.</p><p>In his “Strategic Scala Style” blog post series, Li Haoyi explores <a href="http://www.lihaoyi.com/post/StrategicScalaStyleDesigningDatatypes.html">patterns for enforcing invariants in datatypes</a> using techniques such as self-checks and structural enforcement. Some of the techniques described in the blog post rely on runtime assertions. Thus, while they prevent invalid data from appearing in your datatypes, the datatype construction is not fully represented in the type system.</p><p>In this blog post, I’ll expand the techniques by demonstrating ways to enforce invariants using type-safe, compile-time techniques. First, I’ll demonstrate how the runtime assertion style works using an example datatype. I’ll then show how we can enforce invariants in the example datatype in a type-safe style. Finally, I’ll briefly cover the pitfalls of using case classes for datatypes with type-safe invariant validation, and how we can regain the case class features using tricks in the class inheritance system and ScalaMeta macros.</p><h3>Invariant validation using runtime assertions</h3><p>As an example, let’s create a datatype for conferences. A conference has a name, a start date, and an end date. The name of the conference cannot be empty, and the end date cannot be before the start date. Using the runtime assertion technique, the datatype could be represented as follows:</p><pre>import java.time.LocalDate</pre><pre><strong>case</strong> <strong>class</strong> <strong>Conference</strong>(<strong>name</strong>: <strong>String</strong>, <strong>startDate</strong>: <strong>LocalDate</strong>, <strong>endDate</strong>: <strong>LocalDate</strong>) {<br>  <strong>require</strong>(name.nonEmpty)<br>  <strong>require</strong>(startDate.isEqual(endDate) || startDate.isBefore(endDate))<br>}</pre><p>In the example above, we use Scala’s builtin function require to ensure our datatype complies to our requirements. In order to ensure we&#39;ve captured the potential runtime errors, we can either wrap the datatype construction with a try-catch block or the Try constructor:</p><pre><strong>try</strong> {<br>  val invalidConference = <strong>new</strong> Conference(&quot;&quot;, LocalDate.now(), LocalDate.now())<br>} <strong>catch</strong> {<br>  <strong>case</strong> ex: IllegalArgumentException =&gt;<br>    <em>// Handle the error in any way you like here</em><br>    println(&quot;Invalid parameters when creating a conference: &quot; + ex.getMessage)<br>}</pre><pre>val invalidConference: <strong>Try</strong>[Conference] = <strong>Try</strong>(<strong>new</strong> Conference(&quot;&quot;, LocalDate.now(), LocalDate.now()))</pre><p>The issue here is the same as with any other function that throws errors: the function is partial, not total. This means that only a subset of inputs will produce a value corresponding to the expected type while the rest of the inputs will cause the program execution to escape the normal program flow. The outcome of the invalid inputs is not represented in the type system, thus it is not type-safe.</p><p>In practice, the issue with invariant validation that is not type-safe is that it puts the burden of capturing errors on the user’s side. Failing to capture errors produces non-working software in places where you’d normally expect them work just fine. As the places where the datatype is constructed increases, so does the chance of failing to capture the errors.</p><h3>Enforcing invariants in a type-safe style</h3><p>In order ease the burden of manually catching errors, we can make the invariant validation type-safe by representing the potential runtime errors in the type system. This can be done by providing the users a constructor that returns either the constructed value (an instance of a conference) or an error value.</p><pre><strong>class</strong> <strong>Conference</strong> <strong>private</strong> (<br>  name: String,<br>  startDate: LocalDate,<br>  endDate: LocalDate<br>)</pre><pre>object Conference {<br>  def apply(name: String, startDate: LocalDate, endDate: LocalDate): Option[Conference] =<br>    <strong>if</strong> (name.nonEmpty &amp;&amp; (startDate.isEqual(endDate) || startDate.isBefore(endDate))) {<br>      Some(<strong>new</strong> Conference(name, startDate, endDate))<br>    } <strong>else</strong> {<br>      None<br>    }<br>}</pre><pre>val validConference: Option[Conference] = Conference(&quot;ScalaDays 2017&quot;, LocalDate.<strong>of</strong>(2017, 5, 30), LocalDate.<strong>of</strong>(2017, 6, 2))<br>val invalidConference: Option[Conference] = Conference(&quot;&quot;, LocalDate.now(), LocaDate.now())</pre><p>In the example above, we’ve defined a class for the conference datatype, and an alternative constructor function in the datatype’s companion object that validates the input. For the sake of simplicity, we’ve represented the return type of the alternative constructor as an Option[Conference], where the absence of the value represents a validation error.</p><p>We’ve also hidden the primary constructor of the datatype. This way the constructor can only be used in the scope of the alternative constructor to create validated instances. If the constructor is not hidden, invalid instances may be created by the user accidentally using the wrong constructor. Hiding the primary constructor also effectively prevents the extension of the class.</p><p>A more detailed representation of the construction could include more details about the invariant validation errors. When using the Either type, one of the sides in the type could be used for representing one or more validation errors, while the other side would represent the successful value. For example in Either[List[Error], Conference], the left-side represents all of the errors found during construction, and the right-side represents the successfully built instance of a conference. Regardless of which return type is used, the pattern for building type-safe values is similar: the return value must be &quot;unwrapped&quot; to reach the actual value.</p><p>We can further enhance the validation process by creating meaningful datatypes for the datatype’s fields. For example, the name of the conference can made to its own datatype with its own validation rules:</p><pre>class Name <strong>private</strong> (val name: String) extends AnyVal</pre><pre><strong>object</strong> Name {<br>  def apply(name: String): Option[Name] =<br>    <strong>if</strong> (name.nonEmpty) Some(<strong>new</strong> Name(name))<br>    <strong>else</strong> None<br>}</pre><p>Here the name is encapsulated in a single value class. By making the datatype a value class (i.e. it extends AnyVal), we can in some cases avoid the overhead of allocating the object around the string, but at the same time enjoy the type-safety it provides compared to plain strings. As a value class, the class will also automatically have equals and hashCode methods based on the type it wraps.</p><p>With the Name type in place, we can make the Conference type use it without having to repeat the validation process.</p><pre>class Conference <strong>private</strong> (<br>  name: Name,<br>  startDate: LocalDate,<br>  endDate: LocalDate<br>)</pre><pre><strong>object</strong> Conference {<br>  def apply(name: Name, startDate: LocalDate, endDate: LocalDate): Option[Conference] =<br>    <strong>if</strong> (startDate.isEqual(endDate) || startDate.isBefore(endDate)) {<br>      Some(<strong>new</strong> Conference(name, startDate, endDate))<br>    } <strong>else</strong> {<br>      None<br>    }<br>}</pre><pre>val validConference: Option[Conference] = <strong>for</strong> {<br>  name &lt;- Name(&quot;ScalaDays 2017&quot;)<br>  conference &lt;- Conference(name, LocalDate.of(2017, 5, 30), LocalDate.of(2017, 6, 2))<br>} <strong>yield</strong> conference</pre><h3>Escaping invariant validation in case class datatypes</h3><p>In Scala, case classes bring a bag full of goodies to regular old classes. For example, case classes have an automatically implemented equals, hashCode, toString methods, and an extractor for pattern matching based on the class fields.</p><p>Case classes are convenient for implementing datatypes, so it makes sense to use them as the base type for datatypes where invariants are validated in a type-safe way. However, they also make it easy to bypass the validation checks. Unlike regular classes, case classes have more than one constructor that need hiding. Besides the regular constructor, case classes can also be constructed using their auto-generated apply function and copy methods.</p><pre><strong>case</strong> class Conference <strong>private</strong> (<br>  name: String,<br>  startDate: LocalDate,<br>  endDate: LocalDate<br>)</pre><pre><strong>object</strong> Conference {<br>  def create(name: String, startDate: LocalDate, endDate: LocalDate): Option[Conference] =<br>    <strong>if</strong> (name.nonEmpty &amp;&amp; (startDate.isEqual(endDate) || startDate.isBefore(endDate))) {<br>      Some(<strong>new</strong> Conference(name, startDate, endDate))<br>    } <strong>else</strong> {<br>      None<br>    }<br>}</pre><pre><em>// Invalid instance through apply function</em><br>val invalidConference1: Conference = Conference(&quot;&quot;, LocalDate.now(), LocalDate.now())</pre><pre><em>// Valid instance...</em><br>val Some(validConference) = Conference.create(&quot;ScalaDays 2017&quot;, LocalDate.of(2017, 5, 30), LocalDate.of(2017, 6, 2))</pre><pre><em>// ...can be a gateway to an invalid instance.</em><br>val invalidConference2: Conference = validConference.copy(name = &quot;&quot;)</pre><p>In the example above, we’ve replaced the normal Conference class with a case class. We can still create validated instances of the datatype using the create function in the companion object. However, we can still access the auto-generated apply method, and create invalid instances that way. Moreover, we can use the copy method to create an invalid copy of the datatype from a valid datatype.</p><p>The copy method can be erased by manually overriding it with a method that doesn&#39;t produce invalid copies, but the apply function can neither be overridden or hidden. The inability to replace the function is why the validating constructor function has to occupy a different name. These features make case classes unfeasible for datatypes that enforce invariants in a type-safe way.</p><h3>Regaining the case class features</h3><p>As mentioned earlier, case classes contain a lot of useful features. Thus it would be a shame to lose them just because their apply and copy constructors clash with the invariant validation process. How can we keep the case class features that don&#39;t conflict with the validation?</p><p>One way to have case classes without apply and copy constructors is to make the case classes <a href="https://gist.github.com/tpolecat/a5cb0dc9adeacc93f846835ed21c92d2">abstract and sealed</a>. Like any other class, case classes can be made abstract. This means that the class may define function interfaces that are left open for implementation in its subclasses. It also means that the class must be extended as no instance of it can be created directly even when there&#39;s nothing left for the subclass to implement. Therefore, apply or copyconstructors are not generated for the case class because there&#39;s no known constructor to base their implementation on.</p><p>Because there is no final modifier for limiting subclassing with traits and abstract classes, we&#39;ll have to use the sealed modifier instead. The sealed modifier allows us to limit the scope in which subclasses are made to the source file. Thus, no instances can be made without accessing the constructors we provide.</p><pre><strong>sealed</strong> <strong>abstract</strong> <strong>case</strong> class Conference(name: String, startDate: LocalDate, endDate: LocalDate)</pre><pre><strong>object</strong> Conference {<br>  def apply(name: Name, startDate: LocalDate, endDate: LocalDate): Option[Conference] =<br>    <strong>if</strong> (name.nonEmpty &amp;&amp; (startDate.isEqual(endDate) || startDate.isBefore(endDate)))<br>      Some(<strong>new</strong> Conference(name, startDate, endDate) {})<br>    <strong>else</strong><br>      None<br>}</pre><p>In the example above, we’ve recreated the earlier Conference datatype, but this time as a sealed abstract case class. Our only means of constructing an instance is through the custom constructor we provide. However, as the datatype is now a case class, we can use its case class features such as auto-generated equals and hashCode functions.</p><p>An alternative way to get case class features in a regular class is to use <a href="http://scalameta.org/">ScalaMeta</a>’s @data annotation macro. The @data annotation macro automatically generates case class features for any regular class that uses the annotation. The annotation allows selecting which case class features are included for each class.</p><p>In order to use the annotation, we first need to enable ScalaMeta and the <a href="https://github.com/scalameta/paradise">paradise compiler plugin</a> for the project. Here’s an example of what needs to be added to our SBT configuration:</p><pre><em>// Resolvers for the ScalaMeta library and paradise plugin</em><br>resolvers <strong>in</strong> ThisBuild += Resolver.url(https://medium.com/&quot;scalameta&quot;,%20url(&quot;http://dl.bintray.com/scalameta/maven&quot;))(Resolver.ivyStylePatterns)</pre><pre><em>// Enable paradise compiler plugin</em><br>addCompilerPlugin(&quot;org.scalameta&quot; % &quot;paradise&quot; % &quot;3.0.0.138&quot; cross CrossVersion.full)<br>scalacOptions += &quot;-Xplugin-require:macroparadise&quot;</pre><pre><em>// Add library dependency for ScalaMeta</em><br>libraryDependencies += &quot;org.scalameta&quot; %% &quot;scalameta&quot; % &quot;1.3.0&quot;</pre><p>After enabling the library and the compiler plugin, we can use the @data annotation.</p><pre>class Conference <strong>private</strong> (name: String, startDate: LocalDate, endDate: LocalDate)</pre><pre><strong>object</strong> Conference {<br>  def apply(name: String, startDate: LocalDate, endDate: LocalDate): Option[Conference] =<br>    <strong>if</strong> (name.nonEmpty &amp;&amp; (startDate.isEqual(endDate) || startDate.isBefore(endDate)))<br>      Some(<strong>new</strong> Conference(name, startDate, endDate))<br>    <strong>else</strong><br>      None<br>}</pre><p>In the example above, we’ve annotated the Conference class with the @data annotation. By default, all of the case class features are enabled for the class. Here we&#39;ve disabling the copy and apply constructors, thus we can have full control of the constructors that are visible to the datatype user.</p><h3>Conclusions</h3><p>In this article, I’ve demonstrated a type-safe way for enforcing invariants in Scala datatypes. I’ve shown common techniques for invariant validation that are not type-safe and the issues commonly encountered with them. I’ve also shown the pitfalls of using case classes in combination with the type-safe invariant validation, and how those problems can be avoided using class inheritance and ScalaMeta macros.</p><p>As usual, I’ve made examples for the different invariant validation techniques available in a <a href="https://gist.github.com/jkpl/4932e8730c1810261381851b13dfd29d">Github Gist</a> to play around with. Thanks for reading!</p><p>- <strong>Jaakko Pallari</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=30509e066c3d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>