<?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[Alex Hart’s Blog - Medium]]></title>
        <description><![CDATA[Opinions, Thoughts, and Examples from an Android Developer and Funcitonal Programming Enthusiast - Medium]]></description>
        <link>https://medium.com/thoughts-from-exallium?source=rss----f860b448464b---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Alex Hart’s Blog - Medium</title>
            <link>https://medium.com/thoughts-from-exallium?source=rss----f860b448464b---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 15:26:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/thoughts-from-exallium" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Functional MVVM on Android]]></title>
            <link>https://medium.com/thoughts-from-exallium/functional-mvvm-on-android-cd6c6cb07e06?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/cd6c6cb07e06</guid>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[android-app-development]]></category>
            <category><![CDATA[mvvm]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 19 Apr 2017 18:06:30 GMT</pubDate>
            <atom:updated>2017-04-25T16:15:38.320Z</atom:updated>
            <content:encoded><![CDATA[<p>This post serves as a rewrite for a previous post of the same title. The original post was a little too full of theory, so I made the decision to distill it down to it’s core, and try to present a concise overview of what MVVM is, how to make it functional, and why I think it is important with respect to a scalable Android application.</p><h3>Agenda</h3><p>In this post, I plan to cover the following topics.</p><ol><li>Definition of MVVM and Reactive Programming</li><li>Android Databinding</li><li>Android Databindings and Rx Interop</li><li>Unidirectional Flow of Data</li></ol><h3>MVVM</h3><p>MVVM stands for Model-View-ViewModel, and is a design pattern which tries to maintain a very low level of coupling between each component. It is very similar to the more well known MVP (Model-View-Presenter) but with a single glaring difference, being the ViewModel itself. Instead of a Presenter which is injected with a View interface, there exists a ViewModel which the View can observe.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/148/1*jegnbK1ueVONi-zPFS_Sog.png" /><figcaption>MVVM</figcaption></figure><p>What really ends up separating this from MVP is that the View, be it an Android Activity or otherwise, does not need any information about the ViewModel or the View it happens to be inflating. It simply gets injected with a ViewModel which it instantly binds into the Android Databinding object, which we will come back to later.</p><p>What this allows for is a flexible, scalable system. A single Activity could be comprised of multiple Views, or multiple ViewModels, none of which are the wiser about each other. This makes for very reusable screen components and ViewModels alike. For example, I could utilize the exact same View XML and ViewModel for every toolbar in my application, and combine it on a screen with another View and ViewModel which then represents a login form or some other piece of UI.</p><h3>Reactive Programming</h3><p>Reactive Programming is an enormous topic, so I don’t want to try to fully explain what it is in a couple of paragraphs. Suffice to say, is that Reactive programming means that we will work with asynchronous streams of data, in a way which allows for composition and other functional utilities, like mapping and reducing data. If you are not familiar with reactive programming on Android, I encourage you to take a look at RxJava, as it will greatly aide you through the rest of this post.</p><h3>Android Databinding</h3><p>Android Databinding is a relatively new library that allows us to tie callbacks, observable fields, and other things directly into attributes in our layout XML. This is a great fit for the MVVM model, as it allows then for whomever is hosting the View the layout inflates into to be as ignorant of the inner workings of the View and it’s relationship to the ViewModel as possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/006f2525aadd86b1a18916549bd9e32f/href">https://medium.com/media/006f2525aadd86b1a18916549bd9e32f/href</a></iframe><p>Note in the above example, the use of the “@{}” syntax, which gives me access to different fields on the ViewModel. The &lt;variable&gt; tag lets me specify what my ViewModel is. The attributes utilizing Android Databinding in this example are all custom, and will be brought up again in the section about Rx Interop. More information on Android Databinding can be found <a href="https://developer.android.com/topic/libraries/data-binding/index.html">here</a>.</p><h3>Android Databinding and Rx Interop</h3><p>As you probably guessed, “app:bindTextChanges”, “app:bindError” and “app:bindClicks” are all custom attributes. These all map to binding adapters within the host application.</p><p>Bind Error is probably the simplest of these. It is set up to watch an observable field, viewModel.firstNameError for example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c6d6e9d0e4605bb9df4be50b5234656/href">https://medium.com/media/7c6d6e9d0e4605bb9df4be50b5234656/href</a></iframe><p>In this example, we’ve created a new BindingAdapter which will be applied to “bindError” attributes. We do not have to specify “app” here, and we will get a warning about it being ignored if we do. This function takes two arguments, the view to bind to, as well as the error string, and then updates the TextInputLayout error field and visibility as necessary.</p><p>The other two, text changes and clicks, utilize Jake Wharton’s library <a href="https://github.com/JakeWharton/RxBinding">RxBinding</a>. Utilizing a Consumer interface, we can hand the ViewModel an observable stream of text changes or clicks. Note that the “StringConsumer” and “ClickConsumer” here are necessary, due to a bug which strips out generic type information when the databinding classes are generated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/797d00420a9ef80b459dc5a201bfbee1/href">https://medium.com/media/797d00420a9ef80b459dc5a201bfbee1/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3d4c01396dbd61f8c3d7a7d2243f3e8/href">https://medium.com/media/c3d4c01396dbd61f8c3d7a7d2243f3e8/href</a></iframe><p>Doing this gives me a very straightforward way to utilize this information within my ViewModel, who shouldn’t really know about Android Views.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed866950e08cdb6a8f6c35098d63ba65/href">https://medium.com/media/ed866950e08cdb6a8f6c35098d63ba65/href</a></iframe><p>Note here, we utilize Jake Wharton’s RxRelay library for relaying these interactions to our Model. The model in this case just propagates onNext events to UseCases.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8e8ba3fc69d95f0dc7dd2902b0881c7b/href">https://medium.com/media/8e8ba3fc69d95f0dc7dd2902b0881c7b/href</a></iframe><p>Each UseCase implements ObservableTransformer, taking in whatever it needs, and returning a UseCaseResult, which is an empty interface which Results extend, and allows for all of these interactions to have their results merged back together. This idea comes straight out of a recent talk from Jake Wharton, found <a href="https://www.youtube.com/watch?v=0IKHxjkgop4">here</a>.</p><p>In it, he talks a lot about our next point of discussion.</p><h3>Unidirectional Flow of Data</h3><p>This UseCaseResult seems a bit weird at first, but there is actually a good reason for it. What it allows for is a single, continuous flow of data through the system. From our handlers, into our UseCases, and back into our ViewModel, who then updates the View’s state accordingly via ObservableFields and other events. Each UseCase implements it’s own set of results, and then the ViewModel is free to pick and choose which ones it cares about. For example, the following is a UseCase which will validate a user’s first name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e70546438e93ffeb25f3d7437d8b17c0/href">https://medium.com/media/e70546438e93ffeb25f3d7437d8b17c0/href</a></iframe><p>The InProgress doesn’t make a lot of sense in this case, but imagine a scenario where we need to check a username vs. a database of usernames for uniqueness. As soon as we introduce any kind of blocking action into the stream, the InProgress Result becomes necessary, as it allows us to see that progress is happening within the subscriber in the ViewModel, and set up any loading indicators or other things as necessary.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/468c8d8e43971d87ff209953a5216388/href">https://medium.com/media/468c8d8e43971d87ff209953a5216388/href</a></iframe><p>The ViewModel will subscribe to all of the UseCaseResults through the same subscriber, and can process them through there. Since everything is done by type, and the type breaks down through a few hierarchies, this is a very easy function to split up however you wish.</p><p>You could make the case to keep the streams for each Input/UseCase pair separate, as this could quite quickly become hard to maintain. It’s really up to you. In that case, the Model would most likely disappear.</p><p>Regardless, it is important to note the Unidirectional Flow of Data here:</p><ol><li>User Changes First Name Text</li><li>Change Event is fired</li><li>UseCase validates event, firing an InProgress signal in the meantime</li><li>ViewModel updates View State appropriately</li><li>UseCase eventually fires Success or Failure</li><li>ViewModel updates View State appropriately</li></ol><h3>Conclusion</h3><p>Utilization of MVVM and following the principle of unidirectional flow of data can help keep your View class from knowing too much about the layout or the ViewModel. This can be very helpful when designing reusable components, and helps to make for a flexible, reactive, and scaleable system.</p><p>By following the flow presented here and within the <a href="https://github.com/exallium/mvvmexample2">sample application</a> you can create a simple, easy to follow, and easy to test application which encourages data immutability, unidirectional flow, and functional purity.</p><p>Oh, and go watch Jake’s video!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cd6c6cb07e06" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/functional-mvvm-on-android-cd6c6cb07e06">Functional MVVM on Android</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Monoids: It’s just Reduce!]]></title>
            <link>https://medium.com/thoughts-from-exallium/monoids-its-just-reduce-9248334ba5e7?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/9248334ba5e7</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Tue, 17 Jan 2017 19:37:51 GMT</pubDate>
            <atom:updated>2017-01-17T19:41:29.183Z</atom:updated>
            <content:encoded><![CDATA[<p>Oversimplifications happen to be something I’m good at, so I’ll apologize in advance if this is another one. A lot of the time when people approach a language like Haskell, they start seeing big scary words, like “Monad” and “Monoid”. Well, I’m here today to try to enlighten you for the latter. Monoids, as it turns out, are just units you can reduce <a href="https://en.wikipedia.org/wiki/Endomorphism">endomorphically</a>. There’s another big word, so let me break this down in a way that should be understandable.</p><p>Monoids require two basic functions, and follow a few rules. In Haskell, these functions are called memptyand mappend. The former is essentially an identity function, and the second is an <a href="https://en.wikipedia.org/wiki/Operator_associativity">associative</a>, binary operation. A very simple example of this is summation. The Sum Monoid would contain functions for the identity and apply for summing two numbers together. Simply, 0and add . We could define a Product Monoid as well, which would have the identity 1 and append function multiply.</p><p>It should be clear here in these two simple examples, the intended functionality of these functions. Monoids include a type of some kind. In our example, the type is some variant of numbers. Numbers have two associative operations, so we distinguish between them by their names. The identity function of each of these monoids, if it was applied within the append function, would result in an output the same as it’s other input:</p><p>mappend mempty x = x</p><p>This is one of the laws of Monoids. It becomes pretty simple if you replace mappend with add and mempty with 0.</p><p>So, what we’re really able to do with Monoids is take two values of a given type, and mappend them down into a single value. This is, simply, a reduction.</p><p>This idea of an associative binary operation and identity function is very generic. Think of Monoid as an interface (it is, after all, a class in Haskell, which is it’s analog to an interface in languages like Java or C#). If we have a type, T, we can describe it in terms of Monoidial combination as long as:</p><ul><li>We can define an associative binary operation that takes two T’s and returns a T</li><li>We can define an identity element such that mappend mempty x = x</li></ul><p>This is a hugely powerful concept. We can define Monoid in almost any language, and use it as a container to perform reduction operations on, allowing us to quickly build up reduction operations, reduce over sets of Monoids, etc. What’s more, this is scalable. If we can define our problem in the Map-Reduce sense, and utilize the Monoidial structure, we end with a solution that can be spread across multiple cores, multiple machines, etc.</p><p>Here’s an example of a Monoid in Kotlin.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1056871c51ae5cce97ff0dcb96f988cc/href">https://medium.com/media/1056871c51ae5cce97ff0dcb96f988cc/href</a></iframe><p>Note here how reduce doesn’t know anything about how a ValidationResult is reduced, only that it can be, because it’s class object is a Monoid. In this simple example, we are validating the length of all of the strings inside of strings and printing the reduced result.</p><p>How do you apply this? Simple. Next time you’re building anything, start asking yourself. How do these things combine? How could I identify an Identity here? What flexibility does this provide me?</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9248334ba5e7" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/monoids-its-just-reduce-9248334ba5e7">Monoids: It’s just Reduce!</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reactive MVP in Android]]></title>
            <link>https://medium.com/thoughts-from-exallium/reactive-mvp-in-android-2d4a934c3874?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/2d4a934c3874</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 04 Jan 2017 19:16:12 GMT</pubDate>
            <atom:updated>2017-01-04T17:56:10.471Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve looked at a lot of different implementations of the MVP pattern within Android applications over the last year. Some I agree with, and some I don’t. Today, I had a thought about the pattern I currently use, and thought that I would share that implementation in it’s current state.</p><h3>What Is MVP</h3><p>I guess that this is the question I should answer first. MVP stands for Model View Presenter, and is a refinement of Model View Controller. The more popular approach that you will see today is called Passive-View MVP. The View is as dumb as possible, which boils down to basic view bindings and click handlers. Clicks are forwarded to the presenter, and data is set by the presenter.</p><p>The Presenter contains all of your presentation logic for mediating displaying data, fetching data, and the like between the view and the model. It is where we try to contain all of our logic, and the primary focus when we unit test.</p><p>The model can be a few different things. It could be a collection of objects injected into your presenter with a tool like Dagger, or it could be a single interactor defined within your component, which itself is injected with backend classes. A good rule of thumb here is to give yourself an upper limit of model classes you are willing to inject into your presenter before you utilize an interactor. This way, you maintain the ability to keep code easy to understand, as well as easy to maintain. Abstraction for the sake of abstraction can increase complexity when it’s unnecessary.</p><h3>The Role of a Model / Interactor</h3><p>There is a common pattern of thought that states that all of your logic should be contained within your presenter. I tend to disagree with this sentiment a little. When we think of SOLID software, we often think of having a class do exactly one thing very well. Which, from a high level, makes a lot of sense. The presenter takes care of business, the model provides data, and the view shows it. However, I think that we can split logic up into two different sections, domain logic and presentation logic.</p><p><em>Domain logic</em> concerns itself with “what” data is being displayed. <em>Presentation logic</em> concerns itself with “how” that data is displayed. The view, of course, has no logic, and just happens to denote “where” something is displayed. I suppose then, in the Uncle Bob sense, my Model feels more like an Interactor than a model, though I tend to use these things fairly interchangeably. It should be noted that the presenter still controls “what” data it’s pulling from the model, if given multiple options. The model would simply expose these choices as different methods. That being said, any data manipulation or other wiring that involves providing the presenter with exactly what it is asking for becomes a task for the model.</p><h3>The State of the World</h3><p>I read a lot of code. Both from people I may be interviewing, or random code I find on reddit, or code at work that I am involved in developing. There is a very common MVP pattern where each of these three M, V, and P are Interfaces, implemented by concrete classes. Either that, or they exist as Abstract classes. The View will get a reference to the presenter, and the model will either also get a reference to the presenter, or provide its own Callback or Listener interface for which it is the responsibility of the presenter to implement. Note that in the case of the callback interface, the presenter interface is then only utilized by the view. I find this to be a bit inconsistent. Moreover, I find that the necessity of the View knowing anything about the presenter to oppose my desire to make it as dumb as can be. Surely, we can isolate ourselves to a point where the Model and View know nothing about each other or the presenter, but only how to take in information and provide information. Be it the result of a Database query, or a tap on a button. This is where ReactiveX comes in.</p><h3>ReactiveX as a Boundary</h3><p>Thus, I propose utilizing ReactiveX as a boundary between these three layers. There are actually several reasons to do so, but the foremost is that in all of these MVP implementations, suddenly the P interface goes away. We only need M and V, and these are injected into the Presenter in runtime.</p><p>The View, who’s views may be bound with a tool like Butterknife, now just provides methods by which someone can subscribe to clicks.</p><p>The Model simply provides methods by which someone can subscribe to data fetches.</p><p>And all of the error handling is “Free”</p><p>Furthermore, given we are now in Rx land as soon as someone clicks a button, we have a massive amount of operators at our immediate disposal. We can initiate a database save via a simple flatMap, or we can dismiss our current screen or show a validation error. We can debounce clicks, and map data into our views, all reactively.</p><p>Testing is still simple. We can utilize <em>TestSubscriber</em> from RxJava to ensure the right flows of behaviour occur. We can set up chains of clicks or different data sets to see how our presenter reacts. And since we use this on both sides of our interactor, we are also able to verify that any data massaging it does is done as well, in the exact same manner.</p><h3>Sample</h3><p>This is a small sample of what I am going on about.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aeb98dc2c22b12075a019f6cd230440e/href">https://medium.com/media/aeb98dc2c22b12075a019f6cd230440e/href</a></iframe><p>There are a few things here missing, such as unsubscribing, but I think it is enough to illustrate the point. There is an argument to be made about making the view reactive as well, but I think you’ll eventually overcomplicate it. Allow the Presenter to be both your Active and Reactive component. It initiates data requests, handles thread scheduling, and handles passing data between the view and the model. The model handles talking to the database layer, and perhaps any extra filtering on the returned data that the presenter doesn’t need to concern itself with.</p><p>I’m interested in feedback about this approach, but remember to keep it constructive.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d4a934c3874" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/reactive-mvp-in-android-2d4a934c3874">Reactive MVP in Android</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring an Either Monad in Kotlin]]></title>
            <link>https://medium.com/thoughts-from-exallium/exploring-an-either-monad-in-kotlin-92618b9c4623?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/92618b9c4623</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Mon, 21 Nov 2016 15:14:27 GMT</pubDate>
            <atom:updated>2016-11-21T15:14:39.902Z</atom:updated>
            <content:encoded><![CDATA[<p>Recently, I was enlightened. I finally, fully grasped how the Either Monad works. At least I think I do. In this post, I am looking to report my findings, both for the education of others of this powerful tool, as well as to see if my understanding of this monadic concept really holds water.</p><h3>What’s an Either Monad?</h3><p>An Either Monad consists of two basic types, Left and Right. It is, essentially, the If/Else statement of the Monad world. Left signifies that something went wrong, while Right signifies that things are working as they should. Just remember, that you want your code to be all right. As the monad passes through different bindings and is worked with, it can either report a Left, and, essentially, skip the rest of the call chain, or it can report Right and continue in fashion.</p><h3>But wait, what’s a Monad?</h3><p>Think of a Monad as a box. In this box, you can store stuff. A Monad is simply a data wrapper with a few different, unifying properties. For example, the Java8 Optional is considered a Monad, as is Kotlin’s ? types and Haskell’s Maybe, among others.</p><p>Monads follow some simple rules. They include two sequencing functions, a return function and a fail function. The sequencing functions are, in my example, noted as bind and seq.</p><p>Bind will take a Monad and, if all is well, apply a function to it’s contents, and return another Monad of the same general type. For example, an Either Monadic bind operation will always return another Either Monad, though the type of the data being wrapped might have changed, say from int to bool.</p><p>Seq will take a Monad and return the monad passed to it. It is a way to finish a chain of operations and ignore the result, and instead pick up from a new source Monad.</p><p>Return simply takes a variable, and returns it wrapped in a new Monad.</p><p>Fail takes a string, and throws an exception with it as the message. It’s type returns the Monad in question in order to be compliant with the bind function.</p><p>An example, written in Kotlin:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1cced68776824ba8408257adedf02c2/href">https://medium.com/media/a1cced68776824ba8408257adedf02c2/href</a></iframe><p>Here, we have a Sealed class. This is because we only ever want to have two options for the Either monad, Left or Right. Each of these simply define a toString method, for convenience.</p><p>We have two methods within either, which represent the aforementioned bind and sequence functions. (In Haskell, these are (&gt;&gt;=) and (&gt;&gt;), respectively). These are infix methods, who’s usage is explained in the sample usage code below.</p><p>The bind method simply takes a function. If the Either in context is Left, we simply return a Left of proper type. If it is Right, then we apply the function to it.</p><p>The seq method simply returns whatever its input is.</p><p>We then have the two other functions required for a monad defined as static functions, as these are “creation” methods. Ret simply returns a new Right instance for whatever value is passed in a. Fail throws an exception with the message as defined in the parameter.</p><p>Ret is a convenience function for creating new Rights. Fail is a convenience function for throwing basic exceptions. For example, you can easily fail from within a bind, as shown in usage.</p><h3>Using this class</h3><p>Here are some examples of usage. Note the use in some places of bind as an infix operator. Also note that there is a lot of Type parameters in the code. This is due to Either needing to know information about both the left and right hand side of a given instance. I believe that this is ok. It’s not as concise as I would like it to be, but it’s a trade-off for strong typing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c7e33ad0e6076ced45dd8a888d807a2/href">https://medium.com/media/0c7e33ad0e6076ced45dd8a888d807a2/href</a></iframe><h3>Monads as a concept, not a base class</h3><p>One mistake often made when someone is learning about Monads is that there should be some sort of Monad base class. I believe that this is driven by backgrounds in object oriented programming. OOP does not translate very well into a functional context. While there is definitely a class definition of a Monad in Haskell, because of the differences in the language, functional paradigm, and really just the strength and power of the Haskell type system, it does not translate well to a Java interface. Specifically when the data within the Monad changes, the type system is lacking in some ways to completely express, say, the bind function, when we move from an R value of Int to an R value of boolean.</p><p>Thus, Monads should be understood as a general concept, not as some base class we extend. They are not really meant to be interoperable with each other. Each Monad is a unique tool that provides it’s own benefits, such as the aforementioned Java8 Optional, or Haskell’s State monad. Each would need to be explicitly written, and not be expected to co-mingle.</p><h3>Conclusion</h3><p>Monads are powerful. Really powerful. They’ve started to take the OOP world by storm, from simple language conventions like Nullability in Kotlin, to the advent of RxJava over the last year or so. As we move into a more multi-processed world, where core count continues to rise and processor speeds continue to stagnate, it will be more important than ever to understand Functional programming concepts, whether it be immutability, pure functions, or this, the Monad.</p><p>Thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=92618b9c4623" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/exploring-an-either-monad-in-kotlin-92618b9c4623">Exploring an Either Monad in Kotlin</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Redundant tests and Square’s Burst]]></title>
            <link>https://medium.com/thoughts-from-exallium/redundant-tests-and-squares-burst-68f6ed64a02?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/68f6ed64a02</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 16 Nov 2016 17:03:04 GMT</pubDate>
            <atom:updated>2016-11-14T16:48:12.196Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of times we find ourselves writing 4 or more tests for the same function, just in order to vary it’s inputs. We copy and paste, and while it doesn’t take a long time, it quickly clutters up our unit test. What if there was a better way?</p><p>The other day, I was listening to a Fragmented podcast, which I frequent. Within that podcast, they mentioned a whole heap of helpful tools for any good Android developer. One of these tools was called Burst, and it was explained as an alternative to JUnit Parameterized classes. So, I did what any keep developer would do, and wrote a very small sample project.</p><p>This project simply has a single class, with a single method, which checks if the inputs are dissimilar. In that, I mean that they pass an XOR test. If they do, we return one string, if not, another.</p><p>I then wrote a Unit test which would verify the expected behaviour of this test. What’s different in this test from other ones that I have written is the logic within the test itself, but I believe that this is a side effect of parameterization, not a sign of bad tests.</p><p>The tests ran perfectly on their first try. The whole process was extremely present, and what’s more, my app was all written in Kotlin, and the 100% Java Interop objective rings as true as ever.</p><p>Check it out here: <a href="https://github.com/exallium/burst-example">https://github.com/exallium/burst-example</a></p><p>Burst can be found here: <a href="https://github.com/square/burst">https://github.com/square/burst</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=68f6ed64a02" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/redundant-tests-and-squares-burst-68f6ed64a02">Redundant tests and Square’s Burst</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[When Architecture is a Burden]]></title>
            <link>https://medium.com/thoughts-from-exallium/when-architecture-is-a-burden-a2c5f4f36fc?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/a2c5f4f36fc</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[android-app-development]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 02 Nov 2016 14:33:38 GMT</pubDate>
            <atom:updated>2016-11-02T14:33:37.542Z</atom:updated>
            <content:encoded><![CDATA[<p>A lot of people will say that software developers go through different stages throughout their career. One such stage could be coined the apply-everywhere stage, in which a developer learns about a cool new pattern or library and instantly wants to start applying this everywhere. I know that I am certainly guilty of it, and I’ve identified that this is the current stage of development I happen to sit in.</p><p>At the present, for me, this stage is that of applying MVP, no questions asked, to absolutely every screen in every application I write, no matter what. This, I think, can give a good separation of concerns, which comes along with good boundaries for testing. I can easily isolate a presenter and test the presentation logic. If my models happen to contain domain logic, I can test them as well. This seems great, but at some point, adding this kind of architecture is going to become more of a burden than it’s worth.</p><p>Let’s take the classic example, and classic joke, of a first year’s solution to “Hello World” in Java. Simply put, it could look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/100eb2b74fff7edd4ec88098af6c24a9/href">https://medium.com/media/100eb2b74fff7edd4ec88098af6c24a9/href</a></iframe><p>This is very simple and easy to understand. We can see that the main function does exactly one thing, print “Hello, World!” and exit.</p><p>The joke continues and displays something akin to this as the next, full on enterprise developer’s version:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9686aaff86575a5ffb5c59c31ebf065b/href">https://medium.com/media/9686aaff86575a5ffb5c59c31ebf065b/href</a></iframe><p>I could have, of course, gone a step further and created a GreeterFactory interface which a GreeterFactoryImpl implements, which is subsequently injected into my HelloWorld class through… whichever injection library you wish, but I think the point here is clear. This is a lot of code, to do something very simple.</p><p>One realization to make here, is that yes, this is a trivial example. It is very easy to look a this and laugh at it, because it’s very obvious that this is over-engineered. You need to read through and understand a lot of code here to simply see that “Hello, World” is going to be printed to the screen.</p><p>So, how does this apply in our every day lives? Well, let’s imagine a simple Android application. You have a lot of screens in it, and you want to be able to quickly and efficiently unit test your controller layer. So, you utilize MVP in a smart way and have all of your Android View references off within a View layer object, and all of your data layer stuff off in your Model layer. this gives you a nice, simple, and clean presentation layer to work with. However, there are times when this just isn’t necessary.</p><p>I will be the first and foremost to say that this view layer should always exist between your controller and the user. The View Holder pattern is a great one, and allows you to easily decouple your View objects from your presenter, be it an Android Activity, a Conductor Controller, or whatnot. The model layer on the other hand is really just a mediator for different services. It’s usefulness begins to break down as your views simplify. A model makes a lot of sense if you’ve got a large portion of business logic that utilizes a bunch of different services. It allows you to segregate that logic into a single container and facilitates easy unit testing away from the presentation logic.</p><p>However, when you’re only working with one or two services in your presenter, the model loses a lot of value. It becomes abstraction for the sake of abstraction.</p><p>There comes a point in any software lifespan where something needs to be reworked or rewritten. One such place is in how we organize our code to make it modular and extendible. The recommendation I would place forth here is to not think of a pattern as the end-all-be-all, but simply an implementation detail. When you create a class, think about why you are creating this class. Who is using this class? What logic is being localized to this class?</p><p>Blindly following a pattern like MVP or MVVM makes for very clean looking code, but not necessarily the best code possible. Code should be simple and concise. If you start a new screen that might only be reading a few values from a form and then interacting with an authorization layer, perhaps you don’t need to suddenly create 8 new interfaces and classes just for this simple operation.</p><p>Through all of this, I can’t help but feel like one of the core principles of software development is thrown out when we start this sort of “MVP as a framework” behaviour. That which we exhibit when we start utilizing templates for new views in our app, generating tens or hundreds of lines of code purely for the sake of conformity and unity.</p><p>So, next time you want to start your next great app, and you want to unit test all of it, and keep everything clean and concise as possible, and follow the best patterns, stop. Think about what you’re doing. Ask yourself if all these abstractions are needed on every single view you’re showing your user. Ask yourself if this interface is actually necessary. If that abstraction adds any value.</p><p>And remember. Keep it simple, stupid.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a2c5f4f36fc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/when-architecture-is-a-burden-a2c5f4f36fc">When Architecture is a Burden</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating a simple Git Commit Parser in Haskell]]></title>
            <link>https://medium.com/thoughts-from-exallium/creating-a-simple-git-commit-parser-in-haskell-4202251cebc9?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/4202251cebc9</guid>
            <category><![CDATA[git]]></category>
            <category><![CDATA[parsing]]></category>
            <category><![CDATA[haskell]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 02 Nov 2016 13:56:56 GMT</pubDate>
            <atom:updated>2017-01-06T20:17:57.313Z</atom:updated>
            <content:encoded><![CDATA[<p>While browsing Reddit this morning, I came across a neat project involving the parsing of Git Commits for proper grammar and syntax. This post can be found <a href="https://www.reddit.com/r/programming/comments/3ka5lv/fit_commit_a_git_hook_to_validate_your_commit/">here</a>, and contains all the links you could need to the source or otherwise.</p><p>Looking at it, I decided that maybe this could be a good way to stretch my Parsec legs and learn a little on the go. I decided to whip up an exceedingly simple Haskell git commit parser, which would be able to suite some of my specific needs. Mainly, it should be able to check to see that a commit message is prepended with a Jira-style Issue number, in the format Project code — issue number.</p><h3>Goals</h3><p>The code presented will check for three main components:</p><ul><li>Check that the Commit Summary (first line) is preceeded by a Jira issue number (for example, MA-1234)</li><li>If there is more than one line, check that the second line is blank.</li><li>Check that no line exceeds 72 characters.</li></ul><p>The full code for this exploration can be found <a href="https://github.com/exallium/hs-commit-msg">here</a>. I don’t intend on this being complete by any definition, but I like writing, so here we go.</p><p>Note that I assume the reader has some experience playing with Haskell code, and I’ve not made an effort to thoroughly explain syntax.</p><h3>Tools</h3><p>First and foremost, if you want to implement and run the code yourself, you’ll need to make sure you have Haskell (GHC etc.) installed on your system, as well as Make, if you’d like to just build the project from Github.</p><h3>Modules and Imports</h3><p>Let’s get started. We have a single source file, as we don’t have a huge amount of code. Like any Haskell project, we’re going to start off with some imports, like so:</p><pre>module Main where<br>import Text.ParserCombinators.Parsec<br>import System.Environment<br>import System.IO<br>import System.Exit</pre><p>Let’s go over each of these. The first line simply denotes that we’re creating the Main module for our application, where our main function will reside. <em>Parsec</em> is the parsing engine of choice, and will do a lot of the heavy lifting for us once we get into writing the code. <em>System.Environment</em> is necessary for grabbing command line arguments. Git’s Commit-msg hook will pass us the filename of the temporary commit file which contains the commit message via command line. <em>System.IO</em> is then used to read that file into a string so that we may parse it. <em>System.Exit</em> allows us to exit with either success or failure depending on the output of our parser. Commit-msg hook wants to see either a zero for success or a non-zero for failure, which <em>System.Exit</em> makes very simple for us.</p><h3>Reading in a file</h3><p>The first thing we need to do is load the file we’re supposed to be parsing. This is done in the main function:</p><pre>main :: IO ()<br>main = do<br>    (fname:_) &lt;- getArgs<br>    fdata &lt;- readFile fname</pre><p>At this point, we’ve read in the file that Git hands to us into a String, and that’s really all there is to it. We bind it to the name fdata so that we can use it later.</p><h3>Validating length of lines</h3><p>The next thing we’d like to do is check that each line in the file is at most 72 characters. Now that we have the content of the commit message in a handy string (<em>fdata</em>), we can go ahead and pass it to a validation function. The function is going to perform three operations:</p><ul><li>Transform our string into a list of strings (our <em>lines</em>)</li><li><em>Map</em> each of these strings to True or False, based on our constraint.</li><li><em>Fold</em> each of these true or false values down into a single value to return.</li></ul><p>In the code snippet, we compose <em>map</em> and <em>fold</em> together, and hand it the value returned by <em>lines</em>. <em>Fold</em> is initialized with True.</p><pre>validateLineLength :: String -&gt; Bool<br>validateLineLength xs = foldl (&amp;&amp;) True . map (&lt;=72) $ lines xs</pre><p>We then apply this function within our main function:</p><pre>main :: IO ()<br>main = do<br>    (fname:_) &lt;- getArgs<br>    fdata &lt;- readFile fname<br>    if validateLineLength fdata<br>        then -- ???<br>        else print &quot;too many characters&quot; &gt;&gt; exitFailure</pre><p>All we’re missing now is what happens when the lines are all ok to go. This is where the parser comes in.</p><h3>Parsing the commit message</h3><p>Now is the part where Parsec comes into play. Our then block in the above if expression will simply become:</p><pre>then readCommit fdata</pre><p>And we will delve into what processing will occur there.</p><p>ReadCommit is fairly simple. All we’re really doing is invoking the parsing engine with a parser of our choice, and evaluating it’s return value. If we get a Left value, we print the error and report failure. If we get a Right value, we print it and report success.</p><pre>readCommit :: String -&gt; IO ()<br>readCommit input = case parse parseFile &quot;commit-msg&quot; input of<br>    Left err -&gt; print err &gt;&gt; exitFailure<br>    Right val -&gt; print val &gt;&gt; exitSuccess</pre><p>All “commit-msg” is here is a label for this parser. ParseFile is where the work starts:</p><pre>data CommitContent = CommitContent String String String deriving Show</pre><pre>parseFile :: Parser CommitContent<br>parseFile = do<br>    pc &lt;- parseProjectCode<br>    is &lt;- parseIssueNumber<br>    cs &lt;- parseCommitSummary<br>    newline<br>    parseEOF &lt;|&gt; parseBody<br>    return $ CommitContent pc is cs</pre><p>So what’s going on here? Well, first we’re parsing the project code, from our Jira scheme mentioned before. Then, we’re parsing the issue number. After that, we grab the commit summary. These three items are bound to values for later use. We then assert that there’s a newline, and that at that point we’ve either reached the end of the file or the body. We then return a CommitContent value placing in each piece of bound data. Parser is a Monad, so we need to lift our output into a Monad via return.</p><p>Parsing the project code is pretty simple.</p><pre>parseProjectCode :: Parser String<br>parseProjectCode = do<br>    code &lt;- many alphaNum<br>    char &#39;-&#39;<br>    return code</pre><p>Essentially, we want to grab the first x characters, then grab a ‘-’. If we don’t, parsing will fail. We then return the parser with the value contained in code. This parser is then processed further, in similar functions:</p><pre>parseIssueNumber :: Parser String<br>parseIssueNumber = do<br>    is &lt;- many digit<br>    space<br>    return is</pre><pre>parseCommitSummary :: Parser String<br>parseCommitSummary = many $ noneOf &quot;\n&quot;</pre><p>Where it gets a little weird is when you want to check if you have the EOF or a body. My solution was to introduce a new data type, CommitBox, and two new functions that would perform the action I wanted and return a CommitBox. The problem is in utilizing <em>&lt;|&gt;</em>, which requires that each side be of the same type.</p><pre>data CommitBox = CommitBox deriving Show</pre><pre>parseEOF :: Parser CommitBox<br>parseEOF = eof &gt;&gt;= \x -&gt; return CommitBox</pre><pre>parseBody :: Parser CommitBox<br>parseBody = newline &gt;&gt;= \x -&gt; return CommitBox</pre><p>At the end of everything, if we are successful, we then return a new CommitContent value that contains the project id, issue number, and commit summary.</p><h3>Hooking up with Git</h3><p>There’s a small shell script that will run called commit-msg. It then delegates out to the executable we’ve built. This whole thing can be stuck into .git/hooks. Or, you can create a script with the mentioned name, make it executable, and point it wherever you are storing the executable.</p><h3>Comments, Concerns</h3><p>I am not a professional Haskell programmer. I love the language and am still very much learning it. Therefore, if you have constructive criticism (Constructive being the key word), I’d love to hear it. Obviously, this is nowhere near complete, and may never be completed, but I felt like it was a good use of time to explore and learn something new. (For me, mainly, file I/O in Haskell and Git hooks).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4202251cebc9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/creating-a-simple-git-commit-parser-in-haskell-4202251cebc9">Creating a simple Git Commit Parser in Haskell</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Saved Instance State]]></title>
            <link>https://medium.com/thoughts-from-exallium/one-of-the-pain-points-when-you-re-getting-into-android-development-is-how-to-deal-with-state-5643cc7b63f3?source=rss----f860b448464b---4</link>
            <guid isPermaLink="false">https://medium.com/p/5643cc7b63f3</guid>
            <category><![CDATA[android]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Alex Hart]]></dc:creator>
            <pubDate>Wed, 02 Nov 2016 13:56:42 GMT</pubDate>
            <atom:updated>2015-10-06T13:21:33.268Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the pain points when you’re getting into Android development is how to deal with state. I’m not talking about how you deal with persisting data between activities, between user sessions, or whatever. What I’m really talking about is instance state.</p><p>I’m talking about what happens when your user is playing around in your app, and then has to take a phone call. By the time the phone call is over, they’ve received a Facebook message, and go to check that. After that, their friend arrives at their house to pick them up for a movie.</p><p>As soon as a user leaves your activity, your state becomes volatile. At any point, the system could destroy the activity instance you had. When the user comes back, it will recreate that activity instance, in an attempt to make it look like the user had never left at all.</p><p>So what does this mean for you as a programmer? It means that you need to know how to persist this instance state between activity destructions, and maintain your presentation to your user regardless of whatever else your user does.</p><p>There are likely several different ways you can help deal with state, but I’m going to cover two of what I think are the most important.</p><p>The first is rather short. Reduce state in activities. This could be done simply by rethinking how your activities are implemented, or by moving your state to a parcelable Presenter or Controller object, which will help for the second point. A lot of people these days will advocate for clean architecture in Android, which does not come easy at first, but is absolutely amazing at making code testable and more maintainable. Not only that, but it’ll reduce the amount of state you’re holding on to in your activity =)</p><p>Obviously, it isn’t always so easy to just remove state, so the second point is to leverage the Android Activity API. Use onSavedInstanceState. Check whether savedInstanceState is null or not in onCreate. If it’s not null, guess what, you’re reinitializing from a known state! You don’t need to re-add fragments, just grab them by name and set them up as needed.</p><p>savedInstanceState is a bundle, meaning you can store almost anything in it, including parcelables (<a href="http://stackoverflow.com/questions/9323044/android-parcelable-and-serializable">avoid serializables</a>). Just remember to re-inject as necessary, if you’re using dependency injection.</p><p>Everything is saved to this bundle via onSavedInstanceState, which is up to you as a programmer to implement. It gives you a bundle instance to fill in. Then you just read the data back as needed in onCreate.</p><p>Want to test that this is all working as you want? Check out developer options. There’s an option called “Don’t keep activities” which does exactly what it sounds like it will do. Then, go into your activity, and then some other activity, and then back into your original activity. That’s all there is to it.</p><p>That last paragraph should be part of your QA’s testing suite. You should 100% be testing this state reinstantiation. Android is so fragmented on a device level that you can never assume anything about the hardware, amount of memory, etc. Furthermore, you can’t assume anything about how the user is going to utilize your application. Testing your edge cases will save you from massive headaches in the future.</p><p>Bonus points if you write espresso tests to do this for you =)</p><p>Happy Coding.</p><p>~Alex</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5643cc7b63f3" width="1" height="1" alt=""><hr><p><a href="https://medium.com/thoughts-from-exallium/one-of-the-pain-points-when-you-re-getting-into-android-development-is-how-to-deal-with-state-5643cc7b63f3">Saved Instance State</a> was originally published in <a href="https://medium.com/thoughts-from-exallium">Alex Hart’s Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>