<?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 Ivan Gori on Medium]]></title>
        <description><![CDATA[Stories by Ivan Gori on Medium]]></description>
        <link>https://medium.com/@kioan000?source=rss-702217a6a8c9------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*nQ7JUHGjjNGX_ZNltqEBuQ.png</url>
            <title>Stories by Ivan Gori on Medium</title>
            <link>https://medium.com/@kioan000?source=rss-702217a6a8c9------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 20:13:46 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@kioan000/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[MEGA: Enchanting decoders (part 1)]]></title>
            <link>https://medium.com/prima-engineering/mega-enchanting-decoders-part-1-ddf068f12348?source=rss-702217a6a8c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/ddf068f12348</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ivan Gori]]></dc:creator>
            <pubDate>Thu, 22 Sep 2022 07:42:09 GMT</pubDate>
            <atom:updated>2022-09-29T08:18:28.802Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uklpF7NCYwQdxFSx4S7hyw.png" /><figcaption>MEGA: Enchanting decoders (part 1)</figcaption></figure><h4>In this MEGA’s article, we’ll see some useful patterns to discover magic powers hidden inside Elm decoders.</h4><h3>Introduction: The gate to darkness</h3><blockquote>Once upon a time, in the Pure Language realm, everything was simple, bright and predictable.<br>That was until a despicable programmer fairy opened the gates to the realm of Impure Languages…</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/497/1*4Wi6fcFnPRbY9RVVWFrNHw.gif" /></figure><p>This could quite easily be your story as an Elm beginner. You were used to writing clean and composable code. But then you realised that everything’s sandboxed. So you still need to deal with stuff like browser, JavaScript and API calls.</p><p>And that’s when you probably met your first decoder.</p><h4>A programmable parser</h4><p>A decoder is a piece of code that builds a parser to turn your serialized data into your Elm types. <strong>Otherwise, it fails</strong>.</p><p>It’s needed every time you need to obtain data at runtime. For instance, events, API calls, ports and subscriptions.</p><p>Out of the box Elm ships with basic JSON parsing capabilities, that allow you to deal with JavaScript and REST API. <br> Some libraries empower JSON decoding. And others allows us to deal with data different to JSON (like GraphQL).</p><p>In the following examples, I’ll show some interesting (I hope) cases of JSON parsing of a rest API. <br>And I’ll use <a href="https://github.com/NoRedInk/elm-json-decode-pipeline">elm-json-decode-pipeline</a>, a great package that we use a lot here at <strong>Prima</strong>.</p><h3>Master decoders and keep your world fair</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/267/1*LvwunmdHRLpQuto3V2mvtQ.gif" /></figure><p>Granted, decoders can be a bit of a headache. But once you master them, you can rid your Elm code of a lot of data consistency checks.</p><p>Decoders allow you to move all that “if-then” logic in one single point. You can then build your application model not around the backend, but around the user application needs and keep your code cleaner.</p><p>Do you remember the examples from <a href="https://kioan000.medium.com/mega-maybe-maybe-is-not-the-right-choice-b1d2e966b27e">Maybe maybe is not the right choice</a> article?</p><p>Let’s imagine the situation where Gift is provided by a REST API like the following (I’m using jsdoc to describe explicit nullable fields, so imagine a case where we have some kind of type guarantee from BE).<strong> And</strong> <strong>you’re writing a </strong><strong>Payment application:</strong></p><pre><em>/**<br> * </em><strong><em>@typedef </em></strong><em>{{<br> * hasGreetingCard: !boolean,<br> * gCTitle: string|null,<br> * gCBody: string|null,<br> * gCSignature: string|null,<br> * price: number|null<br> * }} Gift<br> */</em></pre><h4>Let’s reorder messy types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*XMtd8L6juFkvNwsb-LqSmQ.gif" /></figure><p>Let’s consider the price key at first.</p><p>Do we need to have Maybe Float in our model?</p><p>The answer’s no. Because the API contract says that, in every legal case that value exists, there’s a number type and it’s always a price. So a more suitable data type for the frontend could be a Decimal of <a href="https://package.elm-lang.org/packages/prikhi/decimal/latest/">decimal package</a>.</p><p>The package exposes a nice function:</p><pre>fromFloat : <strong>Float </strong>-&gt; <strong>Maybe Decimal</strong></pre><p>So now we have two options:</p><ol><li><strong>The not-so smart option. </strong>Decode a Maybe Float and keep that in our model. Every time we’ll need it we’ll turn that into a Decimal resolving two Maybes. Since we can’t handle Nothing variant (it’s a payment page) we’ll probably resolve the Nothing with a default.</li><li><strong>The smart option</strong>. Attempt to decode our Maybe Float into a Decimal and if we can’t… well probably something is going very wrong outside there!</li></ol><p>Since we want to be smart let’s write our decimal decoder joining together existing ones with a pinch of custom logic to make it <strong>decode</strong> a Decimal <strong>or fail:</strong></p><pre>import <strong>Json.Decode</strong> as <strong>Decode</strong></pre><pre>...</pre><pre>decimalFromFloatDecoder : <strong>Decode.Decoder Decimal<br></strong>decimalFromFloatDecoder =<br>  Decode.float<br>     |&gt; Decode.andThen<br>         (\decodedFloat -&gt;<br>             -- Float -&gt; Maybe Decimal<br>             Decimal.fromFloat decodedFloat<br>                 -- if Just decimal -&gt; success<br>                 |&gt; Maybe.map Decode.succeed<br>                 -- if Nothing -&gt; failure<br>                 |&gt; Maybe.withDefault (decodingFailure decodedFloat)<br>            )<br><br><br>decodingFailure : <strong>Float </strong>-&gt; <strong>Decode.Decoder Decimal<br></strong>decodingFailure decodedFloat =<br>    &quot;Can&#39;t turn &quot;<br>        ++ String.fromFloat decodedFloat<br>        ++ &quot; into a decimal&quot;<br>        |&gt; JsonDecode.fail</pre><p>Now it’s time for Json.Decode.Pipeline ! We can use its required function to ensure that the price field exists and our new decoder to turn it into a Decimal:</p><pre>import <strong>Json.Decode</strong> as <strong>Decode</strong><br>import <strong>Json.Decode.Pipeline</strong> as <strong>DecodePipeline</strong></pre><pre>...</pre><pre>type alias Gift =<br>    { price : <strong>Decimal </strong>}<br><br><br>giftDecoder : <strong>Decode.Decoder Gift<br></strong>giftDecoder =<br>    Decode.succeed Gift<br>        |&gt; DecodePipeline.required &quot;price&quot; decimalFromFloatDecoder</pre><p>That’s all. Now your Gift model has its nice and well typed price field!</p><h4>Decode union types</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*OcOYjY-cIAf6NmDeWs2Bzw.gif" /></figure><p>So now imagine that we want to decode the Gift type with its optional greeting card pieces of information.</p><p>The first naive approach is to write a very simple decoder (because you know they can be a headache) that decodes a record like this:</p><pre>type alias Gift =<br>    { hasGreetingCard : <strong>Bool<br>    </strong>, greetingCardTitle : <strong>Maybe String<br>    </strong>, greetingCardBody : <strong>Maybe String<br>    </strong>, greetingCardSignature : <strong>Maybe String<br>    </strong>, price : <strong>Decimal<br>   </strong>}</pre><p>Instead of something better shaped like:</p><pre>type Gift<br>    = Simple { price : <strong>Decimal </strong>}<br>    | WithGreetingCard { price : <strong>Decimal</strong>, greetingCard : <strong>GreetingCard</strong>}</pre><pre>type alias GreetingCard =<br>    { title : <strong>String<br>    </strong>, body : <strong>String<br>    </strong>, signature : <strong>String<br>    </strong>}</pre><p>As seen in the previous article, we prefer the second choice. So we’d need to convert that record into our union type.</p><p>But how?</p><p>Well, with a well-structured decoder, we can make all the “<em>bogus</em>” cases collapse into the decoding failure and clean everything up.</p><blockquote>When you work with decoders, it helps to think locally. So we’ll try to break down the big problem into simpler tasks.</blockquote><p>First of all, we’ll try to decode the raw pieces of information that we need to build a SimpleGift:</p><pre>type alias SimpleRawData =<br>    { price : <strong>Float</strong>, hasGreetingCard : <strong>Bool </strong>}<br></pre><pre>simpleRawDataDecoder : <strong>Decode.Decoder SimpleRawData<br></strong>simpleRawDataDecoder =<br>    Decode.succeed SimpleRawData<br>        |&gt; DecodePipeline.required &quot;price&quot; decimalFromFloatDecoder<br>        |&gt; DecodePipeline.required &quot;hasGreetingCard&quot; Decode.bool</pre><p>Let’s do the same with the other variant, reusing the previous decoders. We could rewrite a whole decoder. But I’m lazy and I can use Json.Decode.Pipeline.custom function:</p><pre>type alias <strong>WithGreetingCardRaw</strong> =<br>    { simpleRaw : SimpleRaw<br>    , body : String<br>    , signature : String<br>    , title : String<br>    }<br><br>withGreetingCardRawDecoder : <strong>Decode.Decoder WithGreetingCardRaw</strong><br>withGreetingCardRawDecoder =<br>    Decode.succeed <strong>WithGreetingCardRaw</strong><br>        |&gt; DecodePipeline.custom simpleRawDecoder<br>        |&gt; DecodePipeline.required &quot;gCBody&quot; Decode.string<br>        |&gt; DecodePipeline.required &quot;gCSignature&quot; Decode.string<br>        |&gt; DecodePipeline.required &quot;gCTitle&quot; Decode.string<br>        <br>rawToWithGreetingCardDecoder : <br>   <strong>WithGreetingCardRaw</strong> <br>   -&gt; <strong>Decode.Decoder Gift</strong><br>rawToWithGreetingCardDecoder rawData =<br>    if rawData.simpleRaw.hasGreetingCard then<br>        WithGreetingCard<br>            { price = rawData.simpleRawData.price<br>            , greetingCard =<br>                { title = rawData.title<br>                , body = rawData.body<br>                , signature = rawData.signature<br>                }<br>            }<br>            |&gt; Decode.succeed<br>    else<br>        Decode.fail &quot;Not has greeting card. It can&#39;t be WithGreetingCard variant&quot;<br><br>giftWithGreetingCardDecoder : <strong>Decode.Decoder Gift</strong><br>giftWithGreetingCardDecoder =<br>    withGreetingCardRawDecoder<br>        |&gt; Decode.andThen rawToWithGreetingCardDecoder</pre><p>Now we can simply combine them with Json.Decode.oneOf . This function tries to resolve the serialized data with a list of decoders until one succeeds (so pay attention to priority, in case you don’t have a discriminating value like hasGreetingCard ) :</p><pre>module <strong>MyApp.Gift</strong> exposing (Gift, fetch, decoder)</pre><pre>decoder : <strong>Decode.Decoder Gift</strong><br>decoder =<br>    Decode.oneOf<br>        [ simpleDecoder<br>        , withGreetingCardDecoder<br>        ]<br>        <br>fetch: <strong>(Result Http.Error Gift -&gt; msg) -&gt; Cmd msg</strong><br>fetch msg = ...</pre><p>That could become (with some love and modularization that I’ll leave to you) something like:</p><pre>module <strong>Gift</strong> exposing (Gift, decoder)</pre><pre>import <strong>Json.Decode</strong> as <strong>Decode</strong><br>import <strong>Gift.SimpleGift</strong> as <strong>SimpleGift</strong> exposing (SimpleGift)<br>import <strong>Gift.WithGreetingCardGift</strong> as <strong>WithGreetingCardGift</strong> exposing (WithGreetingCardGift)<br><br><br>type <strong>Gift</strong><br>    = <strong>Simple</strong> SimpleGift<br>    | <strong>WithGreetingCard</strong> WithGreetingCardGift<br>    <br>decoder : <strong>Decode.Decoder Gift</strong><br>decoder =<br>    Decode.oneOf<br>        [ SimpleGift.decoder <br>           |&gt; Decode.map Simple<br>        , WithGreetingCardGift.decoder <br>           |&gt; Decode.map WithGreetingCard<br>        ]</pre><p>And that’s it. We’ve moved all our data coherence checks into a single point. Plus, we can expose only a simple fetch function, the whole decoder, or both as preferred.</p><p>We’ve reached more than one goal with that:</p><ul><li>We wiped out a loosely typed <em>maybish</em> record in favour of a more fashionable union in the whole app.</li><li>We can move the whole business logic and consistency checks about Gift in a single point.</li><li>We can make our consistency checks more or less strict based on our BE and requirements. We can morph the raw data directly here, providing default cases instead of making everything fail. For example what happens if gift card values are truly nullable but you always provide them even if not given (with fallback values)? You can simply provide the decoder with your fallback in case of null:</li></ul><pre>greetingCardRawDataDecoder : <strong>Decode.Decoder GreetingCardRawData<br></strong>greetingCardRawDataDecoder =<br>    Decode.succeed GreetingCardRawData<br>        |&gt; DecodePipeline.custom simpleGiftRawDataDecoder<br>        |&gt; DecodePipeline.required &quot;gCBody&quot;<br>            (stringOrDefaultDecoder &quot;Your greeting message&quot;)<br>        -- ...<br><br>stringOrDefaultDecoder : <strong>String</strong> -&gt; <strong>Decode.Decoder String<br></strong>stringOrDefaultDecoder def =<br>    Decode.nullable Decode.string<br>        |&gt; Decode.map (Maybe.withDefault def)</pre><h4>Intercept errors and keep your flows clean</h4><p>Surely you’ve noticed how messy your update function becomes when you have more than one API call and a little logic (like some security checks on it):</p><pre>type AppMsg<br>    = GetGiftResult (<strong>Result Http.Error Gift</strong>)<br>    | GetAnotherResult (<strong>Result Http.Error Another</strong>)<br>    --...</pre><pre>appUpdate : <strong>AppMsg </strong>-&gt; <strong>Model </strong>-&gt; <strong>Update<br></strong>appUpdate msg model =<br>    case msg of<br>        GetGiftResult (Result.Ok gift) -&gt;<br>            -- store and then do something<br><br>        GetGiftResult (Result.Err httpError) -&gt;<br>            case httpError of<br>                Http.BadStatus 401 -&gt;<br>                    -- Unauthorized handling code<br><br>                _ -&gt;<br>                    -- show generic error<br><br>        GetAnotherResult (Result.Ok another) -&gt;<br>            -- store and then do something<br><br>        GetAnotherResult (Result.Err httpError) -&gt;<br>            case httpError of<br>                Http.BadStatus 401 -&gt;<br>                    -- Unauthorized handling code<br><br>                _ -&gt;<br>                    -- show generic error<br>        --...</pre><p>You have to admit that it’s not nice or scalable. A lot of branches are probably the same. You can group the logic with functions but the update case will stay huge.</p><p>We can do better. Let me explain.</p><p>You probably noticed that your http calls always produce a Result Http.Error decodedData as come back result. <br>But Elm’s faces 2 possible failures.<br>The first is during the request process (that always comes out as a Response type):</p><pre>-- Http.elm</pre><pre>type Response <strong>body<br>  </strong>= BadUrl_ <strong>String<br>  </strong>| Timeout_<br>  | NetworkError_<br>  | BadStatus_ <strong>Metadata body<br>  </strong>| GoodStatus_ <strong>Metadata body</strong></pre><p>The other possible failure happens during the decoding process and results in a parsing error:</p><pre>-- Decoder.elm<br><em><br></em>type Error<br>  = Field <strong>String Error<br>  </strong>| Index <strong>Int Error<br>  </strong>| OneOf (<strong>List Error</strong>)<br>  | Failure <strong>String Value</strong></pre><p>This because you’re used to passing Http.expectJson as request expectation:</p><pre>fetch :<br>    (<strong>Result Http.Error Gift </strong>-&gt; <strong>msg</strong>)<br>    -&gt; <strong>AuthToken<br>    </strong>-&gt; <strong>Cmd msg<br></strong>fetch tag authToken =<br>    Http.request<br>        { method = &quot;GET&quot;<br>        , headers = [ AuthToken.header authToken ]<br>        , url = &quot;https://my.api.it/get-my-gift&quot;<br>        , body = Http.emptyBody<br>        , <strong>expect = Http.expectJson tag decoder</strong><br>        , timeout = Nothing<br>        , tracker = Nothing<br>        }</pre><p>Such function takes the internal Response body type, if the response is ok, then attempts to decode the body with your decoder.</p><p>If Response indicates a failure <strong>or </strong>decoder fails then the result will be a Http.Error type that wraps the previous two errors:</p><pre>type Error<br>  = BadUrl <strong>String </strong>-- Response.BadUrl_ case<strong><br>  </strong>| Timeout -- Response.Timeout_ case<br>  | NetworkError -- Response.NetworkError_<br>  | BadStatus <strong>Int </strong>-- Response.BadStatus with metadata statusCode<br><strong>  </strong>| BadBody <strong>String </strong>-- Decode.Error serialized as String</pre><p>It’s fast and simple. But there are a couple of drawbacks:</p><ol><li>It hides some Response information. (We can’t access the body in the case of a BadStatus. We can’t see response headers. And we can’t intercept decoding failures.)</li><li>In the case of a reusable library, you’re demanding a lot of business logic of the consumer regarding the API.</li><li>The component’s API can’t be self-explanatory.</li></ol><p>We can fix almost all of these weak points though.</p><p>First of all, let’s define the Gift error that we’re interested to catch:</p><pre>import MyApp.Unauthorized as Unauthorized exposing (Unauthorized)</pre><pre>type Error<br>    = UnauthorizedError <strong>Unauthorized<br>    </strong>| NotInterestingError <strong>String</strong></pre><p>And after that, we can write our custom expect , that intercepts 401 status code and applies another decoder on that body:</p><pre>expect : (<strong>Result Error Gift </strong>-&gt; <strong>msg</strong>) -&gt; <strong>Http.Expect msg<br></strong>expect tag =<br>    Http.expectStringResponse tag responseResolver<br><br><br>responseResolver : <strong>Http.Response String </strong>-&gt; <strong>Result Error Gift<br></strong>responseResolver response =<br>    case response of<br>        Http.BadUrl_ string -&gt;<br>            &quot;Bad Url: &quot;<br>                ++ string<br>                |&gt; NotInterestingError<br>                |&gt; Result.Err<br><br>        Http.Timeout_ -&gt;<br>            NotInterestingError &quot;Timeout&quot;<br>                |&gt; Result.Err<br><br>        Http.NetworkError_ -&gt;<br>            NotInterestingError &quot;NetworkError&quot;<br>                |&gt; Result.Err<br><br>        Http.BadStatus_ metadata b -&gt;<br>            if metadata.statusCode == 401 then<br>                case <strong>JDecode.decodeString Unauthorized.decoder b</strong> of<br>                    Result.Ok data -&gt;<br>                        UnauthorizedError data<br>                            |&gt; Result.Err<br><br>                    Result.Err decodeError -&gt;<br>                        &quot;Decode unauthorized response failure: &quot;<br>                            ++ JDecode.errorToString decodeError<br>                            |&gt; NotInterestingError<br>                            |&gt; Result.Err<br><br>            else<br>                &quot;BadStatusError:&quot;<br>                    ++ String.fromInt metadata.statusCode<br>                    |&gt; NotInterestingError<br>                    |&gt; Result.Err<br><br>        Http.GoodStatus_ _ body -&gt;<br>            JDecode.decodeString decoder body<br>                |&gt; Result.mapError<br>                    (\err -&gt;<br>                        &quot;Decode gift failure: &quot;<br>                            ++ JDecode.errorToString err<br>                            |&gt; NotInterestingError<br>                    )</pre><p>We can now make our fetch function more expressive:</p><pre>type alias FetchArgs =<br>    { authToken : <strong>AuthToken<br>    </strong>, onGiftFetched : <strong>Gift </strong>-&gt; <strong>msg<br>    </strong>, onUnauthorized : <strong>UnauthorizedData </strong>-&gt; <strong>msg<br>    </strong>, onError : <strong>String </strong>-&gt; <strong>msg<br>    </strong>}<br><br><br>fetch : <strong>FetchArgs </strong>-&gt; <strong>Cmd msg<br></strong>fetch args =<br>    Http.request<br>        { method = &quot;GET&quot;<br>        , headers = [ AuthToken.header args.authToken ]<br>        , url = &quot;https://my.api.it/get-my-gift&quot;<br>        , body = Http.emptyBody<br>        , expect = expect args<br>        , timeout = Nothing<br>        , tracker = Nothing<br>        }</pre><p>And change our custom expect function, adding the message retagging:</p><pre>expect : <strong>FetchArgs </strong>-&gt; <strong>Http.Expect msg<br></strong>expect args =<br>    Http.expectStringResponse (resultToTag args) responseResolver<br><br><br>resultToTag : <strong>FetchArgs </strong>-&gt; <strong>Result Error Gift </strong>-&gt; <strong>msg<br></strong>resultToTag args result =<br>    case result of<br>        Ok gift -&gt;<br>            args.onGiftFetched gift<br><br>        Err (Unauthorized unauthorizedData) -&gt;<br>            args.onUnauthorized unauthorizedData<br><br>        Err (NotInterestingError errAsString) -&gt;<br>            args.onError errAsString</pre><p>And finally, in our update function, we can collapse every common logic in one dedicated state, like this:</p><pre>type AppMsg<br>    = GiftFetched <strong>Gift</strong><br>    | AnotherThingFetched <strong>AnotherThing<br>    </strong>| Unauthorized <strong>UnauthorizedData</strong><br>    | FatalError <strong>String<br>    ...</strong></pre><pre>appUpdate : <strong>AppMsg </strong>-&gt; <strong>Model </strong>-&gt; <strong>Update<br></strong>appUpdate msg model =<br>    case msg of<br>        GiftFetched gift -&gt;<br>            -- store and then do something ...</pre><pre>        AnotherThingFetched anotherThing -&gt;<br>            -- store and then do something ...</pre><pre>        Unauthorized unauthorized -&gt;<br>            model -- here we can start a re-auth flow<br>               |&gt; withCmd Unauthorized.fetchAuth unauthorized       <br><br>        FatalError errString -&gt;<br>            model -- here we simply show a error page and log all<br>               |&gt; Model.setFatalError errString <br>               |&gt; withCmd Logger.logError errString</pre><pre>         --...</pre><h4>Congratulations you have reached the end…</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/1*HuKCAGiQn-T7a0jtwjNATg.gif" /></figure><p>If you’ve reached this point (without a headache), you’ve gained an <strong><em>entry-level </em></strong><em>Decoder Master.</em></p><blockquote>Wait a minute… all of this and I’m still an <strong>entry-level </strong>??</blockquote><p>Ehm yes… You’ve learned that decoders can be more than simple string parsers, and how to make them more effective in cleaning up a malformed server API.</p><p>You should be able to decode complex elm types and rewrite the basic “decode or fail” logic hidden inside HTTP requests.</p><p>This is great and helps make you a better Elm’s sorcerer. But there is still much to say about decoders. I’ll try to cover up the most interesting parts in future articles.</p><p><em>See you soon in the next castle!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ddf068f12348" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/mega-enchanting-decoders-part-1-ddf068f12348">MEGA: Enchanting decoders (part 1)</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEGA: Maybe Maybe is not the right choice]]></title>
            <link>https://medium.com/prima-engineering/mega-maybe-maybe-is-not-the-right-choice-b1d2e966b27e?source=rss-702217a6a8c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1d2e966b27e</guid>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[elm-lang]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[frontend-architecture]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Ivan Gori]]></dc:creator>
            <pubDate>Tue, 29 Jun 2021 07:13:17 GMT</pubDate>
            <atom:updated>2022-07-28T14:04:15.530Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="MEGA: Make Elm Great Again logo made with tangram" src="https://cdn-images-1.medium.com/max/1024/1*_MdK5g5v_-EyPlTb5VOCzQ.png" /><figcaption>MEGA: Maybe Maybe is not the right choice</figcaption></figure><h4>In this article of MEGA I’ll talk about some useful patterns and personal thought about Maybe types in Elm.</h4><h3>Introduction: What is a Maybe?</h3><figure><img alt="Question mark made with tangram pieces" src="https://cdn-images-1.medium.com/max/800/1*XuZHvD8_wdowcrkCI_gNmQ.png" /><figcaption>What is a Maybe ?</figcaption></figure><p>In Elm you don’t have the concept of undefined, you can&#39;t do things like define an optional key in a record or runtime declaration but there is the concept of null. The most common scenario can be the result of an API call that must be saved in a key inside your model but since you don&#39;t have the result at init you&#39;re forced to declare it as a Maybe and initialize your model with a Nothing until the API call will assign the proper value to it. Under the hood, a Maybe is quite different from other languages equivalents, even javascript, mainly because Elm <strong>doesn&#39;t have implicit null references</strong>.</p><blockquote><em>I call it my billion-dollar mistake. It was the invention of the null reference in 1965. At that time, I was designing the first comprehensive type system for references in an object-oriented language (ALGOL W). My goal was to ensure that all use of references should be absolutely safe, with checking performed automatically by the compiler. But I couldn’t resist the temptation to put in a null reference, simply because it was so easy to implement. This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years.</em></blockquote><blockquote>The inventor of null references, Tony Hoare</blockquote><p>If in the most common languages the access of a null variable is legit, with a Maybe you (always) must address the unavailability of the value.</p><h3>Avoid Maybes: how and why</h3><p>The <em>nullable</em> concept is quite common and familiar in programming but in Elm, it tends to become insidious. The enforcement to always handle the possibility that a Maybe is not valued properly tends to make your code rapidly unclear and less scalable. You should always <strong>think twice</strong> before wrapping your type inside a Maybe because it will probably hide some architectural deficiencies that can be addressed more elegantly and expressively.</p><h4>Every Maybe it’s like a spoon of baking powder in your cake</h4><p>As we said before in a common imperative language you’ll probably be able to handle your nullable with exceptions and some if and despite all you can write your code without worrying about it because you are quite sure that the value will never be null in that part of the code.</p><p>In Elm’s world every time you need to use a Maybe you <em>must</em> handle both the valued and not valued case. For each Maybe your function will become less readable stuffed of withDefault or maybeMap and it will soon rise, doubling its length for each nullable data.</p><h4>Can you build a house with Maybe bricks?</h4><figure><img alt="A house made with tangram with a missing piece" src="https://cdn-images-1.medium.com/max/580/1*gcDn_jX6kSpXYRBnXivSMg.png" /></figure><p>It probably sounds banal to say but if a Nothing means an Error or a data inconsistency then that result mustn&#39;t be a Maybe! This is a quite common scenario in your API that are written in other languages and where databases are stuffed with nullable fields due to relations with other tables or progressive entity finalization.</p><p>Let’s make an example with a native library, the side-effect function Dom.getElement that tries to find an element with a specific id in your DOM.</p><pre>getElement : String -&gt; Task Error Element<br>getElement =<br>  Elm.Kernel.Browser.getElement</pre><p>The element could not be there but it will be an error trying to find an element that is not rendered. You can notice that the result is not a Maybe Element but an Error or Element that allows you to track the error case explicitly in your update cycle.</p><p>Our API (and our decoders too) should act similarly: or our data are correctly evaluated for the purpose of the API or the whole thing must fail. You should not allow your API to emit implicitly nullable data that will make the consumption of the API impossible, it’s like hiding the dust under the carpet.</p><p>Does have any sense a nullable price into a payment page API only because the price field is nullable in the database (probably because is evaluated by a second microservice in a delayed moment)? No, not for the payment page. If the price is not available for unknown reasons the page can’t show properly so it must be broken!</p><p>👎🏻</p><pre>type alias PaymentData =<br>    { price: Maybe Float<br>    , products: List Product<br>    }</pre><p>👍🏻</p><pre>type alias PaymentData =<br>    { price: Float<br>    , products: List Product<br>    }</pre><p>In a future article, we’ll see some useful tricks to empower decoders allowing us to handle all the problematic cases of a bad structured API but is just a patch on a bigger problem. You should argue with API maintainers if something smells.</p><h4>They’re coming outta the godd** walls!</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F108KUzjTMEp2gw%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F108KUzjTMEp2gw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F108KUzjTMEp2gw%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/36f0fe1be7ca9d09c277c0252ed6f60a/href">https://medium.com/media/36f0fe1be7ca9d09c277c0252ed6f60a/href</a></iframe><p>Maybesw are like rabbits, they multiply and despite our efforts, there are some cases where we can’t avoid to declare some Maybe data in our model. In such cases, we should analyze the reason behind that proliferation and how to reduce it.</p><p>Often a lot of data are nullable for the same reason or “case”, in such situation it can be handy to group them all in a single nullable data that store them all in their valuated types. Some examples of that are a group of fields in a form or some data needed by an optional part of your view.</p><p>👎🏻</p><pre>type alias Gift =<br>    { hasGreetingCard: Bool<br>    , greetingCardTitle: Maybe String<br>    , greetingCardBody: Maybe String<br>    , greetingCardSignature: Maybe String<br>    --<br>    }</pre><p>👍🏻</p><pre>type alias Gift =<br>	{ greetingCard: Maybe GreetingCard<br>	--<br>	}<br><br>type alias GreetingCard =<br>	{ title: String<br>	, body: String<br>	, signature: String<br>	}</pre><p>Such an approach has different advantages:</p><ul><li>we’ve logically grouped all the fields related to GreetingCanrd in a dedicated type. This makes the model more expressive and easy to understand.</li><li>we’ve reduced the key length name and relative functions (greetingCard.name)</li><li>we can make a GreetingCard module that defines the type and stores all related functions that are based on its evaluated case</li><li>we’ve removed a redundant flag hasGreetingCard that can be replaced with a simple function that checks if greetingCard is Nothing or Just. We should always prefer functions over the stored data when it&#39;s possible. It&#39;s much more scalable and allows us to change a single point (our function) in future refactorings or when your logic changes. If the type is opaque is even better.</li></ul><h4>Maybe it’s a very private person</h4><p>In general a Maybe says a lot about how we must handle it but nothing about why it&#39;s there: <em>when, how and why that value can be null ?</em></p><p>Semantically it’s a simple union type that doesn’t make the case talkative and that’s the reason why understanding the logic behind it’s difficult. If in a common imperative language this is commonly acceptable in Elm where you can write strongly declarative types easily it’s not.</p><pre>type alias Model = <br>    { isPrivacyAccepted: Maybe Bool<br>    }</pre><p>That’s a simple example, here we know that isPrivacyAccepted flag can be Nothing Just True or Just False.</p><p>But what does a first-time programmer can imagine?</p><ul><li>Probably there is a checkbox that can’t be visible/initialized under some circumstances</li><li>Maybe it’s used to model a “tri-state” checkbox</li><li>The data comes from the backend but only in some cases</li><li>…</li></ul><p>Even with such a simple example, we can have a lot of ambiguity.</p><p>Let’s try to use a different type:</p><pre>type alias Model = <br>	{ privacyConsent: Consent<br>	}<br><br>type Consent <br>	= Assent <br>	| Denial <br>	| NotExplicitAnswered</pre><p>Now is much more clear: that key is probably an answer to a tri-state checkbox. And it makes clear that a user could also not express clearly his consent to privacy data treatment. Pay attention, this type <strong>doesn’t resolve the Maybe</strong> but includes it inside its variants.</p><h4>Important things can’t be Maybe</h4><p>Let’s go back to the Gift example</p><pre>type alias Gift =<br>	{ greetingCard: Maybe GreetingCard<br>	-- ...<br>	}<br><br>type alias GreetingCard =<br>	{ title: String<br>	, body: String<br>	, signature: String<br>	}</pre><p>Now let’s imagine that the presence or absence of a GreetingCard will change dramatically our application. A gift with a greeting card produces a dramatically different view, with specific messages, API calls, validations... As a direct result, your code will start to grow because you&#39;ll need to check on that value in a lot of different points and this will make everything less declarative, readable and difficult to maintain.</p><p>In such cases rewrite the whole Gift as an union type may be an interesting solution:</p><pre>type Gift <br>	= Simple GiftData <br>	| WithGreetingCard GiftWithGreetingCardData</pre><p>During the init there will be a creator function for the Gift type that will have the ownership to create Simple or WithGreetingCard variant based on the raw data. You&#39;ll indeed have probably a bunch of redundant functions (but they will be small and simple) but now you&#39;ve strictly enforced all your flow. Now every part of your code will have to handle in a strictly different way the two cases. You&#39;ll probably notice that isolate such logics (update/view/helpers...) in functions that work only on one type is much more convenient and you can store them in their named modules. Gift&#39;s module will take care of hiding the implementation logic working as a &quot;logic hub&quot;.</p><pre>view: Gift -&gt; Html Msg<br>view gift =<br>   case gift of<br>      Simple data -&gt; GiftData.view data<br>      WithGreetingCard data -&gt; GiftWithGreetingCard.view data</pre><p>As a final result, you’ll have 2 sub-applications smaller, simpler and more scalable.</p><p>It’s a great step forward to remove only one Maybe, isn’t it?</p><h4>Maybe’s friends</h4><p>There are some types and patterns that hide Maybe, we could call them Maybish. The Consent type seen before is an example. Collections ( List and Dict) are a common family of types that hide Maybe. We know that picker functions on these types will always return a Maybe a because collections can be legitimately empty. It would be an error to write this in Elm:</p><pre>type alias Model = <br>    { cryingList: Maybe (List (Maybe Int))<br>    }<br><br>addElement: Int -&gt; Model -&gt; Model<br>addElement el model =<br>    { model<br>        | cryingList = Maybe.map (List.append [Just el]) model.cryingList<br>    } <br><br>sumToAll : Int -&gt; Model -&gt;  Model<br>sumToAll addend model =<br>    { model<br>        | cryingList = Maybe.map (List.map (Maybe.map ((+) addend))) model.cryingList<br>    }</pre><p>So if a collection can be legitimately empty you should think carefully about using a simple List if your model or logic needs almost one element to work properly. A more safe model could be the following:</p><pre>type ValuedList a = <br>    ValuedList <br>        { first: a<br>        , remaining: List a <br>        }<br>        <br>toList: ValuedList a -&gt; List a<br>toList (ValuedList {first, remaining}) = <br>    first :: remaining<br><br>head: ValuedList a -&gt; a<br>head (ValuedList { first }) = <br>    first</pre><p>This type is able to guarantee that almost one element is present (common List.head can&#39;t).</p><h3>Don’t hide a Maybe under the carpet</h3><p>If despite all your attempts the Maybe is still there well then <strong>respect</strong> it. If you’re writing <strong>highly reusable</strong> code then try to write functions that work directly on the concrete case.</p><p>There are two main reasons behind this choice:</p><ul><li>you can’t write your logic without another Maybe or a Maybish situation</li><li>you can’t predict how the user will handle the Nothing</li></ul><p>It&#39;s much more convenient to allow the consumer of your code to handle the Nothing case by itself and don&#39;t take care of it and all your code will become much easy to write and understand.</p><p>Let&#39;s think about the ValuedList creation function:</p><p>👎🏻</p><pre>valuedList: List a -&gt; Maybe (ValuedList a)<br>valuedList list =<br>    case list of<br>        (x::xs) -&gt; Just (ValuedList { first = x, remaining = xs })<br>        <br>        _ -&gt; Nothing</pre><p>👍🏻</p><pre>valuedList: a -&gt; List a -&gt; ValuedList a<br>valuedList first rest =<br>    ValuedList { first = first, remaining = rest }<br><br>-- Helper but not the main way to consume your type<br>fromList: List a -&gt; Maybe (ValuedList a)<br>fromList list =<br>    case list of<br>        (x::xs) -&gt; Just (ValuedList { first = x, remaining = xs })<br>        <br>        _ -&gt; Nothing</pre><p>The main creation function asks explicitly for head and tail parts. The fromList is just a convenient helper for some cases.</p><h3>A case study: Form and validations</h3><p>Our forms are probably Maybe’s best friends, the whole html input logic is based on nullable values (text, input, select)</p><pre>type alias FormData = <br>    { name: Maybe String<br>    , selectedOption: Maybe Option<br>    , availableOptions: List Option<br>    , privacyConsent: Consent<br>    }</pre><p>What happens when we need to send this data through an API? What happens if we would need to validate such data to ensure that they are not empty or that they’re properly selected? The simplest approach is to create a function that can express the client-side validation</p><pre>validations: List (FormData -&gt; Bool)<br>validations =<br>    [ .name &gt;&gt; isJust<br>    , .selectedOption &gt;&gt; isJust<br>    ]<br><br>isValid: FormData -&gt; Bool<br>isValid =<br>    List.map validations<br>        |&gt; List.all identity</pre><p>In our update, we’ll probably have an if that will trigger the post only if FormData is valid</p><pre>update: Model -&gt; Msg -&gt; (Model, Cmd Msg)<br>update model msg =<br>    case msg of<br>        Submit -&gt; <br>            model<br>              |&gt; withCmds [<br>                  if FormData.isValid model.formData then<br>                      postFormData model.formData<br>                  else<br>                      Cmd.none<br>              ]</pre><p>It’s simple, but we’ve only moved the problem. In our function postFormData we&#39;ll have to handle the encoding of name and selectedOption null cases. We could use a Maybe.map2 or some empty strings/default cases. What happens if FormData will grow or become more nested? What happens if we need to make some logic that works only on validated data? Again our Maybe it&#39;s not scalable. The solution in such a case can be a type able to store both the raw and the validated version of our formData. Let&#39;s try to write an abstract component to help us:</p><pre>type Validatable raw valid<br>    = NotValidated raw<br>    | Validated valid<br><br><br>create : raw -&gt; Validatable raw valid<br>create raw =<br>    NotValidated raw<br><br><br>validate : (raw -&gt; Maybe valid) -&gt; Validatable raw valid -&gt; Validatable raw valid<br>validate validatorFunction validatable =<br>    case validatable of<br>        NotValidated raw -&gt;<br>            validatorFunction raw<br>                |&gt; Maybe.map Validated<br>                |&gt; Maybe.withDefault validatable<br><br>        validated -&gt;<br>            validated<br>            <br>update: (raw -&gt; raw) -&gt; Validatable raw valid -&gt; Validatable raw valid<br>update rawMap validatable =<br>    case validatable of<br>        NotValidated raw -&gt; NotValidated (rawMap raw)<br>        <br>        validated -&gt; validated<br>        <br><br>map : (valid -&gt; c) -&gt; Validatable raw valid -&gt; Maybe c<br>map  mapper validatable =<br>    case validatable of<br>        NotValidated _ -&gt;<br>            Nothing<br><br>        Validated valid -&gt;<br>            valid<br>                |&gt; mapper<br>                |&gt; Just<br><br>isValidated: Validatable raw valid -&gt; Bool<br>isValidated validatable =<br>    case validatable of<br>        Validated _ -&gt; True<br>        <br>        _ -&gt; False</pre><p>Now we need to define the data model of the form. Let’s make our MyForm module</p><pre>type alias MyForm = Validatable FormRaw FormValid<br><br>type alias FormRaw = <br>    { name: Maybe String<br>    , surname: Maybe String<br>    }<br><br><br>type alias FormValid =<br>    { name: String<br>    , surname: String<br>    }<br>    <br>setName: Maybe String -&gt; MyForm -&gt; MyForm<br>setName value = <br>    Validatable.update (\raw -&gt; {raw | name = value })<br><br>setSurname: Maybe String -&gt; MyForm -&gt; MyForm<br>setSurname value = <br>    Validatable.update (\raw -&gt; { raw | surname = value })</pre><p>now we’ll write the most important function: validator with the use of Maybe.Extra library. Validator is a function that will try to apply a sequence of changes to a dummy version of FormValid in order to try to create a FormValid from FormRaw.</p><pre>dummyFormValid: FormValid<br>dummyFormValid =<br>    { name = &quot;&quot;<br>    , surname = &quot;&quot;<br>    }<br><br>validator : FormRaw -&gt; Maybe FormValid<br>validator raw =<br>    Just dummyFormValid <br>        |&gt; MaybeExtra.andThen2 (\v partialValidated -&gt; Just { partialValidated | name = v }) raw.name<br>        |&gt; MaybeExtra.andThen2 (\v partialValidated -&gt; Just { partialValidated | surname = v }) raw.surname</pre><p>Some remarks:</p><ul><li>dummy is needed to don&#39;t hurt the compiler since we can&#39;t dynamically extend a record</li><li>dummyFormValid could be a little smarter and initialize also all that fields that won&#39;t be validated and can be copied directly fromFormRaw</li><li>each mapping function of andThen2 is a validator function of the single field with a type signaturefieldValidator: FieldValueType -&gt; FormData -&gt; Maybe FormData that in our case is quite simple but could eventually make some extra checks over the field and eventually returnNothing if is not passed</li><li>with a little effort we could rewrite this pipe with a fold on a list of functions as we’ve seen in the previous example</li></ul><p>Finally, we can expose this last function of MyForm</p><pre>validatedCmd: (FormValid -&gt; Cmd msg) -&gt; MyForm -&gt; Cmd msg<br>validatedCmd cmdMap =<br>    Validatable.validate validator<br>        &gt;&gt; Validatable.map cmdMap <br>        &gt;&gt; Maybe.withDefault Cmd.none</pre><p>It’s done. Now we can use our side effects that will work only on FormValid (setter/mapper functions are omitted)</p><pre>update: Model -&gt; Msg -&gt; (Model, Cmd Msg)<br>update model msg =<br>    case msg of<br>        SetName val -&gt;<br>            model<br>                |&gt; Model.updateMyForm (MyForm.setName val)<br>                |&gt; withoutCmds<br>        SetSurname val -&gt; <br>            model<br>                |&gt; Model.updateMyForm (MyForm.setSurname val)<br>                |&gt; withoutCmds<br>        Submit -&gt; <br>            model<br>                |&gt; withCmds <br>                    [ MyForm.validatedCmd postFormValid model.myForm <br>                    ]</pre><p>Some other remarks:</p><ul><li>the validated form state is not stored on the model to avoid inconsistencies. It’s not allowed the possibility to update a field once the form has been validated (you should define a function valid -&gt; raw to go back from aValidated state)</li><li>Validatable.validate always need our validator that probably will never change. Maybe it would be convenient if Validatable would be able to validate (or invalidate) by itself on each update</li><li>Validatable could include another variant to express the condition of “Not yet validated”, maybe we’ll like to show some validation messages only after a first submit attempt</li><li>How we could express the validation logic for each field if we’d like to show some messages under each form field?</li><li>validatedCmd looks like a special mapper isn’t it? Maybe we could make an abstract one for other purposes</li></ul><p>I leave all these observations without an answer hoping that your phantasy and talent will find some interesting solutions.</p><h3>Finally, the end</h3><figure><img alt="super mario dramatic end of level" src="https://cdn-images-1.medium.com/max/256/1*wNbGRV8PeXSfx1OHaUMpNg.gif" /></figure><p>I hope I’ve managed to give you a more clear vision behind the reasons to avoid Maybe abusing. Keep in mind that some data inconsistency is however inevitable but being able to reduce it will improve your code. The next time you’ll be tempted to write Maybe on your keyboard hold on for a while, think if is needed and if you can spare.</p><p><em>Originally published at </em><a href="https://prima.engineering/2021/06/14/mega-maybe-maybe-is-not-the-right-choice/"><em>https://prima.engineering</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1d2e966b27e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/mega-maybe-maybe-is-not-the-right-choice-b1d2e966b27e">MEGA: Maybe Maybe is not the right choice</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[MEGA : Make Elm Great Again]]></title>
            <link>https://medium.com/prima-engineering/mega-make-elm-great-again-fd3c0c2c4704?source=rss-702217a6a8c9------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd3c0c2c4704</guid>
            <category><![CDATA[programming-languages]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm-lang]]></category>
            <dc:creator><![CDATA[Ivan Gori]]></dc:creator>
            <pubDate>Tue, 15 Jun 2021 09:39:50 GMT</pubDate>
            <atom:updated>2021-07-06T12:46:09.962Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="MEGA logo made with tangram" src="https://cdn-images-1.medium.com/max/1024/1*_MdK5g5v_-EyPlTb5VOCzQ.png" /><figcaption>MEGA: Make Elm Great Again</figcaption></figure><h3>MEGA : Make Elm Great Again</h3><h4>An introduction article about Elm development and MEGA series. Why we use it in Prima and why you should be interested in Elm.</h4><p>This is the introduction article of <strong><em>MEGA: Make Elm Great Again</em></strong> series in which I will try to condense some helpful patterns and techniques that I learnt during real-world frontend applications in Elm. These articles are dedicated to mid or experienced Elm and functional programming developers so if you’ve never experienced such topics before you’ll probably find it obscure and unuseful.</p><h3>Introduction to Elm</h3><p>As I said before these articles are not designed for beginners but could prove useful for everyone as a general explanation of a language that you could fairly define <strong><em>exotic</em></strong>. The purpose is just to make a summary on the technical aspects which you probably have never thought about. So if you’re just curious or you’ve never used Elm before it may help you to get a more precise idea about it.</p><p>When we say Elm we talk about two different worlds that are connected but different:</p><ul><li>TEA (<strong><em>The Elm Architecture</em></strong>) it’s the framework that implements the MVU pattern (<strong><em>Model View Update</em></strong>) that allows writing browser applications in the Elm language.</li><li>Elm, an <strong>ML</strong> family programming language. It’s a purely functional language strongly and statically typed. It supports type inference (but writing your type signatures is strongly recommended).</li></ul><p>Elm is independent from TEA but without TEA you can’t do much (well you can always try your functions in elm-repl)</p><p>But what is all this in practice?</p><h3>Elm is a compiled language</h3><p>Elm is a true language with its own compiler Elm -&gt; Javascript but there are some other projects for writing a compiler to other languages ( <a href="https://discourse.elm-lang.org/t/webassembly-compiler-update/5866">WASM</a> for example). The compiler produces javascript code that fully respects Ecma 5 standard. The final result is bundled in a whole monolithic js file that contains all your working code, barely readable and highly optimized. This bundle can be directly included in some external bundle written by you.</p><figure><img alt="An image with compiled javascript from elm code, barely readable" src="https://cdn-images-1.medium.com/max/1024/0*d75uUkvycnJMCHOh.png" /><figcaption>How compiled Elm looks like</figcaption></figure><p>The compiler can be launched directly via CLI or with a bundler (like webpack) plugin that targets <em>.elm</em> files. Using these plugins allows you to import and use your main Elm files directly in your javascript source like any other javascript module and makes your Elm program run like any other javascript object.</p><p>Third-party Elm packages cannot include javascript (since the 0.19 version). TEA and its native libraries are not based on javascript features more recent than Ecma 5. All this means that Javascript compiled by Elm <strong>doesn’t need poly-filling</strong>.</p><h3>Functions are first-class travelers</h3><p>Functions are the main skeleton and probably the only. Any nominal reference inside Elm code is a function, both when the function depends on some input (variable function) and when not (constant function). This allows us to express composition, application and partial application of functions natively, elegantly and expressively. Inside Elm a function like this</p><pre>myFunc: A -&gt; B -&gt; C</pre><p>can be evaluated differently by its use:</p><ul><li>given A and B returns C</li><li>given A returns a fuction B -&gt; C</li></ul><p>Type signatures are a read help for humans. The following is perfectly valid for the compiler (but probably deserves programmer’s hand amputation)</p><pre>evilSum: ((number) -&gt; (number -&gt; number))<br>evilSum = (+)</pre><p>Type signatures are recommended but not mandatory. The compiler is always able to infer the situation but if you use them remember that they are right associative so consider to use brackets to declare high order function types.</p><pre>-- Ok<br>sum: Int -&gt; (Int -&gt; Int)<br>sum = (+)<br><br>-- Ok but less readable<br>sum2: Int -&gt; Int -&gt; Int<br>sum2 = (+)<br><br>-- Ok - automatic type inference<br>mapNoTS mapper = mapper 5</pre><pre>-- Ok<br>map: (Int -&gt; Int) -&gt; Int<br>map mapper = mapper 5</pre><pre>-- Error<br>mapWrongTS: Int -&gt; Int -&gt; Int<br>mapWrongTS mapper = mapper 5</pre><p>Functions that are defined by you can be used only in prefix notation. Operators (eg &lt; &gt; =) are the only functions allowed to be used in prefix and infix notation (and yes like in math operators are functions too). Brackets are not used to define function input but to sort function evaluation and they are &quot;dummy&quot; alternatives to application operators|&gt; or &lt;| that are more convenient when you write your functional code as a pipeline.</p><pre>infixNotation: Int<br>infixNotation = 5 + 5<br><br>prefixNotation: Int<br>prefixNotation = (+) 5 5<br><br>orderWithBrackets: Int<br>orderWithBrackets = mul 5 (sum 3 2)<br><br>orderWithLeftApplication : Int<br>orderWithLeftApplication = mul 5 &lt;| sum 3 2<br><br>pipelineApplication: Int<br>pipelineApplication =<br>    2<br>        |&gt; sum 3<br>        |&gt; mul 5<br>    <br>composition: Int -&gt; Int -&gt; Int<br>composition =<br>    sum<br>        &gt;&gt; mul 5</pre><h3>Your code is not designed around “line number” or “step” concepts</h3><p>Classic procedural/imperative languages are designed around Turing Machine architecture, to resume it shortly:</p><ul><li>a program is a collection of instructions written on a paper roll (virtually infinite)</li><li>a “magic finger” points to/reads a line at a time on the paper roll</li><li>a memory stores data and tells the finger which is the paper row number to point on</li><li>each instruction is read, evaluated, then it changes memory and defines the next row to read</li></ul><p>A language like this can express relatively global or local memory scope. This allows changing things when something knowable at execution time only happens. Throw exceptions, jump to different “lines” of code, access/allocate/change memory, declare and init named references, add debug breakpoints. These features are useful but the compiler is unable to detect unpredictable and potentially destructive situations (runtime errors).</p><p>Well with Elm <strong>no</strong></p><ul><li><em>All</em> the effects that can be generated inside Elm code are evaluable at compile time in term of type. The roll paper can be seen and evaluated in the whole from the first line to the last and you can’t compile code that may produce an unknown result or a type inconsistency.</li><li>Whatever it’s not knowable at compile time (eg an API call or non-elm code execution) is defined as a <strong><em>“side effect”</em></strong>. Side effect production is strongly handled by the architecture</li><li>you can produce a side effect result only in precise “moments” and the result will re-enter in your code in the future, in a <strong>“state”</strong>, dedicated expressively for it.</li><li>you must handle and type properly your side effect result. You’ll have to handle and type both happy (your expected result) and unhappy (some type of error that could happen) possibilities.</li><li>The architecture is the “deus ex machina” that allows us to write something real with this paradigm. It slices your paper roll in discrete sheets (not accordingly line of code but accordingly programmer-defined states ) it evaluates the “sheet” in the whole like a huge big function, stores its result in internal memory, aligns the virtual dom (your view) and then waits quietly for the next event that will determine the next “state” and which “sheet” evaluate.</li></ul><p>Ultimately Elm guarantees that your application, once booted, would <em>never</em> reach an unknown or partially inconsistent state that is not handled. It’s not possible to introduce true runtime errors inside your application besides architecture or compiler bugs (well you could always break the application deliberately in the browser). Even unexpected results from side effect will bring your application to an error state that must be handled.</p><h3>Everything is created, nothing is transformed</h3><ul><li><strong>Pass-by value</strong> is the only admitted</li><li>Change a data structure means <strong>recreate</strong> it interely. The notation to “assign” a value to a record</li></ul><pre>setN: Int -&gt; A -&gt; A<br>setN value a = <br>    { a <br>        | kn = value <br>    }</pre><p>it’s just syntactic sugar to avoid you the boring enumeration of all record’s keys.</p><pre>setN: Int -&gt; A -&gt; A<br>setN value a =<br>    { k1 = a.k1<br>    , k2 = a.k2<br>    -- ...<br>    , kn = value<br>    -- ...<br>    }</pre><h3>The type system is lean but expressive</h3><p>Elm types are <strong>algebraic structures</strong>: a set with some operations (functions) on them. If this definition reminds you of some course of linear algebra you’re not wrong. In Elm you’ve only two ways to define your types:</p><h4>Real type aliasing:</h4><p>With the aliasing you can assign a referenced name to some other types, it allows us to do some things:</p><ul><li>Redefine type name. It can be used to shorten long signatures (like generic/high order functions), writing it once for all, or define parametric types when you’ve generics (see the following sections)</li></ul><pre>type alias MaybeInt = Maybe Int  <br><br>type alias ABToC = MaybeInt -&gt; MaybeInt -&gt; Int<br><br>type alias WithIntTuple a = (a, Int)</pre><ul><li>Define a record with a name and some named keys</li></ul><pre>type alias A = { aValue: Int }</pre><ul><li>Use record type alias named reference to build rapidly a record from arguments (the order of arguments is relative to record keys)</li></ul><pre>type alias A = { aInt: Int, aString: String }<br><br>myA : A<br>myA = A 5 &quot;Ciao&quot;</pre><p>Type aliases are <em>“only”</em> new names, useful to write shorten code but it’s only sugar syntax and it can be very misleading if used unproperly. You could think that you’re building a type-checked type but it’s not.</p><pre>type alias A = { v: String }<br><br>type alias B = { v: String }<br><br>pickV: A -&gt; String<br>pickV {v} = v <br><br>vOfA : String<br>vOfA =<br>    A &quot;Ciao A&quot; |&gt; pickV<br><br>vOfB : String<br>vOfB =<br>    B &quot;Ciao B&quot; |&gt; pickV<br><br>vOf : String<br>vOf =<br>    { v = &quot;Ciao ?&quot;} |&gt; pickV</pre><p>A, B and { v : String } are the same for the type system. The function pickV can accept a record typed A, B or even an unnamed record but formerly consistent with { v: String }.</p><p>Similarly the following situation</p><pre>myA: B<br>myA = A &quot;A&quot;<br><br>myB: A<br>myB = B &quot;B&quot;</pre><p>is still valid for the compiler.</p><p>You should try to limit (or avoid totally) the construction of a record with type alias reference: it’s misleading as we’ve seen before (it’s not clear that you’re building a record) but it’s not scalable neither. When your record has several keys your constructor will be very unreadable (you may remember perfectly the key order but a colleague probably won’t).</p><p>You should also avoid type alias concrete types when this is not giving you a real advantage to your code, the aliasing hides the real type to the reader so someone could not be aware of which types lays behind your alias and as said before it doesn’t protect you from type abusing. Let’s see an example</p><pre>type alias Id = String<br>type alias Slug = String<br>  <br>type alias MyServerData =<br>  { id: Id<br>  , slug: Slug<br>  -- ...<br>  }</pre><p>Id and Slug are not allowing to control your data (everyone can still use String), you can&#39;t express any constraint on these types or help a future developer (when does a string is a valid slug? They must be treated in some different way? Where can I find this logic eventually?). If you need to express this kind of constraints you probably need a simple concrete type.</p><h4>Concrete type:</h4><p>Concrete types, or real types, are declared slight differently: type NameAlias = ConstructorTag &lt;type1&gt; &lt;type2&gt; ... a <em>label</em> or <em>tag</em> followed, eventually, by one ore more other types (primitive or not) that are able to store your data. They can be classified in 3 groups:</p><ul><li>simple (not variant)</li></ul><pre>type RGB = RGB Int Int Int<br><br>type Id = Id String<br><br>type Data = Data Id { rgbColor: RGB, description: String }<br><br>myData: Data<br>myData =<br>    Data <br>      (Id &quot;1&quot;) <br>      { rgbColor = RGB 255 0 0<br>      , description = &quot;my data with red color&quot; <br>      }</pre><ul><li>unions (not intersecting subsets)</li></ul><pre>type Pantone<br>  = Red032C<br>  | Red485C<br><br>type ColorSchema<br>  = RGB Int Int Int<br>  | HEX String<br>  | CMYK Int Int Int Int<br><br>toRgbColorSchema: Pantone -&gt; ColorSchema<br>toRgbColorSchema pantone = <br>  case pantone of <br>      Red032C -&gt;  RGB 239 51 64<br><br>      Red485C -&gt; RGB 218 41 28</pre><ul><li>mutually recursive unions</li></ul><pre>type StringBinaryTree<br>  = Node String StringBinaryTree StringBinaryTree <br>  | Leaf String</pre><p>The <em>labels</em> are constructor functions of the type and they can be directly used only if the type is explicitly exposed by the module where you placed them (this feature allows to restrict type handling and manipulation). Real types are strictly type-checked, two types with different names are different even if they are structurally the same and cannot be used on functions that are not designed for them.</p><h3>Limited polymorphic</h3><p>The only allowed form of polymorphism is parametric polymorphism, similar to diamond &lt;T&gt; of other languages. It can be expressed with lowercase named reference in type declaration (or function signatures). Use parametric types allows reusing your code nicely.</p><pre>type BinaryTree a <br>    = Node a (BinaryTree a) (BinaryTree a) <br>    | Leaf a<br><br>type alias RecordWithA record =<br>    { record<br>        | a : String<br>    }<br>    <br>reusableView: msg -&gt; Html msg<br>reusableView onClickMsg =<br>    div [ onClick onClickMsg ] [ text &quot;Click on Me!&quot;]</pre><p>Remember that runtime evaluation is not admitted. The abstraction must be resolved at compile time to be valid. It means that the code must explicit the generic type at some point to compile.</p><pre>type alias ParentModel =<br>    { intBinaryTree: BinaryTree Int<br>    , stringBinaryTree: BinaryTree String<br>    , recordWithABC: RecordWithA { b: String, c: Int }<br>    }<br>    <br>parentView: Html Msg<br>parentView =<br>    div [] [ reusableView ParentMsg.Click ]</pre><p>Subtyping is not allowed (this is the price for type inference). Any attempt to “generify” using a parametric type, even in a safe way, will be blocked by the compiler.</p><pre>type AFamily<br>    = A (RecordWithA {})<br>    | WithB (RecordWithA { b : Int })<br><br><br>type alias RecordWithA record =<br>    { record<br>        | a : String<br>    }<br><br>-- This function will throw a compiler error because the compiler will type the function output and it will signal the discrepancy in type.<br>-- If you keep in mind that type signatures are not used by the compiler this is more understandable.<br><br>generifyAFamily : AFamily -&gt; RecordWithA record<br>generifyAFamily a =<br>    case a of<br>        A record -&gt;<br>            record<br><br>        WithB record -&gt;<br>            record<br><br><br>pickA : AFamily -&gt; String<br>pickA =<br>    generifyAFamily &gt;&gt; .a</pre><p>function overloading (Ad hoc polymorphism) is not allowed either.</p><h3>It looks like Haskell</h3><p>If you’re a Haskell developer you may think that Elm is just a Haskell dialect with a simpler syntax but it’s an error. There are a lot of differences between these two but to resume:</p><ul><li>Native types are implemented natively (in Javascript) due to performance reasons (eg. String it&#39;s not a List Char).</li><li>Polymorphism is highly limited. Typeclasses can’t be implemented outside kernel code. Accessible type-class are just a few: number, comparable and appendable and they are convenient to be used only in heavy-abstract functions.</li><li>It’s not possible (since the 0.19 release) to define or extend operators.</li><li>Elm code is not lazy evaluated by default, the way to make your function lazy is different and not easy to understand. Write recursive algorithms in Elm needs some attention.</li></ul><h3>Robust but free-form</h3><p>At the net of all these features, the code developing in Elm is fairly less opinionated.</p><p>The developer has a huge control, and responsibility, over the model architecture and code organization. Adding new features on the codebase and refactoring old parts are in general secure and relatively simple tasks. Any part of code that you may have forgotten will be noticed by the compiler.</p><p>The capability to express scalable and strongly declarative architectures is the Elm true force. The need to isolate API communication makes the isolation (or exclusion) of business logic profitable. For the same reason is much convenient to re-build your data in the form that is most suitable for the frontend (and not for the database or BE stack) and in general express your types and functions in a high-level format. Definitely, this is what makes Elm development not only educative (you won’t write procedural code in the same way) but even funny.</p><h3>Target acquired: become a Wise Architect</h3><p>Web development is not famous for the organized planning of software architecture. Services evolve rapidly following Agile’s methods, solutions and architectures tend to become rapidly non-sufficient and untidy due to overgrowing. If this is true in general it’s even more true on frontend: new flows, SEO requests, ABTesting, graphic changes, experimental UX, tracking… are all requirement that often born from non-technical teams and often developed as semi-prototypes that will last forever. It becomes important for an evergreen project to be able to develop architectures that can be <strong>flexible, scalable, clear and talkative</strong>.</p><p>Elm is a powerful tool to reach this target but it can be hard to be able to use it properly. In the next articles we’ll see how to recognize problems and anti-patterns, why we should avoid them and how to replace them with more readable and maintainable code.</p><p><em>Originally published at </em><a href="https://prima.engineering/2021/06/14/mega-make-elm-great-again/"><em>https://prima.engineering</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd3c0c2c4704" width="1" height="1" alt=""><hr><p><a href="https://medium.com/prima-engineering/mega-make-elm-great-again-fd3c0c2c4704">MEGA : Make Elm Great Again</a> was originally published in <a href="https://medium.com/prima-engineering">Prima Engineering</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>