<?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 Andric LibreSinn on Medium]]></title>
        <description><![CDATA[Stories by Andric LibreSinn on Medium]]></description>
        <link>https://medium.com/@andric.libresinn?source=rss-8e6a302b52a6------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*hnWT2SU68nFsmWZem-cXnA.jpeg</url>
            <title>Stories by Andric LibreSinn on Medium</title>
            <link>https://medium.com/@andric.libresinn?source=rss-8e6a302b52a6------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 27 Nov 2026 19:50:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@andric.libresinn/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[Naming your functions, files & paths]]></title>
            <link>https://medium.com/@andric.libresinn/naming-your-functions-files-paths-3f15317e257a?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f15317e257a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functions-in-javascript]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Tue, 17 Aug 2021 00:34:32 GMT</pubDate>
            <atom:updated>2021-08-17T00:34:32.528Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_OteGVkj11-Fdir88Ano-A.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thevictorbarrios?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Victor Barrios</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Long function names are a scourge of codebases around the world.</p><p>Why do people write long names in the first place[1]? Is there a solution[2]? Will there be examples[3]?</p><p>[1] Naming functions and files in software projects comes down primarily to context. Context is everything between the environment in which the function exists and the software project itself. Context is the intended user, where the function is defined (file, path, object etc) or namespace.</p><p>Let us not forget about long names scattered around codebases around the world. One of the many, many job of us engineers is to take complex ideas and break them down into smaller more easily maintainable abstractions.</p><blockquote><strong><em>The function names detail too much of what the function does because it excludes too much context</em></strong></blockquote><p>[2] Yes.</p><p>[3] Of course.</p><p><strong><em>Note</em></strong>: I will not be mentioning classes but all the same rules apply.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VfnF0HqWpgZQVDVCMtu_TQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@startaeteam?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Startaê Team</a> on <a href="https://unsplash.com/s/photos/meeting?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Some background on functions</h3><p>Functions are a peculiar thing. Most all that I know view functions as a “thing” that “does a thing”. Many of us wax philosophical about functions. “Why function()?”</p><p>Mathematically a function is:</p><blockquote>A relation for which each value from the set the first components of the ordered pairs is associated with exactly one value from the set of second components of the ordered pair.</blockquote><p>or simpler</p><blockquote>A <strong>function</strong> is an equation for which any <strong>x</strong> that can be plugged into the equation will yield exactly one <strong>y</strong> out of the equation.</blockquote><p>Input → output. Now, while this next part is not always correct a function should be able to be replaced with its resulting output. Essentially a hashmap/cache of inputs → returns.</p><p>When thinking functions think “side effect free” and “small”. All these things makes functions less complex and easier to name. Which leads to the next topic.</p><h3>Let’s discuss functions</h3><blockquote>Every non-empty function “does something” — Me the wise one</blockquote><p>Let me offend you right off the bat. Functions should mostly be nouns. Functions should be named after what they return rather than <em>what</em> they <strong><em>do</em></strong>. Think about it, every non-empty function “<strong>does something</strong>”. Adding numbers, starting the app, closing the app, side effects such as querying the database or making an API call. Functions will always <strong><em>do</em></strong> something. Even side effects don’t require verbs. Verbs are rarely necessary; every function “does something”.</p><p>Consider getting all the users from an API call. We’re “getting” and it’s a side effect. Yet I’d still call that function users() because the response from that request will be a collection of users or an empty set ([]). The get is in the method of the request. You don’t need to be redundant. Then again there are instances where you’ll need a verb that isn’t based on the method of the request. Typically, tho, you’ll fall into one of the CRUD operations. PUT, GET, DELETE, POST and so on and so forth. If you need to deactivate a user’s credit card because there was possible fraud detected you’d use a PUT to modify the card’s use. Try to keep it to the spec.</p><p>Okay great. Is your blood pressure elevated? Your face flush? Good.</p><p><strong>Stop. Using. Verbs.</strong></p><p>So, then, what do I name it after? I name my functions as nouns. Definitive nouns. You should strive to make all your functions return something. If it returns something then I name the function of which it could be replaced. I base it on its return value.</p><blockquote>Verbs are rarely necessary; every function “does something”.</blockquote><p>Now that I’ve made everyone reading this angry let me calm everyone down. I don’t often admit this. But … there are times that it makes sense to write verbs into your function names.</p><p>Just, don’t <strong><em>rely</em></strong> so heavily on verbs. I implore you. Rely primarily on nouns. The verb of the function will be in the return statement or in the HTTP METHOD. In [functional] programming we <em>should</em> care about values and expressions not how the work is accomplished. In the future we’ll be so abstracted away from how things are done we’ll tell computer “I need all previous order links but only text for orders that don’t exist anymore” and the computer will figure out the fastest way to do it.</p><p>I like the 90/10 rule. 90% nouns. 10% verbs.</p><p>So, verbs aren’t a complete no-no. You should lean <strong><em>primarily</em></strong> on nouns and lean less on verbs. Use verbs sparingly. Limit your verb use to predicates and (user triggered) events.</p><p><strong>Note</strong>: <em>If a function is curried (and unary) I may use special rules if they aren’t being used directly in a composition function.</em></p><p><strong><em>Note</em></strong>: <em>Any function that </em><em>returns something is a function that </em><em>get()s you something. So you never need to start a function name with </em><em>getRestOfFunctionName).</em></p><h4>Business logic FUBARs everything (but not really)</h4><p>I only mention this because business logic tends to be where you either compose all your functions together (or just implement) or where there is a dumping ground of functionality and it does “a lot”.</p><p>Take for example these two cases. Both of these are business logic. One is easier to name than the other.</p><ol><li>Get a filtered list of products in a person’s cart</li><li>Disabling checking out if there was a fraud notification on the back end</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iQ2R9dPBsw5axnseRukkEQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@barnimages?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Barn Images</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>My rules (and why)</h3><p>It all comes down to organization. Remember, you have so much context available to you to un-complicate your code. Naming code is very similar to how you’d put together a simple REST endpoint (leave out the versioning).</p><h4>Simplify</h4><p>The more a function does the more complex everything around it will end up being. Refactor it until it’s simple and easy to quickly read, easy to</p><h4>Name based on the return</h4><p>Remember: “input → output”.</p><h4>Write your code as if it’s open source</h4><p>The first tip I give every new engineer is to write your code as if you’re going to open source it for the greater populace. That makes you much less lazy when writing code. Abstract as necessary, write <em>some</em> documentation etc.</p><h4>Expel redundancy</h4><p>If you have a UI tree that deals with, say, a product listing then it would make sense to contain everything within a folder named “products”. Using images this is what I’d do to limit that redundancy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i9Nxsfz_hnYT5TdJbbNh-Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1oiLOXgVntHJpGiT0AYX7Q.png" /></figure><p>The context here is products. We don’t need to include it again now that we’re further down the tree. As a matter of fact you never need to reference it again anywhere down the tree (file paths, code is a different story)</p><p>Let’s talk functions tho. This is how I’d clean up this trivial example</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D11W7FDPy9OMq5r8hYnjxA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IDyccgx_X5gj_pcN4VHvbA.png" /></figure><p>Notice how I use the file tree to determine the naming of the functions?</p><h4>Be laconic in all aspects of naming</h4><p>Think: Fewer words, fewer parameters, overall fewer characters. Type less.</p><p>Everyone says that code should be able to be read like a book. That’s fine but it isn’t true. For the sake of argument let’s say it is but it’s better to write your book for a 3rd grader rather than someone on their 3rd PhD in philosophy where their dissertation is on Kant.</p><p>getUsersCartItemsFilteredByAvailableInRegionSortedByDate() is an absurdly terrible name. cartItems()a is a better name and yet we and we can do better. For instance, put this function under a namespace/directory called cart and the function in here would be called items. There, simplified.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0fQWFVCmTtXPrgzlukBvwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cjCp32pdw5hEMuRFcTtifw.png" /><figcaption>Use the context to be laconic in naming your identifiers.</figcaption></figure><h4>Use context to your advantage</h4><p>This was displayed some in the above screenshots under “<strong>Expel redundancy</strong>”. The example below shows just some simplicity of using the contexts of the file path and filename to determine the names of functions used. Anything further here I would use functional programming paradigms to compose this functionality further (currying, composition etc). Also note that I made all the function names shorter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dVPPPJaR-SlgrkgB2cSmAw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*abIfxRpokp0KQuAz6wdnLw.png" /><figcaption>This is trivial, clearly, but you can see some of the benefits. It’s easier to read. It’s less menacing when peering in.</figcaption></figure><p><strong><em>A glaring note about the example above. Other than significant readability improvements this could have been fixed in a few different ways.</em></strong></p><h4>Exceptions to the ruleset</h4><p>Of course there were going to be exceptions 😀.</p><ul><li>You don’t need to type out identifier for it to be descriptive in a for loop.</li><li>Project names, just have fun with it. Every product starts “doing one thing” and always end up with bloat. Soon your recipe app is pulling in recipes w/o the large text, has an API for finding plagiarists, has it’s own rendering engine and so on and so forth.</li></ul><p>How I utilize verbs in function names. In these 3 cases I go simple and use past tense. Events, predicates and top-level business logic(1). But, to the exception, I have a method in which I go about naming verb’d functions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6da24055bf60b03083fef8112905fbd6/href">https://medium.com/media/6da24055bf60b03083fef8112905fbd6/href</a></iframe><p>I use past tense because I care about the return. I care that an event happened and when calling a function I’m not “in” the function I’m waiting on it to complete.</p><p><strong><em>Note</em></strong>: When to use the imperative present tense verb for a function (preferably never but) when you need to mutate data. Strive to not mutate.</p><h3>Naming smells</h3><h4>The name of a solution/tech/offering</h4><pre>./src/common/database-interface<br>  ⟶ mysql.js<br>    ⟶ initMysql<br>    ⟶ mysqlPool()<br>    ⟶ closeMysql<br>    ⟶ query<br>    ⟶ update()</pre><p>We’ve all worked in codebases where there is an interface that is named after an ancient provider that was swapped out ages ago but the function names still reference it. It’s confusing to work with.</p><p>This naming smell isn’t a hard rule for me as it’s something that’s easy to fix but please abstract away provider details to a more generic interface. I think this is part of SOLID but who really cares about … SOLID <strong><em>anyway</em></strong>?</p><h4>Multiple words</h4><p>Anything that is multiple words tends to be better if it’s broken down into single words. Don’t fear the path. The context of your directory structure, your file and what you’re returning are the Big 3 when it comes to context. Take advantage of that context to name your functions.</p><h3>Fin.</h3><p>I part saying that naming doesn’t need to be hard. Follow some simple rules, limit the amount of keystrokes you have to press and write based on returns you’ll make your life a lot easier.</p><p>I hope this helps.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f15317e257a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding TS Generics better]]></title>
            <link>https://medium.com/@andric.libresinn/understanding-ts-generics-better-c802b3766fed?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/c802b3766fed</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[fpt]]></category>
            <category><![CDATA[generics]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Fri, 16 Oct 2020 19:53:31 GMT</pubDate>
            <atom:updated>2020-10-16T19:53:31.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SYyfIdLR1PMxDF4qx0o59g.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@frank_romero?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Frank Romero</a> on <a href="https://unsplash.com/s/photos/learning?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>I can’t tell others how to write their libraries so that I can understand them easier. That’s a given. That’s also nonsense. I can do this with code at work though (which I do all the time). What I can do is learn how to read these things better. So I can decipher how others write their code.</p><p>But if you read the docs or take a bunch of courses you might not come away with a better understanding. I think it’s just fine if your use cases are regular imperative code. When things are curried and you can write a signature for a function as a type within a type that’s when things get more difficult.</p><p>And honestly, that’s where I like to live. So it’s time to do a little learning.</p><h3>Problem statement</h3><p>I was having issues with complex TypeScript generics/types. I wanted to figure out what was going on with the following function signature. I’m not used to generics especially complicated ones. I’m fully aware that there are even more complicated ones but this isn’t a dick measuring contest. I’m learning, others are too.</p><pre>export const map: &lt;A, B&gt;(f: (a: A) =&gt; B) =&gt; &lt;E&gt;(fa: Either&lt;E, A&gt;) =&gt; Either&lt;E, B&gt; = (f) =&gt; (fa) =&gt;<br> isLeft(fa) ? fa : right(f(fa.right))</pre><p>It’s just a simple map() function so why is it so difficult to understand? I couldn’t parse out the types as to what they were supposed to be doing and how. I get it now tho. It’s actually super simple but when starting out it is crazy hard to understand.</p><p>First of all I want to give the answer first. No need to wait on dessert I want to give that right away so I can explain the process.</p><p>Which results in (my formatting)</p><pre>exports.map = function (f) {<br>  return function (fa) {<br>    return exports.isLeft(fa)<br>      ? fa<br>      : exports.right(f(fa.right))<br>  }<br>}</pre><h3>Process</h3><p>Firstly what I did was gather everything up. I went to the source code and pulled everything out of the Either.ts from fp-ts and put it into it’s own file JUST for the map() function.</p><p>Which would be the following</p><pre>type Either&lt;E, A&gt; = Left&lt;E&gt; | Right&lt;A&gt;</pre><pre>interface Left&lt;E&gt; {<br>  readonly _tag: &#39;Left&#39;<br>  readonly left: E<br>}</pre><pre>interface Right&lt;A&gt; {<br>  readonly _tag: &#39;Right&#39;<br>  readonly right: A<br>}<br><br>export const isLeft = &lt;E, A&gt;(ma: Either&lt;E, A&gt;): ma is Left&lt;E&gt; =&gt; ma._tag === &#39;Left&#39;<br><br>export const right = &lt;E = never, A = never&gt;(a: A): Either&lt;E, A&gt; =&gt; ({ _tag: &#39;Right&#39;, right: a })<br><br>export const map: &lt;A, B&gt;(f: (a: A) =&gt; B) =&gt; &lt;E&gt;(fa: Either&lt;E, A&gt;) =&gt; Either&lt;E, B&gt; = (f) =&gt; (fa) =&gt;<br>  isLeft(fa) ? fa : right(f(fa.right))</pre><p>I ran it through the compiler and got (some extra formatting from me)</p><pre>exports.__esModule = true<br>exports.map = exports.right = exports.isLeft = void 0<br>exports.isLeft = function (ma) { return ma._tag === &#39;Left&#39; }<br>exports.right = function (a) { return ({ _tag: &#39;Right&#39;, right: a })}<br><br>exports.map = function (f) {<br>  return function (fa) {<br>    return exports.isLeft(fa)<br>      ? fa<br>      : exports.right(f(fa.right))<br>  }<br>}</pre><p>So the function is exactly what you’d expect. Return a function that map()&#39;s over a value. Although it returns either a Left or Right but that is for another discussion on FP which I don’t want to have here (learn it, it’s awesome and makes your code type safe. Please, for the sanity of good code please learn it and use it).</p><h3>Explanation</h3><p>The generics is what makes this hard to read. It’s a side effect of generics. I wish there were a way to make this better but there currently isn’t. So let’s learn.</p><p>What will make this easier to learn is to break it down.</p><pre>export const map: &lt;A, B&gt;(f: (a: A) =&gt; B) =&gt; &lt;E&gt;(fa: Either&lt;E, A&gt;) =&gt; Either&lt;E, B&gt; = (f) =&gt; (fa) =&gt;<br>  isLeft(fa) ? fa : right(f(fa.right))</pre><p>There are 3 parts (last part is an addendum):</p><h4>Declare the function</h4><pre>export const map</pre><p>Nothing extra needs to be said here I hope.</p><h4>The function’s type</h4><pre>&lt;A, B&gt;(f: (a: A) =&gt; B) =&gt; &lt;E&gt;(fa: Either&lt;E, A&gt;) =&gt; Either&lt;E, B&gt;</pre><p>This for me is where it got complicated. If it weren’t for the output of the TypeScript code to show me what the function actually looked like then I’d have a really difficult time understanding how this worked. The output showed me that the function itself was just (f) =&gt; (fa) =&gt; &#39;some value&#39;.</p><p>So after comparing the original TypeScript code and the compiled JavaScript you can see where the division is. It’s the = sign. That’s where the type of the function signature ends and the function declaration (function body) begins. I want to discuss that a bit further to help further explain it.</p><p>To do that I need to break it down even further. To break it down I will separate everything at each fat arrow (=&gt;).</p><p><strong>Part 1</strong>: &lt;A, B&gt;(f: (a: A) =&gt; B)<br>There are 2 generics in this section A, B and one type.</p><p>This is a unary function where it takes one parameter that happens to be a function. To me this is where it gets super complicated as all the :s and ()s make it very difficult to read.</p><p>The type is (f: (a: A) =&gt; B). The parameter is f with the type of function that takes an A and returns a B</p><p><strong>Part 2</strong>: &lt;E&gt;(fa: Either&lt;E, A&gt;)<br>This is a unary function. It defines a generic E where it takes a single parameter fa of type Either&lt;E, A&gt;</p><p><strong>Part 3</strong>: Either&lt;E, B&gt;<br>This is the return type. It returns an Either of error or B.</p><h4>The actual function’s operation</h4><p>(f) =&gt; (fa) =&gt; isLeft(fa) ? fa : right(f(fa.right))</p><p>A curried function that returns either a Left or Right depending on if the predicate fails or not.</p><h4>The dooer</h4><p>In functional programming most functions aren’t just unary they are also curried (when multiple args) to allow for laziness of computation (allows for setup, easier failures and recovery). So the final part of the function signature is a return value (a function) but when run it does the following</p><p>isLeft(fa) ? fa : right(f(fa.right))</p><h3>What makes it easier for me to read</h3><p>This is all in hindsight of course and I know this is more text but I feel like the signature itself is much easier to read. But now knowing that all I had to do was separate out the code from the function name const map: to the signature to the = sign it’s much easier to understand now.</p><pre>type mapSig = &lt;A, B&gt;(f: (a: A) =&gt; B) =&gt; &lt;E&gt;(fa: Either&lt;E, A&gt;) =&gt; Either&lt;E, B&gt;</pre><pre>export const map: mapSig = (f) =&gt; (fa) =&gt;<br>  isLeft(fa)<br>    ? fa<br>    : right(f(fa.right))</pre><p>So what have I learned?</p><p>I learned oodles. I hope this process was illuminating to you to do the same if you’re stuck on a type signature that you can’t wrap your head around at first.</p><ol><li>That separating the type signature from the implementation makes it significantly easier to understand (previous heading).</li><li>Compiling it down to regular JS is super helpful</li><li>Taking the code itself and breaking it down (reformatting, indentation et al) makes it easier.</li><li>That the = just like regular currying is where you should start</li></ol><p>I hope this helps someone else coming to this</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c802b3766fed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Language and tech speculation]]></title>
            <link>https://medium.com/@andric.libresinn/language-and-tech-speculation-b67bcd782550?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b67bcd782550</guid>
            <category><![CDATA[speculative-fiction]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[english]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Thu, 27 Dec 2018 16:16:04 GMT</pubDate>
            <atom:updated>2018-12-27T16:21:06.438Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BClyfWVr1xcJd6SB4gqEkQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/photos/ANJHXftvvJ8?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Ryan Tang</a> on <a href="https://unsplash.com/?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Everyone knows my dislike of the english language; I think I’ve made that abundantly clear if you’ve known me for longer than 20 min. What people don’t know is that I secretly love language in general and even the english language at that.</p><p>Having written code for a better part of my life I’ve grown tired of it’s strict restraints in grammar and use. Even the organization of ideas is difficult. Normal language, though, isn’t as such. It’s fluid and ever changing.</p><p>In programming, depending on the language, we may get errors thrown at us for forgetting that horrid useless semi-colon. In prose we often don’t even use the period. Poems are a different structure to regular prose. In screenplays it’s written like we talk which has no proper grammar. Heck, we even change where we place the period if we are in the end of a quote. Do we put it in the quotation mark or outside? I prefer outside.</p><p>This is obviously not something people haven’t thought about but it is something that I have been thinking about recently. I’m not a linguist or english major. My english (i.e., grammar) is clearly very poor though this isn’t important.</p><p>The looseness of language incredibly powerful. We can communicate w/o throwing errors to each other. If I am talking with a nonnative speaker I or they don’t have a seizure and fall to the ground. We work through it. What about slang? The person listening to someone speaking slang can derive the meaning through the context clues of the sentences. You won’t get the exact meaning, of course, but you can still distill it’s essence. Oftentimes that’s the most important part of language. Communication needn’t always be philosophical arguments and perfect grammar. The abstract, the concept, is what sticks with people more than what they said specifically. We are a species of emotion after all.</p><p>No, it isn’t [always] efficient, no it isn’t [always] the favored option but it still works. There are of course problems but you can understand what someone is trying to communicate whether they are speaking with an accent, flawed language, broken language, mixed language or slang.</p><p>Now, a partial aspect of this article is to say to be more accepting of people that don’t speak like you but also that what we do as engineers will eventually be on it’s way out. Writing code will eventually be something that we do as a hobby or for fun to get something to light up. Programming languages will eventually “go away”. Or so I believe.</p><p>Granted, I don’t want to code this loosely but this looseness is what is important. Possibly code in the future won’t be written but rather told. Or taught. Perhaps in the future we’ll become much more loosey goosey with commands like “I want this, I want that, look over there, this should look more like this, follow this path, do not let people do this or that”.</p><p>You don’t need to know computer science to program or even to program “well”. Hell, you don’t need a degree to make Facebook, or Microsoft or even Apple. None of them did (most were in college though).</p><p>So where do I think that leaves us in the future? Well, I believe …</p><p>We’ll eventually teach computers more and program less.</p><p>Lest we forget because of our egos:</p><ul><li>Programming is inefficient.</li><li>Programming is error prone.</li><li>Programming is a discipline that most do not have.</li><li>Programming is slow.</li><li>Programming is boring.</li></ul><p>So eventually we’ll build systems much faster because they will build themselves. For better or worse. We’re already on our way there what is up to us is how we handle the future.</p><p>But for the future programming will be less common and plain english (or whatever) language is what we’ll be using.</p><p>&lt;/ Speculation&gt;</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b67bcd782550" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming [2]: Starting with Style]]></title>
            <link>https://medium.com/@andric.libresinn/functional-programming-2-starting-with-style-759a2ac92a19?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/759a2ac92a19</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Fri, 30 Nov 2018 19:50:45 GMT</pubDate>
            <atom:updated>2018-12-01T01:02:06.925Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A6vTunK4Vq1ydwcYf1p9Yw.jpeg" /></figure><p>I think it’s important to consider Functional Programming not just as an actual methodology but potentially as a style. It’s a great way to get started and get others to play with it as well. Think of it as imposing a great deal of limits on yourself and having to overcome those limits. You’ll see yourself grow and adapt to these limits in interesting ways.</p><p>There are three limits I suggest everyone impose on themselves right away.</p><h3>0: Overview</h3><p>I tend to be verbose so I wanted to go over the 3 self imposed limits and benefits/side effects quickly. A TL;DR if you will.</p><p><strong>Rules</strong>: Don’t mutate variables, Functions should be no longer than 5 lines and files should be no taller than 100 lines.</p><p><strong>Side Effects</strong>: Better testable code, more composable code, easier to read code, better named code. You’ll end up composing so much more, less statements and overall you’ll view functions are values instead of simply as executable expressions.</p><p><strong>BUT WHY LIMIT YOURSELF?</strong></p><p>Setting limitations on yourself has a few benefits that come out of it that you may not know.</p><ul><li>Failing faster enables results to display faster.</li><li>You grow because you have to adapt.</li><li>You steer yourself away from bad practices.</li></ul><h3>1: Do not mutate variables.</h3><blockquote>Just. Fucking. Stop. — Andric, on the topic of everything.</blockquote><p>Aren’t applications <strong><em>supposed</em></strong> to be deterministic? Well, not if you go ahead and start mutating state all willy nilly.</p><p>I’ve been in many large code bases. Nothing like, say, Google or Amazon but large enough where a team of 2 people have to maintain, fix and add to it. Around 100K lines of [custom] code.</p><p>There have been very abstract race conditions where I spent days trying to figure out the issue. I had watch Clicktales or take control of a customer’s OS to see an error in action. Hell, I’ve even had direct the customer to a custom server (only they could access) running prod code and data and modify the code live while I ask them to repeat the process.</p><p>Then only to find that the issue was in an obscure function _filterTransform and it’s mutating the object coming in and with all your other business rules you’re just like “Bruh” and go for a very long coffee break.</p><blockquote>If you mutate state or the parameters going into your function you’re breaking the trust of user of your API — Andric, the brilliant author of this piece.</blockquote><p>Do. Not. Mutate. State.</p><p>I swear to god if you mention performance I’m going to talk to your mom and have her ground you for 3 months. No Nintendo for you.</p><h4><strong>Side Effects</strong></h4><p><strong>Your code is forever predictable</strong>. You aren’t modifying objects directly you’re returning a new object. I know that when I’m going to use the isUserActive function it’s a safe operation.</p><pre>// Look at this contrived example. LOOK AT IT!<br>const isUserActive = (userObject) =&gt; {<br>  if (userObject.active) {<br>   user.name += &#39;‰&#39;<br>  }<br>}</pre><pre>const u = {<br> name: &#39;Andric&#39;,<br> active: true,<br>}</pre><pre>isUserActive(u)</pre><pre>// u = {<br>//  name: &#39;Andric‰&#39;,<br>//   active: true,<br>// }<br>//</pre><p><strong>Your code is simply easier to test</strong>. Try testing a function with an embedded random in it</p><pre>// Look at this contrived example. LOOK AT IT!<br>const greeting = () =&gt; {<br>  const date = new Date()<br>  const randNum = rand(1, 14)<br>  const friendlyHello = &#39;Hello good fellow :)&#39;</pre><pre>  if (date === &#39;04/20/69&#39; &amp;&amp; randNum &gt; 7) {<br>    friendlyHello = `HOLLA KID U KNOW WHAT DAY IT IS?!?!?! Fo&#39; 20!`<br>  }</pre><pre>  return friendlyHello<br>}</pre><p>Here we’re modifying friendlyHello but we’re also relying on the Date and rand side effects. Making this inherently more difficult to test and thusly making predictability more difficult. We could DI it (add more params) but now we’ve gotta test for more params as well. We could use Sinon to stub/mock those functions but really, are we getting what we want out of it? I suggest no, no we aren’t.</p><h3>2: Functions can be no taller than 5 lines</h3><p>This is the one that is going to through you for a loop.</p><p>See how cute this is?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PMpZ0AW-RL7qTEyRS4Gjzw.jpeg" /><figcaption>Copyright: <a href="http://mosthdwallpapers.com/">http://mosthdwallpapers.com</a> (found: <a href="https://goo.gl/XMD2k8">https://goo.gl/XMD2k8</a>)</figcaption></figure><p>Compare it to how utterly un-cute this is</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f63hVUm3n3HoalNkUcn4Og.jpeg" /><figcaption>Origin: <a href="https://goo.gl/dthzAH">https://goo.gl/dthzAH</a></figcaption></figure><p>The bigger your function becomes the uglier it is. I mean, that werewolf has a face only a mother could love. But the kind of love where a mother <strong>HAS</strong> to love their offspring but doesn’t really. Why don’t you love me mom? I’ve done so much! HOW MANY MORE TIMES MUST I PLOW THE FIELDS?!</p><p>Here’s the thing. The more logic that you have the more bugs you have. The more you have to know in order to maintain or modify the code. The more you are required to fix, test et al. The more likelihood you’ll add mutations and side effects. The harder it is to read. And worst of all the more bugs you’re going to have.</p><p>Think about having a block of code that is, say, 200 lines tall. It takes 14 parameters. There is string building, number crunching, API calling and DB querying and retrieving from a file. This is a function that is used to change some UI for the user based on permissions, what they’ve purchased and say 10 other business rules. This function is used in many areas of the codebase. Let’s say at minimum 100 instances this code is called.</p><p>Cray cray example right? I’ve seen this in production at past companies. Here’s the thing. That is terrifying to change because now you have 100 different places to test that functionality now. Congrats, you done fucked yourself.</p><p>Imagine if that function was, instead, 5 lines. Would you fear changing it? How different would your tests be? Hoe much more confident in your tests would you be? This partly touches on the idea of abstraction. If we wanted to change this code we could do so easily w/o affecting the overall structure of the application. That is what we want.</p><p>I mused enough let’s talk about the practical.</p><p>Limiting function length is brilliant. You get functions that are much more quickly reasoned. Testability goes through the roof.</p><h4>Side effects</h4><p><strong>Fewer parameters</strong>. I feel like this is enough to mention but fewer parameters is a huge, huge win. The more logic you have is more complex and more likely something is going to break right? Well, by this logic then the more parameters we have the more paths a function is going to take in order to resolve. MEANING that we have to test all those paths PLUS all the data permutations. So the fewer params we have the easier it is.</p><p>I mentioned data permutations of parameters. I’m speaking specifically of JavaScript. Unless you’re using Flow or TypeScript then you’ll have to test against Boolean, Null, Undefined, Number, String, Symbol, Object. Let’s go further. If you have 2 parameters you’ll have to test against those 6 types for both parameters. Keep multiplying for every parameter you add. So keep the parameter list minimal (3 or less) and use a static typing platform as required.</p><p><strong>You’ll rely less on blue keywords</strong>. And by extension you’ll write fewer statements. You don’t realize it yet but you don’t need most of these all that often (when in ES6). You’ll be using import, export, const like crazy but most of your code will be expressions and you won’t bother to use a for loop or a switch statement. You’ll even figure out how to do error logging w/o try/catch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/281/1*TslGuov4hOWt6PyJgf6Y3g.png" /></figure><p>The things that you do require (branching logic, mapping, error handling) will be solved in better ways that do not mutate state and are much shorter.</p><p><strong>returning is much more important</strong>. You’ll put a lot more emphasis on returning stuff.</p><p><strong>Your code doesn’t do more than one thing</strong>. This is mostly because you can’t. You often can’t do more than one thing and if you do (and you inevitably will) then that will be caught must faster in a peer review diff (Pull Request).</p><p><strong>Your naming will change</strong>. You will focus so much less on what your function does but rather what it returns.</p><p><strong>You’ll start to compose more</strong>. And eventually, hopefully at least, you’ll start to curry functions more. Given a world where Haskell Curry didn’t exist and you heard nothing about functional programming you most likely wouldn’t think to curry your functions. You’ll see the benefits of composition first and that is what is important.</p><p>When you view functions as values to be expressed [in the future] you’ll start composing bigger more complex behaviors from smaller blocks of behaviors. Eventually ending in a complex system of interchangeable parts.</p><p>Currying isn’t something that you’ll naturally think to use even over time. But once someone shows you, well, you’ll be all like *<a href="https://media.giphy.com/media/2rqEdFfkMzXmo/giphy.gif">brain explosion gif</a>*. Some 4 smart dudes in a NYC street gang even said</p><blockquote>Favor object <strong>composition over</strong> class <strong>inheritance — Right before beating someone’s ass for their initiation.</strong></blockquote><p>I’ll go into currying and composition in another article because it’s far too big a discussion to limit to this article.</p><h3>3: Files can be no taller than 100 lines</h3><p>What is the average height of one of your files? 50 lines? 200 lines? 2000 lines? 5 thousand lines?!?!</p><p>The major problem with really tall files is that the context of the file dilutes any possible expressiveness you could have had with function and variable names. If you’ve ever thought “Man, naming stuff is hard” it is almost always because your codebase is unorganized and files are huge. What is the context of a variable where you’re 4 callbacks deep into some async function in a file that is 500 lines tall? Exactly, this is why functions become longer, and longer and so on.</p><h4>Side Effects</h4><p>This one is simple and compounds the above limit but boy, your functions become very expressive and you know exactly what they’re supposed to do.</p><h3>Uncle Bob Martin on Twitter</h3><p>The length of a variable name should be proportional to its scope. The length of a function or class name is the inverse.</p><blockquote>The longer the scope of a function, the shorter its name should be. Functions that are called locally from a few nearby places should have long descriptive names, and the longest function names should be given to those functions that are called from just one place. — Uncle Bob, full quote</blockquote><h3>Uncle Bob Martin on Twitter</h3><p>The shorter the scope the shorter the variable names, and the longer the function &amp;amp; class names. And vice versa.</p><p>These two tweets are so important. If your scope is 5 lines of code you could name anything in there x and you won’t lose the context as a reader. The taller the file the more scope you have, the more context that is required to be stored in the reader’s head and now x becomes unmaintainable in that person’s memory and it only makes sense to call it valueFromApiOrFalse.</p><p>Short variable names are okay if the name of the function is descriptive and one or two words in a short file is [often] perfectly expressive. If reading code is supposed to be like reading a book then long variable names is like reading Kant and short is like reading Mark Twain. Be Mark Twain.</p><p>I’ll leave it here to let you get to your next class quicker and so that professor doesn’t nail you with a tardy slip.</p><h3>Risks</h3><p>Everything is now either get or set and you learned nothing. We need to have a talk and you need to reevaluate what you’re doing. I believe in you just not current you.</p><h3>In conclusion</h3><p>This isn’t functional programming but it’s a great step to get started. Don’t look at these rules as written in stone and cannot move away from them.</p><p>Sometimes you need to mutate state but if you do prefix that function with _UNSAFE_ and/or hide it away so it isn’t part of your API (or make a “private” package just for you and hide it even further from your co-workers). Have fun, learn more stuff, better better tomorrow than you are today.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=759a2ac92a19" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A little poem about JS String Literals]]></title>
            <link>https://medium.com/@andric.libresinn/a-little-poem-about-js-string-literals-4546c5ce1e7e?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/4546c5ce1e7e</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Thu, 13 Sep 2018 14:44:17 GMT</pubDate>
            <atom:updated>2018-09-13T14:47:57.183Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/caef8b799a6f5c6dd071de651a8173a3/href">https://medium.com/media/caef8b799a6f5c6dd071de651a8173a3/href</a></iframe><p>Believe it or not we don’t have unlimited RAM. We can only hold so much in our head (and I can only hold very little) so for the sake of me reading your code let’s keep it simple :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4546c5ce1e7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming [1]: Fundamentals]]></title>
            <link>https://medium.com/@andric.libresinn/functional-programming-1-fundamentals-b4d816481690?source=rss-8e6a302b52a6------2</link>
            <guid isPermaLink="false">https://medium.com/p/b4d816481690</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[batman]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[pure-function]]></category>
            <dc:creator><![CDATA[Andric LibreSinn]]></dc:creator>
            <pubDate>Wed, 04 Apr 2018 00:33:59 GMT</pubDate>
            <atom:updated>2018-04-04T00:33:59.300Z</atom:updated>
            <content:encoded><![CDATA[<blockquote>“Simplicity is a great virtue but it requires hard work to achieve it and education to appreciate it. And to make matters worse: complexity sells better.”</blockquote><blockquote>― Edsger W. Dijkstra (On why Java blows, his words not mine³)</blockquote><h3>What is?</h3><p>Functional programming is a new way of thinking about writing code. Think “paradigm shift”. Normally we think of code as “Computer conditional here, memory this, loop that, oh don’t forget to log this guy”. Functional Programming and this new way of thinking is “I need you to get me these objects and they need to go to this address”.</p><p>re: math, math, math</p><p>I’ll get to that later.</p><p>Also, if thinking functionally we are considering how damaging state is to our products. State sucks. State breaks things. State is the #1 reason for programming errors. We should ban state forever and ever. Except when we need it. We’ll worry about that later.</p><p>Oh, and side effects. Screw side effects. She’s a mean mistress that only wants to see us be frustrated and hurt and cry. Side effects do nothing to make you happy as a person and corrodes the soul.</p><p>There is so much jargon too which I’ll quickly dive into, this is just a quick breeze through these new baller-ass concepts I don’t want to spend too much time on any one thing.</p><p>Also, inheritance is just the worst. I’ll be going into these in no particular order and explaining how a functional or behavioral approach benefits us and the soul.</p><p>I also want to touch on the differences between OOP/Imperative and Functional Programming. Not too deep because it isn’t super important but it is something worth nothing and is kind of interesting to think about. In this, our journey of the paradigm shift.</p><p>Also, semi colons are bad.</p><p>I’m kind of assuming anyone reading this either knows or is familiar with JavaScript and ES6. The baller-ist version of JS right now. Until they ruin it with pipeline operator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/441/1*xqTX7vA_yGwj71hB2kogZw.png" /><figcaption><a href="https://www.linkedin.com/pulse/definition-functional-programming-rainer-grimm">https://www.linkedin.com/pulse/definition-functional-programming-rainer-grimm</a></figcaption></figure><h3>Let’s get Jargon out of the way</h3><p>Some beneficial jargon to get out of the way and this is also in no particular order. These definitions aren’t complete but for the purposes of this article they will be enough (Lifted from <a href="https://github.com/hemanth/functional-programming-jargon">here</a>).</p><h4><strong>Arity</strong></h4><p>The number of arguments a function takes</p><pre>const foo = (bar, totes) =&gt; (bar + totes)</pre><h4>Higher-Order Functions (HOF)</h4><p>A function that takes or returns a function (or both, GASP!)</p><h4>Currying</h4><p>A function that will convert a multi-parameter function into one that takes them one at a time. It’s concerned with ARITY@!!!</p><pre>const sum = (a, b) =&gt; (a + b)</pre><pre>const curriedSum = (a) =&gt; (b) =&gt; (a + b)</pre><pre>curriedSum(40)(2)</pre><pre>const add2 = curriedSum(2)</pre><pre>add2(10)</pre><h4>Closures</h4><h3>Josh Burgess 🤔 on Twitter</h3><p>@matzatorski functions that &quot;remember&quot; the enviornment (enclosing scope) they were defined within, maintaining access to vars in that scope</p><p>Access a variable outside of it’s scope. This is how most people build privacy into their variables. Unfortunately though these same people MUTATE THAT STATE LIKE IT’S THEIRS TO MUTATE</p><p>Also, it should be noted, that your functions within a module is also a closure. It’s all closures baby!</p><h4>Function Composition</h4><p>Think PEMDAS. You’re creating functions by interlocking them. You’re putting functions together where the output of one function is the input of another</p><pre>// This function takes two functions, and returns a function <br>// that takes a single param.<br>const composeDizzle = (f, g) =&gt; (<br>  (a) =&gt; (<br>    f(g(a))<br>  )<br>)</pre><pre>// The result of g(a) is passed into f(...).<br>composeDizzle(&#39;here&#39;)</pre><p>Function math dawg.</p><h4>Purity (no side effects!)</h4><p>Any function that always returns the same result given the same parameters.</p><pre>const foo = (a, b) =&gt; (a + b)</pre><ul><li>Always returns something (no void)</li><li>No side effects (API calls, et al)</li><li>[Preferably] Does not mutate state (even local)</li></ul><p>That last bullet is important but not required. We do not mutate state outside of the function or [preferably] within the function. If we need to add.</p><p>And an example that looks like none of the others:</p><pre>// This is the preferred way. We don&#39;t modify the param variable we // just return the result of adding on.<br>const addsOneToParam_GOOD = (param) =&gt; (<br>  param + 1<br>)</pre><pre>// This is bad. We&#39;ve mutated the parameter. We should nont do this // because outside of this function will be using that param. It&#39;s // going to be return changed. It&#39;ll live in that outside world and <br>// it&#39;ll need therapy because you touched it inappropriately.<br>const addsOneToParam_BAD = (param) =&gt; (<br>  param++<br>)</pre><p>Assume all variables are immutable.</p><h4>Side effect</h4><p>A function or expression is said to have a side effect if apart from returning a value, it interacts with or is influenced by external [mutable] state.</p><pre>const foo = (a, b) =&gt; {<br>  const c = getFromAPI(b);<br>  return a + c<br>}</pre><p>Examples: IO, API calls, threading, database query, modifying thewindowobject.</p><h4>Referential Transparency</h4><p>Any expression that can be replaced with it’s value w/o changing behavior. Think pure functions.</p><pre>const getConfig = ({ option: &#39;something&#39;&#39;, })</pre><h4>Functor</h4><p>An object that implements a map function which, while running over each value in the object to produce a new object. It mustn’t change the original object (preserve state) and must be composable.</p><pre>// Doesn&#39;t mutate state.<br>[].map((item) =&gt; (item + 1))</pre><pre>// Can compose<br>[].map((item) =&gt; (item + 1))<br>  .filter((item) =&gt; (item + 1))<br>  .map((item) =&gt; (item + 1))</pre><h3>State: Let’s talk to the meat of functional programming (imo)</h3><blockquote><strong>Shared objects</strong> and <strong>data fixtures</strong> can <strong>cause functions to interfere with each other</strong>. <strong>Threads competing for the same resources can trip each other up</strong>. A program can be reasoned about and outcomes predicted only when data flows freely through pure functions. — Eric Elliot (emphasis mine)</blockquote><p>Have you wondered why the web is stateless? It’s not just because it’s dope as fuck. It’s because state is a problem. If we have problems with state and side effects in single functions and the order of other functions can you imagine the same issues on a website that has distributed resources that load asynchronously? Also, am I the only one that has noticed that STATE is just SATAN re-arranged¹?</p><p>No really. State is a problem for all programmers for all things since the beginning of time and if we don’t stop STATE then we will forever have this looming dark cloud! I hope that was grandiose enough to get the point across.</p><p><strong>Mutable state introduces unpredictability</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*BsASwAOzsP6y05wopPCrPQ.png" /><figcaption>Your code interactions using mutable [global] state²</figcaption></figure><p>If you have two functions and they both mutate the global state then the outcome will always be dependent on the order (imperative) of functions running. While this can work, and we all have made this work, whenever we write tests or upgrade, fix bugs or any hiccup in the system we need to go through all the steps, in the order that we defined to make sure we can track down a bug.</p><p>(There has got to be a better way!) <a href="https://i.imgur.com/nLi8VcX.gif">https://i.imgur.com/nLi8VcX.gif</a></p><h4>React as an Example</h4><p>Okay, let’s take React as an example.</p><p>React has great systems for building UI and even has lifecycle methods for acting upon state. But React is living a double life. It wants to have it’s cake and eat it too. It wants to be functional while double dipping into state and OOP. React has Higher Order Components (HoF), Composition, Stateless components (Pure Functions), unidirectional data flow (reactive programming). But then it’s all like “But I’ll also let you mess with state and side effects like whoa. Oh, and let’s do classes too”. Like, dude, lol, wut? Pick an isle and stay there. Pffft</p><p>When I talk about React and how I structure my React components some people throw a hissy fit because I believe that no only should all the data be unidirectional I believe that React should also be like a complex view layer. The state, the side effects should all be outside of your component. I try to have as few if any containers as possible.</p><p>The best react components are less than 100 lines tall, are stateless and all state management should be handled outside of React with an immutable store. Which, finally, brings me to immutability.</p><h3>Immutability FTW</h3><p>State, variables, all should be immutable.</p><p>Earlier I mentioned <strong>Functors.</strong> Functors are essentially an object that has map attached to it. Taking from Haskell and the great article <a href="https://medium.com/@tzehsiang/javascript-functor-applicative-monads-in-pictures-b567c6415221">Javascript Functor, Applicative, Monads in pictures</a> think of these object’s data as being wrapped.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/160/1*MKaaZDWw5_m5lkX6Te6Hlw.png" /></figure><p>To get that value we apply a function to it. In our case a functor has map associated with it and it looks just like you expect it to look.</p><pre>[].map((item) =&gt; ())</pre><p>It returns a NEW object and does not mutate the existing object.</p><p>Why is this important you ask? You’re smart figure it out while I go onto the next topic.</p><p>But really, it mixes right into what I was just talking about. Immutability. We don’t change the state object but rather we return a new object, new data. Why is this important though?</p><blockquote>Immutability enhances predictability while mutation attempts to erase history.</blockquote><p>There are 5 principals from the <a href="https://medium.com/javascript-scene/the-dao-of-immutability-9f91a70c88cd">Dao of Immutability</a> by Eric Elliott and I think that they are just absolutely excellent. I don’t think I can do them justice if I wanted to so here they are verbatim.</p><blockquote><strong>Immutability</strong>: The true constant is change. Mutation hides change. Hidden change manifests chaos. Therefore, the wise embrace history.</blockquote><blockquote><strong>Separation</strong>: Logic is thought. Effects are action. Therefore the wise think before acting, and act only when the thinking is done.</blockquote><blockquote><strong>Composition</strong>: All things in nature work in harmony. A tree cannot grow without water. A bird cannot fly without air. Therefore the wise mix ingredients together to make their soup taste better</blockquote><blockquote><strong>Conservation</strong>: Time is precious, and effort takes time. Therefore the wise reuse their tools as much as they can. The foolish create special tools for each new creation.</blockquote><blockquote><strong>Flow</strong>: still waters are unsafe to drink. Food left alone will rot. The wise prosper because they let things flow.</blockquote><h3>Let’s Briefly Talk About Pure Functions</h3><p>As stated before there are plenty of benefits.</p><p><a href="https://alvinalexander.com/scala/fp-book/benefits-of-pure-functions">https://alvinalexander.com/scala/fp-book/benefits-of-pure-functions</a></p><blockquote><em>When asked, “What are the advantages of writing in a language without side effects?,” Simon Peyton Jones, co-creator of Haskell, replied, “You only have to reason about values and not about state. If you give a function the same input, it’ll give you the same output, every time. This has implications for reasoning, for compiling, for parallelism.”</em></blockquote><blockquote>From the book, <a href="http://amzn.to/2bedXb4">Masterminds of Programming</a></blockquote><p>Here is a listical of the benefits of pure functions.</p><ul><li>Easier to reason about</li><li>Easier to combine</li><li>Easier to test</li><li>Easier to debug</li><li>Easier to parallelize</li><li>Idempotent</li><li>They offer referential transparency</li><li>They are memoizable!!!</li><li>They can be lazy</li><li>They tend to be smaller (if you’re doing your job right)</li></ul><pre>const addsOneToParam = (param) =&gt; (<br>  param + 1<br>)</pre><p>That function will always return the same number if you give it the same param 1 time for 4 billion times. Since it’ll always return the same output you can memoize (cache) it. It has referential transparency; if the return expression is taken and placed where this function is called it’s the same output.</p><p>They are composeable but also combinable because it’s all about the value that is returned and in turn they are much easier to reason about. Take the following code as an example (any DSL really):</p><pre>const bus = the().wheels().on().the().bus()<br>  .go().round().and().round<br>  .round().and().round<br>  .round().and().round<br>  .the().wheels().on().the().bus()<br>  .go().round().and().round<br>  .all().through().the().town()</pre><h3>OOP v functional</h3><p>There are three main differences between imperative/OOP and functional programming. How state is handled, how you program and how concepts are traditionally modeled.</p><h4>1. How state is handled</h4><p>Hands down the most important thing that the Functional Programming paradigm attempts to solve is the state problem while OOP and Imperative programming embraces the manipulation of state/data. Which is why some people consider imperative programming <strong><em>Programming by side effect.</em></strong></p><p>I’ve already explained my stance on why we do not want side effects, why we want to focus on removing all mutable state from the equation and making all state immutable.</p><p>OOP uses classes, private variables and inheritance to encapsulate state so that it isn’t mutated from the outside world thought it does manage to manipulate it itself. In [pure] functional programming you would use pure functions, recursive looping, Immutability, Currying, High Order Functions and composition to build behaviors while not mutating state.</p><h4>2. Imperative vs declarative</h4><p>How vs What</p><p>Imperative is how you want something done vs declarative is what you want done.</p><p>An imperative approach would be an attendee going to the kiosk and demanding “this and that seat” because they can look into the stadium and see which seat is open.</p><pre>const imperativeLoop = (array) =&gt; {<br>  // Here I&#39;m mutating state.<br>  for (let i = 0; i &lt; array.length; i++) {<br>    // Here I&#39;m mutating the array.<br>    array[i] += 10<br>  }</pre><pre>  return array<br>}</pre><p>A declarative approach would be going to the kiosk and asking for a ticket. Declarative is like a fluid [chained] API.</p><pre>const functionalLoop = (array, fn) =&gt; (<br>  array.map((index) =&gt; (<br>    index += 10<br>  ))<br>)</pre><p>These are both trivial but there are a few huge differences between the two. The first consistently modified the i variable and the array variable. functionalLoop is using a function to iterate over each array item and creating a new array. The cognitive load on the second example is lessened greatly. How can you NOT love that? Impossible and I don’t believe you. It’s the best ever.</p><p>Also, since I’m sure you’re interested, to do functional looping on something that isn’t a functor (re: doesn’t have a .map function) it would be pretty simple.</p><pre>const factorial = (num) =&gt; (<br>  (num === 0 || num === 1)<br>    ? 1<br>    : factorial(num - 1) * num<br>)</pre><h4>3. How concepts are modeled</h4><blockquote>Favor object composition over class inheritance — 4 pretty smart people</blockquote><h4>Inheritance</h4><p>This is a big one and requires lots of rambling. I hope you’re ready.</p><p>Functional programming is concerned with behavior. Not what something does but rather what needs to be done. As described in the last section.</p><p>The main reasons I like FP is because I am worrying about what something DOES not what it IS. When I worry more about what it DOES I focus less on it’s type and what belongs to it. The owner of a junkyard doesn’t care if the dog has a tail and blue eyes but rather if it will protect them from burglars. He cares more about it’s BEHAVIOR and less about what it IS. It has a function to serve and this is the particular object he chose (for whatever reason).</p><p>To begin with FP you don’t need to worry about functional algebraic data types or doing loops via recursion. Care about pure functions, HoF, currying &amp; composition. Then you’ll start using behavioral object composition. It’ll be dope. I promise() (which is a monad btw).</p><h4>The Platypus Problem</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/471/1*R2hXady4__XpuxYzZQ-i_w.png" /><figcaption>A platypus lays eggs, has a duck bill and is a mammal. Everything I know is a lie!</figcaption></figure><p>A platypus has qualities of many different species (at least via looking and observing). It’s sharing functionality between different classifications. Haven’t you seen this before where you’ve had a hierarchy like this and have seen copied functionality and have thusly spent even more work fixing the hierarchy to do what you need? That tree is now more fragile and deployments are slower because everyone wants to test it because now they don’t have trust that you’ll deploy something with relatively few bugs. You want to inspire confidence not fear.</p><h3>So focused on what something IS</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*f9NwyIjqUJ9aPemT6vUCFw.jpeg" /><figcaption>Fun fact. Batman Begins is about Functional Programming</figcaption></figure><p>Above I showcased a foundational problem with hierarchal taxonomies. I find them to be a code smell honestly.</p><p>OOP encourages hierarchical taxonomies. Inheritance is far too concerned about what <strong>IS</strong> whereas we should be concerned more with what something <strong>DOES</strong>. You know when you hear people say “I don’t care what they say I care what they do” or “Actions speak louder than words”. This is the same thing.</p><p>One more example.</p><p>I don’t try to model the “real world” I want to act and manipulate the real world and return something new. A new representation that contains the change. Besides, it’s easier to model the real world using tags than a tree.</p><p>Think platypus.</p><p>Or, think about picture galleries. On our file systems we’re currently bound to what our OS forces us to do. It’s the same in many online or open sourced image galleries. The galleries are, basically, trees. That isn’t how it should work though.<br><br>Let’s say I need to organize 4 pictures. A cactus, a spaceship, a desert and a person. How would we organize that in a tree? At first we’d use a desert and put the cactus and desert into there. Then the spaceship and person would be in an “Organize me later” or “Misc” folder. Essentially a junk drawer.</p><p>It would be a lot easier if I could just tag them and then using the tags I could build the the views, or galleries, and then it’s okay if we have pictures that show up in two galleries or views.</p><p>Imagine you build a generic vehicle object. It takes a passenger and has 4 wheels and the wheels are 2 on either side. You have a bunch of children classes. Caddy, Golf, Big Rigs. Now the business wants to sell roller skates. Well, they take a passenger, they have 4 wheels. I guess we can make that a child of vehicle. What about rollerblades? Skateboards or heelies? Now we need to change all our classifications. WHAT IF THEY WANT TO SELL BOATS!</p><p>You either have to model the entire world and have to think about everything ahead of time or, well, you’re gonna have some interesting builds ahead of you. Slippery slope I know.</p><p>I prefer to model behaviors and then, if I’ve build everything right, and I have because I’m me, then the biggest thing I’ll have to do is either rename or move things around in folders.</p><p>Anyhow, one should not hard-wire non-trivial taxonomies/classification-systems into code. That is what databases are for. And they’re delightful.</p><h3>But how to solve those issues?</h3><p>If our code is pure, idempotent, referentially transparent and composeable then we really have nothing to worry about. I’m not hiding functions so they can be shared across the code base. I care less about what something is rather than what it does</p><p>Let’s take the class of platypus for example. It could look something like this:</p><pre>import hideFn from &#39;/path/to/some/composed/hide/fn&#39;</pre><pre>const platypus = {<br>  name: &#39;Drew&#39;,<br>  swim: () =&gt; (),<br>  sleep: () =&gt; (),<br>  hide: (hideFn) =&gt; (fn()),<br>}</pre><p>So if behavior changes it’s okay, you can put any function in any place and you’ll get the same functionality. Fear not intrepid engineer!</p><h3>Effects</h3><p>“Andric. I’m eventually going to need to write to a database or call an API”. Oh you. You don’t <strong>*NEED*</strong> to but I guess you do want to keep your job. Okay. Let me let you in on a little secret.</p><p>Of-fucking-course you’re going to have to write effects.</p><h4>Use them carefully</h4><p>Do not introduce functions with side effects where one does not expect. There is nothing more frustrating than having running code that passes tests where, at some point in the future, does not work anymore because there was a side effect that had an edge case.</p><h4>Monads Bruv</h4><p>Think of monads as functor * functor.</p><blockquote>Another way of introducing side effects to a pure language is to simulate them using monads. While the language remains pure and referentially transparent, monads can provide implicit state by threading it inside them.</blockquote><blockquote>Allowing side effects only through monads and keeping the language pure makes it possible to have lazy evaluation that does not conflict with the effects of impure code. Even though lazy expressions can be evaluated in any order, the monad structure forces the effects to be executed in the correct order. — Haskell Wiki on <a href="https://wiki.haskell.org/Functional_programming#Purity_and_effects">Functional Programming</a></blockquote><p>In JavaScript every new Promise() is a monad. Coolio.</p><h3>Testing</h3><p>Testing pure functions is pretty cool. When you have properties such as purity, idempotency and the like have property based testing. There is a JavaScript library that handles this and it’s called JSVerify: <a href="http://jsverify.github.io/">http://jsverify.github.io/</a></p><p>Some sample code looks like thus</p><pre>import jsc from &#39;jsverify&#39;</pre><pre>// forall (f : bool -&gt; bool) (b : bool), f (f (f b)) = f(b).<br>var boolFnAppliedThrice =<br>  jsc.forall(&#39;bool -&gt; bool, &#39;bool&#39;, function (f, b) {<br>    return f(f(f(b))) === f(b)<br>  })</pre><pre>jsc.assert(boolFnAppliedThrice)<br>// OK, passed 100 tests</pre><p>I’ll be honest with you. I’ve been working on this article for a talk and I learned about property based testing not too long ago and it has me excited. Unfortunately I cannot get too in-depth with this but as you can see this is just amazeballs.</p><h3>Pitfalls / Cons / Difficulties</h3><ul><li>The cognitive load can be great.</li><li>You need to work at it. It doesn’t come easy. I am still working at it.</li><li>Convincing people is much harder than it should be. Like, seriously, why? JUST TRUST ME!</li></ul><h3>Conclusion</h3><p>I’m not saying to write everything always functionally and as purely functional as possible but being aware of state, how OOP is awful and working towards being better engineers we can do better not just by us but for the projects we work on.</p><blockquote>The opposite of functional is <em>dysfunctional</em>.</blockquote><p>I did this as a talk and <a href="https://docs.google.com/presentation/d/1yygAA3b26Ww0DQroUqPfY6afaIoaOcDF0PzdXbcjreI/edit?usp=sharing">the slides</a> are linked in here.</p><ol><li>That was a joke. Chill.</li><li>Also a joke.</li><li>Yes, you guessed it, this is also a joke. The parens not the actual quote.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b4d816481690" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>