{"id":2179495,"date":"2022-05-29T23:12:00","date_gmt":"2022-05-29T21:12:00","guid":{"rendered":"http:\/\/nhub.news\/?p=2179495"},"modified":"2022-05-30T05:02:56","modified_gmt":"2022-05-30T03:02:56","slug":"how-to-streamline-the-customer-experience-with-monads-in-kotlin","status":"publish","type":"post","link":"http:\/\/nhub.news\/fr\/2022\/05\/how-to-streamline-the-customer-experience-with-monads-in-kotlin\/","title":{"rendered":"How to Streamline the Customer Experience with Monads in Kotlin"},"content":{"rendered":"<p style=\"text-align: justify;\"><b>Learn more about Monads and how they can be used to streamline the customer experience in Kotlin.<\/b><br \/>\nJoin the DZone community and get the full member experience. At my company, we see a lot of SDKs and Swagger-generated clients that could throw exceptions at any time. This could be a fault in our logic, or it could be a fault with some 3rd party SDKs that have no rhyme or reason to how their exception handling works. But either way, when our customers want to fetch a Git commit history for a service, they do not want to be greeted with an error message. We&rsquo;ve seen GitHub go down during a customer demo and 3rd party integrations throwing other unexpected exceptions. Overall, it was a very discouraging experience for our customers that we had no control over. Thus, `IntegrationValue ` was born. It is a type that can return any value but encapsulates all possible errors from 3rd party integrations. Now expected and unexpected exceptions and errors are (mostly) handled gracefully and we can surface clean error messages to our customers when we cannot retry or handle them. It&rsquo;s a monad. (Just kidding, but will get back to this concept at the end.)<br \/> We do all of our backend development in Kotlin, and `IntegrationValue ` is first and foremost a way to work around the fact that Kotlin doesn&rsquo;t support checked exceptions. But even more than exceptions, it can capture unexpected errors that don&rsquo;t necessarily raise exceptions. For example, if I want to fetch a service&rsquo;s Github repo details, but the workspace doesn&rsquo;t have a GitHub integration enabled, what should it return? We could return null, but what does this mean for the caller of `GithubService. gitDetails(serviceId: Long): GitDetails?`? It could be that:<br \/> Basically, it could be one of a plethora of errors, and we don&rsquo;t want to callously bundle them all together in our type system as a null. Rather we should be explicit on what exactly those error types could be. And so we created `IntegrationError`, which is a sealed class (like a compiler-friendly enum in Kotlin) of possible error types for all of our integrations. This is exactly what we need from our 3rd party integrations, where we need to surface clean error messages back to the customer as well as have tightly scoped error handling strategies, depending on the error. One failing of a monolithic error type is that it might encompass errors that are not possible for a specific operation, but for this reason, we only limit this type to code involving 3rd party integrations. But we\u2019ll get back to this at the end. Almost there! So now if we need all of our integration services to return possible error types, and we don&rsquo;t want to throw exceptions because callers are unaware, we need a way to bake errors into our type system. Basically, the resulting type of integration service function is either a failure (`IntegrationError`) or a success (any type `T`). And there&rsquo;s a handy concept from functional programming land that captures this concept: `Either `. Going back to our GitHub example, now we can transform that useless null version into:<br \/> So now callers of `GithubService. gitDetails` can explicitly handle specific error cases:<br \/> And to finally answer your question, `IntegrationValue ` is just a synonym for `Either`. This is done because all integrations should have unified error types, and allows us to chain these requests with the power of monads. Monads! Monads are a pretty abstract concept \u2014 just google \u00ab\u00a0What Are Monads\u00a0\u00bb to see literally hundreds of articles trying to explain it simply. And now n+1 articles. But the best explanation to conceptualize them is that they \u00ab\u00a0box\u00a0\u00bb values. We could have some value `T`, and the \u00ab\u00a0boxed\u00a0\u00bb version of `T` is `IntegrationValue `. Explicitly monads can do exactly 3 things:<br \/>fun `box(t: T): Boxed `<br \/>`fun Boxed. map(f: (t: T) -&gt; U): Boxed`<br \/>`fun Boxed. flatMap(f: (t: T) -&gt; Boxed): Boxed`<br \/>flatMap is needed to avoid cases where we continually box values. we don&rsquo;t want a situation where we get `Boxed&gt; &gt; &gt; `<br \/> These methods `map` and `flatMap` look familiar because our friend `List ` is secretly a monad! And many other Collections. And Kotlin&rsquo;s nullable type `T?`. And many more. To drive the point home, the 3 methods for `List ` are:<br \/> Similarly, the Either monad (IntegrationValue) has:<br \/> If `IntegrationValue` is `Either. Left`, the final result will be the new failure<br \/> If `IntegrationValue` is `Either. Right`, the final result will be the new success case. How IntegrationValue as a monad works are that it eagerly fails the first time it encounters a failure (IntegrationError). Suppose we try to map a failed `IntegrationValue ` to another `IntegrationValue`. In that case, the computation to map won&rsquo;t even happen, and the final result will be the first error we found. And this brings us to the final point, that Arrow (our functional programming library of choice) comes with some handy utilities so that we don&rsquo;t need to chain a million maps and flatMaps to get any work done. We can use Arrow\u2019s Fx library to easily chain together IntegrationValues with some syntactical sugar:<br \/> Using that magical `!`. The Fx library is built upon Kotlin coroutines and guarantees the purity of the monads with referential transparency. Which is a fancy way of saying we can\u2019t cheat and \u201cescape\u201d the monad (or boxed value). How it works is that it (in the context of the Either.fx block) tries to unbox an IntegrationValue, and if the result was an error (a Left), then it eagerly exits with that error without doing any following computation. Otherwise, it continues sequentially through the block. It&rsquo;s handy just because the alternative would be a nested mess:<br \/> And you can just imagine how arbitrarily complex that could get. Monads are especially helpful for us here at Cortex because as our codebase grows, it becomes easier and easier for errors to propagate without our knowledge. Pure monads enable us to pin down possible sources of errors and force callers to deal with all possible types of errors if they want to unbox the value they\u2019re looking for. Overall, monads have been an amazing abstraction for our codebase, and have allowed us to streamline the customer experience through unexpected errors. Opinions expressed by DZone contributors are their own.<\/p>\n","protected":false},"excerpt":{"rendered":"<p>Learn more about Monads and how they can be used to streamline the customer experience in Kotlin. Join the DZone community and get the full member experience. At my company, we see a lot of SDKs and Swagger-generated clients that could throw exceptions at any time. This could be a fault in our logic, or [&hellip;]<\/p>\n","protected":false},"author":1,"featured_media":2179494,"comment_status":"closed","ping_status":"closed","sticky":false,"template":"","format":"standard","meta":[],"categories":[93],"tags":[],"_links":{"self":[{"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/posts\/2179495"}],"collection":[{"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/comments?post=2179495"}],"version-history":[{"count":0,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/posts\/2179495\/revisions"}],"wp:featuredmedia":[{"embeddable":true,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/media\/2179494"}],"wp:attachment":[{"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/media?parent=2179495"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/categories?post=2179495"},{"taxonomy":"post_tag","embeddable":true,"href":"http:\/\/nhub.news\/fr\/wp-json\/wp\/v2\/tags?post=2179495"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}