<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by John McClean on Medium]]></title>
        <description><![CDATA[Stories by John McClean on Medium]]></description>
        <link>https://medium.com/@johnmcclean?source=rss-95e3f9916fae------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ngfFgYpvZpvHmIV0xqUS1Q.jpeg</url>
            <title>Stories by John McClean on Medium</title>
            <link>https://medium.com/@johnmcclean?source=rss-95e3f9916fae------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 13 Nov 2026 03:34:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johnmcclean/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com" rel="hub"/>
        <item>
            <title><![CDATA[A Java long read : Is functional programming worth it?]]></title>
            <link>https://medium.com/@johnmcclean/a-java-long-read-is-functional-programming-worth-it-ca53bfcd0c6a?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca53bfcd0c6a</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Sat, 06 Apr 2019 15:06:44 GMT</pubDate>
            <atom:updated>2019-04-06T18:44:58.319Z</atom:updated>
            <content:encoded><![CDATA[<p>This blog post is extracted from a talk I gave at St. Petersburg’s excellent Joker Conf in 2018.</p><p>The goal of this post is to examine whether the cost-benefit trade-off stacks up for functional programming in Java across 3 dimensions</p><blockquote>Correctness</blockquote><blockquote>Performance</blockquote><blockquote>&amp; Complexity</blockquote><h4>Correctness</h4><p>An informal definition of correctness is :</p><blockquote>an algorithm is correct if it is error free.</blockquote><p>In Java we could define hierarchy of errors as something like</p><p><strong>Compile time errors</strong> : errors the Java compiler catches and alerts us about.</p><p><strong>Runtime errors</strong> : Runtime exceptions and errors the Java runtime (hopefully) alerts us about.</p><p><strong>Logic errors</strong> : potentially more insidious errors that provide no explicit feedback that something has gone wrong.</p><p>As we move through this hierarchy of errors, the maximum potential cost of an error explodes upwards at each stage. If I introduce a compile time error, I really should only inconvenience myself. With proper processes in place, I will find and fix the problem on my development branch before it is committed to master.</p><p>If I cause a Runtime error to appear on our codebase, if we have good unit tests, I may be lucky enough to be alerted to the problem before it gets merged into master. If we are not so well prepared (and lucky!) we may instead get a call late at night when the effected code path is triggered and our monitoring and alerting systems kick in and do their jobs.</p><p>With logic errors the situation is worse again, the compiler won’t alert us if we have misunderstood a requirement and no exceptions may be thrown at runtime. Our software could run, incorrectly, for years, giving or storing incorrect data costing our employers or their customers money.</p><h4>Functional programming (in Java)</h4><p>As we shall see functional programming imposes a cost (often at the nexus of a performance / complexity trade off), and the main benefit of FP in Java is the ability to improve application correctness by pushing most (if not all) errors that may occur in the Runtime Error Tier down a level to the Compile time Error tier where they are easy to spot and cheap to fix.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KZkc4nIrFnwol9D3OggP3A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ug5t9ibJBbc?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Robert Baker</a> on <a href="https://unsplash.com/search/photos/algorithm?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Let’s examine functional and imperative Collections</h3><p>And discover what the trade offs are between application correctness, performance and complexity.</p><h4>Traditional mutable Collections</h4><p>The JDK Collections are standard imperative collections that are (or can be) mutated in place. It’s generally easier to implement Mutable Collections (e.g. see the stub for a mutable ArrayList with set method below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/186ac7aa3be27093d03ea6018a6a9c13/href">https://medium.com/media/186ac7aa3be27093d03ea6018a6a9c13/href</a></iframe><p>In addition to being straightforward to implement, they also set the gold standard for performance. While it’s possible for functional data structures to approach the performance of imperative ones, this often comes at a cost of increased complexity of implementation.</p><p>If we were to summarize the characteristics of mutable Collections in terms of performance and complexity it would look something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mHHsdLGbBSgJq40xubZngw.png" /></figure><p>So far — so good! But… You can probably guess that they are going to fall down in terms of application correctness (or otherwise there wouldn’t be much point in this blog post!). Let’s take a look at how these are often used in practice..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/768/1*fL2JwGa-qnIZeXjjIdiJeA.png" /></figure><p>This type of method signature is very common in Java applications. It consists of</p><p><strong><em>void</em></strong> return type</p><p><strong><em>mutable</em></strong> input parameters</p><p>The void return type indicates that this method is performing a side-effect, hopefully this is limited to some I/O operation, but as we are also providing mutable input parameters we can’t be sure that the scope of this method is limited to I/O. (If we allow the mutation of global state held in static variables we can be even less confident about the nature of this method).</p><p>In terms of our List of user ids, because it is mutable we can never really be sure it is unchanged after passing it as a method parameter. In Java <strong><em>it is not uncommon</em></strong> (unfortunately) <strong><em>for methods</em></strong> with signatures like the one above <strong><em>to mutate it’s input parameter </em></strong>🤮.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/1*Ar8feToA65z4FSn94V2zMA.png" /></figure><p>With the implementation above we see an I/O operation and a call to a method that in all likelihood has a similar method signature. If we want to be sure that our input parameter hasn’t changed, we’d need to check that method too. It really is mutable turtles all the way down🐢!</p><p>We could take a risk and write a method that makes use of our List without making a costly defensive copy first. In the listAndPersistUsers method below we extract the active user ids from the current context and persist them before returning them to the caller for further processing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I55bMa0uLJcK-pmX5d9QPQ.png" /></figure><h4>But, can we rely on this?</h4><p>Callers of listAndPersistUsers have to assume that none of the child calls recieving the mutable list of active users change it in any way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M4X0Xv5mpS97OQO9XbPwEw.png" /></figure><h4>Can we rely on this now and in the future?</h4><p>At some point in the future we may decide to always persist a Special Admin user, by adding it to our mutable list we also return it to clients of listAndPersistUsers. If this causes problems for them, there is nothing the type system and the compiler can do to help us here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*3zRPX1kHG_Wb01_s5HGYBw.png" /></figure><p>If we have introduced a bug we are relying on having good unit tests to catch it (in a piece of code that is also performing I/O, so expect the unit tests to be gnarly knot of mocking infrastructure and occasional asserts).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YtU4AKKiL3qgupRJUiWCGw.png" /></figure><p>With some additional insight, we can revisit our classification of mutable datastructures. While they are often the easiest to implement, they push uncertainty and complexity down into our application code! Perhaps we should split our complexity classification in two?</p><p>complexity of<strong> implementation </strong>— which remains simple</p><p>complexity of<strong> client code</strong>— which as we have seen can start to become difficult to reason about.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mOLoTu_sWOQj-gdOYTDvvw.png" /></figure><h3>Are JDK Unmodifiable datastructures any better?</h3><p>These are collections that expose an <strong><em>unmodifiable view</em></strong> into a mutable collection, and if anything, they are worse! Let’s start by looking at the characteristics they share with mutable collections :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b-17DnrEZKXshOf7zrsxAg.png" /></figure><p>We’ve already broken out the performance classification into two aspects (only one of which will be good like mutable collections)</p><p>read (or access) <strong>performance</strong> : remains identical (almost) to mutable collections</p><p>write (append / update) <strong>performance</strong> : well, let’s see</p><p>It’s pretty easy to create an unmodifiable collection, and we can modify our current code to pass one in to saveAndLogActiveUsers</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3ArCX03yfYZMG-DxtRg9RQ.png" /></figure><p>But this has no compile time impact on what code is permissable in saveAndLogActiveUsers (but it does have a runtime one).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*gVxJ9A6BQROZxBTRnF0awQ.png" /></figure><p>We can still add our Special Admin, to a supposedly immutable collection and our application will still compile! When we run this code however..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fhT8FCUP_vsMbw9RFM7Fg.png" /></figure><p>We get an UnsupportedOperationException, and we’ve swapped an insidious logic error for a slightly less insidious runtime one. Perhaps, we should be thankful for small mercies?, But if enough of these sneak into application the probability of us being rudely awakened out-of-hours by our boss with a production issue rapidly approaches 1!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qkzkNiiqAOP2WEVMf6UVNg.png" /></figure><p>Not only does this introduce the possibility of a new set of exceptions being thrown, the fact that these immutable views also masquerade as mutable ones (and are accepted as input into methods that take mutable collections) makes our code <strong><em>even harder</em></strong> to reason about than it was before.</p><p>In order to ensure the correct behaviour of our application once we have introduce unmodidfiable views, we should make a defensive copy of our collection before making changes to it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/798/1*lEjXlZQtdOPAc11RK0pB5A.png" /></figure><h4>Time complexity</h4><p>But what will this do to performance?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gEsdelrQEBfjXqfuBH5irQ.png" /></figure><p>Because, in order to change an unmodifiable view we need to perform a copy-on-write operation performance really suffers as Collection sizes increase. What this means is — to make any change we must make a defensive copy of the existing view into a new mutable collection, make the change and create a new replacement unmodiable view. The performance of modification operations scale linearly with the size of the collection! By contrast changing a single entry in an ArrayList takes the same amount of time regardless of its size!</p><p>That leaves us with a set of characteristics that looks like this -</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5NgL8Qi-uSE7A8VEXt276A.png" /></figure><p>But there is more — and it gets worse! Unmodifiable Views are just wrappers over independently modifiable mutable datastructures. As the underlying datasstructure can still change we can’t rely on Unmodifiable Views to keep our data (and it’s meaning) in tact! Let’s take a look at an example :</p><p>We could modify listAndPersistUsers to make the call to saveAndLogActiveUsers on a different thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGUxT3aGjMHzFGdUie1e_A.png" /></figure><p>Although we are passing in an Unmodifiable View of the currently active users into saveAndLogActiveUsers, this is not actually immutable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ptfgG0EootLqREUUPQL0pg.png" /></figure><p>The mutable list of currently active users still exists, and in the code above, we retain and return a reference to it</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hLhVfWRJvvFobYnINMcgHg.png" /></figure><p>If some client code were to change the returned list this would result in a race condition — saveAndLogActiveUsers expects the full list of active users to be past to it, and despite the fact that we pass a List to it we may feel is immutable — it is still possible to change it. Above we remove the first active user from the List and as the Unmodifiable View is a proxy into the List it is gone from there too!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PJwFQssMQTg_U9Z1UdoZNw.png" /></figure><p>Unmodifiable Collections in the JDK really are a very poor way to implement immutability in your applications introducing needless additional complexity and performance cost. There must be better alternatives..</p><h3>Immutable Collections (copy-on-write a la Guava)</h3><p>We could define immutable collections as simply collections that can’t be changed. This would include two distinct types of immutability</p><ol><li>Datastructures with copy-on-write semantics — that copy the entire datastructure when making a change</li><li>So-called persistent data structures that utilize shared portions of memory to make updates more efficient.</li></ol><p>#1 above is by far the most common type of immutable collection in Java, largely thanks to the immense popularity of Google’s Guava library.</p><p>The chief benefit of Immutable copy-on-write collections that continue to implement the mutable JDK collection interfaces over the awful Unmodifiable Views is that they remove the loose reference to the underlying mutable collection. This leaves their core characteristics as looking something like this :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EVCCEvs3DoyFSYOQxttz9A.png" /></figure><p>And we can see this in action if we plug Guava into our listAndPersistUsers method :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lJBPlnYql1JE9UZZIntq-g.png" /></figure><p>Because ImmutableList implements List, this is all we need do. Of course if saveAndLogActiveUsers still adds the Special Admin directly to the input parameter we will be in trouble. Because Guava’s ImmutableList implements List we can still attempt to add elements to an immutable Collection and the compiler will not stop us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*gVxJ9A6BQROZxBTRnF0awQ.png" /></figure><p>Running this code will still result in a nasty Exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fhT8FCUP_vsMbw9RFM7Fg.png" /></figure><p>It would be nice if the compiler could help us out here, and unlike with Unmodifiable Collections Guava does provide us with a specific type ImmutableList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/872/1*yIq6zX-FQ7RtaZTSoMASBw.png" /></figure><p>When we replace the input parameter to saveAndLogActiveUsers the buggy code that attempts to add a new element to that code still compiles! (Albeit with a warning that add has been deprecated on ImmutableList — again we should probably be thankful for small mercies). Running this code will result in the same Exception as before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7fhT8FCUP_vsMbw9RFM7Fg.png" /></figure><p>We can fix this error (when we are lucky enough to spot it) via a defensive copy-on-write operation. Guava provides us with a nice fluent interface to do this, but the performance impact is the same :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*inKAxYd1LSwXVEnZAYYKVg.png" /></figure><p>The cost of this operation is going to scale linearly with the size of the collection.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DniPi8tanmFI6SbDXqNgUA.png" /></figure><h4>Immutable and Unmodifiable : the risks</h4><p>We could summarize the downsides of JDK Unmodifiable Views and Guava style Immutable Collections as follows</p><p><em>Reduced</em> <strong>compile time safety</strong> due to</p><ol><li>Increased complexity due to the availability of illegal operations on the API</li><li>Increased complexity due to the ability to masquerade as a completely different and incompatible type (mutable v immutable)</li></ol><p><em>Significantly Reduced</em> <strong>runtime performance</strong> due to</p><ol><li>Poor scaling characteristics of modification operations (add, delete, set)</li></ol><iframe src="https://drive.google.com/viewerng/viewer?url=https%3A//www.cs.cmu.edu/%7Erwh/theses/okasaki.pdf&amp;embedded=true" width="600" height="780" frameborder="0" scrolling="no"><a href="https://medium.com/media/a306d489bf89503bdfe15d3e23783cc1/href">https://medium.com/media/a306d489bf89503bdfe15d3e23783cc1/href</a></iframe><p>To chart away out of this morass, to unlock the chief benefits of typed functional programming in terms of enhanced compile time safety and roughly comparable performance to imperative &amp; mutable alternatives we need to turn to Chris Okasaki and his seminal paper on <a href="https://www.cs.cmu.edu/~rwh/theses/okasaki.pdf">Purely Functional Data Structures</a>.</p><h3>Persistent Collections</h3><p>Persistent collections are immutable collections that leveraged shared memory a la Chris Okasaki to enable more efficient modification operations ideally approaching the scaling characteristics of their imperative analogues.</p><h4>Bitmapped Vector Trie an efficient Persistent ArrayList</h4><p>For persistent ArrayList type structures the Bitmapped Vector Trie, pioneered by Rich Hickey in Clojure offers reasonably close performance to it’s imperative cousin.</p><p>At it’s core the Bitmapped Vector Trie is an array of arrays, indexed by groups of bits in a single bitmap index.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/593/0*ZEsnUtrIGWnRm5V0" /></figure><p>Daniel Spiewak walks through one implementation approach in his rather excellent talk “<a href="https://www.youtube.com/watch?v=pNhBQJN44YQ">Extreme Cleverness: Functional Data Structures in Scala</a>”, and this was the approach we took when implementing a functional ArrayList (or Vector) in the functional library for Java —<a href="https://github.com/aol/cyclops"> Cyclops</a>.</p><p>There are some interesting features of this particular approach which I will attempt to cover here. First the Array of Arrays used is sized to the size of the Vector. If the Vector has a less than 32 elements then a 1D “Array-of-arrays” is used, I’ve put Array-of-arrays in quotes as a 1D Array-of-arrays is best implemented as a single Array. A small persistent Vector implemented in this way will have identical look up charcteristics as a standard mutable array (the implementations being virtually identical). The larger the array becomes (as per Guava style copy-on-write collections and JDK Unmodifiable views) the slower modification operations become. But we cap the max array size at 32 elements. This means our most expensive individual copy operation copies 32 entries. Once our 1D array exceeds 32 elements we switch to a 2D array structure. And we’ll need to figure out way to locate each element within that structure.</p><h4>Indexing a Bitmapped Vector Trie</h4><p>For a single Array of 32 elements we can use an int to capture the index, and in practice only the first 5 bits are needed.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/1*-vIYu0apcy2aN40iBhnrWw.png" /><figcaption>1D array with 4 values (0–3)</figcaption></figure><p>The index for a 1D Bitmapped Vector Trie looks just like it would for a stanadard Java Array or ArrayList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITLZ9UoLBnNGUYFxnnFE_A.png" /></figure><p>But once we move on to a 2D array, we need an index into the root level (or parent array), to extract the active node (or child array) that contains the data we need.</p><p>Let’s visualize a numeric sequence from 0 stored in a 2D Array of Arrays sized at 32 elements.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PFwqeGF4NOi28QBWDdWBZQ.png" /><figcaption>2D Array</figcaption></figure><p>In the truncated diagram above the top level Array contains other Arrays, the child Arrays contain Integers. At position A in the root we have a child array containing 0–31, at position 2 we have a child array containing 32–63 (and so on).</p><p>To access any element we need two numbers — the index in the root array, and the index in the child array. As each array as a max size of 32 elements we can store each index in 5 bits, or both together in 10 bits of a single integer. To extract each index we first shift by 5 (if needed) and then mask by anding with 31 (if needed). As our list get bigger we will scale from 2D to 3D, from 3D to 4D and so on.</p><h4>Performance</h4><p>Because we have to walk the multi-dimensional array structure retrieval and modification times scale logarthimically with the size of the collection. For small collections, stored in a standard array read performance should even be as fast as for JDK mutable collections! For larger collections modifications should perform orders of magnitude better than for JDK Unmodifiable Views and Guava Immutable collections!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n8aPxMOyCYxdQpBYm_Hv3g.png" /></figure><p>If we run a benchmark for get operations on small (typical most of the time) lists we can see performance is pretty much identical across all 3 types.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bs41XkGjRzkHwLhuXUIq0g.png" /></figure><p>In fact we won’t see differences until the sizes are a lot larger. By the time we are accessing Strings from a List with 10k elements the overhead of the indexing and nested array lookup becomes apparent (note these times are in <strong><em>micro-seconds</em></strong>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GizJf2Oxb39SKm8X1tm0nA.png" /></figure><p>But as expected the overhead of mutating large copy-on-write Immutable Collections is extortionate : (note these times are in <strong><em>milli-seconds</em></strong>!!)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a4DwIUSsnjW1TMCqEEY3RQ.png" /></figure><p>Appending to Persistent Vector performs better on average then even a mutable ArrayList because the occasional overhead of having to copy a full (and large) array into an even larger one is avoided entirely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u8lnP7_LsZ6eB033Hq0dGA.png" /></figure><p>To put things in perspective the access operation on a very large Persistent Vector is much faster than the relatively performant append operation on a similarly large Vector.</p><p>Unlike copy-on-write Immutable datastructures, Persistent shared-memory datastructures in the purely functional style have great all round performance characteristics.</p><h4>Correctness</h4><p>Now that we have found away to build immutable datastructures with sound performance, it would be good to ensure that we also cleanly and completely solve the real challenges with imperative mutable datastructures. We should aim to make our code easier to reason about. The core design principal to follow here is to make illegal states unrepresentable in our code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g2tZG-sfJOnm0VN4u-TQNA.png" /></figure><p>If we bought a toy for a child that broke when we pulled it’s levers or pressed it’s buttons, we’d consider it exceptionally bad design. We would probably think twice about purchasing from the company again. But, we make heavy use development kits and libraries that will blow up our apps when we call public methods on their APIs. We make heavy use of these libraries in the code that powers our financial markets, our civil infrastructure, our enterprise software, our consumer gadgets, our self-driving cars and our healthcare projects. But it really shouldn’t be this way.</p><p>The APIs of our libraries should guide is as developers along the right path and not into states from which the only way out is to throw an Exception. For Immutable Collections this means they can’t implement or extend java.util.Collection. Why not?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oQbMie3oR__GJNVKFDM8Gw.png" /></figure><p>If our Persistent Vector implements List we would be forced to implement methods such as add. Look at the method signature — the return type is a boolean, this forces us to make no change or mutate in place. We can either fail silently, and implement an alternative method to add that returns a new Vector — or follow the direction of the spec and throw that nasty UnsupportedOperationException : a Hobson’s choice. Better to start from scratch and create a new API which prevents developers from ever getting the Vector into an exceptional state!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Ry_TZVhc6sFkE2Ng-0IMg.png" /></figure><p>Instead in Cyclops we created a ‘plus’ method instead, this returns a new Vector with the new element efficiently added.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sFP8zFp-1ImxwOwUrcWe6A.png" /></figure><p>There is no legacy add method. It is just not possible to write code that will cause it to throw an Exception at runtime.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ajfkLIN3P-twKWg4zTc-dg.png" /></figure><p>And — we can always rely on listAndPersistUsers returning only (and all of) the currently active users no matter how deep we pass our Vector to other methods before returning it. Our code becomes much easier to reason about.</p><h4>Not just Collections</h4><p>If we make all our datastructures efficiently immutable with safe, with helpful and guiding APIs our application code will become much more easy to reason about and much less likely to fall prey to runtime Exceptions.</p><p>Within something as simple as a List (or Vector) there are many places where we would traditionally default to throwing Exceptions — when attempting to retrieve an element at an out-of-bounds index for example.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/0*zUCCSnq1FoZJzmLF" /></figure><p>Running this traditional imperative Java code results in another nasty runtime Exception</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/0*TOdQI2M8vjnvGmqw" /></figure><p>A better an alternative to throwing an IndexOutOfBoundsException, as shown in the example below is to return an Optional or Option type.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-f5YmF5c8Zdfl6yad5KfXA.png" /></figure><h4>But why not Optional?</h4><p>Although it is inspired by functional ideas, the JDK’s Optional type does not adhere to the pinciple of making illegal states unrepresentable :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/0*kiTLTxR4wGarqlme" /></figure><p>Running this code also results in a nasty runtime error</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*7tvYtm80yx7lwGDT" /></figure><p>So for Cyclops we had to define our own more principled implementation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/580/0*13dSP8qxXA230CFz" /></figure><p>The key goal is to switch our application call-stack from a messy hierarchy of mutable turtles all the way down, to a safe principled stack of immutable datastructures — simplifying our code.</p><h4>Because life is complicated enough</h4><p>Performant, safe immutable datastructures often don’t come for free. The nested multi-dimensional arrays of a Persistent Vector certainly gave a more complex view in the debugger than traditional simple mutable ArrayLists.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/720/1*IVDamexgMiQvhjZz1_X7SQ.png" /><figcaption>A large Persistent Vector in the IntelliJ debugger</figcaption></figure><p>The overall characteristics for Persistent Collections looks like this :- shared memory implementation leading to decent performance, and principled implementations will simplify client and help drive application correctness.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cgvrAEBJiMUg3D9ONdCjqA.png" /></figure><h3>Is functional programming in Java worth it?</h3><p>By adopting functional techniques and principles you introduce a learning curve for your team (e.g. See the standardized ladder of Functional Programming - <a href="http://lambdaconf.us/downloads/documents/lambdaconf_slfp.pdf">http://lambdaconf.us/downloads/documents/lambdaconf_slfp.pdf</a>). Although you don’t have to climb high to reap significant benefits in terms of improvements in application correctness and the ability to simplify your code. Immutable datastructures and pure functions are enough to get you started. Just be sure to choose wisely and select those that will help ensure your application is performant and correct!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca53bfcd0c6a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Java Functional and Reactive Weekly : 30th Nov & 7th Dec 2018]]></title>
            <link>https://medium.com/@johnmcclean/the-java-functional-and-reactive-weekly-30th-nov-7th-dec-2018-8f8f3b8e863d?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/8f8f3b8e863d</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[functionalreactiveweekly]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Fri, 07 Dec 2018 11:25:28 GMT</pubDate>
            <atom:updated>2018-12-08T20:01:09.083Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Java Functional and Reactive Weekly : 30th Nov &amp; 7th Dec 2018</h3><h4>This weeks functional and reactive Java blogs and talks!</h4><p>A roundup of the last 2 weeks blogs and talks (with the winding down of conference season the throughput of blogs and talks has fallen slightly).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSc3ULT6uEuaQVsmNvIRqw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/luhbI6_pIdg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Jörg Angeli</a> on <a href="https://unsplash.com/search/photos/skiing?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Links</h4><p><a href="https://www.youtube.com/watch?v=KbcciytZJm0&amp;feature=youtu.be&amp;a=">Full Stack Reactive Java with Project Reactor and Spring Boot</a> by <a href="https://twitter.com/mkheck">Mark Heckler</a></p><p><a href="https://www.youtube.com/watch?v=UtDG7AKuuA4&amp;feature=youtu.be">Reactive Java a new asynchronous database access API</a> by <a href="https://twitter.com/kmensah">Kuassi Mensah</a></p><p><a href="https://dzone.com/articles/from-functional-to-imperative-programming">From Functional to imperative programming</a> by Francisco Alvarez</p><p><a href="https://www.javacodegeeks.com/2018/12/functional-java-functions-parameters.html">Functional Java by Example | Part 6 — Functions as Parameters</a> by <a href="https://twitter.com/tvinke">Ted Vinke</a></p><p><a href="https://www.javacodegeeks.com/2018/11/functional-style-part-7.html">The Functional Style — Part 7</a> by Richard Wild</p><p><a href="https://www.infoq.com/presentations/spring-kotlin-functional?utm_campaign=infoq_content&amp;utm_source=infoq&amp;utm_medium=feed&amp;utm_term=Java&amp;utm_content=24725288">Spring, Kotlin and the Functional Way</a> by <a href="https://twitter.com/sdeleuze">Sébastien Deleuze</a></p><p><a href="https://mromeh.com/2018/12/04/java-functional-retry-with-resilience4j-retry/">Java Functional Retry with resilience4j-retry</a> by <a href="https://twitter.com/mromeh">mahmoud romeh</a></p><p><a href="https://youtu.be/54YK4I7_KGI">Object Oriented vs Functional</a> by <a href="https://twitter.com/tonyxzt">Tonino Lucca</a></p><p><a href="https://medium.com/@johnmcclean/powerful-extensible-code-with-tagless-final-in-java-4094f923cdea">Powerful, extensible code with Tagless Final in … Java</a> by <a href="https://twitter.com/johnmcclean_ie">john mcclean</a></p><h4>Embeds</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2F54YK4I7_KGI%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3D54YK4I7_KGI&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2F54YK4I7_KGI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d8f06c6fe916c6470ed430bca03be46c/href">https://medium.com/media/d8f06c6fe916c6470ed430bca03be46c/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FKbcciytZJm0%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DKbcciytZJm0&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FKbcciytZJm0%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/28cc248748e12b54550a6062d7907552/href">https://medium.com/media/28cc248748e12b54550a6062d7907552/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FUtDG7AKuuA4%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DUtDG7AKuuA4&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FUtDG7AKuuA4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4f885c936e1da8554beffdf038b57075/href">https://medium.com/media/4f885c936e1da8554beffdf038b57075/href</a></iframe><ul><li><a href="https://medium.com/@johnmcclean/powerful-extensible-code-with-tagless-final-in-java-4094f923cdea">Powerful, extensible code with Tagless Final in … Java!</a></li><li><a href="https://www.javacodegeeks.com/2018/12/functional-java-functions-parameters.html">Functional Java by Example | Part 6 - Functions as Parameters</a></li><li><a href="https://www.infoq.com/presentations/spring-kotlin-functional?utm_campaign=infoq_content&amp;utm_source=infoq&amp;utm_medium=feed&amp;utm_term=Java&amp;utm_content=24725288">Spring, Kotlin and the Functional Way</a></li><li><a href="https://www.javacodegeeks.com/2018/11/functional-style-part-7.html">The Functional Style - Part 7</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8f8f3b8e863d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Powerful, extensible code with Tagless Final in … Java!]]></title>
            <link>https://medium.com/@johnmcclean/powerful-extensible-code-with-tagless-final-in-java-4094f923cdea?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/4094f923cdea</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Tue, 04 Dec 2018 08:41:15 GMT</pubDate>
            <atom:updated>2018-12-05T13:30:44.945Z</atom:updated>
            <content:encoded><![CDATA[<p>Tagless final is all the rage in the Scala community at the moment. It is a technique that allows you to define the general structure of the code to be executed, such that we can configure different implementations (or interpreters) to inject effects such as Optionality, Asynchronicity, Parallelism, Non-Determinism, Error Handling depending on our needs. Need to simplify a highly concurrent piece of code for a test case so that you can debug a nasty production issue? With Tagless final — no problem!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTjYqbGzEmX1kmwN4qp9JQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/J6hE2DTWSEw?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Vitaly Taranov</a> on <a href="https://unsplash.com/search/photos/infinity?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Defining Mini-DSLs</h4><p>Much like the Free Monad, Tagless Final allows us to define mini-DSLs and apply different interpreters to them. Unlike the Free Monad, Tagless Final is (relatively) simple.</p><h4>A high level overview of the process</h4><p>We need to define the operations available in our mini-language (in Tagless Final parlance — the Algebra, in the Java-world an Interface with some default methods) — methods such as createOrder, deleteOrder, listOrders go here.</p><p>We define our programs abstractly in terms of the Algebra. E.g. createOrder -&gt; saveOrder -&gt; listOrders</p><p>We provide implementations of our i̶n̶t̶e̶r̶f̶a̶c̶e̶ (sorry I mean Algebra).</p><p>So far, so Object Oriented.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/561/1*PG9wi2TJc1fNQwvK0qqG1Q.png" /></figure><h4>A higher level of abstraction (or generality)</h4><p>The key difference from standard Java is that the i̶n̶t̶e̶r̶f̶a̶c̶e (Algebra) is defined at a higher level of abstraction. Using the library KindedJ we can define a higher order generic type something like this</p><pre><strong>Hk</strong>&lt;W,Order&gt; createOrder(User user, OrderData data);</pre><p>Hk is an interface that higher order types (such as the Monadic types in Cyclops) can implement, and W is the ‘witness’ type that let’s know which higher order type we are working with. More concretely a Cyclops Option would look something like this</p><pre>Hk&lt;option,Order&gt; option = Option.some(order);</pre><h4>The Monad ‘pattern’</h4><p>The nice thing about Monads is they all implement the same general suite of methods (of / map / flatMap and so on) that all behave in predictable ways. This means that if we define our programs to work with Monads, and define our Algebra in a generic manner so that the concrete Monadic type is pluggable — we can reuse the same Algebra and ‘program’ definition with many different Monadic datastructures. In fact we aren’t even constrained to using Monads (but that is for another article!)</p><h4>Monads all do something different</h4><p><em>Option</em> : represents Optionality</p><p><em>Future</em> : represents an asynchronously calculated value</p><p><em>Vector</em> : represents something that can be absent, have one value or many values</p><p><em>Try</em> : represents something that can fail</p><p>And so on. By defining our interfaces in a very general way, we can easily extend our application by pluggin in the behaviour we need by switching Monad types. As we shall see later, we can also mix monad types and stack them up too!</p><h4>Tagless final v Free</h4><p>A previous blog series dived into the details of creating mini-DSLs using the Free Monad in Java — it may be instructive to compare and contrast the approaches as Tagless Final appears <strong><em>a lot more straightforward</em></strong>.</p><p><a href="https://medium.com/modernnerd-code/dsls-with-the-free-monad-in-java-8-part-i-701408e874f8">DSLs with the Free Monad in Java 8 : Part I</a></p><p><a href="https://medium.com/@johnmcclean/simulating-higher-kinded-types-in-java-b52a18b72c74">Simulating Higher Kinded Types in Java</a></p><p><a href="https://medium.com/@johnmcclean/dsls-with-the-free-monad-in-java-8-part-ii-f0010f012ae1">DSLs with the Free Monad in Java 8 : Part II</a></p><h4>Let’s move on to an example</h4><p>To start with we will convert the simple Account credit and debit example from Chapter 1 of <a href="https://twitter.com/debasishg">Debasish (দেবাশিস্) Ghosh</a>’s awesome <a href="https://www.manning.com/books/functional-and-reactive-domain-modeling">Functional and Reactive Domain Modeling</a></p><p>The first step is to define our algebra or mini language, we could sketch this out as something like the ability to debit or credit an bank account.</p><pre><strong>AccountAlgebra</strong>{<br><br>    <strong>debit</strong>(Account account, double<strong> </strong>amount);<br>    <strong>credit</strong>(Account account, double<strong> </strong>amount);<br><br>}</pre><p>We might define an interface for this in traditional Java something like this</p><pre>interface<strong> AccountAlgebra</strong>{<br><br>    Account <strong>debit</strong>(Account account, double<strong> </strong>amount) throws Exception;<br>    Account <strong>credit</strong>(Account account, double<strong> </strong>amount) throws Exception;<br><br>}</pre><p>But if you have been following the <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-a-functional-tutorial-20e0bebd2ec9">Dysfunctional Programming in Java</a> series then you’ll know that <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">throwing Exceptions isn’t good functional practice</a>. A better idea would be to return an Either that captures the error as it’s left type value, or even an Option that is empty if debiting or crediting failed.</p><p>E.g. using <strong><em>Either</em></strong></p><pre>interface<strong> AccountAlgebra</strong>{<br><br>    Either&lt;AccError,Account&gt; <strong>debit</strong>(Account account, double<strong> </strong>amount);<br>    Either&lt;AccError,Account&gt; <strong>credit</strong>(Account account, double<strong> </strong>amount);<br><br>}</pre><p>Using <strong><em>Option</em></strong></p><pre>interface<strong> AccountAlgebra</strong>{<br><br>    Option&lt;Account&gt; <strong>debit</strong>(Account account, double<strong> </strong>amount);<br>    Option&lt;Account&gt; <strong>credit</strong>(Account account, double<strong> </strong>amount);<br><br>}</pre><p>We live in a reactive world and perhaps we should consider debit &amp; credit should be executed asynchronously, we could return a Future here instead.</p><pre>interface<strong> AccountAlgebra</strong>{<br><br>    Future&lt;Account&gt; <strong>debit</strong>(Account account, double<strong> </strong>amount);<br>    Future&lt;Account&gt; <strong>credit</strong>(Account account, double<strong> </strong>amount);<br><br>}</pre><p>One of the <strong><em>nice things about tagless final is.. we don’t have to choose</em></strong>!</p><h4>A higher level of Abstraction</h4><p>We simply define AccountAlgebra at a higher level of abstraction with KindedJ :-</p><pre>interface<strong> </strong>AccountAlgebra&lt;<strong>W</strong>&gt;{<br><br>    <strong>Hk</strong>&lt;<strong>W,</strong>Account&gt; debit(Account account, double<strong> </strong>amount);<br>    <strong>Hk</strong>&lt;<strong>W</strong>,Account&gt; credit(Account account, double<strong> </strong>amount);<br><br>}</pre><p><a href="https://github.com/aol/cyclops/tree/master/cyclops-pure">I’m using Cyclops</a>, which defines an interface Higher that extends Hk from KindedJ and adds some handy conversion methods.</p><pre>interface<strong> </strong>AccountAlgebra&lt;<strong>W</strong>&gt;{<br><br>    <strong>Higher</strong>&lt;<strong>W,</strong>Account&gt; debit(Account account, double<strong> </strong>amount);<br>    <strong>Higher</strong>&lt;<strong>W</strong>,Account&gt; credit(Account account, double<strong> </strong>amount);<br><br>}</pre><p>The type parameter <strong><em>W</em></strong> in the above example represents the monad type which we can plug in at compile time. If we want to use the IO monad to perform the actions asynchronously we define an implementation (or interpreter) like so :-</p><pre><strong>class </strong>AccountIO <strong>implements </strong>AccountAlgebra&lt;io&gt; {<br>    <br>    Higher&lt;io, Account&gt; <strong>debit</strong>(Account account, double<strong> </strong>amount) {<br>        return<strong> </strong>IO.<em>of</em>(()-&gt;account,exec)<br>                 .map(a-&gt;a.debit(amount));<br>    }<br><br>    Higher&lt;io, Account&gt; <strong>credit</strong>(Account account, double<strong> </strong>amount) {<br>        return<strong> </strong>IO.<em>of</em>(()-&gt;account,exec)<br>                 .map(a-&gt;a.credit(amount));<br>    }<br>}</pre><h4>Constructing a mini-program</h4><p>With the operators available to us we could construct a simple program to transfer money from one account to another.</p><pre>class TransferManager {</pre><pre>     Account from;  <br>     Account to;</pre><pre>}</pre><p>We should also pass in our Algebra (or interface that defines the allowable operations)</p><pre>class TransferManager&lt;W&gt;{</pre><pre>     Account from;  <br>     Account to;<br>     AccountAlgebra&lt;W&gt; acountService;</pre><pre>}</pre><p>We’re going to be working with Monads. It’s not normally possible to define an generic Interface for working with Monads in Java (as we can’t directly express higher kinded types — or generic type parameters that themselves accept a type parameter), but we can do it indirectly thanks to KindedJ. Cyclops defines such a higher kinded Monad interface for us.</p><pre>class TransferManager&lt;W&gt;{</pre><pre>     Account from;  <br>     Account to;<br>     AccountAlgebra&lt;W&gt; acountService;<br>     Monad&lt;W&gt; monad;</pre><pre>}</pre><p><strong><em>Now we can leverage our AccountAlgebra with any Monad type</em></strong> (we only need to implement the Monad interface!).</p><h4>Defining our transfer method</h4><p>We can define a method to transfer money from each of these accounts</p><pre>public ??? transfer(double amount)</pre><p>Inside transfer we can compose the building blocks of our mini-language (defined in AccountAlgebra) to transfer between accounts.</p><p>given an <strong>amount</strong></p><p><strong>debit</strong> account ‘<em>from’</em></p><p><strong>credit</strong> account ‘<em>to’</em></p><p>return both accounts.</p><p>Because we are working with monads, we could call the of (or unit) method on our Monad Interface to create a instance which contains amount, then we can compose calls to AccountAlgebra::credit and AccountAlgebra::debit via flatMap.</p><pre>monad.flatMap(monad.of(amount), amount-&gt; {</pre><pre>  return monad.flatMap(accountService.<strong>credit</strong>(<em>to</em>,amount),account-&gt; {</pre><pre>                return accountService.<strong>debit</strong>(<em>from</em>,amount);</pre><pre>      });<br>});</pre><p>Pretty ugly!</p><p>But this is a standard pattern. We can easily put together a generic class that will orchestrate these calls for us and allow us to clean up our code (in Cyclops this is the Do builder)</p><pre>Do.<em>forEach</em>(monad)<br>        ._of(<strong>amount</strong>)<br>        .__(this::<strong>debitFrom</strong>)<br>        .__(<em>_1</em>(this::<strong>creditTo</strong>))<br>        .yield(<em>__23</em>(Tuple::<strong><em>tuple</em></strong>))</pre><p>To get a nice fluent flow with method references all we need to do is define a couple of helper methods</p><pre>private<strong> </strong>Higher&lt;W,Account&gt; <strong>debitFrom</strong>(double<strong> </strong>amount){<br>    return<strong> </strong>accountService.<strong>debit</strong>(<em>from</em>,amount);<br>}<br>private<strong> </strong>Higher&lt;W,Account&gt; <strong>creditTo</strong>(double<strong> </strong>amount){<br>    return<strong> </strong>accountService.<strong>credit</strong>(<em>to</em>,amount);<br>}</pre><p>When we construct our program object all we need to do is pass in an instance of our AccountIO implementation of AccountAlgebra and the IO Monad Instance. If we want to change to a blocking implementation we could plugin an Option based implementation of the Algebra and it’s Monad instance (for example).</p><h4>Combining Monads</h4><p>It’s pretty straight forward to combine different monad types also.</p><p>Most Tagless final blogs seem to add some logging at this point (and I don’t really see any reason to break with tradition). So let’s define the algebra for our logging DSL.</p><pre>LogAlgebra {<br><br>    void info(String message);<br>    void error(String message);<br><br>}</pre><p>Which can translate into Tagless Final form</p><pre>LogAlgebra&lt;W&gt; {<br><br>    Higher&lt;W,Void&gt; info(String message);<br>    Higher&lt;W, Void&gt; error(String message);<br><br>}</pre><p>And given a LogAlgebra instance, and an AccountAlgebra instance</p><pre>LogAlgebra&lt;<strong>W</strong>&gt; logService;<br>AccountAlgebra&lt;<strong>W</strong>&gt; accountService;</pre><p>We can define a method to log account some account details</p><pre>Higher&lt;W, Void&gt; logBalance(Account a) {<br>    return<strong>  </strong>logService.<strong>info</strong>(<strong>&quot;</strong>Account<strong> </strong>balance<strong> &quot; </strong>+ a.getBalance());<br>}</pre><p>And we can then plug this into our for comprehension</p><pre>Do.<em>forEach</em>(monad)<br>  ._of(<strong>amount</strong>)<br>  .__(this::<strong>debitFrom</strong>)<br>  .__(<em>_2</em>(this::<strong>logBalance</strong>))<br>  .__(<em>__1</em>(this::<strong>creditTo</strong>))<br>  .__(<em>___4</em>(this::<strong>logBalance</strong>))<br>  .yield(<em>____24</em>(Tuple::<strong>tuple</strong>))</pre><p>Because we have the same type parameter (which determines the monad type) in both the Log and Account Algebras, everything composes together quite nicely.</p><pre>LogAlgebra&lt;<strong>W</strong>&gt; logService;<br>AccountAlgebra&lt;<strong>W</strong>&gt; accountService;</pre><p><strong>But what if they were different?</strong></p><p>If the Monad types (as determined by the type parameters specified) were W1 and W2 rather than just W for both :-</p><pre>LogAlgebra&lt;<strong>W1</strong>&gt; logService;<br>AccountAlgebra&lt;<strong>W2</strong>&gt; accountService;</pre><p>This is still no problem! We just need to make sure we do a conversion back to one of the types (in this case W2). A <strong><em>NaturalTransformation</em></strong> is an interface for converting between two different monadic structures holding the same type :-</p><pre>@FunctionalInterface<br>interface<strong> </strong>NaturalTransformation&lt;W1,W2&gt;{</pre><pre>    &lt;T&gt; Higher&lt;W2, T&gt; apply(Higher&lt;W1, T&gt; a) ;<br>}</pre><p>We pass in Monad &lt;W1,T&gt; and get back Monad&lt;W2,T&gt;.</p><h4>A logging algebra</h4><p>Let’s define a blocking LogAlgebra iterpreter that uses the Identity Monad (rather than IO or another non-blocking alternative)</p><pre>LogID <strong>implements </strong>LogAlgebra&lt;identity&gt;{ <br><br>Higher&lt;identity, Void&gt; info(String message) {<br>  <strong>return </strong>Identity.<em>of</em>(message).peek(logger::info);<br>}<br><br>@Override<br>Higher&lt;identity, Void&gt; error(String message) {<br>  <strong>return </strong>Identity.<em>of</em>(message).peek(logger::error);<br>}</pre><p>W1 is the Monad type we want to convert from, and W2 is the Monad type we want to convert to. E.g. to convert between an Identity and an IO the NaturalTransformation would look like this</p><pre>class<strong> </strong>IdentityToIO implements<strong> NaturalTransformation</strong>&lt;<strong>identity</strong>, <strong>io</strong>&gt; {<br><br>    public<strong> </strong>&lt;T&gt; <strong>IO</strong>&lt;T&gt; apply(Higher&lt;<strong>identity</strong>, T&gt; a) {<br>        return<strong> </strong>a.<strong>convert</strong>(Identity::<em>narrowK</em>)<br>                .to(IO::sync);<br>    }<br>}</pre><p>Using NaturalTransformations to convert between higher kinded Monads is straight forward as well</p><pre>NaturalTransformation&lt;W2,W1&gt; natTrans<strong>;</strong></pre><pre>Higher&lt;W1, Void&gt; logBalance(Account a) {<br>    return<strong>  </strong>logService.info(<strong>&quot;</strong>Account<strong> </strong>balance<strong> &quot; </strong>+ a.getBalance())<br>                      .<strong>convert</strong>(natTrans.asFunction());<br>}</pre><p>Which leaves our program — pretty much identical to how it was before</p><pre>Do.<em>forEach</em>(<strong>monad</strong>)<br>  ._of(<strong>amount</strong>)<br>  .__(this::<strong>debitFrom</strong>)<br>  .__(<em>_2</em>(this::<strong>logBalance</strong>))<br>  .__(<em>__1</em>(this::<strong>creditTo</strong>))<br>  .__(<em>___4</em>(this::<strong>logBalance</strong>))<br>  .yield(<em>____24</em>(Tuple::<strong>tuple</strong>))</pre><h4>Stacking Monads</h4><p>It’s possible to stack algebras and interpreters, plugging in different Monads to different effect at each layer. Let’s add in a data store and use to store account balances. In plain Java the Store Algebra might look something like this :-</p><pre>StoreAlgebra&lt;K,V&gt; {<br>    Option&lt;V&gt; get(K key);<br>    void put(K key, V value);<br>}</pre><p>With the Tagless Final encoding it becomes :-</p><pre>StoreAlgebra&lt;W,K,V&gt; {<br>    Higher&lt;W, Option&lt;V&gt;&gt; get(K key);<br>    Higher&lt;W, Void&gt; put(K key, V value);<br>}</pre><p>We can modify our AccountAlgebra to allow us to make use of the Store, first by making is available somehow on the algebra (the hacky but easy thing to do is just to add a couple of methods directly to the interface definition).</p><pre>AccountAlgebra&lt;W&gt; {<br><br>    StoreAlgebra&lt;W,Long,Account&gt; store();<br>    Do&lt;W&gt; forEach();<br><br>    Higher&lt;W,Option&lt;Account&gt;&gt; debit(Account account, double<strong> </strong>amount)<br>    Higher&lt;W, Option&lt;Account&gt;&gt; credit(Account account, double<strong> </strong>amount);</pre><pre>}</pre><p>We can even plugin a default implementation that makes use of Store Algebra</p><pre>AccountAlgebra&lt;W&gt; {<br><br> StoreAlgebra&lt;W,Long,Account&gt; store();<br> Do&lt;W&gt; forEach();</pre><pre>Higher&lt;W,Option&lt;Account&gt;&gt; debit(long id, double<strong> </strong>amount){<br> return<strong> </strong>forEach().__(store().<strong>get</strong>(id))<br>                 .__(acc -&gt; acc.<strong>debit</strong>(amount))<br>                 .__(_1(a -&gt; store().<strong>put</strong>(a.getId(),  a)))<br>                 .yield_1((a, b) -&gt; a);<br><br>  }<br>    <br> Higher&lt;W, Option&lt;Account&gt;&gt; credit(long id, double<strong> </strong>amount){<br>  return<strong> </strong>forEach().__(store().<strong>get</strong>(id))<br>                  .__(acc -&gt; acc.<strong>credit</strong>(amount))<br>                  ._1(acc -&gt; store().<strong>put</strong>(acc.getId(),  acc))<br>                  .yield_1((a, b) -&gt; a);<br> }</pre><p>It’s a bit messier this time as we haven’t defined helper methods to use as method references.</p><p>Our program code remains very simple (with the logging removed)</p><pre>Do.<em>forEach</em>(monad)<br>  ._of(<strong>amount</strong>)<br>  .__(this::<strong>debitFrom</strong>)<br>  .__(<em>_1</em>(this::<strong>creditTo</strong>))<br>  .yield(<em>__23</em>(Tuple::<strong>tuple</strong>))</pre><h4>Cyclops : a higher kinded functional library for Java</h4><p>If you want to try this out at home, import the <a href="https://github.com/aol/cyclops-react">cyclops</a> library for functional programming in Java and play about with the examples, <a href="https://github.com/aol/cyclops/tree/master/cyclops-pure/src/test/java/cyclops/typeclasses/taglessfinal">all the code is on the github repo</a>.</p><p><strong><em>Maven</em></strong></p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.oath.cyclops&lt;/groupId&gt;<br> &lt;artifactId&gt;cyclops-pure&lt;/artifactId&gt;<br> &lt;version&gt;10.1.0&lt;/version&gt;     <br>&lt;/dependency&gt;</pre><p><strong><em>Gradle</em></strong></p><pre>compile group: &#39;com.oath.cyclops&#39;, name: &#39;cyclops&#39;, version: &#39;10.1.0&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4094f923cdea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Java Functional and Reactive Weekly : 23rd of November]]></title>
            <link>https://medium.com/@johnmcclean/the-java-functional-and-reactive-weekly-23rd-of-november-a52197fad87a?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/a52197fad87a</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[functionalreactiveweekly]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Fri, 23 Nov 2018 11:11:57 GMT</pubDate>
            <atom:updated>2018-11-23T11:48:44.696Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Java Functional and Reactive Weekly : 23rd of November</h3><h4>This weeks functional and reactive Java blogs and talks!</h4><p>A bumper round up of blogs and talks on Functional Programming &amp; Reactive Programming in Java.</p><h3>Functional and Reactive Blogs and Talks</h3><p><a href="https://medium.com/@johnmcclean/lambdas-are-not-functional-programming-63533ce2eb74">Lambdas are not functional programming</a> by <a href="https://twitter.com/johnmcclean_ie">John McClean</a></p><p><a href="https://www.youtube.com/watch?v=p6cZO5V2ehw&amp;list=PLRsbF2sD7JVp8vBso4ysmj-X0u6uGx1rH">OOP v̶s̶ and FP</a> by <a href="https://twitter.com/mariofusco">Mario Fusco</a></p><p><a href="http://blog.ploeh.dk/2018/11/19/functional-architecture-a-definition/">Functional architecture: a definition</a> by <a href="https://twitter.com/ploeh">Mark Seemann</a></p><p><a href="https://www.youtube.com/watch?v=HSk5fdKbd3o">FP vs OOP: Choose Two</a> by <a href="https://twitter.com/BrianGoetz">Brian Goetz</a></p><p><a href="https://www.youtube.com/watch?v=stWyTMhfcOs">Is Functional Programming worth it?</a> by <a href="https://twitter.com/johnmcclean_ie">John McClean</a></p><p><a href="https://dzone.com/articles/functional-programming-patterns-with-java-8">Functional Programming Patterns With Java 8</a> by <a href="https://twitter.com/VictorRentea">Victor Rentea</a></p><p><a href="https://youtu.be/Edcp7cUMDek">Introduction to AWS SDK v2 for Java</a> by <a href="https://twitter.com/maciejwalkowiak">Maciej Walkowiak</a></p><p>Reactive Java For the Realtime : <a href="https://youtu.be/axsROcftvQc">video</a> and <a href="https://speakerdeck.com/trayan/reactive-java-for-the-realtime">slides</a> by <a href="https://twitter.com/trayaniliev">Trayan Iliev</a></p><p><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-7-immutable-collections-83ba78aaf4dd">Dysfunctional programming in Java 7 : Immutable Collections</a> by <a href="https://twitter.com/johnmcclean_ie">john mcclean</a></p><p><a href="https://www.youtube.com/watch?v=vbGbXUjlRyQ&amp;feature=youtu.be">Project Loom Fibre and Continuations on the JVM</a> by Alan Bateman</p><p><a href="https://www.youtube.com/watch?v=fXWywFRwHOk&amp;feature=youtu.be&amp;a=">Real-world Reactive Programming in Java: The Definitive Guide</a> by <a href="https://twitter.com/erwindeg">Erwin</a></p><h3>Embeds — watch the talks right here!</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qZqIAFSLGBjADpNTsnu9Pw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/LqKhnDzSF-8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Joshua Sortino</a> on <a href="https://unsplash.com/search/photos/matrix?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><ul><li><a href="https://medium.com/@johnmcclean/lambdas-are-not-functional-programming-63533ce2eb74">Lambdas are not functional programming</a></li><li><a href="http://blog.ploeh.dk/2018/11/19/functional-architecture-a-definition/">Functional architecture: a definition</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2Fp6cZO5V2ehw&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3Dp6cZO5V2ehw&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fi.ytimg.com%2Fvi%2Fp6cZO5V2ehw%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/d50e0a526c52070d34738c9156af57ed/href">https://medium.com/media/d50e0a526c52070d34738c9156af57ed/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2Fvideoseries%3Flist%3DPLVe-2wcL84b_DvLWtURPD0Dz2NZil55XI&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DstWyTMhfcOs&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FstWyTMhfcOs%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/98672a0ebfba3d7e58ba6c20232a9ed7/href">https://medium.com/media/98672a0ebfba3d7e58ba6c20232a9ed7/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FHSk5fdKbd3o%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fwatch%3Fv%3DHSk5fdKbd3o&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FHSk5fdKbd3o%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/97cac091b35fbd313dba79b6f56c5794/href">https://medium.com/media/97cac091b35fbd313dba79b6f56c5794/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FEdcp7cUMDek%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DEdcp7cUMDek&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FEdcp7cUMDek%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3ea7c22d3e4bcec198cbe9a5e3dd95d/href">https://medium.com/media/f3ea7c22d3e4bcec198cbe9a5e3dd95d/href</a></iframe><p><a href="https://dzone.com/articles/functional-programming-patterns-with-java-8">Functional Programming Patterns With Java 8 - DZone Java</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FaxsROcftvQc%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DaxsROcftvQc&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FaxsROcftvQc%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8debb4d8b308f010dbafe8dc80559c7d/href">https://medium.com/media/8debb4d8b308f010dbafe8dc80559c7d/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerdeck.com%2Fplayer%2F18d98ad3d6ba4b18b96d22903111cace&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerdeck.com%2Ftrayan%2Freactive-java-for-the-realtime&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerd.s3.amazonaws.com%2Fpresentations%2F18d98ad3d6ba4b18b96d22903111cace%2Fslide_0.jpg%3F477551&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="532" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f1357f76974c28cddaca3c2a9e58072/href">https://medium.com/media/0f1357f76974c28cddaca3c2a9e58072/href</a></iframe><p><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-7-immutable-collections-83ba78aaf4dd">Dysfunctional programming in Java 7 : Immutable Collections</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FvbGbXUjlRyQ%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DvbGbXUjlRyQ&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FvbGbXUjlRyQ%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/517a7cdf76ee605edae944c12c3ae808/href">https://medium.com/media/517a7cdf76ee605edae944c12c3ae808/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FfXWywFRwHOk%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DfXWywFRwHOk&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FfXWywFRwHOk%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/c4bb6cfb134b93cbb1e2919a5566f4ea/href">https://medium.com/media/c4bb6cfb134b93cbb1e2919a5566f4ea/href</a></iframe><p>Interesting blog post missing? Let me know <a href="https://twitter.com/johnmcclean_ie">johnmcclean_ie on Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a52197fad87a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Lambdas are not functional programming]]></title>
            <link>https://medium.com/@johnmcclean/lambdas-are-not-functional-programming-63533ce2eb74?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/63533ce2eb74</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Wed, 21 Nov 2018 13:10:58 GMT</pubDate>
            <atom:updated>2018-12-03T14:48:46.729Z</atom:updated>
            <content:encoded><![CDATA[<p>No-one in Java-land is doing functional programming, and that is a good thing.</p><p>Just because you are using Lambda expressions, does not mean you are doing functional programming.</p><p>Lambda expressions in Java are simply a less verbose way of creating (slightly constrained) Objects and as such the most likely outcome of adopting Lambda’s without a good understanding of core functional concepts is gnarly, twisted, hard to follow, obfuscated imperative Object Oriented code with a nice concise syntax. Yes, we could write exactly the same dodgy code in a more verbose way by creating individual classes and lambdas.</p><p>Conversely, even when writing actual functional code in Java we could write the same code with verbose Class definitions and Objects as we can with concise lambdas.</p><h4>Seek help</h4><p>For those that disagree passionately with my first sentence, and are busy searching for the (strangely hard to find) reply button on Medium (“well actually.. my team have been doing fp in Java“) — ⛔️stop!⛔️. If for some crazy reason you <em>are</em> doing functional programming in Java, instead of reading my rants you probably should have a good long hard think about your language choices.</p><h4>Just what the hell is functional programming then?</h4><p>A lot of people in Java-land are trying to mix traditional imperative Java code and functional-ish code, with varying degrees of success. Java is not a functional language, it is fundamentally an Object Oriented language that allows us to adopt some functional concepts in so far as we enforce their correct implementation through developer discipline. Unlike in Haskell, Idris, Ocaml (and even Scala) the compiler alone won’t save us.</p><p>If we are going adopt functional principles to mix Object Oriented and Functional Programming successfully in Java, we had better know what they are. What are the core features of functional languages?</p><h4>Is it laziness?</h4><p>Streams in Java are lazy (although Optional and CompletableFuture aren’t). Perhaps laziness is a core tenet of fp, and to be truly functional we also must be lazy. Haskell is lazy language, but unfortunately Ocaml, Idris and ML (to name but 3) are strict (eager) by default. I don’t think anyone would argue that Idris is not a functional language.</p><h4>Laziness and performance</h4><p>Laziness can improve performance, after all the most performant code is code not executed. In the simple example below we will stop processing once we have loaded 10 good records from somewhere (rather than load all records first and then filter them).</p><pre>Stream.generate(this::loadFromSomewhere)<br>      .filter(this::identifyStuffWeWant)<br>      .limit(10)<br>      .collect(Collectors.toList());</pre><p>Whether this is a real performance benefit or not is debatable, we can always couple our filtering and limit logic with our loading logic in some manner even when processing the data eagerly to avoid doing excess work (we are arguably getting cleaner code not better performance with laziness). The <a href="https://wiki.haskell.org/Performance/Strictness">Haskell wiki has this to say on laziness and performance</a></p><blockquote>Laziness can be a useful tool for improving performance, but more often than not it reduces performance by adding a constant overhead to everything. Because of laziness, the compiler can’t evaluate a function argument and pass the value to the function, it has to record the expression in the heap in a <em>suspension</em> (or <em>thunk</em>) in case it is evaluated later. Storing and evaluating suspensions is costly, and unnecessary if the expression was going to be evaluated anyway.</blockquote><p><a href="https://www.infoq.com/news/2015/11/haskell-strict-eval-patch">And since at least 2015 it’s been possible to configure Haskell to use strict evaluation by default</a>.</p><p><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-i-laziness-cc9c6981de39">Laziness is a really cool feature of functional languages that we can leverage to our advantage in Java,</a> but I don’t believe it is one of the critical traits of functional languages from which their primary benefits derive.</p><h4>Is it functional composition?</h4><p>This is definitely a big part of it. All of the functional languages previously mentioned have functions as first class citizens and once we have that we can chain function calls together by matching the types.</p><p>E.g. from <a href="https://hackernoon.com/superkleisliisfantasticframeworksareatrocious-a-functional-approach-to-dependency-injection-in-e7bc8c4993fa">A functional approach to dependency injection in Java</a> we can compose a function that accepts a DAO and returns a String with another that accepts a String and returns a String by matching the output with the first, with the input of the second.</p><pre>public<strong> </strong>Function&lt;DAO,String&gt; loadName(long id);</pre><pre><strong>loadName</strong>(10l).<strong>andThen</strong>(name-&gt;&quot;User&#39;s name is &quot;+ name);</pre><pre>Function&lt;DAO,String&gt; sentence = <strong>loadName</strong>(10l).<strong>andThen</strong>(name-&gt;&quot;User&#39;s name is &quot;+ name);</pre><pre>System.out.println(sentence.apply(dao));</pre><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*qG6dbAH-IA5BXLUgk_j0LA.png" /></figure><p>The ability to compose functions like this, opens the door to higher order functions and by extension to implementations of concepts / patterns from category theory like Monads and Functors.</p><p>But all of this only works if the functions are pure -&gt; that is that they are not mutating or impacting state outside of the function. Which brings us to the next potential core trait.</p><h4>Is it immutability?</h4><p>This is also massively important for functional programming. All of the aforementioned languages encourage immutability by default and eschew (to varying degrees) mutability altogether. In the Java ecosystem most of our core datastructures (in the JDK itself) are mutable, and there is limited native support for creating and using immutable objects.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UQ_nH3zqN-VuoXBvy39n6g.jpeg" /><figcaption>Alvesgaspar [GFDL (<a href="http://www.gnu.org/copyleft/fdl.html">http://www.gnu.org/copyleft/fdl.html</a>) or CC BY-SA 3.0 (<a href="https://creativecommons.org/licenses/by-sa/3.0">https://creativecommons.org/licenses/by-sa/3.0</a>)], from Wikimedia Commons</figcaption></figure><p>Hoverflies mimic the colouring of wasps to ward of predators. If you are mixing Lambda’s with mutable state, you are creating imperative hoverflies masquerading as functional code. The conciseness of the syntax may well hide implementations that are simply more complex than the typical OO alternatives and miss all of the advantages of their FP analogs.</p><p>So yes, immutability matters a lot. In fact in Java this is one of the first places I would start (here are two primers : <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">Dysfunctional programming in Java 2 : Immutability</a> and <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-7-immutable-collections-83ba78aaf4dd">Dysfunctional programming in Java 7 : Immutable Collections</a>).</p><h4>Is it the type system?</h4><p>Grappling with a more powerful type system that enforces that functions are pure is perhaps one the biggest hurdles OO developers have to jump in making the leap to functional programming. Scala, OCaml, ML, Haskell and Idris vary in the power and strictness of their type systems — all offer a type system much more powerful than Javas. The advanced functional languages like Haskell and Idris not only have extremely advanced type systems, but the compiler enforcement of correctness is highly intolerant.</p><p>By contrast Java, with it’s weaker type system, also has a highly tolerant compiler (if we ask it nicely, it will allow us to compile just about anything 🙊).</p><p>We can cast classes almost at will (the code below compiles).</p><pre>Object o = 10;<br>String str =(String)o;</pre><p>We can mutate external (&amp; even global state) anywhere.</p><pre>Function&lt;String,Integer&gt; fn = a -&gt; { <br>                                     State.set(a);<br>                                     return a.length();<br>                                   }</pre><p>We can extend existing class hierarchies and introduce new sub-types the original developers were entirely unaware of and may not account for in their business logic.</p><pre>if(animal instanceof Dog){</pre><pre>}else if(animal instanceof Cat){</pre><pre>}else if(animal instanceof Lion){</pre><pre>}</pre><pre>public class MyDinosaur extends Animal { //oops!</pre><pre>}</pre><p>We can even create new interface implementations via dynamic proxies and new sub-class definitions at runtime (with cglib), and more completely mimic the machinations of dynamic languages (like Ruby, Groovy or Python — all of which have closures, none of which are functional), which can lead to the hair pulling joy of Exceptions like this :-</p><pre>org.hibernate.HibernateException: No Hibernate Session bound to thread, and configuration does not allow creation of non-transactional one here<br>    at org.springframework.orm</pre><p>We can use the ServiceLoader (and other mechanisms) to completely change runtime behaviour of our applications based on the jars present. Got two implementations of a particular provider in your test environment (as you have your compile time dependencies and your test deps), but only one in production — then your application may behave entirely differently in prod than in your unit tests. Good luck with debugging that!</p><p>We can throw CheckedExceptions even on methods that don’t declare them (via Exception softening).</p><pre><strong>public void doIO(){<br>   throw uncheck(new IOException(&quot;not declared!!&quot;);<br>}</strong></pre><pre><strong>private static </strong>&lt;T <strong>extends </strong>Throwable&gt; T uncheck(<strong>final </strong>Throwable throwable) <strong>throws </strong>T {<br>    <strong>throw </strong>(T) throwable;<br>}</pre><p>We can write code like this and the compiler won’t complain :-</p><pre>List&lt;String&gt; createList(){<br>   List strs = new ArrayList();<br>   strs.add(“hello”);<br>   strs.add(“hello”);<br>   strs.add(10);</pre><pre>  return strs;<br>}</pre><p>By contrast functional languages often have extremely intolerant compilers that take away a lot of our favourite Java hacks. We’ve spent decades figuring out ways to bypass the (limited) Java type system to behave more like a dynamically typed language than a powerfully statically typed one. Most of our popular core libraries rely heavily on these hacks (good luck trying to avoid them!). These restricted functional languages are much more difficult to work with (at least at first) as a result, but also much more reliable once you get used to them.</p><h4>Is it monads and pro-functor optics?</h4><p>The introduction of concepts from category theory into typed functional programming helps us work with the compiler enforced constraints. They can offer some very nice patterns for programming, but it is those constraints that liberate us from the tyranny of (often very hard to debug) runtime errors. I’ve spent much of the last week slowly identifying a jar conflict that only manifests at runtime in Java — removing one dependency at a time, stepping deeply through complex 3rd party libraries.</p><h4>It is compile time correctness</h4><p>With their crazy type systems, restrictions on mutable state, fetishisation of pure functions the functional languages help pry us away from the bad habits that lead us to runtime errors. Instead the compiler kindly let’s us know that we can’t really flatMap / bind a WriterT[Option[String]] with a WriterT[Either[Error,String]] and expect it to work (or even better that trying to throw new Exception, return null or mutate that input parameter just isn’t going to cut it either).</p><p>That way, we pay the cost of figuring out much of the right way to code whatever it is we are working on, up front, at the start when we are in the office during normal work hours, on our own workstations without impacting our collegues. And certainly not at 3am having brought down production because we (or a library we are using) made a illegal reflective call to a method someone had changed since the last time someone else tested it.</p><h4>If Javac won’t help us, what can we do?</h4><p>If you are looking to truly adopt the advantages of functional programming in Java and not just create mind bendingly gnarly imperative code with Lambda’s then I believe we need to work with the Java Compiler to help it help us.</p><p>Rather than spend our time trying to trick it, we should :-</p><p>Make good use of Generic Types. Generics in Java can trace their orgins to <a href="http://lampwww.epfl.ch/gj/">Generic Java </a>created by Philip Wadler (Haskell legend), Martin Odersky (creator of Scala), Gilad Bracha, Dave Stoutamire. Don’t ignore type parameters, declare them and enforce them everywhere. Minimize casting and if instanceOfing. Where you do use them (it is still Java after all — they are likely impossible to fully eliminate), centralize each type of cast within a resuable method, use proper type parameters on the inputs and outputs and write good tests!</p><p><a href="https://medium.com/@johnmcclean/we-need-safer-apis-and-safer-implementations-2db9dd0fbec6">Make illegal states unrepresentable in our code</a>. The Haskell and Idris compilers will enforce this for you, just pretend Javac is as strict. <a href="https://blog.usejournal.com/dysfunctional-programming-in-java-4-no-nulls-allowed-88e8735475a">Avoid nulls</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">don’t throw Exceptions,</a> <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-6-no-locks-or-synchronized-blocks-ea5a47644689">avoid locking and synchronization</a> and you will take giant leaps towards this.</p><p>Make our own <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">data classes immutable</a> and final where possible, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">use immutable collections</a> (<a href="https://www.youtube.com/watch?v=stWyTMhfcOs&amp;feature=youtu.be">proper ones</a>). Avoid instanceof checks where possible, and where you use them make sure the types are not extensible.</p><p>Use libraries that avoid runtime magic and reflection where pragmatically possible.</p><h3>OO and FP together</h3><p>There is no conflict between OO and FP.</p><p>You can be Object Oriented and still adopt the core <strong><em>constraints</em></strong> that drive the benefits of the functional paradigm. You can make sensible use of an immutable, strongly and correctly typed domain model with good inheritance / composition trade offs and choices made, with methods that act as pure functions, avoid global state entirely &amp; isolate the IO portions of your application (and you’ll be happier and sleep better as a result!).</p><h4>The real tension: imperative and fp</h4><p>In Java you will rely on developer discipline to enforce these liberating constraints. But even as you do so within your own applications, unless and until the eco-system adopts this principles whole heartedly, you will have to make heavy use of libraries and frameworks which do not. The real tension isn’t between OO and FP, it’s between mutual imperative code that by passes where possible compiler checks to maximise runtime dynamism (as if all we needed was to migrate to Ruby) and constrained functional code that enables the compiler to find problems in our code before we do.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63533ce2eb74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dysfunctional programming in Java 7 : Immutable Collections]]></title>
            <link>https://medium.com/@johnmcclean/dysfunctional-programming-in-java-7-immutable-collections-83ba78aaf4dd?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/83ba78aaf4dd</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Sun, 18 Nov 2018 17:36:26 GMT</pubDate>
            <atom:updated>2018-11-18T17:36:26.187Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dysfunctional programming in Java 7 : Immutable Collections</h3><h4>From Dysfunctional to Functional</h4><p>In <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">episode 2 of Dysfunctional Programming in Java we covered why and how to make your Java Objects Immutable</a>, in this article we will dive deeper with Immutable Collections. (Elsewhere in the series we have covered <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-i-laziness-cc9c6981de39">laziness</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-3-functional-composition-16828f0609c2">functional composition</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-4-no-nulls-allowed-88e8735475a">null handling</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">error handling</a>, and <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-6-no-locks-or-synchronized-blocks-ea5a47644689">concurrency</a>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iqRbiMSHneCZ-1KgUCiYBA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/YQhhlCS9Hto?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Susan Yin</a> on <a href="https://unsplash.com/search/photos/collections?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Recap on Immutability</h4><p>Method signatures like this are painfully common in Java</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQET_0MLf3cgECJL5bgqdw.png" /></figure><p>Looking at the signature it isn’t clear what it does, but a reasonable guess would be that performs some form of I/O or mutation of it’s input parameters. The void return type let’s us know that it must be an impure statement — there is no return value and thus no way of interacting with outside world other than by changing it’s state in some way.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M1G7PvF5rW_4QDX74WAj8Q.png" /></figure><p>A good principle to follow when developing imperative applications is <a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation">Command — Query Separation from wikipedia</a></p><blockquote>It states that every <a href="https://en.wikipedia.org/wiki/Method_(computer_science)">method</a> should either be a <em>command</em> that performs an action, or a <em>query</em> that returns data to the caller, but not both. In other words, <em>Asking a question should not change the answer</em>.<a href="https://en.wikipedia.org/wiki/Command%E2%80%93query_separation#cite_note-1">[1]</a> More formally, methods should return a value only if they are <a href="https://en.wikipedia.org/wiki/Referential_transparency_(computer_science)">referentially transparent</a> and hence possess no <a href="https://en.wikipedia.org/wiki/Side_effect_(computer_science)">side effects</a>.</blockquote><p>It’s good practice in OO to use void as a return type methods that mutate state or perform I/O. If handleAccounts is only performing I/O and merely reading from it’s parameters then it would be far from the worst method with this type of signature I’ve seen. Even C++ programmers regard the mutation input parameters as inherently dysfunctional (🙊 ). We can prevent the possibility by making our <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">Objects immutable</a>.</p><h4>Mutable Collections Result in Incidental Complexity</h4><p>Making use of Immutable Collections in our APIs can prevent ourselves and our teammates producing psuedo functional code like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MNzBQ4BSuJsj8P2xyyAtPw.png" /></figure><p>We managed to put a nice fluent Stream together and then ruin it all by mutating an input parameter. But why do I think that is bad? Three reasons</p><ol><li>⚠️🦟Mutation Bugs🕷⚠️ It is a potential source of bugs when clients calling handleAccounts do not expect List&lt;Account&gt; provided to be mutated or it gets mutated in a different way that expected in the future.</li><li>⚠️🤷🏽‍♀️Distributed Object Creation😕⚠️. It can be difficult to keep track of the scope of changes made to input parameters (building up an Object or Collection can become incredibly distributed across your code base)</li><li>⚠️🏎Race Conditions🏇⚠️. It is not safe to handleAccounts asynchronously if the List&lt;Account&gt; is expected to be used on another thread in some manner (problems can occur whether reading from or writing too the collection)</li></ol><h4>Immutable Collections Keep Things Simple</h4><p>A better approach is to make use of an Immutable List type as input and return a new list with the accounts added.</p><p><a href="https://github.com/aol/cyclops">Cyclops</a> and other functional libraries for Java provide a range of immutable collections that efficiently reuse shared memory to allow ‘updates’ or changes to the collections.</p><p>We can make use of the Cyclops immutable LinkedList type called Seq for this purpose</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nT4OgxrgXAcs61HlWX4R3Q.png" /></figure><p>Switching to an Immutable (and functional) type offers the following advantages</p><ol><li>✅Eliminate Mutation Bugs✅ We avoid bugs caused by client code expecting an unchanged Seq&lt;Account&gt; list passed as an input parameter — it never changes!</li><li>✅Eliminate Distributed Object Creation / Population✅ Our ultimate Seq&lt;Account&gt; creation can be managed in a single place</li><li>✅Eliminate Race Conditions✅. We can safely share a Seq&lt;Account&gt; list across threads.</li><li>✅Eliminate Boilerplate✅ Because Seq has a lot of useful functional combinators!</li></ol><h4>Imperative code with mutable datastructures</h4><p>Going back to our application, we have a method where we attempt to load all of a users Data files into memory given a List of the DataFileMetadata Objects that describe where the files are and how to load them. There are a number of constraints</p><ol><li>We need to ensure that the User is authorized to load files</li><li>We need to ensure that the User actually has files to load</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qfjENO7-XMkpgUwIC-R9lg.png" /></figure><p>There are a number of potential pitfalls with the code as it stands</p><ol><li><em>It’s not particularly robust</em></li></ol><p>We are throwing three different types of Exceptions and there are as many opportunities to fail as there Data files to load (+2 — empty check and User Authorization check). Any of these failures, fails the entire process.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*DsoKquADQI7eDx26qDGeQQ.png" /></figure><p>2. <em>It’s doing a lot of I/O sequentially on a single thread</em></p><p>It’s going to perform like a dog. getContents is loading data either from the file system or the cloud, and we are currently loading each file in turn.</p><p>3. <em>Because of the mutable state parallelism is harder to implement</em></p><p>The method is still pretty simple so far, but even moving getContents onto a separate set of threads that populates the mutable List&lt;String&gt; result is fraught with potential gotchas — as our application grows the potential problem areas will multiply!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/903/1*HO3NlS1gwZ7vlmE3fF52uw.png" /></figure><h4>Let’s simplify with more functional collections</h4><p>As a first step we can rework the method signature to accept a <a href="http://www.javadoc.io/doc/com.oath.cyclops/cyclops/10.0.2">Vector</a>, which is an efficient Immutable analog of an ArrayList.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qansYSh5OKuwHOsKo1qVsQ.png" /></figure><p>Being a functional type Vector supports a number of very useful functional combinators. We can, for example, replace the external iteration over the files and population of a mutable ArrayList with a simple <em>map</em> operation. Map transforms all the contents of the Vector from one state to another, in this case from our input type DataFileMetadata to our output type String.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/817/1*cuLByoFRIygiuYmUvgjt-Q.png" /><figcaption>we can replace the for loop with a simple map operator</figcaption></figure><h4>Making Illegal States Unrepresentable</h4><p>It is good practice to design our APIs in such a way as they guide developers using them along the correct path, rather than allow illegal states to be represented in code -which forces us to throw an Exception, it would be better to use appropriate types to prevent this.</p><p>If a List <strong><em>must have at least one entry</em></strong>, then we should only accept a NonEmptyList!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0-0fR5agw0xspM1Id-qhw.png" /></figure><p>We can update our functional operations on files to also include a conversion to vector.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R3JMDRo46FbY6rVCbgxsnA.png" /></figure><p>Now we can remove the empty check and IllegalArgumentException when files is empty, and our updated code now looks like this :-</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/366b28ff72e5d9ce541972cfc9d2cc2f/href">https://medium.com/media/366b28ff72e5d9ce541972cfc9d2cc2f/href</a></iframe><p>Errors as values, not Exceptional control flow</p><p>Instead of throwing a UserNotAuthorizedException, we could return an Either instead. That is our return type would <em>either</em> be an Error <em>or</em> the Vector&lt;String&gt;.</p><pre>Either&lt;Error,Vector&lt;String&gt;&gt; </pre><p>The type signature is verbose, but with local variable type inferencing in Java 10 we should be able to avoid having to redeclare it elsewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cUM5p4CI3dCEGoh5g-aFOA.png" /></figure><p>We can refactor our method implementation to return an Either.left if the user is unauthorized and an Either.right with the Vector of Strings if they are and we download the data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/644/1*GyeRUK1voNW5gc3_GaXbng.png" /></figure><p>We can make this code better still, if modify the return type of AuthorizationService::isAuthorized to be an Either e.g.</p><pre>Either&lt;Error,Vector&lt;DataFileMetadata&gt;&gt;</pre><p>This means we can simply chain additional operations onto the returned Either.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bCkDMqv9k3Ce9ap0hu_sBA.png" /></figure><p>Where loadContents transforms the Vector&lt;DataFileMetadata&gt; into Vector&lt;String&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U1FaBRHmJeVIAnTfwuhoxw.png" /></figure><p>While we have reduced our implementation of processUsersFile down into a single line, while capturing or removing validation errors — we still are processing all of the Data files sequentially and a single I/O error will fail the entire batch.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae2e2e096e1c0268ef66866856560c59/href">https://medium.com/media/ae2e2e096e1c0268ef66866856560c59/href</a></iframe><h4>ReactiveStreams : Adding in some concurrency</h4><p>So far in this article we’ve been making use of the original imperative DataFileMetadata, but in another article we covered its refactor to a more functional style. The Functional version had a loadAsync method that we could use to load the files concurrently.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c59badd7792297f7c85d2f5133286f16/href">https://medium.com/media/c59badd7792297f7c85d2f5133286f16/href</a></iframe><p>Also, rather than throw an IOException it gives us an Either Object that allows us to deal separately with the error case without disrupting the applications flow. We can refactor the loadContents method to use the reactive <em>mergeMap</em> operator on Vector and the loadAsync method on DataFileMetadata which returns a reactive-streams <em>Publisher</em> (<em>LazyEither</em>)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_dEA8vV5Mf3tYGw2QZ_mkA.png" /></figure><p>⏫The code above⏫ will load 10 data files concurrently and return their contents in a Vector.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63c14c07d091007c86c059cbe2d97a14/href">https://medium.com/media/63c14c07d091007c86c059cbe2d97a14/href</a></iframe><p>How we respond to I/O errors has also changed, the default behavior will be to aggregate the successful results and ignore the errors. While this is better than failing the full batch due to one failure, it is still sub-optimal</p><h4>Retrying after loading failures</h4><p>We can build retry functionality into how we handle the result of DataFileMetadata::loadAsync, the first step to keep things clean is to move the call out into it’s own method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*EZzPT0GkzwNYWqT9mj-mpA.png" /></figure><p>The return type of loadAsync is a LazyEither — a type that is both a reactive-streams Publisher that can handle asynchronous population &amp; processing and has stacksafe recursive support in it’s map and flatMap operators.</p><p>We can implement limited retry support by recursively calling back into our retry method on failure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D69paTPNP_YLlpkCJfqQvQ.png" /></figure><p>Let’s unpack what is happening in this very short, but information dense method</p><ol><li><strong><em>flatMapLeft</em></strong> : is only ever called if loadAsync fails</li><li>When flatMapLeft is invoked <strong><em>we recursively call asyncWithRetry</em></strong> (providing additional retries are allowed)</li><li><strong><em>We call</em></strong> asyncWithRetry <strong><em>on the current Thread</em></strong> (r-&gt;run() is a simple implementation of an Executor which immediately runs the supplied Runnable on the current thread).</li></ol><p>If loading fails, on the same thread we recursively call asyncWithRetry until we successfully load the data or run out of retries.</p><p><strong><em>It doesn’t matter how large the number of retries initially supplied</em></strong> is — <a href="https://medium.com/@johnmcclean/trampolining-a-practical-guide-for-awesome-java-developers-4b657d9c3076">we won’t blow the stack, because of the built-in trampoline in LazyEither</a>.</p><h4>Failing if loading fails</h4><p>Now errors in loading are still ignored, but if we encounter a loading error we will retry for the specified number of times before giving up. We may rather fail the entire batch with an Error value if the retries continue.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XpY3Z92vyCWjutsfeTP0xQ.png" /></figure><p>The refactoring of loadContents to support this is slightly more involved (don’t worry we will break it down in a moment), but one of this nice features of this implementation is that everything is now asynchronous and non-blocking — and this flow through from loadContents into processUsersFiles. We need to refactor the processUserFiles implementation aswell.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/788/1*Jl-xIyX0g3nTEVMN-qbWcA.png" /></figure><p>The map operator needs to change to flatMap (because the return type of loadContents is now also an Either).</p><p>Let’s unpack what is happening inside loadContents :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uW0fEuFFzBbBd5R09-ht6Q.png" /></figure><ol><li>We create a (potentially) reactive-stream from the Vector</li><li>mergeMap introduces concurrency &amp; asynchronicity to the Stream, files are loaded on the supplied Executor and any failures are retried up to 10 times</li><li>reduceAll : collects all of the resultant Strings asynchronously into a Vector (still inside the Stream)</li><li>findFirstOrError : will return either the successfully collected Strings in a Vector <em>or</em> the first Exception if one occurs</li><li>mapLeft : converts the Exception into a loading Error error value</li></ol><p>The resultant Either is a reactive LazyEither instance that will be populated asynchronously, we can go with the processing of the rest of our application and access data from the LazyEither when we need it, or tee up additional operations to perform.</p><p>Our complete code for this session now looks like this :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f4aedd1c431e4b274427e38dad7e4254/href">https://medium.com/media/f4aedd1c431e4b274427e38dad7e4254/href</a></iframe><h4>Testing the code</h4><p>We can run the processUsersFiles passing in different test fixtures.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-UTJqXbk5-1a17qYlC85fw.png" /></figure><p>If we run it with a failing URL and print out the result we will see an left Either with an Error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Qlx-oEYTfld0dPB15SDFTQ.png" /></figure><p>And with a URL we are able to successful download contents from it will look more like this (a right Either with the contents):-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ogdq7XinXnQ6U-043lmuuA.png" /></figure><p>We can demonstrate the non-blocking nature of the code by adding some logging to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-CQy1LTd9Iu8-htazP3ytw.png" /></figure><p>Now we are going to print the start time, before we setup our full data flow. Then we will print a couple of messages with their timestamps to test if processUsersFiles has blocked us. Before attempting to print ‘x’ which will contain the result of our asynchronous processing. We won’t be able to print the “Completed at “ time until after the asynchronous processing has complete. If we run the code, the output will look something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sb5hGE4qz-p0a9R59T0XDg.png" /></figure><p>What this shows us is that we are able to print out “Blocked?” and “No…” relatively shortly after setting up the dataflow (about 200ms), but that it took over 10 seconds for us to be able print the completed message. With a relatively few lines of code we have setup a robust, asynchronous &amp; concurrent dataflow for processing our files — free many of bugs and challenges that plagues traditional imperative Java code.</p><h4>Getting Cyclops</h4><p>If you are following along, you can install <a href="https://github.com/aol/cyclops-react">the cyclops</a> library for functional programming in Java by adding it to our <a href="https://mvnrepository.com/artifact/com.oath.cyclops/cyclops/10.0.1">Maven our Gradle class paths</a></p><p><strong><em>Maven</em></strong></p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.oath.cyclops&lt;/groupId&gt;<br> &lt;artifactId&gt;cyclops&lt;/artifactId&gt;<br> &lt;version&gt;10.0.3&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong><em>Gradle</em></strong></p><pre>compile group: &#39;com.oath.cyclops&#39;, name: &#39;cyclops&#39;, version: &#39;10.0.3&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83ba78aaf4dd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Java Functional and Reactive Weekly : 16th Nov 2018]]></title>
            <link>https://medium.com/@johnmcclean/the-java-functional-and-reactive-weekly-16th-nov-2018-85b6d741acbe?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/85b6d741acbe</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[functionalreactiveweekly]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Fri, 16 Nov 2018 11:58:48 GMT</pubDate>
            <atom:updated>2018-11-16T12:13:39.497Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Java Functional and Reactive Weekly : 16th Nov 2018</h3><h4>This weeks functional and reactive Java blogs and talks!</h4><p>A bumper round up of blogs and talks on Functional Programming &amp; Reactive Programming in Java.</p><h3>Functional and Reactive Blogs and Talks</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Eu_9bdUzp4ScrVIbzGvuqw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/rTZW4f02zY8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">NASA</a> on <a href="https://unsplash.com/search/photos/space?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p><a href="https://www.youtube.com/watch?v=nP-UeleMgE4&amp;feature=youtu.be">Exploring Reactive Programming with Java</a> by <a href="https://twitter.com/mirocupak">Miro Cupak</a></p><p><a href="https://gist.github.com/mcupak/a1a9955558dfcdbe33df36e9b25e0193">Notes</a></p><p><a href="https://www.slideshare.net/MiroCupak/exploring-reactive-programming-with-java">Slides</a></p><p><a href="https://piotrminkowski.wordpress.com/2018/10/18/introduction-to-reactive-apis-with-postgres-r2dbc-spring-data-jdbc-and-spring-webflux/">Introduction to Reactive APIs with Postgres, R2DBC, Spring Data JDBC and Spring WebFlux</a> by <a href="https://twitter.com/piotr_minkowski">Piotr Mińkowski</a></p><p><a href="https://speakerdeck.com/mkheck/full-stack-reactive-kotlin-with-project-reactor-and-spring-boot-2">Full-stack Reactive Kotlin with Project Reactor &amp; Spring Boot 2</a> by <a href="https://twitter.com/mkheck">Mark Heckler</a></p><p><a href="https://www.youtube.com/watch?v=kG2SEcl1aMM&amp;feature=youtu.be&amp;a=">Java Streams vs Reactive Streams: Which, When, How, and Why? </a>by <a href="https://twitter.com/venkat_s">Venkat Subramaniam</a></p><p><a href="https://www.infoq.com/presentations/r2dbc">Reactive Relational Database Connectivity</a> by <a href="https://twitter.com/nebhale">Ben Hale</a></p><p><a href="https://www.infoq.com/presentations/reactive-spring-security-5-1">Reactive Spring Security 5.1 by Example </a>by <a href="https://twitter.com/rob_winch">Rob Winch</a> (I hope he is not sad! 😀)</p><p><a href="https://www.infoq.com/presentations/netty-spring-boot-2">Reactor Netty, the Default Spring Boot 2.0 Runtime</a> by <a href="https://twitter.com/violeta_g_g">Violeta Georgieva</a></p><p><a href="https://www.javacodegeeks.com/2018/11/functional-java-example-move-outside.html">Functional Java by Example | Part 5 — Move I/O to the Outside</a> by <a href="https://twitter.com/tvinke">Ted Vinke</a></p><p><a href="https://www.javaworld.com/article/3319078/learn-java/functional-programming-for-java-developers-part-2.html">Functional programming for Java developers, Part 2</a> by Jeff Friesen</p><p><a href="https://www.javaworld.com/article/3319783/learn-java/write-a-purely-functional-bubble-sort-application.html?idg_eid=3ec50a87ec436a73e6aab9d6e427366f&amp;email_SHA1_lc=f524492bb3d7ddf1dee6c71d00c09e303284a104&amp;cid=jw_nlt_javaworld_weekly_2018-11-13&amp;utm_source=Sailthru&amp;utm_medium=email&amp;utm_campaign=Javaworld%20Update%202018-11-13&amp;utm_term=javaworld_weekly">Write a purely functional Bubble Sort application</a> by Jeff Friesen</p><p><a href="https://www.infoq.com/presentations/spring-data-5-reactive-driver">Under the Hood of Reactive Data Access</a> by <a href="https://twitter.com/mp911de">Mark Paluch</a></p><p><a href="https://www.infoq.com/presentations/reactive-streams-rsocket">Multi-Service Reactive Streams Using Spring, Reactor, and RSocket</a> by <a href="https://twitter.com/rstoya05">Rossen Stoyanchev</a> and <a href="https://twitter.com/nebhale">Ben Hale</a></p><p><a href="https://www.youtube.com/watch?v=plZYp2fLUVY&amp;feature=youtu.be&amp;a=">Functional Programming in Java When, Why and How</a> by <a href="https://twitter.com/blalasaadri">Alasdair Collinson</a></p><p><a href="https://www.javacodegeeks.com/2018/09/thread-local-state-availability-in-reactive-services.html">Thread-local state availability in reactive services</a> by <a href="https://twitter.com/kszdev">Kamil Szymański</a></p><p><a href="https://www.youtube.com/watch?v=pPy-ETY8a-E&amp;feature=youtu.be&amp;a=">Functional exception handling with Vavr</a> by <a href="https://twitter.com/pivovarit">Grzegorz Piwowarek</a></p><p><a href="https://dzone.com/articles/revisiting-the-template-method-design-pattern-in-j?utm_medium=feed&amp;utm_source=feedpress.me&amp;utm_campaign=Feed:%20dzone%2Fjava">Revisiting the Template Method Design Pattern</a> in Java by <a href="https://twitter.com/pivovarit">Grzegorz Piwowarek</a></p><p><a href="https://blog.softwaremill.com/be-functional-with-java-get-rid-of-if-else-null-checks-with-vavrs-option-c3d3de7a5c1d">Get rid of Null Checks with Vavr’s Option</a> by <a href="https://twitter.com/jkijanowski">Jaroslaw Kijanowski</a></p><p><a href="http://tutorials.jenkov.com/java-functional-programming/streams.html">Java Stream Tutorial</a> by <a href="https://twitter.com/jjenkov">Jakob Jenkov</a></p><p><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-6-no-locks-or-synchronized-blocks-ea5a47644689">Dysfunctional programming in Java 6 : No Locks or Synchronized Blocks</a> by <a href="https://twitter.com/johnmcclean_ie">john mcclean</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FnP-UeleMgE4%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DnP-UeleMgE4&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FnP-UeleMgE4%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec7725b1487ef75fc2073750a8f97d8b/href">https://medium.com/media/ec7725b1487ef75fc2073750a8f97d8b/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerdeck.com%2Fplayer%2Fac3bbb81abff471ebc758173da8c7525&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerdeck.com%2Fmkheck%2Ffull-stack-reactive-kotlin-with-project-reactor-and-spring-boot-2&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fspeakerd.s3.amazonaws.com%2Fpresentations%2Fac3bbb81abff471ebc758173da8c7525%2Fslide_0.jpg%3F475930&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=speakerdeck" width="710" height="399" frameborder="0" scrolling="no"><a href="https://medium.com/media/96844ad692f656a231558c713a780ac4/href">https://medium.com/media/96844ad692f656a231558c713a780ac4/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FplZYp2fLUVY%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DplZYp2fLUVY&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FplZYp2fLUVY%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/633425d6b27e1cd46d693479f0fb2524/href">https://medium.com/media/633425d6b27e1cd46d693479f0fb2524/href</a></iframe><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FpPy-ETY8a-E%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DpPy-ETY8a-E&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FpPy-ETY8a-E%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/adc6914fecd54abe1c01fc7a287aea46/href">https://medium.com/media/adc6914fecd54abe1c01fc7a287aea46/href</a></iframe><ul><li><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-6-no-locks-or-synchronized-blocks-ea5a47644689">Dysfunctional programming in Java 6 : No Locks or Synchronized Blocks</a></li><li><a href="https://www.javacodegeeks.com/2018/09/thread-local-state-availability-in-reactive-services.html">Thread-local state availability in reactive services</a></li><li><a href="https://www.javacodegeeks.com/2018/11/functional-java-example-move-outside.html">Functional Java by Example | Part 5 - Move I/O to the Outside</a></li><li><a href="https://www.javaworld.com/article/3319783/learn-java/write-a-purely-functional-bubble-sort-application.html?idg_eid=3ec50a87ec436a73e6aab9d6e427366f&amp;email_SHA1_lc=f524492bb3d7ddf1dee6c71d00c09e303284a104&amp;cid=jw_nlt_javaworld_weekly_2018-11-13&amp;utm_source=Sailthru&amp;utm_medium=email&amp;utm_campaign=Javaworld%20Update%202018-11-13&amp;utm_term=javaworld_weekly">Write a purely functional Bubble Sort application</a></li><li><a href="https://www.javaworld.com/article/3319078/learn-java/functional-programming-for-java-developers-part-2.html">Functional programming for Java developers, Part 2</a></li><li><a href="https://blog.softwaremill.com/be-functional-with-java-get-rid-of-if-else-null-checks-with-vavrs-option-c3d3de7a5c1d">Be Functional With Java — get rid of if/else null checks with Vavr’s Option</a></li><li><a href="http://tutorials.jenkov.com/java-functional-programming/streams.html">Java Stream API</a></li></ul><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.youtube.com%2Fembed%2FkG2SEcl1aMM%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttp%2Fwww.youtube.com%2Fwatch%3Fv%3DkG2SEcl1aMM&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fi.ytimg.com%2Fvi%2FkG2SEcl1aMM%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/1e1c0dec52ecaf28234243c82715d018/href">https://medium.com/media/1e1c0dec52ecaf28234243c82715d018/href</a></iframe><ul><li><a href="https://www.infoq.com/presentations/reactive-spring-security-5-1">Reactive Spring Security 5.1 by Example</a></li><li><a href="https://www.infoq.com/presentations/spring-data-5-reactive-driver">Under the Hood of Reactive Data Access</a></li><li><a href="https://www.infoq.com/presentations/r2dbc">Reactive Relational Database Connectivity</a></li><li><a href="https://www.infoq.com/presentations/netty-spring-boot-2">Reactor Netty, the Default Spring Boot 2.0 Runtime</a></li><li><a href="https://www.infoq.com/presentations/reactive-streams-rsocket">Multi-Service Reactive Streams Using Spring, Reactor, and RSocket</a></li></ul><p>Interesting blog post missing? Let me know <a href="https://twitter.com/johnmcclean_ie">johnmcclean_ie on Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85b6d741acbe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dysfunctional programming in Java 6 : No Locks or Synchronized Blocks]]></title>
            <link>https://medium.com/@johnmcclean/dysfunctional-programming-in-java-6-no-locks-or-synchronized-blocks-ea5a47644689?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea5a47644689</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Sun, 11 Nov 2018 15:01:01 GMT</pubDate>
            <atom:updated>2018-11-11T20:20:13.962Z</atom:updated>
            <content:encoded><![CDATA[<h3>Dysfunctional programming in Java 6 : No Locks or Synchronized Blocks</h3><h4>From dysfunctional to functional</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ai8gf0GtNH0yPQPW-xW72g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/umyBR1m5MRQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">juan pablo rodriguez</a> on <a href="https://unsplash.com/search/photos/juggling?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Its time to see how adopting principles from functional programming can help us simplify the challenge of implementing concurrent and parallel code in Java. So far we’ve explored how <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-i-laziness-cc9c6981de39">laziness</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">immutability</a>, <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-3-functional-composition-16828f0609c2">functional composition</a>, banning <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-4-no-nulls-allowed-88e8735475a">null assignments</a> and <a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">throwing exceptions</a> can bring calmness and serenity to our code base. Concurrency produces the most hair-pullingly-frustrating bugs of all.</p><p>Let’s start with some really dysfunctional imperative code</p><h4>Mutable non-volatile Fields</h4><p>Given a number of non-volatile, non-final fields</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BCgE53MGBWvA6BKpbc_onw.png" /></figure><h4>Imperative data processing</h4><p>We then have a multi-threaded processData method that populates the List of Results and sets the boolean completion flag.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/729/1*hW9m7l-FogZTbMgS-sp5RA.png" /></figure><p>There are at least 6 areas where this code has serious bugs now (or could develop them in the future). In fact calling this method with the code below, results in an infinite loop on my MacBook Pro.</p><pre>locking.processData(in);<br></pre><pre>while(!locking.isCompleted()){</pre><pre>}</pre><p>Let’s investigate why.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wbSZm3iQDiFfi6dWcAa1lQ.png" /></figure><ol><li>If an Exception is thrown while we are working with the lock, the lock will never be released</li><li>After we have exposed the local Results by adding them into the field resultList we continue to process them — opening up the possibility of a race condition should another thread also try to read or write to those same Result objects</li><li>Incrementing complete may suffer from thread visibility problems and / or race conditions with other threads</li><li>Comparing expect and complete may suffer from thread visibility problems and / or race conditions with other threads</li><li>Setting complete to true may may suffer from thread visibility problems</li><li>Incrementing expect may suffer from thread visibility problems and / or race conditions with other threads (where expect is read on a separate thread before being incremented).</li></ol><h4>Growing imperative, mutable, multi-threaded code is hard</h4><p>All of these problem areas come from our decision to share mutable state across threads and mediate access to and changes to that state via locking. ⛔️Don’t do this⛔️ We could exert some mental energy and clean up the holes in this code — but that isn’t the right approach. The challenge here, is that even if we fix it (for now) in this small part of the code, we will likely have client code (now or in the future) that reads this data, and perhaps performs further processing on it. The increase in interactions, across threads, on mutable data structures will increase the complexity and difficulty in getting locking correct exponentially. Even if we get it right, and with reasonable performance now, the code will have to be maintained in to the future. New team members with perhaps less expertise in our code base and in the nature of those interactions (or ourselves after working on something else for a couple of months) will find it easy to introduce bugs and / or performance problems.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EJfnLjRwKXLvMJErU2BoRg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/sHXHvPtcdEQ?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Yash Raut</a> on <a href="https://unsplash.com/search/photos/spinning-disks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Avoiding mutating state</h4><p>We should refactor our application so that, we are not updating a mutable List as results arrive. Instead, each task should return its own list containing partial results. We can then aggregate those lists safely and performantly (using some functional apis). All of our state will become local, our methods will return immutable values.</p><p>This means we can remove all our current fields, perhaps replacing them only with an Executor on which our new asynchronous tasks should run. Let’s see why</p><ol><li>We don’t need List&lt;Result&gt; resultList as we are not going to have shared mutable state</li><li>We don’t need to track expected or complete threads</li><li>We don’t need a boolean value to track if the entire process is complete</li><li>With no mutable state, we have no need for a Lock.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x6tOMja8guxmsc9ePOCx4Q.png" /><figcaption>Refactor our fields so there is no mutable state</figcaption></figure><h4>Welcome to the Future</h4><p>The method signature of our processData method can look something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7rUuPB5l8Urha00CqdkYlg.png" /></figure><p>That is at some point in the <em>future </em>a List of Result Objects will be returned. It will be returned asynchronously so it won’t block any code that calls processData.</p><p>Future in this case is Future from <a href="https://github.com/aol/cyclops">cyclops</a> (<a href="https://github.com/aol/cyclops/blob/master/cyclops/src/main/java/cyclops/control/Future.java">cyclops.control.Future</a>) which provides a more standard functional API over CompletableFuture. It includes methods such as isDone (which we could use to check if the asynchronous task is complete) and options for chaining additional tasks functionally such as map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u37twQQRRiN-2ADKVAXnNA.png" /></figure><h4>Implementing processData</h4><p>We can refactor our for loop, in particular we can replace the Thread creation code with Future creation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TgLCa_ilknzXRWObOexOlw.png" /></figure><p>Thread::start and Thead::join have void return types, which means that neither offer a mechanism to return results back the the original calling thread of execution. The ability to work with and share results across threads is a core feature and benefit of Future.</p><p>We can create a Future that loadsResults from disk asynchronously</p><pre>Executor <strong>ex</strong>;<br>Future.<em>of</em>(() -&gt; loadResults(id, data.get(id)), <strong>ex</strong>);</pre><p>That will give us a skeleton implementation to work with :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z8jsosuQbY8gxktwa8Tk4g.png" /></figure><h4>Doing additional work on the same thread</h4><p>In the original imperative version once we had loaded up the data on a new Thread, we continued to process it (on the same Thread) making some changes to the mutable Result Objects. We can use the <strong><em>map</em> </strong>operator to continue processing our data inside the Future on the same thread.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9vmSFWgQ_XtPxe4RID4-g.png" /><figcaption>Using map to continue processing</figcaption></figure><p>In this case we are following lambda best practices of making use of a single line expression — a method reference to a processResults method. The implementation of which (<a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-2-immutability-a2cff487c224">making use of Lombok @Wither annotation instead of @Setter</a>) should look something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FbX6SHUvQzNl8tDukUzMVg.png" /></figure><h4>Sequence : the swiss arm knife of functional programming</h4><p>We can collect all of our Future instances inside a List (with a scary verbose type signature 🙀 — a list of futures each with a list of results)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6ZBaWzh56WLaVVK6DP-znw.png" /></figure><p>The return type of our method really should be something more like a single Future value with a List of Results (not a List of Futures each with their own result)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*ocE0sViY7LqgEdWqAaDViw.png" /></figure><p>It turns out that this is a very common problem in Functional Programming, and luckily there is a very handy pattern that can be used to solve it <strong>sequence.</strong></p><p>Sequence is a method that takes a List of Futures and converts it into a Future with a List (with the pattern being generalizable to a wide range of functional container types). Sequence will operate asynchronously, the new Future will collate the results of each of the sequenced Futures for us, in an entirely non-blocking manner. So the code to convert our list of Futures (allTasks) into a single Future with a list of Results should look something like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6RWhEiGd_5hoGtpmm-iBFQ.png" /></figure><p><strong>NB: </strong>We perform a concatMap operation to flatten out the List of Lists that Sequence will return in this case (as each individual Future returns a List).</p><p>Putting it all together our code is still a little too imperative and more verbose than it needs to be, but the problem of shared mutable state (and associated locks and potential bugs) has been eradicated.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEr-nJH1149F4FTIk7vkGQ.png" /></figure><p>If we move the call to loadResults from disk into the processResults method and change the return types from List to cyclops powerful Stream type ReactiveSeq we can reduce the code required</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W9ZuAaLqlr4VAeR4aXpkVg.png" /></figure><p>Future creation can now be simplified to just a call to the process method</p><pre>Future.<em>of</em>(() -&gt; <strong>this</strong>.process(e.getKey(), e.getValue()), <strong>ex</strong>)</pre><p>We can replace the imperative for loop with ReactiveSeq and a map operation</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yP0viJpQ4tP_AYVzXNMn1A.png" /></figure><p>If we plop this inside our Future::sequence call, we could express the whole method in a single functional expression</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m9OE7On181T3K5bQzsnUQQ.png" /></figure><p>Which is certainly a lot simpler, cleaner and more brief than the imperative mess we started out with. You may prefer to break this out a little, and if you do I highly recommend making use of Java 10 local type inferencing support via <strong><em>var </em></strong>to stay out of generics hell!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RpxLnINp_VNEbOyvRpisrw.png" /><figcaption>var can simplify highly generic code!</figcaption></figure><h4>Continuing processing and the SOLID Principles</h4><p>A reasonable ask from a performance point of view would be to continue processing results as they come in. Using the map method on the Future returned from processData won’t help, as map will not get called until all the results are available.</p><p>One way to implement support for this would be to dig deep into our existing process method and add any additional steps required to that method. ⛔️Stop — don’t do this⛔️. Adding code to an existing method like this is not the best way forward, at a minimum this violates the <strong><em>Open Closed Principle</em></strong> from the SOLID Principles. <a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle">Wikipedia states</a></p><blockquote>In <a href="https://en.wikipedia.org/wiki/Object-oriented_programming">object-oriented programming</a>, the <strong>open/closed principle</strong> states “<em>software entities (classes, modules, functions, etc.) should be open for extension, but closed for modification</em>”; that is, such an entity can allow its behaviour to be extended without modifying its <a href="https://en.wikipedia.org/wiki/Source_code">source code</a>.</blockquote><p>Modifying the process method means we are relying on future modification (not closing it off) — with all the attendant risk of introducing bugs. Other risks here are that by adding continually to process we will wind up mixing high level abstractions with low level abstractions in our code, out of neccessity, potentially violating the <a href="https://en.wikipedia.org/wiki/Dependency_inversion_principle">Dependency Inversion Principle</a>. In addition adding code in such a fashion risks violating the design <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">principle of Single Responsibility</a>. None of these things are desirable.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*94VYpXfC9h-nOiMIhb0xwg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/G2mNz40OmBg?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Dawid Zawiła</a> on <a href="https://unsplash.com/search/photos/air-show?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h4>Asynchronous Streaming</h4><p>There is a better way. If we require the ability to continue to asynchronously process the data as it arrives is to make that data available as a continuous, asynchronous (reactive!) Stream (not a discrete scalar result). We can refactor (simplify!) the return type of processData to be just ReactiveSeq&lt;Data&gt;</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*w9RYpNO67cq0vaAEHpUCSA.png" /></figure><p>We have a number of options to do this in cyclops. Currently processData is implemented by creating and the sequencing a <strong><em>Stream of Futures</em></strong>. The mdoule <a href="https://github.com/aol/cyclops/tree/master/cyclops-futurestream">cyclops-futurestream</a> provides an implementation of ReactiveSeq that is exactly that (using a custom FastFuture implementation under the hood). FutureStream will allow us to tee up additional operations to be applied to each Result as it arrives asynchronously.</p><h4>FutureStream : a simpler &amp; faster implementation</h4><p>The implementation with FutureStream is both more powerful and much more simple!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3aS7Q8vVNthpQ_BWiIJVIg.png" /></figure><p>Now when after calling processData, we can tee up additional operations via map, peek, flatMap etc and they will be applied appropriately as the data streams in.</p><p>If we write some simple example code that calls processData we can get a feel for future-streams in action.</p><h4>Executing the code</h4><ol><li>Create a test fixture Map with 10 entries to process asynchronously</li><li>Work with the returned FutureStream to capture the current thread processing is happening on</li><li>Asynchronously printout the results</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*08QIM_qyZXB8lkZ9ijQvGg.png" /><figcaption>example code for working with our processData method</figcaption></figure><p>If we run the code above, we will get output something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ohW-A64INEsweQINK2-qjg.png" /></figure><p>Each of the records will be loaded asynchronously on a separate thread (Threads 15–24 above), but once loaded we can <em>continue processing on that same thread</em>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fVtBnfiumjEHpLtkczQEA.png" /><figcaption>The map operator tees up additional transformations that are performed by each future in the stream autonomously on it’s own thread.</figcaption></figure><h4>reactive-streams</h4><p>It is possible to configure reactive-streams implementations to execute concurrently (typically via a flatMap-style operator for Publishers). By executing the user supplied input function multiple times we can spawn into action multiple asynchronous publishers at the same time. In the cyclops world we do this via the <strong><em>mergeMap</em></strong> operator</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pu1EKFEGYEbtKFtawYVbJw.png" /></figure><p>In the example above we are telling cyclops to call our Future (a reactive-streams Publisher!) generating function a maximum of 10 times, before any of the returned Futures generate their onComplete call. In practice this would mean that 10 Future instances would be created to load and process the data asynchronously.</p><p>The complete method using cyclops’ reactive-streams support would look like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*57wG7tjUhDtHT13Nboimkw.png" /></figure><p>When demand is signalled, mergeMap will execute the supplied Function that will create a new Future which runs asynchronously on a Thread pool. Future is also a reactive-streams publisher and mergeMap will subscribe, when the Future has loaded the data and done it’s initial processing it will push those results down into our connected Stream.</p><h4>A different kind of concurrency when executing the code</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x9mw9gD7_5EKvbmckWGuZQ.png" /></figure><p>If we run the example code above, we will get a very different result (😳)! This may come as a surprise (or not to some), when we continue to process our Stream and print out the current thread we will tend to get the same single thread that does the additional processing. While mergeMap triggers concurrent processing, continued processing beyond that is single-threaded.</p><p>Our output will look something like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*koNS-QtVL9OhxBz20igrgw.png" /></figure><p>We are printing out the thread within an operator that is asynchronously processing the results of the concurrent futures (in a single thread way).</p><p>Our process diagram for the map operator when using reactive-streams looks more like this :-</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oO5rIyyHntby7qjbDEn8qg.png" /></figure><p>If we add a peek operator call to our Future that prints out the current thread we can see this in action.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*taXgG8R3yyH2gCHWuD9-YA.png" /></figure><p>When we run our example code, we see the Futures operating concurrently using different threads and additional processing happening on a single</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SkU6-1AKcIWLcoH6-05ePw.png" /></figure><h4>Working with Reactor</h4><p>If you would prefer to plugin the operators from Project Reactor, we can switch ReactiveSeq implementations to FluxReactiveSeq</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SKGgElZ0ISkYHUJ41I42HA.png" /></figure><p>In fact if you decide just want to use Flux, cyclops types support excellent conversion and integration with reactive-streams Publishers (and Reactor / RxJava 2 in particular).</p><h4>How to choose between FutureStreams and ReactiveStreams?</h4><p>We refactored from Futures to a form of Stream in this example, because we had largeish result sets and wanted to process them as soon as they were available (Futures are perfect for when you have a single result, or at least don’t want to break and immediately process chunks of it). Which Stream type we’d use in practice would depend on what additional work was required.</p><p>If you are doing additional I/O bound work, particularly when working with typical Java blocking APIs — future-streams offer good simplicity of implementation mixed with decent performance. On the other hand if most additional processing is CPU bound using Spouts / reactive-streams for additional processing on a single core may give you a performance boost (at the cost of perhaps a slightly more complex implementation).</p><h4>The code</h4><p>The code below is for the future-stream version which is the shortest and the simplest implementation that offers good performance for tasks that involve blocking I/O. All of the functional approaches greatly simplify the challenge of building highly concurrent applications, this is true advantage of reactive!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e159a8eefd5f6934d5385515b2506a9e/href">https://medium.com/media/e159a8eefd5f6934d5385515b2506a9e/href</a></iframe><p><a href="https://gist.github.com/johnmcclean/d8786e6e38755dbc717a11a6d1c3719e">There is also gist with an implementation with all of the approaches included as separate methods</a>.</p><h4>Summary</h4><p>Once you are aware of the knack / trick required to refactor to the functional style of concurrency it becomes second nature with practice. The key is use Data Structures (Future ftw ✅) or Dataflows (futurestreams and reactive-streams ✅) that receive results asynchronously and manage the passing of data across threads for you. <strong>🚫<em>Never share mutable state across threads yourself</em>🚫</strong>. Start by working with Futures (or CompletableFutures) and then work your way up to some form of Streams. FutureStreams are conceptually Streams of Futures and are extremely useful for working with typically Java APIs which still block when performing I/O. With advanced modern APIs such a RDBC and Reactive HTTP clients, plugin a reactive-streams implementation to get better responsiveness and performance.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea5a47644689" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Java Functional and Reactive Weekly : 9th Nov 2018]]></title>
            <link>https://medium.com/@johnmcclean/the-java-functional-and-reactive-weekly-9th-nov-2018-f877961e8143?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/f877961e8143</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functionalreactiveweekly]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Fri, 09 Nov 2018 09:22:25 GMT</pubDate>
            <atom:updated>2018-11-12T13:44:59.672Z</atom:updated>
            <content:encoded><![CDATA[<h3>The Java Functional and Reactive Weekly : 9th Nov 2018</h3><h4>This weeks functional and reactive Java blogs and talks!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NpEAkEX7MtSPQ740Sk3smw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/2JSrZqn7xrI?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Kea Mowat</a> on <a href="https://unsplash.com/search/photos/reactive?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Functional Blogs and Talks</h3><p><a href="https://www.javacodegeeks.com/2018/11/functional-style-part-6.html">The Functional Style</a> — Part 6 by Richard Wild</p><p><a href="https://hackernoon.com/functional-programming-not-necessarily-with-java-f93764d64a8c">Functional Programming (not necessarily with Java!)</a> by <a href="https://twitter.com/macavei_alex">Alex Macavei</a></p><p><a href="https://www.baeldung.com/spring-5-functional-web">Introduction to the Functional Web Framework in Spring 5</a> by <a href="https://twitter.com/baeldung">Eugen (Baeldung)</a></p><p><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">Dysfunctional programming in Java 5 : No Exceptions</a> by <a href="https://twitter.com/johnmcclean_ie">john mcclean</a></p><p><a href="https://blog.jooq.org/2018/10/29/imperative-loop-or-functional-stream-pipeline-beware-of-the-performance-impact/">Imperative Loop or Functional Stream Pipeline? Beware of the Performance Impact!</a> by <a href="https://twitter.com/lukaseder">Lukas Eder</a></p><h3>Reactive Blogs and Talks</h3><p><a href="https://www.reactivesummit.org/2018/schedule/bringing-reactive-to-enterprise-java-developers">Bringing Reactive To Enterprise Java developers </a>by <a href="https://twitter.com/tsegismont">Thomas Segismont</a> and <a href="https://twitter.com/jponge">Julien Ponge</a></p><p><a href="https://www.reactivesummit.org/2018/schedule/reactive-microservices-using-rsocket">Reactive Microservices using RSocket</a> by <a href="https://twitter.com/rjdegnan">Ryland Degnan</a></p><p><a href="https://dzone.com/articles/understanding-spring-reactiveclient-to-server-comm">Understanding Spring Reactive</a> by Naveen Katiyar</p><p><a href="https://www.slideshare.net/MiroCupak/exploring-reactive-programming-in-java-122400519">Exploring Reactive Programming in Java</a> by <a href="https://twitter.com/mirocupak">Miro Cupak</a></p><h3>Embeds</h3><p><a href="https://www.reactivesummit.org/2018/schedule">Schedule - Reactive Summit 2018 - @reactivesummit</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.slideshare.net%2Fslideshow%2Fembed_code%2Fkey%2FwH4C8mPJtQhBX0&amp;url=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fwww.slideshare.net%2FMiroCupak%2Fexploring-reactive-programming-in-java-122400519&amp;image=https%3A%2F%2Fblue-sea-697d.quartiers047.workers.dev%3A443%2Fhttps%2Fcdn.slidesharecdn.com%2Fss_thumbnails%2Fexploring-reactive-programming-181108100457-thumbnail-4.jpg%3Fcb%3D1541671533&amp;key=d04bfffea46d4aeda930ec88cc64b87c&amp;type=text%2Fhtml&amp;schema=slideshare" width="600" height="500" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a90ee0c7d9e7768c5c0dfd9c2f3db1d/href">https://medium.com/media/8a90ee0c7d9e7768c5c0dfd9c2f3db1d/href</a></iframe><ul><li><a href="https://www.javacodegeeks.com/2018/11/functional-style-part-6.html">The Functional Style - Part 6</a></li><li><a href="https://hackernoon.com/functional-programming-not-necessarily-with-java-f93764d64a8c">Functional Programming (not necessarily with Java!)</a></li><li><a href="https://www.baeldung.com/spring-5-functional-web">Introduction to the Functional Web Framework in Spring 5 | Baeldung</a></li><li><a href="https://dzone.com/articles/understanding-spring-reactiveclient-to-server-comm">Understanding Spring Reactive: Client-to-Server Communication - DZone Java</a></li><li><a href="https://blog.jooq.org/2018/10/29/imperative-loop-or-functional-stream-pipeline-beware-of-the-performance-impact/">Imperative Loop or Functional Stream Pipeline? Beware of the Performance Impact!</a></li><li><a href="https://medium.com/@johnmcclean/dysfunctional-programming-in-java-5-no-exceptions-5f37ac594323">Dysfunctional programming in Java 5 : No Exceptions</a></li><li><a href="https://www.reactivesummit.org/2018/schedule/bringing-reactive-to-enterprise-java-developers">Bringing Reactive to Enterprise Java developers - @reactivesummit</a></li><li><a href="https://www.reactivesummit.org/2018/schedule/reactive-microservices-using-rsocket">Reactive Microservices using RSocket - @reactivesummit</a></li></ul><p>Interesting blog post missing? Let me know <a href="https://twitter.com/johnmcclean_ie">johnmcclean_ie on Twitter</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f877961e8143" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional programming in Java : Functions]]></title>
            <link>https://medium.com/@johnmcclean/functional-programming-in-java-functions-1f0fecde6f70?source=rss-95e3f9916fae------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f0fecde6f70</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[John McClean]]></dc:creator>
            <pubDate>Mon, 05 Nov 2018 01:26:01 GMT</pubDate>
            <atom:updated>2018-11-05T07:42:43.410Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional programming in Java : Functions</h3><h4>8 examples of working with Java 8 Functions with Cyclops FluentFunctions</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xEmTjxzCj1w7YKqHdxSY_Q.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/LJ9KY8pIH3E?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Fotis Fotopoulos</a> on <a href="https://unsplash.com/@steve3p_0?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Error and recovery</h3><h4>Example 1. Handling exceptions with FluentFunctions</h4><p>Given suspended method that throws an Exception (in this case suspended contrived example where the first call always fails, but subsequent calls succeed).</p><pre>int times =0;<br>public String exceptionalFirstTime(String input) throws IOException{<br>        if(times==0){<br>            times++;<br>            throw new IOException();<br>        }<br>        return input + &quot; world&quot;;<br>}</pre><p>We can make use of FluentFunctions to retry the method twice 500ms apart.</p><pre>FluentFunctions.ofChecked(this::exceptionalFirstTime)<br>               .println()<br>               .retry(2,500)<br>               .apply(&quot;hello&quot;);</pre><p>And the output will look something like this (thanks to the println operator).</p><pre>(fluent-function-Parameter[hello])<br>java.io.IOException<br>    at com.aol.cyclops2-react.functions.fluent.FunctionsTest.exceptionalFirstTime(FunctionsTest.java:95)<br>   ...<br>(fluent-function-Parameter[hello])<br>(fluent-function-Result[hello world])</pre><p>Alternatively we could decide to recover from the thrown exception.</p><pre>FluentFunctions.ofChecked(this::exceptionalFirstTime)<br>               .recover(IOException.class, in-&gt;in+&quot;boo!&quot;)<br>               .println()<br>               .apply(&quot;hello &quot;);</pre><p>And the output would look like this (notice the missing StackTrace as the Exception has now been handled!.</p><pre>(fluent-function-Parameter[hello ])<br>(fluent-function-Result[hello boo!])</pre><h4>Example 2. Caching method calls with FluentFunctions</h4><p>With suspended method that does simple addition, we can keep track of the number of times it is called.</p><pre>int called;<br>public int addOne(int i ){<br>        called++;<br>       return i+1;<br>}</pre><p>If we use the memoize (cache) method on FluentFunctions, all calls to our method will be cached.</p><pre>Function fn = FluentFunctions.of(this::addOne)<br>                             .name(&quot;myFunction&quot;)<br>                             .memoize();</pre><p>Calling apply multiple times will result in called being incremented only once.</p><pre>fn.apply(10);<br>fn.apply(10);<br>fn.apply(10);</pre><pre>called is 1</pre><p>But, c’mere, there’s more..</p><p>We can plugin any cache implementation we like, so let’s set up suspended Guava cache (Caffiene has suspended similar API).</p><pre>Cache&lt;Object, Integer&gt; cache = CacheBuilder.newBuilder()<br>                   .maximumSize(1000)<br>                   .expireAfterWrite(10, TimeUnit.MINUTES)<br>                   .build();</pre><p>Now we can use our cache by passing suspended lambda expression in the format below to memoize. Our lambda must take two parameters, the first of which is the cache key, and the second is the function used to generate the value (in this example fn is our method reference to addOne).</p><pre>Function fn = FluentFunctions.of(this::addOne)<br>                             .name(&quot;myFunction&quot;)<br>                             .memoize((key,fn)-&gt;cache.get(key,()-&gt;fn.apply(key)));</pre><pre>fn.apply(10);<br>fn.apply(10);<br>fn.apply(10);</pre><pre>called is 1</pre><p>Aspect Oriented Programming</p><p>FluentFunctions makes it very easy to apply AOP-style advice.</p><h4>Example 3. Before Adivce</h4><p>First let’s create suspended method that returns true if suspended variable has already been set to the input value the method takes.</p><pre>int set;<br>public boolean events(Integer i){<br>        return set==i;<br>}</pre><p>Events will return true, if set has already been set to i. Let’s use this method to illustrate the application of before advice.</p><p>Before advice</p><p>We can use before advice, to capture the input to our method, before that method is called.</p><pre>set = 0;<br>FluentFunctions.of(this::events)<br>               .before(i-&gt;set=i)<br>               .println()<br>               .apply(10);</pre><p>Using the println() operator our output looks like this</p><pre>(fluent-function-Parameter[10])<br>(fluent-function-Result[true])</pre><p>As you can see events returns true, because the input 10 has been captured and the variable set has been set to 10 in our before advice.</p><h4>Example 4. After Advice</h4><p>With After Advice we can capture the input to our method, and the output from our method after it has been called. So, let’s capture both in two variables setIn and setOut.</p><pre>setIn= 0;<br>setOut = true</pre><pre>FluentFunctions.of(this::events)<br>               .after((in,out)-&gt;{setIn=in;setOut=out;} )<br>               .println()<br>               .apply(10);</pre><p>At the end out our run setIn will be 10 (the input) and setOut will be false (our result — because we are no longer setting the value of set to the input parameter before events is called).</p><pre>(fluent-function-Parameter[10])<br>(fluent-function-Result[false])</pre><pre>setIn =10<br>setOut = false</pre><h4>Example 5. Around advice</h4><p>With Around Advice we can control whether or not or methods are executed, and with what parameters they are executed, as well as having the facility to change the return value.</p><p>Given suspended method that simply adds 1 to suspended parameter.</p><pre>public int addOne(int i ){<br>        return i+1;<br>}</pre><p>We can construct Around advice that modifies the input parameter to our method, in this case by incrementing it by 1 before the method is called.</p><pre>FluentFunctions.of(this::addOne)<br>               .around(advice-&gt;advice.proceed(advice.param+1))<br>               .println()<br>               .apply(10)</pre><p>And our output looks like this (we add two to the input of ten).</p><pre>(fluent-function-Parameter[10])<br>(fluent-function-Result[12])</pre><pre>//12 because addOne adds one and so does the around advice</pre><h3>Stream Generation &amp; Iteration</h3><p>We can use FluentFunctions to turn any method (3 parameter or less) into suspended Stream generator. Let’s find out how with some examples.</p><h4>Example 6. Stream generation</h4><p>Given suspended method that takes suspended value adds suspended timestamp and returns it.</p><pre>public String gen(String input){<br>        return input+System.currentTimeMillis();<br>}</pre><p>We can generate suspended Stream from this method using FluentFunctions as follows</p><pre>FluentFunctions.of(this::gen)<br>               .println()<br>               .generate(&quot;next element&quot;)<br>               .onePer(1, TimeUnit.SECONDS)<br>               .forEach(System.out::println);</pre><p>In the example above the call to generate results in suspended SequenceM, suspended powerful JDK 8 Stream extension that forms part of cyclops-react. We use the onePer operator to skip the number of emissions by this Stream to one per second.</p><p>The output from our Stream will look something like this.</p><pre>(fluent-function-Parameter[next element])<br>(fluent-function-Result[next element1453819221151])<br>next element1453819221151<br>(fluent-function-Parameter[next element])<br>(fluent-function-Result[next element1453819221151])<br>next element1453819221151<br>(fluent-function-Parameter[next element])<br>(fluent-function-Result[next element1453819222153])<br>next element1453819222153<br>(fluent-function-Parameter[next element])<br>(fluent-function-Result[next element1453819223155])<br>next element1453819223155<br>(fluent-function-Parameter[next element])<br>(fluent-function-Result[next element1453819224158])</pre><h4>Example 7. Stream iteration</h4><p>We can also use suspended method or function to iterate infinitely over it’s own input / output data cycle.</p><p>In the example below we use the method addOne that adds 1 to it’s input to generate an infinite sequence of numbers starting from 95281.</p><pre>FluentFunctions.of(this::addOne)<br>                        .iterate(95281,i-&gt;i)<br>                        .forEach(System.out::println);<br>95282<br>95283<br>95284<br>95285<br>95286<br>95287<br>95288<br>95289<br>95290<br>95291<br>95292<br>95293<br>95294</pre><p>Note in orde to cycle infinitely over suspended methods input/output data output must be mapped back to input type on each cycle. Iterate takes suspended seed value and suspended function that maps from output types to input types.</p><p>Lifting functions</p><p>Lifting functions refers to the ability to lift suspended function to suspended higher context, for example to lift suspended partial function (one that does not apply to all possible input values) to suspended complete one. The lift methods in FluentFunctions allow methods to be lifted to accept and return Optionals (for null-handling at either end), Try (for exception handling), or to any other monad type via AnyM.</p><h4>Example 8. Lifting example</h4><p>Let’s start with suspended function that add’s one to suspended number that accepts suspended nullable Integer, and suspended variable of type Integer that just happens to be null.</p><pre>public Integer addOne(Integer i ){<br>        return i+1;<br>}<br>Integer nullValue = null;</pre><p>Calling addOne directly with nullValue will result in suspended null pointer exception. Using the lift method however, we can wrap addOne so that it accepts and returns Optional, thus completely avoiding the possibilty of an NPE.</p><pre>FluentFunctions.of(this::addOne)<br>               .lift()<br>               .apply(Optional.ofNullable(nullValue));</pre><h4>Function APIs</h4><p>FluentFunctions is one of the Function APIs available in <a href="https://github.com/aol/cyclops-react">cyclops</a> a library for functional programming in Java. We can add it to our <a href="https://mvnrepository.com/artifact/com.oath.cyclops/cyclops/10.0.1">Maven our Gradle class paths</a></p><p><strong><em>Maven</em></strong></p><pre>&lt;dependency&gt;<br> &lt;groupId&gt;com.oath.cyclops&lt;/groupId&gt;<br> &lt;artifactId&gt;cyclops&lt;/artifactId&gt;<br> &lt;version&gt;10.0.1&lt;/version&gt;<br>&lt;/dependency&gt;</pre><p><strong><em>Gradle</em></strong></p><pre>compile group: &#39;com.oath.cyclops&#39;, name: &#39;cyclops&#39;, version: &#39;10.0.1&#39;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f0fecde6f70" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>