https://www.endpointdev.com/blog/tags/functional-programming/2021-01-27T00:00:00+00:00End Point DevMonads: Another tool from the functional programming toolboxhttps://www.endpointdev.com/blog/2021/01/monads-another-functional-programming-tool/2021-01-27T00:00:00+00:00Kevin Campusano
<p><img src="/blog/2021/01/monads-another-functional-programming-tool/banner.png" alt="banner"></p>
<p>I was first exposed to the world of <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> back in 2007 with the release of <a href="https://dotnet.microsoft.com/download/dotnet-framework/net35-sp1">.NET Framework 3.5</a> and the introduction of <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/linq/">LINQ</a> into the C# language. At the time, I was just beginning to learn how to code and LINQ seemed to be little more than an extension of the C# language that allowed programmers to use SQL-like syntax to interact with collections of data. This was mostly useful for interacting with databases, via <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/">LINQ to SQL</a>. The concept of “functional programming” never even crossed my mind back then.</p>
<p>Once you had created a <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql/linq/creating-the-object-model">LINQ to SQL Object Model</a> using the tools provided in <a href="https://visualstudio.microsoft.com/">Visual Studio</a>, you could write code like this directly in C#:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#888;font-weight:bold">var</span> customersWithRecentExpensiveOrders =
<span style="color:#888">// Think of db.Orders as your hypothetical "orders" table.
</span><span style="color:#888"></span> <span style="color:#080;font-weight:bold">from</span> o <span style="color:#080;font-weight:bold">in</span> db.Orders
<span style="color:#080;font-weight:bold">where</span> o.Total >= <span style="color:#00d;font-weight:bold">100.00</span> && o.Date == DateTime.Now
<span style="color:#888">// All orders have a customer
</span><span style="color:#888"></span> <span style="color:#080;font-weight:bold">select</span> o.Customer;
</code></pre></div><p>Alternatively, you could also use the so-called method syntax:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#888;font-weight:bold">var</span> customersWithRecentExpensiveOrders =
db.Orders
.Where(o => o.Total >= <span style="color:#00d;font-weight:bold">100.00</span> && o.Date == DateTime.Now)
.Select(o => o.Customer);
</code></pre></div><p>LINQ would take that and turn it into native SQL that got executed against your database. Pretty neat.</p>
<p>So I ran with it and little by little I discovered that the set of tools provided by LINQ offered much more than syntactic sugar over database interactions. I discovered the power of LINQ when it came to interacting with lists of objects, database or no. That’s when the breakthrough came. LINQ was indeed a set of tools for working with collections, but more profound than that, it proposed a paradigm shift when it came to reasoning about problems whose solutions involved any sort of iterative logic.</p>
<p>It was weird to write and think about at first, but eventually, I adopted a programming style where I seldom wanted to write “vanilla” <code>foreach</code> loops. Looping manually using accumulators, iterators, and other types of temporary values began to feel clunky, inefficient, and verbose. LINQ offered a much more succinct and declarative way of expressing such logic. It was transformative.</p>
<p>So, given a variable called “orders” which contains a collection of all orders in our system, if we wanted all customers who had made orders that were more expensive than $100.00, for example, we could certainly do something like:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#888">// a List<Order> orders variable is defined somewhere
</span><span style="color:#888"></span><span style="color:#888;font-weight:bold">var</span> valuableCustomers = <span style="color:#080;font-weight:bold">new</span> List<Customer>();
<span style="color:#080;font-weight:bold">foreach</span> (<span style="color:#888;font-weight:bold">var</span> order <span style="color:#080;font-weight:bold">in</span> orders) {
<span style="color:#080;font-weight:bold">if</span> (order.Total >= <span style="color:#00d;font-weight:bold">100.00</span>) {
valuableCustomers.Add(order.Customer);
}
}
<span style="color:#080;font-weight:bold">return</span> valuableCustomers;
</code></pre></div><p>But I would often try to do something like this instead:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#888">// a List<Order> orders variable is defined somewhere
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">return</span> orders
.Where(o => o.Total >= <span style="color:#00d;font-weight:bold">100.00</span>)
.Select(o => o.Customer);
</code></pre></div><p>Or maybe even:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-csharp" data-lang="csharp"><span style="color:#888;font-weight:bold">var</span> isExpensive = o => o.Total >= <span style="color:#00d;font-weight:bold">100.00</span>;
<span style="color:#888;font-weight:bold">var</span> theCustomer = o => o.Customer;
<span style="color:#888">// a List<Order> orders variable is defined somewhere
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">return</span> orders.Where(isExpensive).Select(theCustomer);
</code></pre></div><p>Reads almost like English.</p>
<p>My learning process was such that whenever I had to write some code, I began with a fully imperative approach, since that’s what I was wired up to do. I wrote loops and conditionals manually. Then, I would take a step back and refactor into the more functional and declarative approach unlocked by LINQ, whenever it made sense for readability.</p>
<p>I’m now at the point where the more functional style comes naturally, usually as a first instinct. I feel like I’ve gained proficiency with the tool. I haven’t “rewired” myself, so to speak, to use iteration functions instead of loop primitives all the time, but rather, I’ve added “new wires” that allow me to use and apply the correct tool for the job.</p>
<p>A great advantage is that most of the other languages that I use today (like <a href="https://www.javascript.com/">JavaScript</a> or <a href="https://www.ruby-lang.org/en/">Ruby</a>) include similar functional-style APIs for working with collections. Learning and getting used to those tools has proved to be a very good investment.</p>
<p>Now, when it comes to monads, I’ve been hearing about them for a while now and decided to take some time to learn more about them, what sort of problems they can help solve, and whether they would be a worthwhile addition to the tool set that I use on a daily basis when writing code. If they give me the same thing that LINQ gave me all those years ago, then I’d say they are undoubtedly worth the time.</p>
<p>In this article I’m going to share the very first steps in my learning about monads, how to take advantage of the concepts and what sort of problems could benefit from being approached with monads in mind. Bear in mind that I’m no functional programming expert, nor am I proficient when it comes to the formal mathematics behind it.</p>
<p>So this will be an exploration from the perspective of a software engineer mostly experienced in object-oriented analysis and design. I use my limited knowledge of functional programming concepts as tools for expressing lower-level implementation details like algorithms within the context of primarily object-oriented languages with functional capabilities sprinkled in, like JavaScript or C#.</p>
<p>So think OOP for the big chunks and FP for the smaller details, when it fits.</p>
<h3 id="what-is-a-monad">What is a monad?</h3>
<p>This is the first question that I had and, in hindsight, as a total beginner, it is probably not the correct one to ask. Counter-intuitive, I know. A better question to ask would maybe be “what can I do with monads?” and we’ll get there soon. For now, let’s look at a few sentences of what <a href="https://en.wikipedia.org/wiki/Monad_(functional_programming)">Wikipedia says about monads</a>:</p>
<blockquote>
<p>In functional programming, a monad is an abstraction that allows structuring programs generically. Supporting languages may use monads to abstract away boilerplate code needed by the program logic. Monads achieve this by providing their own data type (a particular type for each type of monad), which represents a specific form of computation, along with one procedure to wrap values of any basic type within the monad (yielding a monadic value) and another to compose functions that output monadic values (called monadic functions).</p>
</blockquote>
<p>Ok, so right off the bat Wikipedia is telling us about a few key aspects of monads:</p>
<ul>
<li>“They can abstract away boilerplate.” What kind of boilerplate are we talking about here?</li>
<li>“They allow us to structure programs generically.” Sounds good. Generic things are often easy to reuse.</li>
<li>“They are their own data types.” By data types, do you mean classes?</li>
<li>“They represent computations.” Computations, huh? That is a very generic term. Can monads just do whatever you want?</li>
<li>“They wrap around the values of any basic type.” Wrapping around values like a <a href="https://en.wikipedia.org/wiki/Decorator_pattern">decorator design pattern</a>?</li>
<li>“They allow for function composition.” Ok, I like function composition. I do it all the time with LINQ.</li>
</ul>
<p>That’s quite a bit. My intuition and object oriented bias make me conclude a few things about this. This tells me that monads must be some sort of pattern where you have a class that augments other objects (like a decorator or wrapper). This class can implement some behavior, some computations (which can be considered boilerplate) which wrapped objects can take advantage of.</p>
<p>The encapsulated behavior/computation/boilerplate is generic though, so there should be great flexibility as to which types of objects can be wrapped in a monad. They also allow the decorated object to be operated on via method composition, that is, chaining together method calls, where the result of one method is the parameter for the next one. Maybe with a fluent API.</p>
<p>Wikipedia also touches on how they can be useful:</p>
<blockquote>
<p>This allows monads to simplify a wide range of problems, like handling potential undefined values (with the Maybe monad), or keeping values within a flexible, well-formed list (using the List monad). With a monad, a programmer can turn a complicated sequence of functions into a succinct pipeline that abstracts away auxiliary data management, control flow, or side-effects.</p>
</blockquote>
<p>This is where the prospect of monads becomes exciting. “Turn a complicated sequence of functions into a succinct pipeline that abstracts away auxiliary data management, control flow, or side-effects,” you say? I’m in.</p>
<h3 id="how-can-we-use-monads">How can we use monads?</h3>
<p>So now I’m convinced that I need to learn more about these monads. But how to even use these things? What does code that uses monads look like?</p>
<p>Wikipedia does a good job in explaining the concepts in those introductory paragraphs. The code examples however, mostly fly over my head. This is when I looked at <a href="https://twitter.com/getify">Kyle Simpson</a>’s excellent talk on monads, “<a href="https://www.youtube.com/watch?v=PXwtCYymzjE">Mo’ Problems, Mo’ Nads</a>” which was great for seeing code examples and a general introductory explanation of the concept. There’s also <a href="https://mikhail.io/">Mikhail Shilkov</a>’s blog post <a href="https://mikhail.io/2018/07/monads-explained-in-csharp-again/">Monads explained in C# (again)</a>, which was great for me personally given my C# background, but also because of its approach of arriving at the use of monads organically by discovering the need after writing some regular non-monadic code. Mikhail also points out some .NET Base Class Library elements which are actually monads. In my opinion, identifying when new concepts are used out in the wild is always useful when trying to understand them.</p>
<p>Se let’s get into a few examples.</p>
<h3 id="handling-null-checks">Handling null checks</h3>
<p>This seems to be the quintessential example of code using monads. This example is about how we can use monads to rewrite some typical code that we battle with every day: a series of null reference checks down a reference chain.</p>
<p>Consider this JavaScript code:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#888">// Imagine we have a order object that looks like this and comes from some
</span><span style="color:#888">// external source like a database or a web API.
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">const</span> order = {
orderNumber: <span style="color:#d20;background-color:#fff0f0">'123456'</span>,
total: <span style="color:#00d;font-weight:bold">100.00</span>,
customer: {
id: <span style="color:#00d;font-weight:bold">10</span>,
name: <span style="color:#d20;background-color:#fff0f0">'test_customer_name'</span>,
address: {
street: <span style="color:#d20;background-color:#fff0f0">'123 main st'</span>,
state: <span style="color:#d20;background-color:#fff0f0">'New York'</span>,
city: <span style="color:#d20;background-color:#fff0f0">'New York'</span>,
zip: <span style="color:#d20;background-color:#fff0f0">'10001'</span>,
}
}
};
<span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">return</span> order.customer.address.zip;
}
</code></pre></div><p>The <code>getZipCode</code> function is very simple, clear, and succinct. Its implementation communicates its intention very well: getting the zip code of where the customer that placed the order is located.</p>
<p>Now, in the real world things are not usually as simple. For example, it’s common for some of the elements in data structures such as this to be missing. In order to prevent null reference exceptions, we usually check for them manually, before accessing fields. To do such checks, our code would have to change. Our <code>getZipCode</code> function may end up looking like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">if</span> (order !== <span style="color:#080;font-weight:bold">null</span>) {
<span style="color:#080;font-weight:bold">const</span> customer = order.customer;
<span style="color:#080;font-weight:bold">if</span> (customer !== <span style="color:#080;font-weight:bold">null</span>) {
<span style="color:#080;font-weight:bold">const</span> address = customer.address;
<span style="color:#080;font-weight:bold">if</span> (address !== <span style="color:#080;font-weight:bold">null</span>) {
<span style="color:#080;font-weight:bold">return</span> address.zip;
}
}
}
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">null</span>;
}
</code></pre></div><p>This works well and we still can understand it just fine. We’re used to writing code like this. However, there’s no denying that we’ve polluted our main algorithm somewhat with tedious validation. The code is not as succinct nor its intent as obvious anymore. It would be great if we could move all that null checking logic elsewhere, and reuse it easily. That would clean up this code. Let’s see how monads can enter the picture and help us out here.</p>
<p>Let’s define a new monad type to help us with this. In modern JavaScript, we can use a class to model our monad:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#888">// Encapsulates logic to conditionally operate on values depending on whether
</span><span style="color:#888">// they are present or not.
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">class</span> NullHandlerMonad {
<span style="color:#888">// Creates a new instance of NullHandlerMonad that wraps around the given
</span><span style="color:#888"></span> <span style="color:#888">// value.
</span><span style="color:#888"></span> constructor(value) {
<span style="color:#080;font-weight:bold">this</span>.value = value;
}
<span style="color:#888">// Safely executes the given operation over the value wrapped inside this
</span><span style="color:#888"></span> <span style="color:#888">// instance.
</span><span style="color:#888"></span> <span style="color:#888">// Returns a new instance of NullHandlerMonad which wraps around the result of
</span><span style="color:#888"></span> <span style="color:#888">// the executed operation. Returning an instance of NullHandlerMonad is
</span><span style="color:#888"></span> <span style="color:#888">// important so that a method chain can be written in fluent syntax.
</span><span style="color:#888"></span> chain(operation) {
<span style="color:#888">// If the value is not null, execute the operation...
</span><span style="color:#888"></span> <span style="color:#080;font-weight:bold">if</span> (<span style="color:#080;font-weight:bold">this</span>.value !== <span style="color:#080;font-weight:bold">null</span>) {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> NullHandlerMonad(operation(<span style="color:#080;font-weight:bold">this</span>.value));
<span style="color:#888">// ...if it is, then just return null wrapped in the monad
</span><span style="color:#888"></span> } <span style="color:#080;font-weight:bold">else</span> {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> NullHandlerMonad(<span style="color:#080;font-weight:bold">null</span>);
}
}
<span style="color:#888">// Returns the value wrapped inside this instance.
</span><span style="color:#888"></span> getValue() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>.value;
}
}
</code></pre></div><p>Now what’s happening here? This is a class that defines a monad whose purpose is to abstract away null checks. In terms of good old object-oriented principles, this is just a wrapper. It takes an object and augments it with certain logic. In this case, it allows calling code to use said object in a safe manner with regard to null checks. In other words, the calling code does not need to worry about null checks, it can delegate that into this class. Into the monad.</p>
<p>This new class allows us to rewrite our <code>getZipCode</code> function like so:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> NullHandlerMonad(order)
.chain(o => o.customer)
.chain(c => c.address)
.chain(a => a.zip)
.getValue();
}
</code></pre></div><p>Pretty neat, huh? We’ve managed to get our <code>getZipCode</code> function back to a more succinct style while still keeping the safety provided by the null checks on the values that we’re working with: <code>order</code>, <code>customer</code>, <code>address</code> and <code>zip</code>. The repeated boilerplate of the conditionals with null checks is gone, abstracted away inside the monad class.</p>
<blockquote>
<p>This repeated null check pattern is so common in fact, that the designers of JavaScript decided to add a solution to this problem at the language level. This solution comes in the form of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Optional_chaining">optional chaining operator</a>. Using it, the implementation of our <code>getZipCode</code> function would look like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">return</span> order?.customer?.address?.zip;
}
</code></pre></div><p>It would have the same effect of returning <code>zip</code> if it is able to reach it, while short circuiting and returning <code>null</code> if any element in the chain is missing.</p>
</blockquote>
<p>If we go back to what Wikipedia promised us about monads, we can see the promise fulfilled even in this small, trivial example. Wikipedia said that monads…</p>
<ul>
<li>“…can abstract away boilerplate”. Yes, we abstracted away the boilerplate null checks.</li>
<li>“…allow us to structure programs generically”. Yes, our monad can work with any type of object.</li>
<li>“…are their own data types”. Yes, we did define a new data type, via a class.</li>
<li>“…represent computations”. Yes, our monad represents the computation of “checking for null before working on a value”.</li>
<li>“…wrap around the values of any basic type”. Yes, our monad is a wrapper. A decorator.</li>
<li>“…allow for function composition”. Yes, we were able to use a function composition style syntax to get to our solution.</li>
</ul>
<blockquote>
<p>Note on the generic nature of monads: Claiming that some code is “generic” is easier in JavaScript, due to its dynamic typing and lack of compile-time type checks. This advantage manifests in how our monad class is constructed. The constructor can accept any type: a number, a string, an array, an object. In statically-typed languages like C# or Java, the implementation would be a bit more involved and would require the use of language features like <a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/generics/">generics</a>. <a href="https://mikhail.io/">Mikhail Shilkov</a> explains this perfectly in his blog post about <a href="https://mikhail.io/2018/07/monads-explained-in-csharp-again/">Monads explained in C# (again)</a>. Bottom line is, JavaScript’s dynamic nature does make it easier to write generic code, but it is perfectly possible to do so in statically-typed languages as well.</p>
</blockquote>
<blockquote>
<p>By the way, this “NullHandlerMonad” type of monad is so common within functional programming circles that it’s got its own name. It is called the “Maybe” or “Option” monad. Same pattern, different name.</p>
</blockquote>
<h3 id="handling-exceptions">Handling exceptions</h3>
<p>When there’s a series of unsafe operations executed in sequence, exception handling code can also get unwieldy if left unchecked due to nesting and such.</p>
<p>Consider an <code>order</code> object that looks like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#888">// Imagine we have a order object that looks like this and comes from some
</span><span style="color:#888">// external source like a database or a web API.
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">const</span> order = {
orderNumber: <span style="color:#d20;background-color:#fff0f0">'123456'</span>,
total: <span style="color:#00d;font-weight:bold">100.00</span>,
<span style="color:#888">// It has a getCustomer method that fetches customer data from the network.
</span><span style="color:#888"></span> <span style="color:#888">// It could throw an exception.
</span><span style="color:#888"></span> getCustomer() {
<span style="color:#888">// throw new Error("could not find customer");
</span><span style="color:#888"></span>
<span style="color:#080;font-weight:bold">return</span> {
id: <span style="color:#00d;font-weight:bold">10</span>,
name: <span style="color:#d20;background-color:#fff0f0">'test_customer_name'</span>,
<span style="color:#888">// It also has a getAddress method that fetches customer data from the
</span><span style="color:#888"></span> <span style="color:#888">// network. It could throw an exception.
</span><span style="color:#888"></span> getAddress() {
<span style="color:#888">// throw new Error("could not find address");
</span><span style="color:#888"></span>
<span style="color:#080;font-weight:bold">return</span> {
street: <span style="color:#d20;background-color:#fff0f0">'123 main st'</span>,
state: <span style="color:#d20;background-color:#fff0f0">'New York'</span>,
city: <span style="color:#d20;background-color:#fff0f0">'New York'</span>,
getZip() { <span style="color:#080;font-weight:bold">return</span> <span style="color:#d20;background-color:#fff0f0">'10001'</span>; },
}
}
};
}
};
</code></pre></div><p>In order to work with an object like that, we could end up with code like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">try</span> {
customer = order.getCustomer();
<span style="color:#080;font-weight:bold">try</span> {
address = customer.getAddress();
<span style="color:#080;font-weight:bold">try</span> {
<span style="color:#080;font-weight:bold">return</span> address.getZip();
} <span style="color:#080;font-weight:bold">catch</span> (error) {
console.log(error.message);
}
} <span style="color:#080;font-weight:bold">catch</span> (error) {
console.log(error.message);
}
} <span style="color:#080;font-weight:bold">catch</span> (error) {
console.log(error.message);
}
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">null</span>;
}
</code></pre></div><blockquote>
<p>In a simple example such as this, we could gain some readability back by collapsing all the try/catch combos into a single catch all at the end. Code like this however can and does get complicated in the real world. The <code>try</code> blocks could get more complex and the handling blocks could differ slightly from each other. This is, however, a good example to see monads in action.</p>
</blockquote>
<p>Here, we can see that the pattern of boilerplate that repeats itself many times is the try/catch. We could define a new type of monad which would help us rewrite this code in a more succinct manner. We could call it <code>ExceptionHandlerMonad</code> and it could look like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#888">// Encapsulates logic to handle operations that could throw exceptions.
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">class</span> ExceptionHandlerMonad {
<span style="color:#888">// Creates a new instance of ExceptionHandlerMonad that wraps around the given
</span><span style="color:#888"></span> <span style="color:#888">// value.
</span><span style="color:#888"></span> constructor(value) {
<span style="color:#080;font-weight:bold">this</span>.value = value;
}
<span style="color:#888">// Safely executes the given operation over the value wrapped inside this
</span><span style="color:#888"></span> <span style="color:#888">// instance by using proper exception handling logic.
</span><span style="color:#888"></span> <span style="color:#888">//
</span><span style="color:#888"></span> <span style="color:#888">// Meant to be used to chain together multiple subsequent such operations.
</span><span style="color:#888"></span> <span style="color:#888">// If a previous operation in the chain has thrown an exception, the next
</span><span style="color:#888"></span> <span style="color:#888">// operation in the chain is skipped until a catch is called.
</span><span style="color:#888"></span> <span style="color:#888">//
</span><span style="color:#888"></span> <span style="color:#888">// Returns this instance if the wrapped value is an error, that is, if a
</span><span style="color:#888"></span> <span style="color:#888">// previous operation has resulted in an error.
</span><span style="color:#888"></span> <span style="color:#888">// Returns a new ExceptionHandlerMonad containing the result of the given
</span><span style="color:#888"></span> <span style="color:#888">// operation when run on the wrapped value.
</span><span style="color:#888"></span> <span style="color:#888">// Returns a new ExceptionHandlerMonad containing the error if the given
</span><span style="color:#888"></span> <span style="color:#888">// operation results in an error when run on the wrapped value.
</span><span style="color:#888"></span> chain(operation) {
<span style="color:#080;font-weight:bold">if</span> (<span style="color:#080;font-weight:bold">this</span>.isError()) { <span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>; }
<span style="color:#080;font-weight:bold">try</span> {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> ExceptionHandlerMonad(operation(<span style="color:#080;font-weight:bold">this</span>.value));
} <span style="color:#080;font-weight:bold">catch</span> (error) {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> ExceptionHandlerMonad(error);
}
}
<span style="color:#888">// Catches any exception that happens before in the chain.
</span><span style="color:#888"></span> <span style="color:#888">// Executes the given handler passing it the wrapped error.
</span><span style="color:#888"></span> <span style="color:#888">//
</span><span style="color:#888"></span> <span style="color:#888">// Returns this instance if the wrapped value is not an error, that is, if
</span><span style="color:#888"></span> <span style="color:#888">// there hasn't been an exception previously in the chain.
</span><span style="color:#888"></span> <span style="color:#888">// Returns a new empty ExceptionHandlerMonad if the value wrapped is an error,
</span><span style="color:#888"></span> <span style="color:#888">// that is, if there has been an exception previously in the chain.
</span><span style="color:#888"></span> <span style="color:#080;font-weight:bold">catch</span>(handler) {
<span style="color:#080;font-weight:bold">if</span> (!<span style="color:#080;font-weight:bold">this</span>.isError()) { <span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>; }
handler(<span style="color:#080;font-weight:bold">this</span>.value);
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> ExceptionHandlerMonad(<span style="color:#080;font-weight:bold">null</span>);
}
<span style="color:#888">// Returns the value wrapped inside this instance.
</span><span style="color:#888"></span> getValue() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>.value;
}
<span style="color:#888">// Whether the wrapped value is an error.
</span><span style="color:#888"></span> isError() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>.value <span style="color:#080;font-weight:bold">instanceof</span> <span style="color:#038">Error</span>;
}
}
</code></pre></div><p>This class is similar in purpose and structure to <code>NullHandlerMonad</code>. It encapsulates exception handling logic. It also adds a new <code>catch</code> method to its interface which can be used by client code to specify what to do when exceptions are thrown anywhere in the chain.</p>
<p>This class would allow us to rewrite our <code>getZipCode</code> method like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getZipCode() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> ExceptionHandlerMonad(order)
.chain(o => o.getCustomer())
.chain(c => c.getAddress())
.chain(a => a.getZip())
.<span style="color:#080;font-weight:bold">catch</span>(e => console.log(e.message))
.getValue();
}
</code></pre></div><p>Once again we’ve arrived at code that’s more compact and easier to read. Now, the monad takes care of all the exception handling logic and our <code>getZipCode</code> function is only concered with the core algorithm. The core workflow that we need for our solution. Like before, <code>getZipCode</code> returns null and logs to console a message if there is any error; if not, then the zip code is returned.</p>
<blockquote>
<p>In functional programming, there’s a common type of monad called “<a href="https://blog.logrocket.com/elegant-error-handling-javascript-either-monad/">Either</a>” which is generally used for exception handling. “Either” does not have a <code>catch</code> method, like <code>ExceptionHandlerMonad</code> does. Instead, it uses subtypes called “Right” and “Left” to express whether the result of a given operation has been a success or a failure (i.e. an error/exception). It then executes code according to that. Here, I’ve defined this <code>catch</code> method purely for convenience, sort of collapsing “Right” and “Left” logic into one class. Keep in mind that this approach is rather unorthodox as far as monads go.</p>
</blockquote>
<p>At this point we should be familiar with the mechanics of monads and the kinds of things we can do with them. Let’s see another example.</p>
<h3 id="handling-nested-iterations">Handling nested iterations</h3>
<p>Another common task is iterating through various levels of nested arrays in order to produce a list of all the innermost elements across multiple parents.</p>
<p>Imagine we run a company that offers vehicle maintenance services to companies with fleets of vehicles. We may have a data structure like the following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">const</span> cities = [
{
name: <span style="color:#d20;background-color:#fff0f0">'Los Angeles'</span>,
locations: [
{
name: <span style="color:#d20;background-color:#fff0f0">'Port of LA'</span>,
vehicles: [
{
id: <span style="color:#00d;font-weight:bold">1</span>,
licensePlate: <span style="color:#d20;background-color:#fff0f0">'123456'</span>,
wheels: [
{ position: <span style="color:#d20;background-color:#fff0f0">'Front-Right'</span>, dateCode: <span style="color:#00d;font-weight:bold">2001</span> },
{ position: <span style="color:#d20;background-color:#fff0f0">'Front-Left'</span>, dateCode: <span style="color:#00d;font-weight:bold">2001</span> },
{ position: <span style="color:#d20;background-color:#fff0f0">'Rear-Right'</span>, dateCode: <span style="color:#00d;font-weight:bold">2002</span> },
{ position: <span style="color:#d20;background-color:#fff0f0">'Rear-Left'</span>, dateCode: <span style="color:#00d;font-weight:bold">2002</span> },
]
},
<span style="color:#888">// ...more vehicles
</span><span style="color:#888"></span> ]
},
<span style="color:#888">// ...more locations
</span><span style="color:#888"></span> ]
},
<span style="color:#888">// ...more cities
</span><span style="color:#888"></span>];
</code></pre></div><p>We may want to get a list of all the wheels for all the vehicles that we maintain, maybe to then determine which ones are due for a change. We could write a function like this to obtain that list:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getWheels() {
<span style="color:#080;font-weight:bold">const</span> wheels = [];
<span style="color:#080;font-weight:bold">for</span> (<span style="color:#080;font-weight:bold">const</span> city <span style="color:#080;font-weight:bold">of</span> cities) {
<span style="color:#080;font-weight:bold">for</span> (<span style="color:#080;font-weight:bold">const</span> location <span style="color:#080;font-weight:bold">of</span> city.locations) {
<span style="color:#080;font-weight:bold">for</span> (<span style="color:#080;font-weight:bold">const</span> vehicle <span style="color:#080;font-weight:bold">of</span> location.vehicles) {
wheels.push(...vehicle.wheels);
}
}
}
<span style="color:#080;font-weight:bold">return</span> wheels;
}
</code></pre></div><p>We know monads now though, so as soon as we see that repeating pattern of nested loops iterating over nested arrays from our original data structure, we can come up with a new type of monad that could help make that code less imperative and easier to write and read. We could write a class like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#888">// Encapsulates logic to iterate over arrays inside elements of an outer array
</span><span style="color:#888">// and return a new array containing the elements of the inner array.
</span><span style="color:#888"></span><span style="color:#080;font-weight:bold">class</span> NestedIteratorMonad {
<span style="color:#888">// Creates a new instance of NullHandlerMonad that wraps around the given
</span><span style="color:#888"></span> <span style="color:#888">// value.
</span><span style="color:#888"></span> constructor(values) {
<span style="color:#080;font-weight:bold">this</span>.values = values;
}
<span style="color:#888">// Returns a new instance of NestedIteratorMonad which wraps around a new
</span><span style="color:#888"></span> <span style="color:#888">// array containing the combined elements of the inner arrays specified in
</span><span style="color:#888"></span> <span style="color:#888">// selector from each of the elements in the array wrapped inside this
</span><span style="color:#888"></span> <span style="color:#888">// instance.
</span><span style="color:#888"></span> <span style="color:#888">//
</span><span style="color:#888"></span> <span style="color:#888">// Selector must be a function that receives an element from this.values and
</span><span style="color:#888"></span> <span style="color:#888">// returns an array.
</span><span style="color:#888"></span> chain(selector) {
<span style="color:#080;font-weight:bold">const</span> subValues = [];
<span style="color:#080;font-weight:bold">for</span> (<span style="color:#080;font-weight:bold">const</span> value <span style="color:#080;font-weight:bold">of</span> <span style="color:#080;font-weight:bold">this</span>.values) {
<span style="color:#080;font-weight:bold">for</span> (<span style="color:#080;font-weight:bold">const</span> subValue <span style="color:#080;font-weight:bold">of</span> selector(value)) {
subValues.push(subValue);
}
}
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> NestedIteratorMonad(subValues);
}
<span style="color:#888">// Returns the value wrapped inside this instance.
</span><span style="color:#888"></span> getValue() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">this</span>.values;
}
}
</code></pre></div><p>As you can see, this class implements the nested iteration logic. With it, we can rewrite our <code>getWheels</code> function and make it more succinct:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getWheels() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> NestedIteratorMonad(cities)
.chain(c => c.locations)
.chain(l => l.vehicles)
.chain(v => v.wheels)
.getValues()
}
</code></pre></div><p>In fact, modern JavaScript already supports this pattern thanks to the built-in <code>Array.flatMap</code> method. It works directly on arrays so, if we were to use it, our function would look like this instead:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-js" data-lang="js"><span style="color:#080;font-weight:bold">function</span> getWheels() {
<span style="color:#080;font-weight:bold">return</span> cities
.flatMap(c => c.locations)
.flatMap(l => l.vehicles)
.flatMap(v => v.wheels);
}
</code></pre></div><p>Pretty nice, right? JavaScript itself already supports some of these monad-related concepts.</p>
<h3 id="wrapping-up">Wrapping up</h3>
<p>And that’s it for now!</p>
<p>Admittedly, these are very simple examples. However, I do believe they serve very well the purpose of getting your feet wet with the concept of monads, what they can do for us, and the mechanics behind them.</p>
<p>While the monads that we discussed here can become useful on their own, they really come to life when we introduce other supporting types and behaviors into the picture. That’s where libraries can become useful. There’s Kyle Simpson’s <a href="https://github.com/getify/monio">Monio</a>, for example. Monio is a JavaScript library that provides a set of monads and other utilities (“monads and friends”, as he calls them) that can help with things like async code, managing side effects, conditional execution, error handling, etc. Some of these are things that we discussed and implemented by hand in this article; with the library, though, we don’t have to implement things by hand. The library, like I said, also includes other utilities that further unlock the power and flexibility of monads, so it’s worth checking out.</p>
<p>I think it’s also useful to be on the lookout for monads in frameworks and libraries that we use everyday. As Mikhail Shilkov pointed out in his blog post, LINQ’s <code>SelectMany</code> is pretty much a monad. And we implemented similar functionality in our <code>NestedIteratorMonad</code> example. The JavaScript language designers also implemented this same pattern via the <code>flatMap</code> method on arrays.</p>
<p>Now, to conclude, I’m still not ready to say that the discovery of monads has caused a breakthrough in my programming style similar to what I had when I fist discovered LINQ in C#. What I can say is that, from now on, much like I did with LINQ, I will try to take a step back after I’m done writing an algorithm, and consider whether using monads would make it more readable. The journey continues; let’s see where it takes us!</p>
QuickCheck - property based testing in Haskell and JavaScripthttps://www.endpointdev.com/blog/2016/03/quickcheck-property-based-testing-in/2016-03-16T00:00:00+00:00Kamil Ciemniewski
<p>In my <a href="/blog/2016/03/strict-typing-fun-example-free-monads/">last article</a>, I presented a <a href="https://en.wikipedia.org/wiki/Functional_programming">functional programming</a> pattern. The goal was to reach out to the developers who weren’t familiar with advanced type systems like the one found in Haskell and make them a bit curious. This time I’d like to take a step further and present a testing approach coming from the same world, that can be used with mainstream languages with a great success.</p>
<h3 id="many-ways-to-test-the-code">Many ways to test the code</h3>
<p>The importance of testing is almost a cliché nowadays. Out of this relevance, a large number of testing frameworks and paradigms have been created. On the paradigm level we have notions like TDD and BDD. On the level of implementations we have hundreds of projects for each language like RSpec in Ruby and Jasmine or Mocha in JavaScript.</p>
<p>The ideas behind the libraries don’t differ that much. All of them are based on the idea of providing code examples with assertions on how the code should behave in these particular cases.</p>
<p>A bit more revolutionary in its approach was the Cucumber project. In its essence, it allows business people to express the system logic by stating it in specially formed, plain English. An example taken from the Cucumber’s website reads:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-scss" data-lang="scss"><span style="color:#b06;font-weight:bold">Feature</span><span style="color:#555">:</span> <span style="color:#b06;font-weight:bold">Refund</span> <span style="color:#b06;font-weight:bold">item</span>
<span style="color:#b06;font-weight:bold">Scenario</span><span style="color:#555">:</span> <span style="color:#b06;font-weight:bold">Jeff</span> <span style="color:#b06;font-weight:bold">returns</span> <span style="color:#b06;font-weight:bold">a</span> <span style="color:#b06;font-weight:bold">faulty</span> <span style="color:#b06;font-weight:bold">microwave</span>
<span style="color:#b06;font-weight:bold">Given</span> <span style="color:#b06;font-weight:bold">Jeff</span> <span style="color:#b06;font-weight:bold">has</span> <span style="color:#b06;font-weight:bold">bought</span> <span style="color:#b06;font-weight:bold">a</span> <span style="color:#b06;font-weight:bold">microwave</span> <span style="color:#b06;font-weight:bold">for</span> <span style="color:#a61717;background-color:#e3d2d2">$</span><span style="color:#b06;font-weight:bold">100</span>
<span style="color:#b06;font-weight:bold">And</span> <span style="color:#b06;font-weight:bold">he</span> <span style="color:#b06;font-weight:bold">has</span> <span style="color:#b06;font-weight:bold">a</span> <span style="color:#b06;font-weight:bold">receipt</span>
<span style="color:#b06;font-weight:bold">When</span> <span style="color:#b06;font-weight:bold">he</span> <span style="color:#b06;font-weight:bold">returns</span> <span style="color:#b06;font-weight:bold">the</span> <span style="color:#b06;font-weight:bold">microwave</span>
<span style="color:#b06;font-weight:bold">Then</span> <span style="color:#b06;font-weight:bold">Jeff</span> <span style="color:#b06;font-weight:bold">should</span> <span style="color:#b06;font-weight:bold">be</span> <span style="color:#b06;font-weight:bold">refunded</span> <span style="color:#a61717;background-color:#e3d2d2">$</span><span style="color:#b06;font-weight:bold">100</span>
</code></pre></div><p>In this article, I’d like to present an approach that was conceived in the realm of Haskell—the purely functional, statically typed language. Though it started just as a Haskell library, today it could be broadly named an “approach”. We now have implementations for almost every major language. This approach is what is known as <strong>QuickCheck</strong>.</p>
<h3 id="code-testing-limitations">Code testing limitations</h3>
<p>Having a good test coverage is a sign of a potentially stable code. However, even well-tested software needs to be improved occasionally as new bugs are discovered. This happens even in the projects with the largest test suites. Moreover, the tests are code too—they also are prone to being invalid. But do we have a really valid solution when all our tests are valid and the code passes all assertions? Realistically, we can only provide a few examples per use case at most. The best we can do is to choose the most probable use cases and the ones we have a hunch that might go wrong.</p>
<p>This implies that for the tests suite to be guarding us against bugs, we need to have an insight as to where the potential bugs may be before even testing. Isn’t a definition of a bug telling the other story though? If we knew where to find them, we would fix them in the first place. In reality the systems grow so complex that we only can have <em>a feeling</em> of what might go wrong.</p>
<p>In 1969, Edsger W. Dijkstra said at the “<a href="http://homepages.cs.ncl.ac.uk/brian.randell/NATO/nato1969.PDF">Nato Software Engineering Conference</a>”:</p>
<blockquote>
<p>Testing shows the presence, not the absence of bugs.</p>
</blockquote>
<h3 id="ive-got-lots-of-ammo-give-me-a-machine-gun-for-killing-bugs">I’ve got lots of ammo, give me a machine gun for killing bugs!</h3>
<p>What if we could ask the computer to come up with many different use cases for us? Instead of having 2 or 3 cases per some code aspect, we’d have 100 of them including the ones we’d never consider ourselves. We could describe <strong>properties</strong> of the code we’d like to hold for all of the randomly chosen cases. That is exactly the idea behind the QuickCheck. In its functional - Haskell form, it takes advantage of the supreme type system and generates a random set of function parameters based on their types. It then runs the property check for all of them and stops if it’s able to find a counter example making the property falsifiable.</p>
<p>If we’d compare coming up with traditional test cases to shooting with a pistol, the <strong>QuickCheck</strong> approach had to be called firing with a machine gun. The reason is that we’re not focusing on a specific use case, but we’re focusing on certain properties of the code that have to hold for any argument from the accepted domain.</p>
<p>One of the most basic examples we could show, could be ensuring that the <em>reverse</em> function applied twice returns the original array (pseudo-code):</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">arr1</span> == reverse(reverse(arr1))
</code></pre></div><p>The idea here is to make sure this property holds against a large number of randomly selected arguments from the domain. In this example the checker would randomly generate e. g 100 arrays and test if the assertion evaluates to true for every one of them.</p>
<h3 id="working-example--the-haskell-way">Working example — the Haskell way</h3>
<p>Let’s take a look at how the approach is being used in its original environment. Later on we’ll see how the pattern can be used when coding in JavaScript. For this, let’s imagine that we’re developing a graph data structure, to be used in some e-commerce project we’re working on. Here’s the basic very incomplete draft:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">module</span> <span style="color:#b06;font-weight:bold">BlogGraph</span> <span style="color:#080;font-weight:bold">where</span>
<span style="color:#080;font-weight:bold">import</span> <span style="color:#b06;font-weight:bold">Data.Map</span> <span style="color:#080;font-weight:bold">as</span> Map
<span style="color:#080;font-weight:bold">import</span> <span style="color:#b06;font-weight:bold">Data.List</span> <span style="color:#080;font-weight:bold">as</span> List
<span style="color:#888">-- Graph as an adjacency list as described here:</span>
<span style="color:#888">-- https://en.wikipedia.org/wiki/Adjacency_list</span>
<span style="color:#080;font-weight:bold">data</span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Graph</span> (<span style="color:#888;font-weight:bold">Map</span> a [a]) <span style="color:#080;font-weight:bold">deriving</span> (<span style="color:#888;font-weight:bold">Show</span>)
<span style="color:#06b;font-weight:bold">empty</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Graph</span> a
<span style="color:#06b;font-weight:bold">empty</span> <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Graph</span> <span style="color:#888;font-weight:bold">Map</span>.empty
<span style="color:#06b;font-weight:bold">insertNode</span> <span style="color:#080">::</span> (<span style="color:#888;font-weight:bold">Ord</span> a) <span style="color:#080">=></span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a
<span style="color:#06b;font-weight:bold">insertNode</span> node (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Graph</span> $ <span style="color:#888;font-weight:bold">Map</span>.insert node <span style="color:#888;font-weight:bold">[]</span> m
<span style="color:#06b;font-weight:bold">removeNode</span> <span style="color:#080">::</span> (<span style="color:#888;font-weight:bold">Ord</span> a) <span style="color:#080">=></span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a
<span style="color:#06b;font-weight:bold">removeNode</span> node (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Graph</span> $ <span style="color:#888;font-weight:bold">Map</span>.delete node m
<span style="color:#06b;font-weight:bold">insertEdge</span> <span style="color:#080">::</span> (<span style="color:#888;font-weight:bold">Ord</span> a) <span style="color:#080">=></span> a <span style="color:#080">-></span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a
<span style="color:#06b;font-weight:bold">insertEdge</span> parent child (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span>
<span style="color:#888;font-weight:bold">Graph</span> $ <span style="color:#888;font-weight:bold">Map</span>.insertWithKey update parent [child] m
<span style="color:#080;font-weight:bold">where</span>
update <span style="color:#080;font-weight:bold">_</span> <span style="color:#080;font-weight:bold">_</span> old <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">List</span>.nub $ child<span style="color:#888;font-weight:bold">:</span>old
<span style="color:#06b;font-weight:bold">nodes</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">-></span> [a]
<span style="color:#06b;font-weight:bold">nodes</span> (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Map</span>.keys m
</code></pre></div><p>If you’re not proficient yet in reading Haskell code, we’re just using a Map where keys are integers and values are arrays of integers to implement the graph as an <a href="https://en.wikipedia.org/wiki/Adjacency_list">Adjacency List</a>. So each node has its representation in a map as one of its keys. Also, each edge has its representation as a child stored in the parent’s array in the map.</p>
<p>You might be able to find a silly bug in the <strong>removeNode</strong> function. It doesn’t remove the node from the edge definitions of other nodes. We’ll use <strong>QuickCheck</strong> to show how this could be found automatically.</p>
<p>Before doing that, let’s have a warm up, by adding two simple properties:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">prop_insert_empty</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Int</span> <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Bool</span>
<span style="color:#06b;font-weight:bold">prop_insert_empty</span> i <span style="color:#080">=</span>
nodes (insertNode i <span style="color:#888;font-weight:bold">BlogGraph</span>.empty) == [i]
<span style="color:#06b;font-weight:bold">prop_insert_existing</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Int</span> <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Bool</span>
<span style="color:#06b;font-weight:bold">prop_insert_existing</span> i <span style="color:#080">=</span>
nodes (insertNode i $ insertNode i <span style="color:#888;font-weight:bold">BlogGraph</span>.empty) == [i]
</code></pre></div><p>Properties are just simple functions returning true or false. They take arguments which are randomly provided later on by the QuickCheck library.</p>
<p>The first property says that adding a node to an empty graph will always produce a one-node graph. The second one, that adding a node to a graph that already has this node will always return the same unmodified graph.</p>
<p>We can successfully run these cases:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">quickCheck</span> prop_insert_empty
<span style="color:#06b;font-weight:bold">quickCheck</span> prop_insert_existing
</code></pre></div><p>Now we should add a property stating that for all removals of a node from the graph, all references of this node in edge definitions for other nodes are always also being removed:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">prop_remove_removes_edges</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Graph</span> <span style="color:#888;font-weight:bold">Int</span> <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Bool</span>
<span style="color:#06b;font-weight:bold">prop_remove_removes_edges</span> (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span>
<span style="color:#888;font-weight:bold">List</span>.null (nodes graph) || <span style="color:#888;font-weight:bold">List</span>.notElem node elemsAfter
<span style="color:#080;font-weight:bold">where</span>
graph <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">Graph</span> m
node <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">List</span>.head $ <span style="color:#888;font-weight:bold">BlogGraph</span>.nodes graph
elemsAfter <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">List</span>.concat $ <span style="color:#888;font-weight:bold">Map</span>.elems mapAfter
mapAfter <span style="color:#080">=</span>
<span style="color:#080;font-weight:bold">case</span> removeNode node graph <span style="color:#080;font-weight:bold">of</span>
(<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">-></span> m
</code></pre></div><p>As I wrote before, these property testing functions are being run by the <strong>QuickCheck</strong> framework repeatedly with randomly generated values as arguments. Out of the box we’re able to generate random examples for many simple types—including e.g Int. That’s the reason we were able to just specify properties depending on random Int variables—without any additional code. But with the last example, we’re asking QuickCheck to generate a set of random <strong>graphs</strong>. We need to tell it how to construct a random graph first:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">arbitrarySizedIntGraph</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Int</span> <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Gen</span> (<span style="color:#888;font-weight:bold">Graph</span> <span style="color:#888;font-weight:bold">Int</span>)
<span style="color:#06b;font-weight:bold">arbitrarySizedIntGraph</span> s <span style="color:#080">=</span> <span style="color:#080;font-weight:bold">do</span>
nodes <span style="color:#080"><-</span> vectorOf s $ choose (<span style="color:#00d;font-weight:bold">0</span>, <span style="color:#00d;font-weight:bold">32000</span>)
edges <span style="color:#080"><-</span> edges nodes
<span style="color:#080;font-weight:bold">let</span> withNodes <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">List</span>.foldr insertNode <span style="color:#888;font-weight:bold">BlogGraph</span>.empty nodes
return $ <span style="color:#888;font-weight:bold">List</span>.foldr addEdge withNodes edges
<span style="color:#080;font-weight:bold">where</span>
addEdge (parent, child) <span style="color:#080">=</span> insertEdge parent child
edges nodes <span style="color:#080">=</span> <span style="color:#080;font-weight:bold">do</span>
parents <span style="color:#080"><-</span> sublistOf nodes
<span style="color:#080;font-weight:bold">let</span> children <span style="color:#080">=</span> nodes <span style="color:#888;font-weight:bold">List</span>.\\ parents
return [ (parent, child) | parent <span style="color:#080"><-</span> parents, child <span style="color:#080"><-</span> children ]
<span style="color:#080;font-weight:bold">instance</span> <span style="color:#888;font-weight:bold">Arbitrary</span> (<span style="color:#888;font-weight:bold">Graph</span> <span style="color:#888;font-weight:bold">Int</span>) <span style="color:#080;font-weight:bold">where</span>
arbitrary <span style="color:#080">=</span> sized arbitrarySizedIntGraph
</code></pre></div><p>The above generator will be good enough for our case. It generates variable length graphs. A sublist of all nodes are made parents in edges and all parents are connected to the rest of non-parental nodes.</p>
<p>When we try to run the test we get:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#888;font-weight:bold">Failed</span>! <span style="color:#888;font-weight:bold">Falsifiable</span> (after <span style="color:#00d;font-weight:bold">3</span> tests)<span style="color:#888;font-weight:bold">:</span>
<span style="color:#888;font-weight:bold">Graph</span> (fromList [(<span style="color:#00d;font-weight:bold">10089</span>,<span style="color:#888;font-weight:bold">[]</span>),(<span style="color:#00d;font-weight:bold">25695</span>,[<span style="color:#00d;font-weight:bold">10089</span>])])
</code></pre></div><p>QuickCheck shows that the property doesn’t hold for the whole domain—it failed after 3 examples. It also prints the example for which our property did not hold.</p>
<p>We can now reexamine the code for the removeNode function and fix it as per the property’s specification:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">removeNode</span> <span style="color:#080">::</span> (<span style="color:#888;font-weight:bold">Ord</span> a) <span style="color:#080">=></span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a <span style="color:#080">-></span> <span style="color:#888;font-weight:bold">Graph</span> a
<span style="color:#06b;font-weight:bold">removeNode</span> node (<span style="color:#888;font-weight:bold">Graph</span> m) <span style="color:#080">=</span>
<span style="color:#888;font-weight:bold">Graph</span> $ <span style="color:#888;font-weight:bold">Map</span>.map remNode $ <span style="color:#888;font-weight:bold">Map</span>.delete node m
<span style="color:#080;font-weight:bold">where</span>
remNode <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">List</span>.delete node
</code></pre></div><p>Now running the test again we can see that it works.</p>
<h3 id="another-working-example--the-javascript-land">Another working example — the JavaScript land</h3>
<p>As I stated before, this pattern became implemented for many different mainstream languages—this includes JavaScript. I’d like to show you the version of the above process for this language now. This might end up being helpful if you’d like to use it in your project but don’t know much Haskell yet.</p>
<p>As a start, let’s make sure we have the following packages:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash">npm install jsverify
npm install lodash
</code></pre></div><p>We can now create a JS file with what might resemble the Haskell draft implementation:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#080;font-weight:bold">var</span> jsc = require(<span style="color:#d20;background-color:#fff0f0">"jsverify"</span>);
<span style="color:#080;font-weight:bold">var</span> <span style="color:#00d;font-weight:bold">_</span> = require(<span style="color:#d20;background-color:#fff0f0">"lodash"</span>);
<span style="color:#080;font-weight:bold">var</span> Graph = <span style="color:#080;font-weight:bold">function</span>() {
<span style="color:#080;font-weight:bold">var</span> self = <span style="color:#080;font-weight:bold">this</span>;
self.<span style="color:#00d;font-weight:bold">_</span>map = {};
self.insertNode = <span style="color:#080;font-weight:bold">function</span>(node) {
<span style="color:#080;font-weight:bold">if</span>(self.<span style="color:#00d;font-weight:bold">_</span>map[node] === <span style="color:#080;font-weight:bold">undefined</span>) {
self.<span style="color:#00d;font-weight:bold">_</span>map[node] = [];
}
<span style="color:#080;font-weight:bold">return</span> self;
};
self.removeNode = <span style="color:#080;font-weight:bold">function</span>(node) {
self.<span style="color:#00d;font-weight:bold">_</span>map.<span style="color:#080;font-weight:bold">delete</span>(node);
<span style="color:#080;font-weight:bold">return</span> self;
};
self.insertEdge = <span style="color:#080;font-weight:bold">function</span>(a, b) {
<span style="color:#080;font-weight:bold">if</span>(self.<span style="color:#00d;font-weight:bold">_</span>map[a] === <span style="color:#080;font-weight:bold">undefined</span>) {
self.insertNode(a);
}
self.<span style="color:#00d;font-weight:bold">_</span>map[a].push(b);
<span style="color:#080;font-weight:bold">return</span> self;
};
self.nodes = <span style="color:#080;font-weight:bold">function</span>() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.keys(self.<span style="color:#00d;font-weight:bold">_</span>map);
};
}
Graph.empty = <span style="color:#080;font-weight:bold">function</span>() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">new</span> Graph();
}
</code></pre></div><p>To reproduce the first property—for all integers, inserting one as a node to an empty graph results in a graph with one node:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#080;font-weight:bold">var</span> propInsertEmpty =
jsc.forall(<span style="color:#d20;background-color:#fff0f0">"nat"</span>, <span style="color:#080;font-weight:bold">function</span>(i) {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.isEqual(Graph.empty().insertNode(i).nodes(), [i]);
});
jsc.assert(propInsertEmpty);
</code></pre></div><p>The jsVerify DSL takes some time to get used to. It cannot take advantage of the type system as in the Haskell example so aspects like generation of random data based on types requires some documentation reading.</p>
<p>Running <em>jsc.assert</em> we might have expected to get a success, but this time we’re getting:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plain" data-lang="plain">Error: Failed after 1 tests and 5 shrinks. rngState: 001d40a68297fbce35; Counterexample: 0;
</code></pre></div><p>We can see that jsVerify has found 0 as a counterexample. Let’s see what’s happening by running the code by hand passing 0 as a parameter:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">console.log(Graph.empty().insertNode(<span style="color:#00d;font-weight:bold">0</span>).nodes());
</code></pre></div><p>Result:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">[ <span style="color:#d20;background-color:#fff0f0">'0'</span> ]
</code></pre></div><p>Aha! It’s quite easy to shoot your own foot in JavaScript. We can fix it really fast with the following:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">self.nodes = <span style="color:#080;font-weight:bold">function</span>() {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.map(<span style="color:#00d;font-weight:bold">_</span>.keys(self.<span style="color:#00d;font-weight:bold">_</span>map), <span style="color:#080;font-weight:bold">function</span>(i){ <span style="color:#080;font-weight:bold">return</span> <span style="color:#038">parseInt</span>(i, <span style="color:#00d;font-weight:bold">10</span>); });
};
</code></pre></div><p>Running the code again doesn’t show any errors which means that all assertions were valid. What about the bug we saw in the Haskell version? Let’s provide a property for that too:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#080;font-weight:bold">var</span> propRemoveRemovesEdges =
jsc.forall(graphG, <span style="color:#080;font-weight:bold">function</span>(g) {
<span style="color:#080;font-weight:bold">if</span>(g.nodes().length === <span style="color:#00d;font-weight:bold">0</span>){
<span style="color:#080;font-weight:bold">return</span> <span style="color:#080;font-weight:bold">true</span>;
}
<span style="color:#080;font-weight:bold">else</span> {
<span style="color:#080;font-weight:bold">var</span> numNodes = g.nodes().length;
<span style="color:#080;font-weight:bold">var</span> index = <span style="color:#00d;font-weight:bold">_</span>.random(<span style="color:#00d;font-weight:bold">0</span>, numNodes - <span style="color:#00d;font-weight:bold">1</span>);
<span style="color:#080;font-weight:bold">var</span> node = g.nodes()[index];
<span style="color:#080;font-weight:bold">return</span> !<span style="color:#00d;font-weight:bold">_</span>.includes(<span style="color:#00d;font-weight:bold">_</span>.flattenDeep(<span style="color:#00d;font-weight:bold">_</span>.values(g.removeNode(node).<span style="color:#00d;font-weight:bold">_</span>map)), node);
}
});
jsc.assert(propRemoveRemovesEdges);
</code></pre></div><p>We will still need to specify how to generate a random graph. We can use the notion of a <a href="https://en.wikipedia.org/wiki/Functor">Functor</a> that’s coming from the functional programming world and turn a random array into a random graph:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript"><span style="color:#080;font-weight:bold">var</span> graphG = jsc.array(jsc.nat).smap(
<span style="color:#080;font-weight:bold">function</span>(arr) {
<span style="color:#080;font-weight:bold">var</span> ins = <span style="color:#080;font-weight:bold">function</span>(g, i) {
<span style="color:#080;font-weight:bold">return</span> g.insertNode(i);
};
<span style="color:#080;font-weight:bold">var</span> graph = <span style="color:#00d;font-weight:bold">_</span>.reduce(arr, ins, Graph.empty());
<span style="color:#080;font-weight:bold">var</span> numParents = <span style="color:#038">Math</span>.floor(arr.length / <span style="color:#00d;font-weight:bold">2</span>);
<span style="color:#080;font-weight:bold">var</span> parents = <span style="color:#00d;font-weight:bold">_</span>.take(arr, numParents);
<span style="color:#080;font-weight:bold">var</span> children = <span style="color:#00d;font-weight:bold">_</span>.difference(arr, parents);
<span style="color:#080;font-weight:bold">var</span> insEd = <span style="color:#080;font-weight:bold">function</span>(g, parent) {
<span style="color:#080;font-weight:bold">var</span> insF = <span style="color:#080;font-weight:bold">function</span>(r, c) {
<span style="color:#080;font-weight:bold">return</span> r.insertEdge(parent, c);
};
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.reduce(children, insF, g);
};
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.reduce(parents, insEd, graph);
},
<span style="color:#080;font-weight:bold">function</span>(graph) {
<span style="color:#080;font-weight:bold">return</span> graph.nodes();
}
);
</code></pre></div><p>When running the assert for that property we’re getting an error:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plain" data-lang="plain">Error: Failed after 1 tests and 1 shrinks. rngState: 085f6c82ea10439d7b; Counterexample: {"_map":{"21":[44]}}; Exception: self._map.delete is not a function
</code></pre></div><p>This isn’t the issue we were expecting though. Still it’s great to find a problem before showing the code to the client. We can iron it out with:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">self.removeNode = <span style="color:#080;font-weight:bold">function</span>(node) {
<span style="color:#080;font-weight:bold">delete</span> self.<span style="color:#00d;font-weight:bold">_</span>map[node];
<span style="color:#080;font-weight:bold">return</span> self;
};
</code></pre></div><p>When running again, we’re getting an error we were expecting:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-plain" data-lang="plain">Error: Failed after 8 tests and 2 shrinks. rngState: 8c97e25bc36f41da08; Counterexample: {"_map":{"2":[7]}};
</code></pre></div><p>The jsVerify has found a counterexample falsifying our property. It’s also worth noting that it took 8 tests to find this issue. We can notice that for the event of removing a node that is a child and doesn’t have any children itself the property isn’t true. Let’s reexamine our removeNode function:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-javascript" data-lang="javascript">self.removeNode = <span style="color:#080;font-weight:bold">function</span>(node) {
<span style="color:#080;font-weight:bold">delete</span> self.<span style="color:#00d;font-weight:bold">_</span>map[node];
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.mapValues(self.<span style="color:#00d;font-weight:bold">_</span>map, <span style="color:#080;font-weight:bold">function</span>(children) {
<span style="color:#080;font-weight:bold">return</span> <span style="color:#00d;font-weight:bold">_</span>.without(children, node);
});
};
</code></pre></div><p>And now it works!</p>
<h3 id="not-only-haskell-and-javascript">Not only Haskell and JavaScript</h3>
<p>The QuickCheck style testing is available for many different languages. The Wikipedia says:</p>
<blockquote>
<p>Re-implementations of QuickCheck exist for C, C++, Chicken Scheme, Clojure, Common Lisp, D, Elm, Erlang, F# (and C#, VB.NET), Factor, Io, Java, JavaScript, Node.js, Objective-C, OCaml, Perl, Prolog, PHP, Python, R, Ruby, Rust, Scala, Scheme, Smalltalk, Standard ML and Swift.</p>
</blockquote>
<p>You can find many useful links about the approach on <a href="https://en.wikipedia.org/wiki/QuickCheck">Wikipedia</a>. If you’re into Haskell, a good place to start reading about the library is the <a href="https://wiki.haskell.org/Introduction_to_QuickCheck2">Haskell Wiki</a> as well as the documentation found on the <a href="https://hackage.haskell.org/package/QuickCheck">Hackage</a>.</p>
<p>The JavaScript counterpart can be found on <a href="https://github.com/jsverify/jsverify">GitHub</a>. It’s important to note that jsVerify isn’t the only JavaScript library implementing the QuickCheck approach.</p>
Strict typing fun example — Free Monads in Haskellhttps://www.endpointdev.com/blog/2016/03/strict-typing-fun-example-free-monads/2016-03-11T00:00:00+00:00Kamil Ciemniewski
<p>From time to time I’ve got a chance to discuss different programming paradigms with colleagues. Very often I like steering the discussion into the programming languages realm as it’s something that interests me a lot.</p>
<p>Looking at the most popular languages list on GitHub, published last August, we can see that in the most popular five, we only have one that is “statically typed”. <a href="https://github.com/blog/2047-language-trends-on-github">https://github.com/blog/2047-language-trends-on-github</a></p>
<p>The most popular languages on GitHub as of August 2015:</p>
<ul>
<li>JavaScript</li>
<li>Java</li>
<li>Ruby</li>
<li>PHP</li>
<li>Python</li>
</ul>
<p>The dynamic typing approach gives great flexibility. It very often empowers teams to be more productive. There are use cases for static type systems I feel that many people are not aware of though.
I view this post as an experiment. I’d like to present you with a pattern that’s being used in Haskell and Scala worlds (among others). The pattern is especially helpful in these contexts as both Haskell and Scala have extremely advanced type systems (comparing to e. g. Java or C++ and not to mention Ruby or Python).</p>
<p>My goal is not to explain in detail all the subtleties of the code I’m going to present. The learning curve for both languages can be pretty dramatic. The goal is to make you a bit curious about alternative development styles and how they could be very powerful.</p>
<h3 id="short-intro-to-the-idea-behind-the-pattern">Short intro to the idea behind the pattern</h3>
<p>The pattern I’m going to present is called the “Free Monad + Interpreter”. The idea behind it is that we can build <a href="https://en.wikipedia.org/wiki/Domain-specific_language">DSLs</a> (domain specific languages) by making our functions not execute the code immediately, but to build the <a href="https://en.wikipedia.org/wiki/Abstract_syntax_tree">AST</a> (abstract syntax tree) out of it and interpret it in different ways depending on the context.</p>
<p>A fun example I came up with is a DSL for system <a href="https://en.wikipedia.org/wiki/Provisioning#Server_provisioning">provisioning</a> scripts that—among many use cases one could come up with—allows to:</p>
<ul>
<li>present the AST in bash or zsh code or whatever other language like Python, Ruby or Perl</li>
<li>present the AST as a graph to visualize the execution</li>
<li>execute it directly, natively in Haskell</li>
<li>have an easy-to-comprehend set of provisioning instructions while lower level aspects like file handles etc.—being handled in common Haskell code used for the execution of ASTs</li>
</ul>
<p>There are potentially many more use cases but I just wanted to show you a couple—enough to hopefully make you a bit curious. In this post we’ll focus on interpreting the AST as a bash script.</p>
<h3 id="the-coding-part">The coding part</h3>
<p>The first step is to define the set of instructions our interpreted Domain Specific Language will support:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">data</span> <span style="color:#888;font-weight:bold">Provision</span> next <span style="color:#080">=</span>
<span style="color:#888;font-weight:bold">Begin</span> next |
<span style="color:#888;font-weight:bold">Install</span> <span style="color:#888;font-weight:bold">String</span> next |
<span style="color:#888;font-weight:bold">IfNotExists</span> <span style="color:#888;font-weight:bold">String</span> (<span style="color:#888;font-weight:bold">Free</span> <span style="color:#888;font-weight:bold">Provision</span> <span style="color:#038">()</span>) next |
<span style="color:#888;font-weight:bold">Touch</span> <span style="color:#888;font-weight:bold">String</span> next |
<span style="color:#888;font-weight:bold">Cd</span> <span style="color:#888;font-weight:bold">String</span> next |
<span style="color:#888;font-weight:bold">MkDir</span> <span style="color:#888;font-weight:bold">String</span> <span style="color:#888;font-weight:bold">Bool</span> next |
<span style="color:#888;font-weight:bold">Echo</span> <span style="color:#888;font-weight:bold">String</span> next |
<span style="color:#888;font-weight:bold">Continue</span> |
<span style="color:#888;font-weight:bold">Done</span>
<span style="color:#080;font-weight:bold">deriving</span>(<span style="color:#888;font-weight:bold">Functor</span>)
</code></pre></div><p>This odd looking definition is what’s called an <a href="https://en.wikipedia.org/wiki/Algebraic_data_type">Algebraic Data Type</a>. For now it should suffice that the commands can take arguments of different types and almost all of them take a continuation command as the last parameter.</p>
<p>The continuation parameter is meant to store the next “provisioning command” so that we would have e.g:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#888;font-weight:bold">Begin</span> (<span style="color:#888;font-weight:bold">Install</span> <span style="color:#d20;background-color:#fff0f0">"postgresql-server"</span> (<span style="color:#888;font-weight:bold">Echo</span> <span style="color:#d20;background-color:#fff0f0">"installed!"</span> (<span style="color:#888;font-weight:bold">Done</span>)))
</code></pre></div><p>Out of these blocks, our ASTs will be created. We need some way of composing these blocks into AST trees. I’m not going to explain here why the following code works—it’s just a teaser post. Let’s just say that the following functions allow us to just build the tree instead of calling any system-affecting code. In other words, it allows these calls to look as if they’re doing something when in fact they are just constructing the data structure in memory:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">begin</span> <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Begin</span> id
<span style="color:#06b;font-weight:bold">install</span> what <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Install</span> what id
<span style="color:#06b;font-weight:bold">ifNotExists</span> path what <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">IfNotExists</span> path what id
<span style="color:#06b;font-weight:bold">touch</span> path <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Touch</span> path id
<span style="color:#06b;font-weight:bold">cd</span> path <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Cd</span> path id
<span style="color:#06b;font-weight:bold">mkDir</span> path wholeTree <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">MkDir</span> path wholeTree id
<span style="color:#06b;font-weight:bold">echo</span> message <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Echo</span> message id
<span style="color:#06b;font-weight:bold">continue</span> <span style="color:#080">=</span> liftF $ <span style="color:#888;font-weight:bold">Continue</span>
<span style="color:#06b;font-weight:bold">done</span> <span style="color:#080">=</span> liftF <span style="color:#888;font-weight:bold">Done</span>
</code></pre></div><p>Now that we have these building functions defined, we can create a function that uses them to construct a useful AST:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">app</span> <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Free</span> <span style="color:#888;font-weight:bold">Provision</span> a
<span style="color:#06b;font-weight:bold">app</span> <span style="color:#080">=</span> <span style="color:#080;font-weight:bold">do</span>
begin
install <span style="color:#d20;background-color:#fff0f0">"postgresql-server"</span>
mkDir <span style="color:#d20;background-color:#fff0f0">"/var/run/the-app"</span> <span style="color:#888;font-weight:bold">True</span>
cd <span style="color:#d20;background-color:#fff0f0">"/var/run/the-app"</span>
ifNotExists <span style="color:#d20;background-color:#fff0f0">"the-app.log"</span> $ touch <span style="color:#d20;background-color:#fff0f0">"the-app.log"</span> >> continue
done
</code></pre></div><p>Running this function does nothing except for returning AST wrapped inside the “free monad”—which you can think of as a special, useful kind of container. The above function looks like any other Haskell function. It’s also “type safe”—which weeds out one class of errors that we’re only able to notice <strong>after</strong> we ran the code—in languages like JavaScript or Python.</p>
<p>Later on we’ll see that to get different results out of the “provisioning workflow” we defined above, no change in this function will be needed.</p>
<p>Now, having an AST tree wrapped around some “useful” container almost screams for some kind of an interpreter for this to be useful too. That’s in fact part of the description of the pattern I gave you in the beginning of this post.</p>
<p>Let’s define a set of data types linked with the function that we’ll use as an interpreter:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">class</span> <span style="color:#888;font-weight:bold">InterpretingContext</span> a <span style="color:#080;font-weight:bold">where</span>
run <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">Free</span> <span style="color:#888;font-weight:bold">Provision</span> <span style="color:#038">()</span> <span style="color:#080">-></span> a
</code></pre></div><p>The above just says that if we want to use the function <strong>run</strong> to turn the AST wrapped in a monad to some concrete value (by executing it)—we need to implement this function for the type of the concrete value we’d like to get out of it.</p>
<p>For example, let’s say that for the portability sakes we want to turn the AST into the bash script. The natural (though naive) way to do this would be to implement this “class” along with its <strong>run</strong> function for the type of <strong>String</strong>:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">instance</span> <span style="color:#888;font-weight:bold">InterpretingContext</span> <span style="color:#888;font-weight:bold">String</span> <span style="color:#080;font-weight:bold">where</span>
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">Begin</span> next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"#!/usr/bin/env bash</span><span style="color:#04d;background-color:#fff0f0">\n\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ (run next)
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">Install</span> what next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"apt-get install "</span> ++ what ++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ nextStr
<span style="color:#080;font-weight:bold">where</span>
nextStr <span style="color:#080">=</span> run next
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">IfNotExists</span> path what next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"if [ ! -f "</span> ++ path ++ <span style="color:#d20;background-color:#fff0f0">" ]; then</span><span style="color:#04d;background-color:#fff0f0">\n\t</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ whatStr
++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">fi</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ nextStr
<span style="color:#080;font-weight:bold">where</span>
whatStr <span style="color:#080">=</span> run what
nextStr <span style="color:#080">=</span> run next
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">Touch</span> path next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"touch "</span> ++ path ++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ (run next)
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">Cd</span> path next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"cd "</span> ++ path ++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ (run next)
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">MkDir</span> path tree next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"mkdir "</span> ++ treeOption ++ <span style="color:#d20;background-color:#fff0f0">" "</span> ++ path ++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ (run next)
<span style="color:#080;font-weight:bold">where</span>
treeOption <span style="color:#080">=</span>
<span style="color:#080;font-weight:bold">if</span> tree <span style="color:#080;font-weight:bold">then</span> <span style="color:#d20;background-color:#fff0f0">"-p"</span> <span style="color:#080;font-weight:bold">else</span> <span style="color:#d20;background-color:#fff0f0">""</span>
run (<span style="color:#888;font-weight:bold">Free</span> (<span style="color:#888;font-weight:bold">Echo</span> message next)) <span style="color:#080">=</span>
<span style="color:#d20;background-color:#fff0f0">"echo "</span> ++ message ++ <span style="color:#d20;background-color:#fff0f0">"</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">"</span> ++ (run next)
run (<span style="color:#888;font-weight:bold">Free</span> <span style="color:#888;font-weight:bold">Continue</span>) <span style="color:#080">=</span> <span style="color:#d20;background-color:#fff0f0">""</span>
run (<span style="color:#888;font-weight:bold">Free</span> <span style="color:#888;font-weight:bold">Done</span>) <span style="color:#080">=</span> <span style="color:#d20;background-color:#fff0f0">"exit 0"</span>
</code></pre></div><p>Each node kind is being <strong>interpreted</strong> as a data type we chose to be one of the <strong>instances of this class</strong>—in our example a <strong>String</strong>.</p>
<p>What this allows us to do, is to use the <strong>run</strong> function, specifying that we want a <strong>String</strong> as a return value and automatically the instance we’ve just created will be used:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">run</span> app <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">String</span>
</code></pre></div><p>This will return:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#d20;background-color:#fff0f0">"#!/usr/bin/env bash</span><span style="color:#04d;background-color:#fff0f0">\n\n</span><span style="color:#d20;background-color:#fff0f0">apt-get install postgresql-server</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">mkdir -p /var/run/the-app</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">cd /var/run/the-app</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">if [ ! -f the-app.log ]; then</span><span style="color:#04d;background-color:#fff0f0">\n\t</span><span style="color:#d20;background-color:#fff0f0">touch the-app.log</span><span style="color:#04d;background-color:#fff0f0">\n\n</span><span style="color:#d20;background-color:#fff0f0">fi</span><span style="color:#04d;background-color:#fff0f0">\n</span><span style="color:#d20;background-color:#fff0f0">exit 0"</span>
</code></pre></div><p>Pretty printed:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-bash" data-lang="bash"><span style="color:#c00;font-weight:bold">#!/usr/bin/env bash
</span><span style="color:#c00;font-weight:bold"></span>
apt-get install postgresql-server
mkdir -p /var/run/the-app
<span style="color:#038">cd</span> /var/run/the-app
<span style="color:#080;font-weight:bold">if</span> [ ! -f the-app.log ]; <span style="color:#080;font-weight:bold">then</span>
touch the-app.log
<span style="color:#080;font-weight:bold">fi</span>
<span style="color:#038">exit</span> <span style="color:#00d;font-weight:bold">0</span>
</code></pre></div><p>If now we’d like to execute the AST in the context of an action that prints the script to stdout we could do so like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">instance</span> <span style="color:#888;font-weight:bold">InterpretingContext</span> (<span style="color:#888;font-weight:bold">IO</span> <span style="color:#038">()</span>) <span style="color:#080;font-weight:bold">where</span>
run <span style="color:#080">=</span> print . run
</code></pre></div><p>From now on it would be perfectly valid to run the function with AST in both contexts:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#06b;font-weight:bold">run</span> app <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">String</span>
<span style="color:#06b;font-weight:bold">run</span> app <span style="color:#080">::</span> <span style="color:#888;font-weight:bold">IO</span> <span style="color:#038">()</span>
</code></pre></div><p>We could add a context returning an ExitStatus by running the code against the system very easily too:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">data</span> <span style="color:#888;font-weight:bold">ExitStatus</span> <span style="color:#080">=</span> <span style="color:#888;font-weight:bold">ExitSuccess</span> | <span style="color:#888;font-weight:bold">ExitFailure</span> <span style="color:#888;font-weight:bold">Int</span>
<span style="color:#080;font-weight:bold">instance</span> <span style="color:#888;font-weight:bold">InterpretingContext</span> (<span style="color:#888;font-weight:bold">IO</span> <span style="color:#888;font-weight:bold">ExitStatus</span>) <span style="color:#080;font-weight:bold">where</span>
run <span style="color:#080">=</span> (<span style="color:#a61717;background-color:#e3d2d2">…</span>)
</code></pre></div><p>What this gives us is the ability to have the provisioning code that could be run in production while having a different interpreter in the testing suite to be able to ensure the structure of execution without inflicting any changes to the system itself.</p>
<p>If you’d like to play with the code yourself, you’ll need a couple of more lines for this to work:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#888">{-# LANGUAGE DeriveFunctor #-}</span>
<span style="color:#888">{-# LANGUAGE FlexibleContexts #-}</span>
<span style="color:#888">{-# LANGUAGE FlexibleInstances #-}</span>
<span style="color:#888">{-# LANGUAGE TypeSynonymInstances #-}</span>
<span style="color:#888">{-# LANGUAGE OverloadedStrings #-}</span>
</code></pre></div><p>And also:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-haskell" data-lang="haskell"><span style="color:#080;font-weight:bold">import</span> <span style="color:#b06;font-weight:bold">Control.Monad.Free</span>
</code></pre></div><p>Bear in mind though that the code I presented here is by no means optimal—especially memory wise. I chose to present it this way for the clarity of what the code is doing for those of you not familiar with the language.</p>
<h3 id="what-are-other-use-cases-for-this-pattern">What are other use cases for this pattern?</h3>
<p>The pattern presented here has a huge number of uses. It could be used for providing a DSL for building SVG combined with an interpreter that could draw it visually for the ease of work. It could also be used for defining RPC data types describing structures and interpreting them differently based on the underlying <a href="https://en.wikipedia.org/wiki/Remote_procedure_call">RPC</a> (remote procedure call) mechanics (Thrift, SOAP etc).</p>
<p>I doubt that the ability this gives thanks to the <strong>very helpful</strong> Haskell type system could be reproduced in languages like Ruby or Python easily. It is possible of course, but the amount of boilerplate code and complexity would require lots of testing code too. Here on the other hand the code holds many guarantees just because we’re coding in a language with an advanced strict type system.</p>
<p>Also, the similarity to the <a href="https://en.wikipedia.org/wiki/Interpreter_pattern">Interpreter Pattern</a> known from the object oriented languages is only superficial. In that case there’s no way to use regular normal functions (or methods) to build AST—as if it was a regular imperative code. It’s always about some weird mangling of data structures by hand.</p>
<h3 id="curious">Curious?</h3>
<p>If I managed to make you a bit curious about the aspects I presented here, here are some of the resources you might want to take a look at:</p>
<ul>
<li><a href="http://learnyouahaskell.com/chapters">Learn You a Haskell — online book</a></li>
<li><a href="http://book.realworldhaskell.org/read/">Real World Haskell — online book</a></li>
<li><a href="http://adit.io/posts/2013-04-17-functors,_applicatives,_and_monads_in_pictures.html">A pleasant visual tutorial about functors and monads</a></li>
<li><a href="https://wiki.haskell.org/Monad">Haskell Wiki article on monads</a></li>
<li><a href="http://programmers.stackexchange.com/questions/242795/what-is-the-free-monad-interpreter-pattern">A fantastic intro to the Free Monad pattern</a></li>
</ul>
Impressions from Open Source work with Elixirhttps://www.endpointdev.com/blog/2015/03/impressions-from-open-source-work-with/2015-03-26T00:00:00+00:00Kamil Ciemniewski
<p>Some time ago I started working on the Elixir library that would allow me to send emails as easily as ActionMailer known from the Ruby world does.</p>
<p>The beginnings were exciting—I got to play with a <strong>very</strong> clean and elegant new language which Elixir is. I also quickly learned about the openness of the Elixir community. After hacking some first draft-like version and posting it on GitHub and Google groups—I got a <strong>very</strong> warm and thorough code review from the <strong>language’s author</strong> José Valim! That’s just impressive and it made me even more motivated to help out the community by getting my early code into a better shape.</p>
<p>Coding the ActionMailer like library in a language that was born 3 years ago doesn’t sound like a few hours job—there’s lots of functionality to be covered. An email’s body has to be somehow compiled from the template but also the email message has to be transformed to the form in which the SMTP server can digest and relay it. It’s also great if the message’s body can be encoded with „quoted printable”—this makes even the oldest SMTP server happy. But there’s lots more: connecting with external SMTP servers, using the local in-Elixir implementation, ability to test etc…</p>
<p>Fortunately Elixir’s built on top of the Erlang’s „Virtual Machine”—BEAM—which makes you able to use its libraries—a lot of them. For the huge part of the functionality I needed to cover I chose the great <a href="https://github.com/Vagabond/gen_smtp">gen_smtp library</a>. This allowed me to actually send emails to SMTP servers and have them properly encoded. With the focus on developer’s productivity, Elixir made me come up with the nice set of other features that you can check out <a href="https://github.com/kamilc/mailman">here</a>.</p>
<p>This serves as a shout out blog post for the Elixir ecosystem and community. The friendliness that it radiates with makes open source work like this very rewarding. I invite you to make your contributions as well—you’ll like it.</p>
wroc_love.rb a.k.a. “The best Java conference in Ruby world”https://www.endpointdev.com/blog/2015/03/wrocloverb-aka-best-java-conference-in/2015-03-18T00:00:00+00:00Wojtek Ziniewicz
<p><strong>Time and Date:</strong> 13–15th March 2015</p>
<p><strong>Place:</strong> Wrocław University</p>
<p>Amongst many Ruby and Rails talks on this conference, there were some not related to Ruby at all. Since 2013 I have observed a growing number of functional programming topics and concerns. Even the open discussion was mainly devoted not to OOP but to concepts like Event Sourcing or patterns similar to those promoted by Erlang or Clojure.</p>
<p>So let’s enumerate the best moments.</p>
<p>First of all, the <strong>“ClojureScript + React.js”</strong> presented by Norbert Wójtowicz. The link below points to the presentation that was recorded on Lambda Days. It is a fascinating talk about gigantic technology leap that is going to have a impact on the whole OOP world.</p>
<iframe allowfullscreen="" frameborder="0" height="281" mozallowfullscreen="" src="https://player.vimeo.com/video/122316380" webkitallowfullscreen="" width="500"></iframe>
<p>Nicolas Dermine presented <a href="http://overtone.github.io/">Overtone’s</a> implemented mostly in Ruby that’s called <a href="http://sonic-pi.net/">Sonic Pi</a> which lets you basically write code that plays music. It is a great tool from which to learn programming and to use to have fun in the same time. It is also a great tool for teachers (both music and programming).</p>
<blockquote class="twitter-tweet" lang="en">
Awesome project! <a href="http://t.co/c2NUNpYjwS">http://t.co/c2NUNpYjwS</a> Coding music in <a href="https://twitter.com/hashtag/ruby?src=hash">#ruby</a> Thanks <a href="https://twitter.com/nicoder">@nicoder</a> for your talk <a href="https://twitter.com/hashtag/wrocloverb?src=hash">#wrocloverb</a> <a href="http://t.co/sY4MpqhZlf">pic.twitter.com/sY4MpqhZlf</a><br />
— Cecile Veneziani (@cecilitse) <a href="https://twitter.com/cecilitse/status/576775533805092864">March 14, 2015</a></blockquote>
<p>There was also a fascinating talk about some aspects of social engineering in sourcing the requirements from your customers. It was presented by <a href="https://twitter.com/ziobrando">Alberto Brandolini</a>, and the technique is called <strong>Event Storming.</strong></p>
<blockquote class="twitter-tweet" lang="en">
.<a href="https://twitter.com/ziobrando">@ziobrando</a> in action. When walls are no longer enough... for <a href="https://twitter.com/hashtag/EventStorming?src=hash">#EventStorming</a>. Which is awesome by the way <a href="https://twitter.com/hashtag/wrocloverb?src=hash">#wrocloverb</a> <a href="http://t.co/Oq06nFaGub">pic.twitter.com/Oq06nFaGub</a><br />
— a candid mind (@aCandidMind) <a href="https://twitter.com/aCandidMind/status/577486878330511360">March 16, 2015</a></blockquote>
Elixir — a step in a never ending journeyhttps://www.endpointdev.com/blog/2014/06/elixir-step-in-never-ending-journey/2014-06-09T00:00:00+00:00Kamil Ciemniewski
<p>Every now and then a new programming language is born. In fact, since the not-so-distant introduction of early programming languages, we’ve got about 693 of them! (at least that’s what <a href="https://en.wikipedia.org/wiki/List_of_programming_languages">Wikipedia</a> says).</p>
<p>Why can’t we settle for just one or at least just a handful? Creating a new programming language certainly isn’t the easiest task on earth. It’s one thing to have fun with syntax lexers, but completely different to provide all the tooling and libraries. In fact programming languages authors are being held hostage to their own creations. There’s always a multitude of things to do, which makes leading such a project basically a full-time job.</p>
<p>Why are those languages sprouting all the time then? The answer is simple: out of necessity.</p>
<h3 id="pitfalls-of-computer-programming">Pitfalls of computer programming</h3>
<p>Most of today’s mainstream programmers choose object-oriented programming as their paradigm of choice. It solves the problems of procedural programming… we could say: in a classy way. You can find its advocates everywhere. In fact you don’t even need to search—they will yell at you from just about every corner of the Internet.</p>
<p>Truth be told it’s one of the things that makes producing new software possible. Some of today’s projects wouldn’t even be possible to create with procedural programming for the same cost. The tax of complex architecture would simply be too high. It’s especially true for commercial products when time and budget play a crucial role.</p>
<p>It’s equally true that this approach produces its own set of traps to fall into. Even though you’ve got a plethora of design patterns at your disposal (<a href="http://www.oodesign.com/">http://www.oodesign.com/</a>) you will still fall into one of them.</p>
<p>The reason is that the whole concept is by its nature very bug-potent. There are a couple of things that gets us into trouble. One is the inability to quickly and clearly reason about the flow of programs. In object-oriented world the flow of a higher level action may be covered by a large nest of several objects’ class definitions. In every class definition the result and all effects of methods may affect the results and effects of many other methods in different objects. Even at the level of one class the result and effects of a method call depends on the state of this object. This covers processes with a fog that cannot be cleared even after hours of testing and debugging. We have to pay the mental energy tax just because we’re using the most widely applauded technology.</p>
<h3 id="hello-real-world-here-you-are-a-business">Hello?… Real world here… You are a business!</h3>
<p>In a computer programmer’s paradise there are no deadlines. There aren’t any troublemaking users either. You could just spend 10 years developing something you believe in, then get a Nobel Prize for how awesome it is and then shut the whole thing off before you break anything. You could make the code as clear as you like. Your programming heroes could stare at you from pictures of their books with a sense of amazement. All design patterns used. The code written in the Right Way.</p>
<p>There’s a newsflash for you though: you are a business! Even if you just work for a business you still have deadlines, no? You still have to deal with users and investors. And your realistic estimations almost never sound reasonable. Welcome to the real world.</p>
<p>Almost everything you do has a price tag. Time rules software projects—in fact there is no such thing as free time. But it’s not only about time—silly bugs can have profound impact on the perception of businesses. Will users go back to a web shop again after seeing a HTTP 500 error when trying to check out?</p>
<p>At the end of the day all we do is business. That makes certain features more important than others when it comes to choosing technologies. As far as my understanding goes the three of the most important factors are:</p>
<ul>
<li>time-to-market</li>
<li>maintainability</li>
<li>difficulty of shooting yourself in the foot</li>
</ul>
<p>When I was learning Haskell a while ago I was mostly concerned about this third factor. Everyone knows how easy it is to shoot yourself in the foot with a dynamically typed programming language. At the same time having a very strict type system makes productivity drop like a rock. Haskell seemed to have a great solution to this dilemma. Being a functional language, it allows you to narrow or widen the range of types a function can operate on. It’s polymorphism Done Right. It doesn’t restrict functions to operate just on a certain branch of types like OOP languages make them. With type classes, you can also make them extensible in the future. I won’t give any examples—you can look them up in the Internet if you want. The message is simple: Haskell makes you productive <strong>and</strong> it makes your results correct at the same time.</p>
<p>All this holds true as with simple code. In real world, you’ll have lots of app specific type classes and lots of type aliases not to get crazy from reading function signatures. Also, the learning curve is pretty dramatic—for simple cases, it is sufficient to use <a href="https://www.youtube.com/watch?v=ZhuHCtR3xq8&feature=kp">Monads</a>. From all category theory, knowing Monads and Functors is all one needs to write very simple programs in Haskell. But when you need to create something more complex, you need to have a good understanding of the rest and spend a lot of the time on planning out the right architecture.</p>
<p>Looking at what it takes to achieve similar results, using <a href="https://www.yesodweb.com/">Yesod</a>—Haskell’s most popular web framework as one can achieve in Rails—the time-to-market factor is ridiculously high. And what innovation that is if we get worse results? It is true that once your Haskell code is compiled—it’s very probable that it is in fact bug free. And you cannot say the same thing about any Ruby code even with thousands of lines of unit tests.</p>
<h3 id="getting-the-competitive-edge">Getting the competitive edge</h3>
<p>About two years ago a new programming language was born. As it usually goes—it didn’t introduce any new paradigm. In fact it was built around ideas known from languages that have been around for almost 30 years now.</p>
<p><a href="https://elixir-lang.org/">Elixir</a> is a programming language built for the Erlang virtual machine. Its compiler produces exactly the same binaries that come from Erlang’s compiler. The two languages are very alike and libraries developed in one of them can easily be used in another. However, Elixir adds a couple of niceties that Erlang doesn’t have. It also features a nice and clean syntax that many Ruby programmers can immediately <strong>get</strong>.</p>
<p>Above all it enhances a developer’s toolbox with tools for increasing all three aspects of a good business technology. Being created by one of the most known Open Source contributor in the Rails world—Jose Valim, includes a great set of features, making Rails developers feel almost “at home”. Because it is a functional language though, it reduces the number of potential bug kinds significantly. Its polymorphism model isn’t based on type classes, but on easy to grasp protocols. Thanks to philosophy inherited from Erlang, maintainability is at its heights.</p>
<p>Superficially, one might think of Elixir as of some kind of a marriage between Ruby and Haskell. Ruby being a very dynamic language—enhances developer’s productivity in many ways. Its syntax allows creation of custom DSLs that in turn boosts productivity even more. Haskell as a functional language makes the test & fix part of projects <strong>significantly</strong> shorter. As with other functional languages—the resulting code tends to be very terse and easy to grasp just from looking at. In fact, there are some libraries which aren’t that well documented—but it’s not that hard to <strong>get</strong> what they do just from quickly skimming the code.</p>
<p>Elixir shares these benefits, but it takes developer’s productivity to the next level by introducing Lisp style macros. It also shares the same base infrastructure libraries that Erlang has, making it an amazing fit for developing highly available solutions. It is known that Erlang based solutions tend to have an insanely high rate of reliability. Joe Armstrong, an author of the Erlang language once said:</p>
<blockquote>
<p><em>The AXD301 has achieved a NINE nines reliability (yes, you read that right, 99.9999999%). Let’s put this in context: 5 nines is reckoned to be good (5.2 minutes of downtime/year). 7 nines almost unachievable … but we did 9.</em></p>
<p><em>Why is this? No shared state, plus a sophisticated error recovery model.</em></p>
</blockquote>
<p>You can achieve the same with Elixir. Because it runs on the same virtual machine, it features the same hot code reloading ability. This means that you don’t have to shut off your application just to introduce some quick patches or enhancements. Thanks to the famous OTP library you can use so called supervisors too. They define strategies for dealing with failures—e.g automatically restarting a part of the app that has just crashed. It’s very inexpensive as in Erlang and Elixir, parts of applications are built around very lightweight processes. Processes do not share any memory with one another, making them very loosely coupled. They communicate with each other through so-called messages. They don’t need to know if a receiver process lives on the same machine or on some other in the network. All this makes writing highly scalable solutions a cinch.</p>
<h3 id="theres-no-one-right-answer-but-there-will-never-be">There’s no one right answer, but there will never be</h3>
<p>This post is meant as an outline of a small part of what’s available outside of <strong>The Mainstream</strong>. Even though many ideas presented here were known to the programming world for long years, they never really get through to what is considered mainstream. I think we can be more ambitious than that. Collectively as developers we can do much better than how we’re doing now. And because of that I’m so excited about any project that tries to address real programming issues from a much deeper perspective than just a couple of syntax sugar niceties. It’s nice to have pleasant looking code, but it’s even nicer to have pleasing looking end results. I don’t think Elixir is the answer to all our troubles but at least it’s seems to steer in the right direction.</p>
<p>You can find its specifics, syntax, features, tutorials on its website: <a href="https://elixir-lang.org/">https://elixir-lang.org/</a></p>
2014 Mountain West Ruby Conference Day 2https://www.endpointdev.com/blog/2014/03/2014-mountain-west-ruby-conference-day-2/2014-03-27T00:00:00+00:00Brian Gadoury
<p>This past Friday concluded my second Mountain West Ruby Conference right here in my backyard of Salt Lake City, Utah. Just like the 2013 MWRC, this year’s conference was great. It was also nice to meet up with fellow remote co-worker Mike Farmer for both days. Here are a few of my personal favorites from day 2 of the conference, which I almost missed when I had the audacity to show up without a Macbook Air/Pro. (Kidding!)</p>
<h3 id="randy-coulman--affordances-in-programming-languages">Randy Coulman — Affordances in Programming Languages</h3>
<p>Affordances (“A quality of an object or environment that allows someone to perform an action”) are all around us. Randy opened with some examples of poor affordances such as a crosswalk button with two enticing-looking widgets that requires arrows drawn on the box to point to the one that actually is a button. Then, a counter-example showing the “walking” or “standing” footprints painted on an escalator and how they instantly and intuitively communicate how to best use the escalator.</p>
<p>Randy followed with a few examples of affordances in software. One of them was a simple Ruby implementation of an affordance called Deterministic Destructors. It was a method that acquired a resource, yielded to a block argument, then automatically released that resource when the block returned.</p>
<p>The last affordance Randy showed is most near and dear to my heart because it happens to be something I can use in my current project: Subclass iteration. Rather than use a registry pattern to explicitly register components that can handle specific file formats (for example), you can leverage Ruby’s built-in inherited(subklass) class method by overriding it in your parent class. That, along with a one-liner helper method, can be used to automagically register your subclasses. Implement a standard interface (can_handle_thing?) for your subclasses to advertise what type of data they can handle, then use your de facto subclass registry to delegate appropriately at runtime.</p>
<p>Ultimately, Randy’s list of takeaways summed it all up nicely:</p>
<ul>
<li>
<p>“Languages afford certain designs and inhibit others,” thereby shaping how we think about certain problems</p>
</li>
<li>
<p>Learning new languages will increase your “solution space” and expose you to different approaches that may be applicable elsewhere.</p>
</li>
</ul>
<p>Thanks for the talk, Randy! Here is his <a href="https://www.slideshare.net/randycoulman/affordances-in-programming-languages">“Affordances in Programming Languages” Slideshare</a></p>
<h3 id="john-athayde--the-timeless-way-of-building">John Athayde — The Timeless Way of Building</h3>
<p>Patterns. Patterns in nature, human behavior, architecture. Patterns are only truly valuable when used appropriately, which, it is said, requires a certain amount of fluency in the language of patterns. Treating them as “a library of code templates” is a problem, says John. I would agree. Correctly applying design patterns in software development is more than finding a <a href="https://en.wikipedia.org/wiki/Design_Patterns">GoF design pattern</a> and squeezing your problem through it like so much delicious looking <a href="https://web.archive.org/web/20160610111405/http://www.kraftrecipes.com/recipes/kool-aid-play-dough-148569.aspx">Play dough</a>.</p>
<p>John discussed patterns using some interesting architectural examples and ran through a number of anti-patterns and their corresponding pattern “solutions” in a helpful before/after format. He touched on a number of such anti-patterns that one might see in the wild; code that walks the object graph a la @account.customer.address.state,) fat models in need of some module, concern, or gem treatment, and ActiveRecord callback soup.</p>
<p>John’s overall takeaway was that memorizing and applying patterns is neither the crux of the matter, nor is it even sufficient. True skill and the mark of proficiency is to be “fluent in the language of patterns.” This reminds me of the difference between being able to speak a foreign language and being able to <em>think</em> in that language and seamlessly express those thoughts without a need for intermediate translation.</p>
<p>John’s recommended reading: The Timeless Way of Building, A Pattern Language, The Oregon Experiment, Rails Antipatterns, Design Patterns in Ruby</p>
<h3 id="ryan-davis--nerd-party-v31">Ryan Davis — Nerd Party v3.1</h3>
<p>Ryan’s talk covering the various “versions” of the Seattle.rb Ruby user group throughout the years gets an honorable mention because it convinced me to get involved with one of the Ruby user groups here in Salt Lake City.</p>
Functional Handler — A Pattern in Rubyhttps://www.endpointdev.com/blog/2014/01/functional-handler-pattern-in-ruby/2014-01-22T00:00:00+00:00Mike Farmer
<p>First, a disclaimer. Naming things in the world of programming is always a challenge. Naming this blog post was also difficult. There are all sorts of implications that come up when you claim something is “functional” or that something is a “pattern”. I don’t claim to be an expert on either of these topics, but what I want to describe is a pattern that I’ve seen develop in my code lately and it involves functions, or anonymous functions to be more precise. So please forgive me if I don’t hold to all the constraints of both of these loaded terms.</p>
<h3 id="a-pattern">A pattern</h3>
<p>The pattern that I’ve seen lately is that I need to accomplish of myriad of steps, all in sequence, and I need to only proceed to the next step if my current step succeeds. This is common in the world of Rails controllers. For example:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">update</span>
<span style="color:#33b">@order</span> = <span style="color:#036;font-weight:bold">Order</span>.find params[<span style="color:#a60;background-color:#fff0f0">:id</span>]
<span style="color:#080;font-weight:bold">if</span> <span style="color:#33b">@order</span>.update_attributes(params[<span style="color:#a60;background-color:#fff0f0">:order</span>])
<span style="color:#33b">@order</span>.calculate_tax!
<span style="color:#33b">@order</span>.calculate_shipping!
<span style="color:#33b">@order</span>.send_invoice! <span style="color:#080;font-weight:bold">if</span> <span style="color:#33b">@order</span>.complete?
flash[<span style="color:#a60;background-color:#fff0f0">:notice</span>] = <span style="color:#d20;background-color:#fff0f0">"Order saved"</span>
redirect_to <span style="color:#a60;background-color:#fff0f0">:index</span>
<span style="color:#080;font-weight:bold">else</span>
render <span style="color:#a60;background-color:#fff0f0">:edit</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>What I’m really trying to accomplish here is that I want to perform the following steps:</p>
<ul>
<li>Find my order</li>
<li>Update the attributes of my order</li>
<li>Calculate the tax</li>
<li>Calculate the shipping</li>
<li>Send the invoice, but only if the order is complete</li>
<li>Redirect back to the index page.</li>
</ul>
<p>There are a number of ways to accomplish this set of steps. There’s the option above but now my controller is doing way more than it should and testing this is going to get ugly. In the past, I may have created a callback in my order model. Something like after_save :calculate_tax_and_shipping and after_save :send_invoice if: :complete?. The trouble with this approach is that now <em>anytime</em> my order is updated these steps also occur. There may be many instances where I want to update my order and what I’m updating has nothing to do with calculating totals. This is particularly problematic when these calculations take a lot of processing and have a lot of dependencies on other models.</p>
<p>Another approach may be to move some of my steps into the controller before and after filters (now before_action and after_action in Rails 4). This approach is even worse because I’ve spread my order specific steps to a layer of my application that should only be responsible for routing user interaction to the business logic of my application. This makes maintaining this application more difficult and debugging a nightmare.</p>
<p>The approach I prefer is to hand off the processing of the order to a class that has the responsibility of processing the user’s interaction with the model, in this case, the order. Let’s take a look at how my controller action may look with this approach.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">update</span>
handler = <span style="color:#036;font-weight:bold">OrderControllerHandler</span>.new(params)
handler.execute!
<span style="color:#080;font-weight:bold">if</span> hander.order_saved?
redirect_to <span style="color:#a60;background-color:#fff0f0">:index</span>
<span style="color:#080;font-weight:bold">else</span>
<span style="color:#33b">@order</span> = handler.order
render <span style="color:#a60;background-color:#fff0f0">:edit</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>OK, now that I have my controller setup so that it’s only handling routing, as it should, how do I implement this OrderControllerHandler class? Let’s walk through this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">class</span> <span style="color:#b06;font-weight:bold">OrderControllerHandler</span>
<span style="color:#080">attr_reader</span> <span style="color:#a60;background-color:#fff0f0">:order</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">initialize</span>(params)
<span style="color:#33b">@params</span> = params
<span style="color:#33b">@order</span> = <span style="color:#080">nil</span> <span style="color:#888"># a null object would be better!</span>
<span style="color:#33b">@order_saved</span> = <span style="color:#080">false</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">execute!</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">order_saved?</span>
<span style="color:#33b">@order_saved</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>We now have the skeleton of our class setup and all we need to do is proceed with the implementation. Here’s where we can bust out our TDD chops and get to work. In the interest of brevity, I’ll leave out the tests, but I want to make the point that this approach makes testing so much easier. We now have a specific object to test without messing with all the intricacies of the controller. We can test the controller to route correctly on the order_saved? condition which can be safely mocked. We can also test the processing of our order in a more safe and isolated context. Ok, enough about testing, let’s proceed with the implementation. First, the execute method:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">execute!</span>
lookup_order
update_order
calculate_tax
calculate_shipping
send_invoice
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>Looks good right? Now we just need to create a method for each of these statements. Note, I’m not adding responsibility to my handler. For example, I’m not actually calculating the tax here. I’m just going to tell the order to calculate the tax, or even better, tell a TaxCalculator to calculate the tax for my order. The purpose of the handler class is to orchestrate the running of these different steps, not to actually perform the work. So, in the private section of my class, I may have some methods that look like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080">private</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">lookup_order</span>
<span style="color:#33b">@order</span> = <span style="color:#036;font-weight:bold">Order</span>.find(<span style="color:#33b">@params</span>[<span style="color:#a60;background-color:#fff0f0">:id</span>])
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">update_order</span>
<span style="color:#33b">@saved_order</span> = <span style="color:#33b">@order</span>.update_attributes(<span style="color:#33b">@params</span>[<span style="color:#a60;background-color:#fff0f0">:order</span>])
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">calculate_tax</span>
<span style="color:#036;font-weight:bold">TaxCalculator</span>.calculate(<span style="color:#33b">@order</span>)
<span style="color:#080;font-weight:bold">end</span>
... etc, you get the idea
</code></pre></div><h3 id="getting-functional">Getting function(al)</h3>
<p>So far, so good. But we have a problem here. What do we do if the lookup up of the order fails? I wouldn’t want to proceed to update the order in that case. Here’s where a little bit of functional programming can help us out (previous disclaimers apply). Let’s take another shot at our execute! method again and this time, we’ll wrap each step in an anonymous function aka, stabby lambda:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">execute!</span>
steps = [
->{ lookup_order },
->{ update_order },
->{ calculate_tax },
->{ calculate_shipping },
->{ send_invoice! },
]
steps.each { |step| <span style="color:#080;font-weight:bold">break</span> <span style="color:#080;font-weight:bold">unless</span> step.call }
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>What does this little refactor do for us? Well, it makes each step conditional on the return status of the previous step. Now we will only proceed through the steps when they complete successfully. But now each of our steps needs to return either true or false. To pretty this up and add some more meaning, we can do something like this:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080">private</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">stop</span>; <span style="color:#080">false</span>; <span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">proceed</span>; <span style="color:#080">true</span>; <span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">lookup_order</span>
<span style="color:#33b">@order</span> = <span style="color:#036;font-weight:bold">Order</span>.find(<span style="color:#33b">@params</span>[<span style="color:#a60;background-color:#fff0f0">:id</span>])
<span style="color:#33b">@order</span> ? proceed : stop
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div><p>Now each of my step methods has a nice clean way to show that I should either proceed or stop execution that reads well and is clear on its intent.</p>
<p>We can continue to improve this by catching some errors along the way so that we can report back what went wrong if there was a problem.</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080">attr_reader</span> <span style="color:#a60;background-color:#fff0f0">:order</span>, <span style="color:#a60;background-color:#fff0f0">:errors</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">initialize</span>(params)
<span style="color:#33b">@params</span> = params
<span style="color:#33b">@order</span> = <span style="color:#080">nil</span> <span style="color:#888"># a null object would be better!</span>
<span style="color:#33b">@order_saved</span> = <span style="color:#080">false</span>
<span style="color:#33b">@errors</span> = []
<span style="color:#080;font-weight:bold">end</span>
...
<span style="color:#080">private</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">proceed</span>; <span style="color:#080">true</span>; <span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">stop</span>(message=<span style="color:#d20;background-color:#fff0f0">""</span>)
<span style="color:#33b">@errors</span> << message <span style="color:#080;font-weight:bold">if</span> message.present?
<span style="color:#080">false</span>
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">invalid</span>(message)
<span style="color:#33b">@errors</span> << message
proceed
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">lookup_order</span>
<span style="color:#33b">@order</span> = <span style="color:#036;font-weight:bold">Order</span>.find(<span style="color:#33b">@params</span>[<span style="color:#a60;background-color:#fff0f0">:id</span>])
<span style="color:#33b">@order</span> ? proceed : stop(<span style="color:#d20;background-color:#fff0f0">"Order could not be found."</span>)
<span style="color:#080;font-weight:bold">end</span>
...
</code></pre></div><p>I’ve added these helpers to provide us with three different options for capturing errors and controlling the flow of our steps. We use the proceed method to just continue processing, invalid to record an error but continue processing anyway, and stop to optionally take a message and halt the processing of our step.</p>
<p>In summary, we’ve taken a controller with a lot of mixed responsibilities and conditional statements that determine the flow of the application and implemented a functional handler. This handler orchestrates the running of several steps and provides a way to control how those steps are run and even captures some error output if need be. This results in much cleaner code that is more testable and maintainable over time.</p>
<h3 id="homework-assignment">Homework Assignment</h3>
<ul>
<li>How could this pattern be pulled out into a module that could be easily included every time I wanted to use it?</li>
<li>How could I decouple the OrderControllerHandler class from the controller and make it a more general class that can be easily reused throughout my application anytime I needed to perform this set of steps?</li>
<li>How could this pattern be implemented as a functional pipeline that acts on a payload? How is this similar to Rack middleware?</li>
</ul>
<p>Hint:</p>
<div class="highlight"><pre tabindex="0" style="background-color:#fff;-moz-tab-size:4;-o-tab-size:4;tab-size:4"><code class="language-ruby" data-lang="ruby"><span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">steps</span>
[
->(payload){ step1(payload) },
->(payload){ step2(payload) },
->(payload){ step3(payload) },
]
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">def</span> <span style="color:#06b;font-weight:bold">execute_pipeline!</span>(payload)
last_result = payload
steps.each <span style="color:#080;font-weight:bold">do</span> |step|
last_result = step.call(last_result)
<span style="color:#080;font-weight:bold">end</span>
<span style="color:#080;font-weight:bold">end</span>
</code></pre></div>