<?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 Ahmad M. Hawwash on Medium]]></title>
        <description><![CDATA[Stories by Ahmad M. Hawwash on Medium]]></description>
        <link>https://medium.com/@ahmad.m.hawwash?source=rss-bcbadf464e5d------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Er0rl07JsR-sYDRRiPJPlQ.png</url>
            <title>Stories by Ahmad M. Hawwash on Medium</title>
            <link>https://medium.com/@ahmad.m.hawwash?source=rss-bcbadf464e5d------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 23:00:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ahmad.m.hawwash/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[Stop Polishing Sinking Ships]]></title>
            <link>https://medium.com/@ahmad.m.hawwash/stop-polishing-sinking-ships-8a8689c38041?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a8689c38041</guid>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[code-review]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[solution-design]]></category>
            <category><![CDATA[engineering-management]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Thu, 22 Jan 2026 10:01:58 GMT</pubDate>
            <atom:updated>2026-01-22T10:01:58.220Z</atom:updated>
            <content:encoded><![CDATA[<h3>Stop Polishing Sinking Ships: Hierarchy of Effective Code Reviews</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mWuopjV0qyJRXw3EebIk2g.png" /></figure><p>We’ve all been there.</p><p>You grab a fresh cup of coffee and open up a Pull Request. You spend 20 minutes diligently reviewing the code. You leave 15 comments: <em>“Fix this indentation,”</em> <em>“Rename this variable,”</em> <em>“Extract this function.”</em></p><p>You feel productive. You reach the final file.</p><p><strong>Then it hits you.</strong></p><p>You realize the entire architectural approach is wrong. The code works, but it duplicates a service that already exists. Or worse, it solves a problem the Product Manager never asked for.</p><p><strong>The Result:</strong> The PR is rejected. The code is deleted. And those 20 minutes you spent reviewing indentation? <strong>Wasted.</strong></p><p>We need to stop reviewing code “flat.” We need to stop polishing the deck chairs on the Titanic. We need a hierarchy.</p><h3>The Code Review Pyramid</h3><p>Think of a PR like building a house. You don’t check the paint color (code style) before you check if the foundation (architecture) is concrete or mud.</p><p>We use a <strong>“Stop-the-Line”</strong> philosophy. The review happens in layers. If a lower layer fails, <strong>we stop immediately</strong>. We do not look at the layers above it.</p><h3>Phase 1: The Strategy (The “Big Stuff”)</h3><p><em>If these layers fail, the code is dead on arrival.</em></p><p><strong>Layer 0: The Context (“What is this?”)</strong></p><ul><li>Does the PR have a description? Is it linked to a ticket? Is it 5,000 lines long?</li><li><strong>The Rule:</strong> If I have to guess what this code is trying to do, I am not reviewing it.</li></ul><p><strong>Layer 1: The Product (“Why?”)</strong></p><ul><li>Does this actually solve the user’s problem? Is this feature even needed?</li><li><strong>The Rule:</strong> Clean code for the wrong feature is still bad code.</li></ul><p><strong>Layer 2: The Architecture &amp; Design (“How?”)</strong></p><ul><li><em>This is where we validate </em><strong><em>Non-Functional Requirements (NFRs)</em></strong><em>. It’s hard to patch these in later.</em></li><li><strong>Scalability:</strong> Will this explode if traffic doubles? (e.g., synchronous blocking calls).</li><li><strong>Modularity:</strong> Are we respecting service boundaries, or creating a distributed monolith?</li><li><strong>Security:</strong> Are we exposing sensitive data?</li><li><strong>The Rule:</strong> Don’t review the syntax of a Microservice that shouldn’t exist.</li></ul><h3>Phase 2: The Tactics (The Implementation)</h3><p><em>Only if the Strategy passes do we look at the code.</em></p><p><strong>Layer 3: Logic &amp; Correctness</strong></p><ul><li><strong>Functional Correctness:</strong> Are there bugs? Off-by-one errors? Unhandled exceptions?</li><li><strong>Performance (NFR):</strong> Are there N+1 query issues? Is the algorithm efficient (Big O)?</li><li><strong>The Rule:</strong> Does the code actually do what it claims to do?</li></ul><p><strong>Layer 4: Observability, Traceability, Operability &amp; Safety</strong></p><ul><li><em>The “Production Readiness” NFRs.</em></li><li><strong>Traceability:</strong> Can we track a request across the system?</li><li><strong>Debuggability:</strong> Where are the logs? If this breaks at 3 AM, will the on-call engineer know why?</li><li><strong>The Rule:</strong> No invisible code allowed.</li></ul><p><strong>Layer 5: The Polish (Code Style)</strong></p><ul><li><em>The “Maintainability” NFR.</em></li><li><strong>Readability:</strong> Is the code simple? Can others understand it without mental gymnastics?</li><li><strong>Conventions:</strong> Naming, formatting, file structure.</li></ul><p><strong>Pro Tip:</strong> Let robots (Linters/Formatters) handle this. Humans are too expensive to act as spellcheckers.</p><h3>Shifting Left: Validating Strategy Before Implementation</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xhD3Z9YwXbLHf8p34DqZKA.png" /></figure><p>Rejecting a PR at <strong>Layer 2 (Architecture)</strong> is painful. The developer has already written the code. They are emotionally attached to it. Telling them to “rewrite it” hurts morale.</p><p><strong>What if we could approve Layers 0, 1, and 2 before a single line of code was written?</strong></p><p>Enter the <strong>Solution Design</strong> (or Tech Spec).</p><p>By spending a brief session at the whiteboard or writing a one-page design doc <em>before</em> coding, we effectively “Shift Left.” We move the high-risk decisions to the start of the process where they are cheap to change.</p><ul><li><strong>Without Solution Design:</strong> The reviewer sees the Architecture for the first time in the PR. <strong>Risk: High.</strong></li><li><strong>With Solution Design:</strong> The Architecture was approved last week. The PR review becomes a simple verification: <em>“Did you follow the plan?”</em></li></ul><p>When you use Solution Design, Layers 0, 1, and 2 vanish from the Code Review. The reviewer can jump straight to finding bugs (Layer 3).</p><h3>The Hidden Value of Solution Design</h3><p>Beyond efficiency, this step solves four critical problems:</p><ol><li><strong>Avoid wasting effort: </strong>Both your effort and your colleagues’ efforts; when there’s a clear shared plan, the execution is even clearer.</li><li><strong>Knowledge Sharing:</strong> It acts as a preliminary step to share your thoughts about a specific problem with the rest of your team — especially for big features.</li><li><strong>Reveal Ambiguities:</strong> If you go straight to implementation, you often rewrite code multiple times to accommodate new findings. Solution Design forces you to find those ambiguities earlier.</li><li><strong>Clearer Plan:</strong> Once you have the full picture of your architecture, you can divide the work among multiple team members and estimate a much clearer delivery timeline.</li></ol><h3>The New Workflow: The “Two-Pass” Method</h3><p>To respect your team’s time, stop trying to find bugs and check architecture simultaneously. Your brain can’t handle it. Use the <strong>Two-Pass Method</strong>:</p><h3>Pass 1: The Scan (5 Minutes Max)</h3><p>Focus: Layers 0, 1, and 2.</p><p>Open the PR. Read the description. Skim the file structure.</p><ul><li><strong>Ask yourself:</strong> <em>“Does this match the Solution Design? Is the approach sound?”</em></li><li><strong>If No:</strong> <strong>STOP.</strong> Request changes immediately. Do not comment on syntax. Do not pass Go.</li><li><strong>If Yes:</strong> Move to Pass 2.</li></ul><h3>Pass 2: The Deep Dive</h3><p>Focus: Layers 3, 4, and 5.</p><p>Now you can read line-by-line. Hunt for bugs. Check the test coverage. Suggest better variable names. You are safe doing this because you know the foundation is solid.</p><h3>The Takeaway</h3><p>Code review isn’t just about finding bugs; it’s about <strong>building a culture of quality. </strong>(ie: knowledge sharing, platform consistency, architectural alignment, long-term maintainability, reducing operational &amp; cognitive burden, reducing regret — technical or product.</p><p>By establishing a hierarchy, we stop wasting time polishing code that is destined for the trash can. By using Solution Design, we align on the “Strategy” early, so the PR review can focus on the “Tactics.”</p><p><strong>Stop the line. Fix the foundation first. Then paint the walls.</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a8689c38041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: Functors]]></title>
            <link>https://medium.com/bitsrc/functional-programming-oh-functors-5e670d8eeb8d?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e670d8eeb8d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Tue, 06 Dec 2022 09:00:53 GMT</pubDate>
            <atom:updated>2022-12-08T11:11:05.602Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming: Part 5 - Functors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*irC_445R71moFtsj" /><figcaption>Photo by <a href="https://unsplash.com/@adolfofelix?utm_source=medium&amp;utm_medium=referral">Adolfo Félix</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In the <a href="https://medium.com/bitsrc/functional-programming-composition-2e9b863d8bcb">previous article</a> in this series we discussed a very useful pattern; Composition and how we can use it to compose bigger systems out of smaller granular units. In this article we’ll be talking about Functors!</p><h4>Table of content</h4><ul><li>Functors</li><li>A Problem</li><li>The Maybe Functor</li><li>Solving The Problem Using Maybe Functor</li><li>Functors Laws</li><li>Why To Use Functors?</li><li>Why Don’t We See More Functors In Our Codebases?</li><li>Quick Note</li><li>Conclusion</li></ul><h3>Functors</h3><p>(Note: we are talking about <strong>functors,</strong> not functions)</p><h4>What is a Functor?</h4><p>A<strong> </strong>functor is just a</p><ol><li>Wrapper over a value</li><li>That gives us a mapping interface</li><li>And obeys the functor’s laws (we’ll talk about them later)</li></ol><h4>Examples on functors we use daily</h4><ol><li>Array</li><li>Promise</li></ol><h4>Yes Array and Promise are functors, but how?</h4><p>Let’s reflect on the functor definition…</p><p><strong>Array is a:</strong></p><ol><li>Wrapper over a <strong>list of items</strong></li><li>That gives us <strong>map as a mapping interface</strong></li><li>And obeys the functor’s laws</li></ol><p>Example:</p><pre>[1, 2, 3]   // the wrapped value<br>.map        // the mapping interface<br>(x =&gt; x * 2)</pre><p><strong>Promise is a:</strong></p><ol><li>Wrapper over <strong>any JS data type value</strong></li><li>That gives us <strong>then<em> </em>as<em> </em>a mapping interface</strong></li><li>And obeys the functor’s laws</li></ol><p>Example:</p><pre>const promise = new Promise((resolve, reject) =&gt; {<br>  resolve(<br>    { data: &quot;Any JS type&quot; } // the wrapped value<br>  ) <br>});<br><br>promise<br>.then                       // the mapping interface<br>(response =&gt; console.log(response));</pre><h4>What’s the relationship between the Array (and Promise) and the Functor?</h4><p>A Functor is a design pattern, while Array and Promise are data types.</p><h4>Why am I telling you that Array and Promise are Functors?</h4><p>To shutdown the fear of the idea of functors.</p><p>They are easy to understand, yet they have a powerful concept. And we use them daily without consciously knowing!</p><h4>Why to use functors?</h4><p>Great question! Please follow along…</p><h3>A Problem</h3><p>After talking a bit about functors and connecting them with our daily use, it’d be wise to dig deeper and build our own. In order to understand more the idea of a functor.</p><p>Let’s face a problem first…</p><p>Take a look at this piece of data</p><pre>{<br>  products: [<br>    {<br>      name: &#39;building stuff&#39;,<br>      type: &#39;book&#39;,<br>      price: 22, <br>      discount: 20<br>    },<br>  ]<br>}</pre><h4>Our task</h4><p>To find the final price of the first product with discount. While if for any reason we encounter bad data, the fallback should be &quot;Nothing” as string.</p><h4>Algorithmic steps</h4><ol><li>Find first discounted product</li><li>Apply discount</li><li>Keep checking for data invalidity. Where if data is invalid for any reason, we return “Nothing” as a fallback</li></ol><h4>First try (the traditional way)</h4><pre>const isProductWithDiscount  = product  =&gt; !isNaN(product.discount)<br>const findFirstDiscounted    = products =&gt; products.find(isProductWithDiscount)<br>const calcPriceAfterDiscount = product  =&gt; product.price - product.discount;<br><br>const findFinalPrice = (data, fallbackValue) =&gt; {<br>  if(!data || !data.products) return fallbackValue;<br><br>  const discountedProd = findFirstDiscounted(data.products);<br>  if(!discountedProd) return fallbackValue;<br><br>  return calcPriceAfterDiscount(discountedProd);<br>}<br><br>findFinalPrice(data, &quot;Nothing&quot;) // 2</pre><h4>Notes on our first try</h4><p><strong>The good things:</strong></p><ol><li>Granular logical units (isProductWithDiscount, findFirstDiscounted and calcPriceAfterDiscount)</li><li>We defended our logic against data invalidity</li></ol><p><strong>Things we can improve:</strong></p><ol><li>We’re defending too much. (<a href="https://en.wikipedia.org/wiki/Defensive_programming">Defensive programming</a> is a must in any resilient software, but too much is too much. In our code, 50% of findFinalPrice function’s body is checking for data invalidity, which is considered too much defence)</li><li>fallbackValue is almost everywhere</li></ol><p><strong>Why are we concerned about these improvements? </strong>Because they are mentally consuming maintainers. Thus directly impacting DX (<em>Developer Experience</em>) negatively.</p><h4>So there’s still room for improvements, right?</h4><p>Let’s analyse the code and try to come up with a solution…</p><p><strong>Code structure analysis:</strong> The parts we aim to improve are forming a pattern (defence and fallback) and they are actually intact and atomic! And that’s good!</p><p><strong>Solution <em>(Taking in mind analysis above)</em>:</strong> We should be able to abstract that pattern into a wrapper that could handle these corner cases for us.</p><p><strong>Result: </strong>The wrapper will take care of the corner cases. While we’ll only have to take care of the business logic!</p><p>If we’re able to implement this, that’d be great indeed!</p><h3>The Maybe Functor</h3><blockquote>Reminder: A functor is just a wrapper over a value and gives us a mapping interface (i.e. <em>map</em>) and obeys some laws.</blockquote><p>As we discussed earlier. We only want a wrapper that abstracts away handling data (either bad or good).</p><p>So, the role of Maybe functor, is to wrap our data (potentially bad data), and handle the corner cases for us. How is that? Follow along…</p><p><strong>Maybe Functor Implementation</strong></p><pre>function Maybe(value) {<br>  const isNothing = () =&gt; value === null || value === undefined;<br>  const map = (fn) =&gt; isNothing() ? Maybe() : Maybe(fn(value));<br>  const getValueOrFallback = <br>    (fallbackValue) =&gt; isNothing() ? fallbackValue : value;<br><br>  return {<br>    map,<br>    getValueOrFallback,<br>  };<br>}</pre><p><strong>Implementation explanation:</strong></p><ol><li>isNothing: checks if the wrapped value in Maybe functor is invalid.</li><li>map: the mapping interface to our value wrapper, where we use this to apply our business logic lambdas to the wrapped value. <em>(Note: that </em><em>map returns new value in another </em><em>Maybe instance, so we can keep doing </em><em>.map().map().map…)</em></li><li>getValueOrFallback: returns the wrapped value or fallbacks to fallbackValue.</li></ol><p><strong>Let’s use </strong><strong>Maybe:</strong></p><ul><li><strong>With good data:</strong></li></ul><pre>Maybe(&#39;Ahmad&#39;)<br>  .map(x =&gt; x.substring(1))<br>  .getValueOrFallback(&#39;fallback&#39;) // &#39;hmad&#39;</pre><ul><li><strong>With bad data:</strong></li></ul><pre>Maybe(null)<br>  .map(x =&gt; x.substring(1))       // will not be executed<br>  .getValueOrFallback(&#39;fallback&#39;) // &#39;fallback&#39;</pre><p>Sounds good so far! Maybe functor cared for the corner cases for us! And “aborted” execution when data was invalid. While we only cared for business logic!</p><p>It looks like we achieved our goal! Let’s put it to work…</p><h4>Solving the previous problem using Maybe functor</h4><p>Ok, let’s try to solve the products problem using Maybe functor</p><pre>const isProductWithDiscount  = product  =&gt; !isNaN(product.discount)<br>const findFirstDiscounted    = products =&gt; products.find(isProductWithDiscount)<br>const calcPriceAfterDiscount = product  =&gt; product.price - product.discount;<br><br>Maybe(data)<br>  .map((x) =&gt; x.products)<br>  .map(findFirstDiscounted)<br>  .map(calcPriceAfterDiscount)<br>  .getValueOrFallback(&#39;Nothing&#39;) // 2</pre><p><strong>We were able to improve the previous code using </strong><strong>Maybe functor, where</strong></p><ol><li>We no more defend the code ourselves, but the Maybe functor does that for us.</li><li>We configured the fallbackValue only once.</li></ol><h4>Reflecting Maybe functor on functor’s definition</h4><p>Maybe functor is just a</p><ol><li>Wrapper over <strong>any JS data type value</strong></li><li>That gives us <strong>map<em> </em>as<em> </em>a mapping interface</strong></li><li>And obeys the functor’s laws</li></ol><h3>Functors Laws</h3><ul><li><strong>Identity law</strong></li></ul><p>When performing the mapping operation, if the values in the functor are mapped to themselves, the result will be an unmodified functor.</p><p>Example:</p><pre>const w1 = Maybe(value)<br>const w2 = Maybe(value).map(v =&gt; v)<br>// w1 and w2 are equivalent</pre><ul><li><strong>Composition</strong></li></ul><p>If two sequential mapping operations are performed one after the other using two functions, the result should be the same as a single mapping operation with one function that is equivalent to applying the first function to the result of the second.</p><p>Example:</p><pre>const w1 = Maybe(value).map(v =&gt; f(g(v))) <br>const w2 = Maybe(value).map(v =&gt; g(v)).map(v =&gt; f(v))<br>// w1 and w2 are equivalent</pre><h3>Why To Use Functors?</h3><ol><li>**Abstraction of function application</li><li>Empowering <a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">functional composition</a></li><li>Reducing amount of defensive code (in case if we used Maybe functor)</li><li>Cleaner code structure (Did you notice how linear the logic is now? Amazing!)</li><li>Variables are more explicit about what we expect (That Maybe <em>models a value that may or may not be present. That it models a “value” or “nothing”</em>)</li></ol><h4><strong>**What do we mean by “Abstraction of function application”?</strong></h4><p>That we pass a transformer function (i.e. x =&gt; x.products) to the mapping interface (i.e. map) of the wrapper (i.e. Maybe) and it knows how to take care of itself (by its internal implementation).</p><p>We don’t care about the wrapper’s implementation details it has inside (implementation details are hidden), and yet we know how to use the wrapper (Array or Promise) by using their mapping interfaces.</p><p>And that’s actually crucially important in the programming world. Where that lowers the bar on how much we -as programmers- need to understand in order to be able to get stuff done. They can be implemented in any language that supports higher-order functions (which is most of them these days). And that creates a language-agnostic vocabulary.</p><h3>Why Don’t We See More Functors In Our Codebases?</h3><p>Simply, because we’re not used to. Before .map (and .then) we were used to mutate arrays or loop through them manually. But once we discovered .map we started adapting it as the new transformation tool! I hope after understanding the value of functors, we start introducing them more into our daily coding routines as a very usual thing!</p><h3>Quick Note</h3><p>Maybe functor is just an example on functors. It’s not the only functor we have, there are more functors out there and for different purposes. We talked about the simplest here (The Maybe functor), so we can get a bit closer to the idea of functors!</p><h3>Conclusion</h3><p>Functor design pattern is a simple — yet very powerful pattern. We use it daily in different data types without knowing. Hopefully, we can recognise and appreciate functors a bit more and give them more space in our codebase, because they’ll clean code and give us more power; Due to the composability nature they have and abstractions they offer.</p><p>At the end, a functor is just a wrapper over a value that gives us a mapping interface, and obeys some laws.</p><p><em>Thanks a lot for taking time reading through this article</em> ❤️ <em>I’m cooking the next ones in the series. Please let me know what you think in the comments about this article or the series.</em></p><h3>This is an article in a series of articles talking about Functional Programming</h3><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h3>This series discusses:</h3><p>0. <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">A Brief Comparison Between Programming Paradigms</a></p><ol><li><a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">First Class functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-2-pure-functions-85491f3d7190">Pure functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Currying</a></li><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">Composition</a></li><li><em>Functors (this article)</em></li><li>Monads</li></ol><h4>Resources</h4><ol><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb</a></li><li><a href="https://wiki.haskell.org/Functor#:~:text=Functor%20Laws,-Functors%20must%20preserve&amp;text=If%20two%20sequential%20mapping%20operations,the%20result%20of%20the%20second">https://wiki.haskell.org/Functor</a></li><li><a href="https://marmelab.com/blog/2018/09/26/functional-programming-3-functor-redone.html">https://marmelab.com/blog/2018/09/26/functional-programming-3-functor-redone.html</a></li><li><a href="https://medium.com/swlh/beyond-monad-the-applicative-interface-9685d233c1b3">https://medium.com/swlh/beyond-monad-the-applicative-interface-9685d233c1b3</a></li><li><a href="https://jrsinclair.com/articles/2016/marvellously-mysterious-javascript-maybe-monad/">https://jrsinclair.com/articles/2016/marvellously-mysterious-javascript-maybe-monad/</a></li><li><a href="https://blog.ploeh.dk/2018/03/26/the-maybe-functor/">https://blog.ploeh.dk/2018/03/26/the-maybe-functor/</a></li><li><a href="https://jrsinclair.com/articles/2018/how-to-deal-with-dirty-side-effects-in-your-pure-functional-javascript/">https://jrsinclair.com/articles/2018/how-to-deal-with-dirty-side-effects-in-your-pure-functional-javascript/</a></li><li><a href="https://stackoverflow.com/questions/74332025/what-does-abstraction-of-function-application-mean/">https://stackoverflow.com/questions/74332025/what-does-abstraction-of-function-application-mean/</a></li><li><a href="https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch08">https://mostly-adequate.gitbook.io/mostly-adequate-guide/ch08</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e670d8eeb8d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-oh-functors-5e670d8eeb8d">Functional Programming: Functors</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: Composition]]></title>
            <link>https://medium.com/bitsrc/functional-programming-composition-2e9b863d8bcb?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/2e9b863d8bcb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Mon, 13 Jun 2022 06:56:07 GMT</pubDate>
            <atom:updated>2025-03-06T08:21:36.822Z</atom:updated>
            <content:encoded><![CDATA[<h3><strong>Functional Programming (Part 4): Functional composition</strong></h3><p>Where fun meets productivity!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y1vX-CH5ccrlMH5B565AJg.jpeg" /><figcaption>Photo by Tim Mossholder at <a href="https://www.pexels.com/photo/a-clean-automotive-engine-3076820/">Pexels</a></figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In the <a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">previous article</a> in this series we discussed a very useful pattern; Currying and how we can use it, where we also utilised it to apply separation of concerns very elegantly. In this article we’ll be talking about Composition.</p><h3>Table of contents</h3><ul><li>What is Functional Composition</li><li>How composition works</li><li>compose vs pipe</li><li>Examples</li><li>Why Composition</li><li>Conclusion</li></ul><h3><strong>What is </strong>Functional <strong>Composition</strong></h3><p>Composition is the process of <strong>composing</strong> small units into bigger units that solve bigger problems. Where Input of one function comes from the output of previous one.</p><p>For example, if we want to build a castle 🏰 we’ll have to compose bricks 🧱</p><figure><a href="https://bit.cloud/"><img alt="Build in AI speed — Compose enterprise-grade applications, features, and components" src="https://cdn-images-1.medium.com/max/1024/1*yX0vq3scSudyT61IuWFuEg.png" /></a><figcaption>Build in AI speed — Compose enterprise-grade applications, features, and components</figcaption></figure><h3>How Composition Works</h3><p>As the definition states</p><blockquote>“<em>Input of one function comes from the output of another function”.</em></blockquote><p>If we build this mathematical function (f ∘ g)(x) = f(g(x)), which composes 2 small functions, it’ll look like this:</p><pre>const compose = (f, g) =&gt; (x) =&gt; f(g(x))</pre><p>The compose function composes f and g where the output of g will be forwarded as input of f.</p><p>Let’s give it a try:</p><pre>const getAge       = (user) =&gt; user.age<br>const isAllowedAge = (age)  =&gt; age &gt;= 30</pre><p>We have getAge and isAllowed small functions. Let’s compose them:</p><pre>const user = { name: &#39;John&#39;, age: 35 }<br>const isAllowedUser = compose(<br>  isAllowedAge, <br>  getAge<br>)<br>isAllowedUser(user) // true</pre><p><em>Note:</em> compose flows from <em>bottom to top (right to left). </em>We pass user to the composite isAllowedUser, then user goes through getAge first, then the output goes to isAllowedAge.</p><h3>Compose vs Pipe</h3><p>pipe is very similar to compose, they have the same purpose. Both are here to chain functions, however they have different implementations and workflows.</p><h4>Implementation</h4><p>compose is implemented like this:</p><pre>const compose = <br>  (...fns) =&gt; <br>    (x) =&gt; fns.reduceRight((acc, fn) =&gt; fn(acc), x)</pre><p>pipe is implemented like this:</p><pre>const pipe = <br>  (...fns) =&gt; <br>    (x) =&gt; fns.reduce((acc, fn) =&gt; fn(acc), x)</pre><p>Where the only difference here is reduce instead of reduceRight. Which only affects the flow of the data…</p><h4>Flow</h4><p>compose‘s flow is from <em>bottom to top ↑(right to left ←).</em></p><p>pipe‘s flow is from <em>top to bottom ↓ </em>(<em>left to right →)</em></p><h4>Example</h4><p>Let’s say that we have 3 functions, f, g and h</p><p>If we use compose:</p><pre>compose(f, g, h)<br>        <strong>←  ←  ←</strong></pre><p>The <em>evaluation order</em> will go <strong>h, </strong><strong>g then </strong><strong>f (<em>right to left</em>), </strong>and each output is forwarded to the next function.</p><p>If we use pipe:</p><pre>pipe(f, g, h)<br>     <strong>→  →  →</strong></pre><p>The <em>evaluation order</em> will go <strong>f, </strong><strong>g then </strong><strong>h (<em>left to right</em>),</strong> and each output is forwarded to the next function.</p><h4>Which should you use?</h4><p>They don’t differ much. Both will solve the same problem.</p><p>But just to highlight the difference. compose is just closer to the mathematical notation of (f ∘ g)(x) = f(g(x)), where pipe is often easier to read in evaluation order.</p><p>So personally, I prefer pipe because it is more natural.</p><h3>Examples:</h3><p>Note: as a personal preference <strong>I’ll be using </strong><strong>pipe </strong>in the examples.</p><p>Let’s say we need to build a simple price calculator, where we can apply:</p><ol><li>Discount</li><li>Coupon</li><li>Tax (default = 30%)</li><li>Service fees (default = 10)</li><li>Weight-based shipping cost</li></ol><p>Let’s first design the API of the price calculator based on the given requirements</p><pre>const priceCalculator = (<br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount, <br>  percentCoupon, <br>  valueCoupon,<br>  weight, <br>  $PerKg<br>) =&gt; {<br>  /*logic*/<br>}</pre><p>We defaulted tax to 30% and serviceFees to 10$. Waiting for the rest of the params</p><h4>The bad way (non compositional)</h4><p>Let’s build it as an atomic mathematical equation:</p><pre>const priceCalculator = (<br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount, <br>  percentCoupon, <br>  valueCoupon,<br>  weight, <br>  $PerKg<br>) =&gt; {<br>  <strong>return (<br>    price<br>    - (price * percentCoupon) <br>    - discount <br>    - couponValue <br>    + (weight * $PerKg) <br>    + serviceFees<br>  ) * (1 + taxPercentage)</strong><br>}</pre><p>It does the job. <strong>But</strong> <strong>it has very poor reading, testing, debugging and maintenance experiences.</strong></p><h4>Let’s do it the good way (composition approach)</h4><p>Let’s compose…</p><pre>const priceCalculator = (<br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount, <br>  percentCoupon, <br>  valueCoupon,<br>  weight, <br>  $PerKg<br>) =&gt; {<br>  <strong>const applyTax           = (val) =&gt; val * (1 + taxPercentage)<br>  const applyServiceFees   = (val) =&gt; val + serviceFees<br>  const applyPercentCoupon = (val) =&gt; val - val * percentCoupon<br>  const applyValueCoupon   = (val) =&gt; val - valueCoupon<br>  const applyDiscount      = (val) =&gt; val - discount<br>  const applyShippingCost  = (val) =&gt; val + weight * $PerKg</strong></pre><pre><strong>return pipe(<br>    applyPercentCoupon,<br>    applyDiscount,<br>    applyValueCoupon,<br>    applyShippingCost,<br>    applyServiceFees,<br>    applyTax<br>  )(price)</strong><br>}</pre><p>This looks so much cleaner, more testable, debuggable and maintainable. All due to the modular mindset we’re adapting to.</p><p>We split each operation to be living on its own, then we pipe them and apply price to the piped functions.</p><h4><strong>Give it a try</strong></h4><pre>priceCalculator(10) // NaN</pre><p>We got a NaN and that’s unexpected, right?! How can we fix this?</p><h4>Let’s debug first</h4><p>Let me introduce a very useful utility to debug chains (pipe and compose); inspect function. It’s very simple. It only logs what it gets, and returns it.</p><pre>const inspect = (tag) =&gt; (x) =&gt; {<br>  console.log(`${tag}: ${x}`)<br>  return x<br>}</pre><p>Now let’s add that to our chain of functions</p><pre>const priceCalculator = (<br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount, <br>  percentCoupon, <br>  valueCoupon,<br>  weight, <br>  $PerKg<br>) =&gt; {<br>  const applyTax           = (val) =&gt; val * (1 + taxPercentage)<br>  const applyServiceFees   = (val) =&gt; val + serviceFees<br>  const applyPercentCoupon = (val) =&gt; val - val * percentCoupon<br>  const applyValueCoupon     = (val) =&gt; val - valueCoupon<br>  const applyDiscount        = (val) =&gt; val - discount<br>  const applyShippingCost    = (val) =&gt; val + weight * $PerKg</pre><pre>return pipe(<br><strong>    </strong><strong>inspect(&#39;price&#39;),</strong><br>    applyPercentCoupon,<br><strong>    </strong><strong>inspect(&#39;after applyPercentCoupon&#39;),</strong><br>    applyDiscount,<br><strong>    </strong><strong>inspect(&#39;after applyDiscount&#39;),</strong><br>    applyValueCoupon,<br><strong>    </strong><strong>inspect(&#39;after applyValueCoupon&#39;),</strong><br>    applyShippingCost,<br><strong>    </strong><strong>inspect(&#39;after applyShippingCost&#39;),</strong><br>    applyServiceFees,<br><strong>    </strong><strong>inspect(&#39;after applyServiceFees&#39;),</strong><br>    applyTax<br>  )(price)<br>}</pre><p>The results would look something like</p><pre>priceCalculator(10)<br><strong>// price: undefined</strong><br>// after applyPercentCoupon: NaN<br>//...</pre><p>Oh! The price is undefined, haha that’s because the price is the 3rd parameter, and we’re passing it first instead!</p><h4>Let’s fix it very quickly</h4><p>I’ll just let it accept a single object {} instead of multiple, like:</p><pre>const priceCalculator = (<strong>{</strong><br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount, <br>  percentCoupon, <br>  valueCoupon,<br>  weight, <br>  $PerKg<br><strong>}</strong>) =&gt; {...}</pre><p>And we use it like this</p><pre>priceCalculator({ price: 10 })<br>// price: 10<br><strong>// after applyPercentCoupon: NaN<br></strong>//...</pre><p>We still get NaN, but this time for a different reason. Because percentCoupon is being used while it’s undefined too.</p><p>So let’s fix it by defaulting all parameters (except price)</p><pre>const priceCalculator = (<strong>{</strong><br>  taxPercentage = 0.3, <br>  serviceFees = 10, <br>  price, <br>  discount = 0, <br>  percentCoupon = 0, <br>  valueCoupon = 0,<br>  weight = 0, <br>  $PerKg = 0<br><strong>}</strong>) =&gt; {...}</pre><p>So now if we use it again, we’ll get a result…</p><pre>priceCalculator({ price: 10 }) // 26</pre><p>That’s how composition allows us to test and fix our code easier and quicker, just by inspecting the areas of the pipeline that we suspect.</p><h4>In Real Life</h4><p>The problem we debugged was very simple (for a reason). When we go on bigger scale modules, things go nastier quickly and harder to inspect when we use big <strong>atomic </strong>functions. <strong>Splitting</strong> functions into smaller ones makes them easier to debug, test, maintain, and develop functions.</p><h3>Why Composition</h3><p><strong>Composition</strong> is about composing smaller <strong>modules</strong> into bigger ones. Where we think in a <strong>modular </strong>way (that’s enforced by composition), we’ll enhance:</p><ol><li><strong>Modularity mindset</strong></li><li><strong>Testability</strong></li><li><strong>Debuggability</strong></li><li><strong>Maintainability</strong></li></ol><h3><strong>Conclusion</strong></h3><p>Composition is a way of building big modules out of smaller ones, it makes our code more modular. Thus it’s easier to debug, test, maintain, reuse and even more fun to develop functions. Instead of the old way of jamming all the code into one single area.</p><p><em>Thanks a lot for taking time reading through this article</em> ❤️ <em>I’m cooking the next ones in the series. Please let me know what you think in the comments about this article or the series.</em></p><h3>This is an article in a series of articles talking about Functional Programming</h3><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h3>This series discusses:</h3><p>0. <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">A Brief Comparison Between Programming Paradigms</a></p><ol><li><a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">First Class functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-2-pure-functions-85491f3d7190">Pure functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Currying</a></li><li><em>Composition (this article)</em></li><li>Functors</li><li>Monads</li></ol><h3>References:</h3><ol><li><a href="https://github.com/ramda/ramda/issues/1642">https://github.com/ramda/ramda/issues/1642</a></li><li><a href="https://en.wikipedia.org/wiki/Function_composition_(computer_science)#JavaScript">https://en.wikipedia.org/wiki/Function_composition_(computer_science)#JavaScript</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2e9b863d8bcb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-composition-2e9b863d8bcb">Functional Programming: Composition</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: The Power of Currying]]></title>
            <link>https://medium.com/bitsrc/functional-programming-part-3-the-powers-of-currying-213eb69b234b?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/213eb69b234b</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Mon, 04 Apr 2022 07:31:30 GMT</pubDate>
            <atom:updated>2022-12-02T22:28:48.264Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming (Part 3): The Power of Currying</h3><h4>Separation of Concerns Principle Using Currying!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*prZpCMP_M2TJS7CfjpjVhA.jpeg" /><figcaption>Photo by Engin Akyurt at <a href="https://www.pexels.com/photo/assorted-color-herbs-3368291/">Pexels</a></figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In the <a href="https://blog.bitsrc.io/functional-programming-part-2-pure-functions-85491f3d7190">previous article</a> in this series we discussed a core and fundamental part of any function in any functional language; Pure functions and its characteristics. In this article we’ll be talking about Currying.</p><h3><strong>Table of contents</strong></h3><ul><li>What is Currying</li><li>How currying works</li><li>Why currying</li><li>Why currying makes our code better</li><li>Closure and Currying Relationship</li><li>More Examples</li><li>Conclusion</li></ul><h3><strong>What is Currying</strong></h3><p>A curried function <strong>is a function that keeps returning functions until all its params are fulfilled</strong></p><h3>How Currying Works</h3><p>Let’s say we have add function</p><pre><strong>const</strong> add = (a, b) =&gt; a + b</pre><p>The simplest implementation of currying is to make a function return a function and so on, like:</p><pre><strong>const </strong>add = (a) =&gt; (b) =&gt; a + b</pre><p>Where that can be used like this:</p><pre><strong>const</strong> addOne = add(1) // addOne = (b) =&gt; <strong>1</strong> + b</pre><p>But let’s imagine that we have a curry function that takes the function and curry it. For example:</p><pre><strong>const</strong> add = curry((a, b) =&gt; a + b)</pre><p>As we see, curry is a function that takes another function to lazi-fy the params. So now we can invoke it like this:</p><pre><strong>const</strong> addOne = add(1) // addOne = (b) =&gt; 1 + b</pre><p>So, first we created addOne by passing 1 as a first param (a) to the curried add function. Which yielded another function that waits for the rest of the params, where<strong> the logic of </strong><strong>add will not be executed until all params are provided.</strong></p><pre>addOne(2) // 3</pre><p>Now, passing 2 (as b) to addOne; executes the logic 1 + 2</p><p><strong>Quick conclusion:</strong></p><p>curry function takes a function and makes its params lazy, in other words you provide these params as you need/go. Just like addOne</p><p><strong>Quick note:</strong></p><p>You still can call the curried version of add function like this:</p><pre><strong>const</strong> three = add(1, 2)</pre><p>So it either takes the arguments piece by piece or all the arguments at once.</p><h3><strong>Why Currying</strong></h3><p>Currying will make our code:</p><ol><li>Cleaner</li><li>Less repetitive params passing and less verbose code</li><li>More composable</li><li>More reusable</li></ol><h3>Why Currying Makes our Code Better</h3><h4>Mainly, some functions take “config” data as input</h4><p>If we have functions that take “config” params, we better curry them because these “configs” will probably be repeated over and over again.</p><p>For example, let’s suppose we have a translator function, that takes a locale and a text to be translated:</p><pre><strong>const</strong> translator = (locale, text) =&gt; {/*translation*/}</pre><p>The usage would look like this:</p><pre>translator(&#39;fr&#39;, &#39;Hello&#39;)<br>translator(&#39;fr&#39;, &#39;Goodbye&#39;)<br>translator(&#39;fr&#39;, &#39;How are you?&#39;)</pre><p>Every time we call translator we <strong><em>should provide</em></strong> locale and text. Which is redundant and dirty to provide the locale on every call.</p><p>But instead, let’s curry translator like this:</p><pre><strong>const</strong> translator = curry((locale, text) =&gt; {/*translation*/})</pre><pre><strong>const</strong> inFrench = translator(&#39;fr&#39;) </pre><p>Now inFrench <strong>has</strong> fr as locale provided to the <em>curried</em> translator function and <strong>waits</strong> for text to be provided. We can use it like this:</p><pre>inFrench(&#39;Hello&#39;)<br>inFrench(&#39;Goodbye&#39;)<br>inFrench(&#39;How are you?&#39;)</pre><p>Currying did us a great favour indeed, we don’t need to specify the locale each time, instead the curried inFrench <strong>has</strong> locale due to currying.</p><p>After currying -in this specific example. Code is:</p><ol><li>Cleaner</li><li>Less verbose and less redundant</li></ol><p><strong>Because we separated “config” from actual “data”. Which is quite handy in many areas and use cases.</strong></p><h4>In real life</h4><p>In practice we have dynamic locale (each user has a different language) might be fr, en, de or anything. So instead we better rename inFrench to translate, where translate can be loaded with any locale.</p><p>Now we have translator that takes a locale as “config” and text as data. Due to the fact that translator is curried, <strong><em>we were able to separate “config” from “data” params.</em></strong></p><h4>Why separate “config” from “data” params?</h4><p>Many components and functions need the use of some functionalities (translate in our case) but <strong><em>shouldn’t or can’t</em></strong> <strong><em>know</em></strong> <strong><em>about the “config” part </em></strong>(locale). Where these components or functions <strong><em>have the “data” only part </em></strong>(text). <strong><em>So these functions will be able to use that function without the need of knowing about the “config” part.</em></strong></p><p>Thus, that component or function will be less coupled with the system, which will make the components more composable and more maintainable.</p><h4>When do we apply this idea</h4><p>When we know that there is “config” and there is “data” in a function, we better curry it.</p><p>Currying will give us the ability to <strong><em>separate</em></strong> them. And that is a sign of a mature system design. Because one of the large pillars of code qualities is <strong><em>separation of concerns</em></strong>.</p><p><strong><em>Even if a function needs all the params to operate well, we still know better when to pass the params and on which layer of that app.</em></strong></p><h3>Closure and Currying Relationship</h3><p><strong>A Closure:</strong> <em>is a function returned by a “parent” function and has access to the parent function’s internal state</em>. (described earlier <a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb#:~:text=Exactly%20like%20makeCounter).-,2.%20Closures,-A%20closure%20is">here</a>)</p><p><strong>Currying:</strong> <em>will always result a closure</em>. Because each function returned by a curried function will be provided with parents’ internal state.</p><h3><strong>More Examples</strong></h3><h4>Before we dive deeper</h4><p>Let’s introduce some utilities, so we can have a deeper look.</p><p>Array prototype has utilities like filter, map and others. But they are not curry-able, because they use dot (.) notation.</p><p>So let’s convert them to curry-able format:</p><pre>const filter     = <strong>(fn, list)   =&gt; list.filter(fn)</strong><br>const map        = <strong>(fn, list)   =&gt; list.map(fn)</strong><br>const startsWith = <strong>(starter, s) =&gt; s.startsWith(starter)</strong></pre><p>Now we can use them like this:</p><pre><strong>const </strong>lessThan18 = user =&gt; user.age &lt; 18</pre><pre><strong>// Converting this format</strong><br>const filteredUsers = <strong>users.filter(lessThan18)</strong><br><strong>// To this format instead</strong><br>const filteredUsers = <strong>filter(lessThan18, users)</strong></pre><p>(We eliminated the dot notation, and passed processed data as a last param)</p><p>Then we curry them. <em>Where this </em><em>curry function will take a function and return a curried function</em> (<a href="https://javascript.info/currying-partials#advanced-curry-implementation">you can find the implementation here</a>):</p><pre>const filter     = <strong>curry((fn, list)   =&gt; list.filter(fn))</strong><br>const map        = <strong>curry((fn, list)   =&gt; list.map(fn))</strong><br>const startsWith = <strong>curry((starter, s) =&gt; s.startsWith(starter))</strong></pre><h4>Examples</h4><p>Now we can do some meaningful examples…</p><p><strong>Example 1️:</strong></p><p>Given a list of numbers, increment all numbers by 1</p><p><strong>Input</strong>: [1, 2, 3, 4, 5]</p><p><strong>Output</strong>: [2, 3, 4, 5, 6]</p><p><strong>Solution:</strong></p><pre>// the curried `add` function that we defined earlier<strong><br>const</strong> addOne = add(1)</pre><pre><strong>const</strong> incrementNumbers = map(addOne)</pre><pre><strong>const</strong> incrementedNumbers = incrementNumbers(numbers)</pre><p><strong>Example 2️:</strong></p><p>Given a string, keep all words that start with ‘C’ letter</p><p><strong>Input</strong>: &quot;currying is awesome”</p><p><strong>Output</strong>: “currying”</p><p><strong>Solution:</strong></p><pre><strong>const</strong> startsWithC = startsWith(&#39;c&#39;)</pre><pre><strong>const </strong>filterStartsWithC = filter(startsWithC)</pre><pre><strong>const</strong> filteredWords = filterStartsWithC(words)</pre><p><strong>Example 3️:</strong></p><p>Given a list of ranges and a list of numbers; Create an array of functions that can filter numbers based on provided ranges.</p><p><strong>Input:</strong></p><pre><strong>const</strong> ranges = [<br>  {min: 10, max: 100}, <br>  {min: 100, max: 500}, <br>  {min: 500, max: 999}<br>]</pre><pre><strong>const</strong> numbers = [30, 50, 110, 200, 650, 700, 1000]</pre><pre>// 30 &amp; 50 within 1st range<br>// 110 &amp; 200 within 2nd range<br>// 650 &amp; 700 within 3rd range<br>// 1000 isn&#39;t in any range</pre><p><strong>Output:</strong> an array of functions; Each function can take numbers and return filtered numbers that are within the given range.</p><p><strong>Solution:</strong></p><pre><strong>const</strong> isInRange = curry(<br>  (range, val) =&gt; val &gt; range.min &amp;&amp; val &lt; range.max<br>)</pre><pre><strong>const</strong> filters = ranges.map((range) =&gt; filter(isInRange(range)))</pre><p>This example has double curry if you can spot it, the filter and the isInRange</p><p>filters now is a list of functions, each is <strong>waiting </strong>for numbers to process, loaded (“config”-ed) with min and max</p><p><strong>Explanation:</strong></p><p>The best explanation would be to unfold the currying, and use regular functions instead…</p><pre><strong>const</strong> isInRange = (range, val) =&gt; val &gt; range.min &amp;&amp; val &lt; range.max</pre><pre><strong>const</strong> filters = ranges.map(<br>  (range) =&gt; (numbers) =&gt; numbers.filter(<br>    number =&gt; isInRange(range, number)<br>  )<br>)</pre><p>Remember, () =&gt; () =&gt; ... is still another implementation of currying. The simple version of currying.</p><p>And all thanks to currying! ❤️</p><h3><strong>Conclusion</strong></h3><p>Currying is just about making the params lazy. Where the function keeps returning function until all of its arguments are fulfilled then it computes and returns the result.</p><p>We also saw how it makes our code cleaner, less verbose, more composable and even more reusable through practical examples. And that leveraged separation of concerns principle.</p><p><em>Thanks a lot for taking time reading through this article</em> ❤️ <em>I’m cooking the next ones in the series. Please let me know what you think in the comments about this article or the series.</em></p><h3>This is an article in a series of articles talking about Functional Programming</h3><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h3>This series discusses:</h3><p>0. <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">A Brief Comparison Between Programming Paradigms</a></p><ol><li><a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">First Class functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-2-pure-functions-85491f3d7190">Pure functions</a></li><li><em>Currying (this article)</em></li><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">Composition</a></li><li>Functors</li><li>Monads</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=213eb69b234b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Functional Programming: The Power of Currying</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: Pure Functions]]></title>
            <link>https://medium.com/bitsrc/functional-programming-part-2-pure-functions-85491f3d7190?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/85491f3d7190</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Wed, 16 Mar 2022 08:08:09 GMT</pubDate>
            <atom:updated>2022-12-02T22:28:32.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming (Part 2): Pure Functions</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EoysqU_HNd5B2IoygpTcdg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@padrinan?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Miguel Á. Padriñán</a> from <a href="https://www.pexels.com/photo/photo-of-golden-cogwheel-on-black-background-3785927/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In the <a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">previous article</a> in this series we discussed one of the most important features in a programming language that supports Functional style; First-Class functions. In this article we’ll be talking about Pure functions. Which every FP concept should be built on.</p><h3>Table of contents</h3><ul><li>What are pure functions</li><li>Characteristics of a pure function</li><li>Why impure functions are bad</li><li>Why pure functions are good</li><li>4096-Cores</li><li>Honorship responsibility</li><li>Recap</li><li>Conclusion</li></ul><h3>What are pure functions</h3><p>Simply, a <strong>pure function</strong> is a function that is <strong><em>deterministic</em></strong> and <strong><em>doesn’t produces side effects.</em></strong></p><h3>Characteristics of a pure function</h3><h4>Characteristic #1: ️Pure functions have to be Deterministic</h4><p>A deterministic function is a function that for same input x output should always be the same y.</p><p><strong>Examples on some in-deterministic functions:</strong></p><ol><li><strong>Math.random</strong></li></ol><pre><strong>const</strong> random = () =&gt; Math.random()</pre><p>2. <strong>Date </strong>functions</p><pre><strong>const</strong> getDate = () =&gt; Date.now()</pre><p>3. <strong>getUsers</strong></p><pre><strong>const</strong> getUsers = await fetch(&#39;/users&#39;)</pre><p><em>Those examples are considered </em><strong><em>indeterministic </em></strong><em>because for same input, output will differ.</em></p><p>(Note: getUsers function is indeterministic because users might have updated, there is not internet connection or the server might be down, or whatever)</p><p><strong>Quick conclusion: </strong>determinism<strong> </strong>means that a function will never change its mind on the same input.</p><h4>️Characteristic #2: A pure function must have no side effects</h4><p>Where a <strong>side effect </strong>can be either an:</p><ul><li><strong><em>External dependency</em> </strong>(access to external variables, I/O streams, reading/writing files or making http calls).</li><li>Or a <strong><em>mutation</em>, </strong>(mutations on local/external variables or on passed reference arguments).</li></ul><p>Yes, pure functions <strong>should be deterministic</strong> and <strong>shouldn’t produce any type of side effects</strong>.</p><p>And yes, <strong>it’s impossible to have stateful applications without side effects </strong>(querying a DB, doing an http call, reading user input or even displaying results on a UI).</p><p>But don’t worry, <strong>FP has some more concepts/fixes for that</strong>.</p><p><strong>Examples on side effects:</strong></p><p>1. <strong>isLessThanMin</strong></p><p><strong>With side effect (Impure):</strong></p><pre>let <strong>min</strong> = 60</pre><pre>const isLessThanMin = value =&gt; value &lt; <strong>min</strong></pre><p><strong>Pure:</strong></p><pre>const isLessThanMin = (<strong>min</strong>, value) =&gt; value &gt; <strong>min</strong></pre><p><strong><em>Why impure?</em></strong><em> external dependency</em></p><p><strong><em>Solution:</em></strong><em> dependency injection instead</em></p><p>2. <strong>squares</strong></p><p><strong>With side effect (Impure):</strong></p><pre>const squares = (nums) =&gt; {<br>   for(let i = 0; i <strong>&lt;</strong> nums.length; i++) <strong>nums[i] **= </strong>2;<br>}</pre><p><strong>Pure:</strong></p><pre>const squares = (nums) =&gt; nums.<strong>map</strong>(num =&gt; num * num)</pre><p><strong><em>Why impure? </em></strong><em>imperative code that does mutations on original referenced array</em></p><p><strong><em>Solution:</em></strong><em> use the functional </em><em>.map instead. Which creates a new array at the end</em></p><p>3. <strong>updateUserAge</strong></p><p><strong>Impure:</strong></p><pre>const updateUserAge = (user, age) =&gt; {<br>  <strong>user.age = age<br></strong>}</pre><p><strong>Pure:</strong></p><pre>const updateUserAge = (user, age) =&gt; <strong>({ ...user, age })</strong></pre><p><strong><em>Why impure? </em></strong><em>mutation on passed </em><em>user reference</em></p><p><strong><em>Solution:</em></strong><em> refrain from mutating passed </em><em>user reference, instead return a new object with new/updated properties</em></p><p>4. <strong>getFirst2Elements</strong></p><p><strong>With side effect (Impure):</strong></p><pre>const getFirst2Elements = (arr) =&gt; arr.<strong>splice</strong>(0, 2)</pre><p><strong>Pure:</strong></p><pre>const getFirst2Elements = (arr) =&gt; arr.<strong>slice</strong>(0, 2)</pre><p><strong><em>Why impure? </em></strong><em>mutation on passed </em><em>arr reference using </em><em>.splice</em></p><p><strong><em>Solution:</em></strong><em> use the functional </em><em>.slice method that doesn’t mutate the state of the array instead</em></p><p><strong>Quick conclusion:</strong></p><ul><li>Pure functions are <strong>deterministic</strong> and <strong>have no side effects.</strong></li><li><strong>Deterministic: </strong>for same input x, output y should always be the same</li><li><strong>Side effect: </strong>use of external dependency or variable mutations</li></ul><h3>Why Impure functions are bad</h3><p>After taking a look on breaking the laws of pure functions, there are some obvious drawbacks:</p><ol><li>Makes functions tightly coupled with the surroundings</li><li>Increases developer’s cognitive-load</li><li>Induces state assumptions</li><li>Increases developer’s codebase learning curve</li><li>Race conditions</li><li>Concurrency super enemy</li><li>High unpredictability</li><li>+ All the lost benefits of having pure functions</li></ol><p>Where each drawback might be -totally or partially- a result of another drawback.</p><h3>Why pure functions are good</h3><p>Due to pure functions rules, we have 2 major categories of improvements. On <strong>developer experience </strong>and on <strong>application performance</strong>:</p><p><strong>On Developer Experience side (DX):</strong></p><p>Taking the fact that our functions are now <strong>deterministic, independent and self-contained. </strong>Improvements will be obvious in:</p><ol><li><strong>Predictability:</strong> elimination of external factors and changes of environment will make functions more sane and predictable.</li><li><strong>Maintainability:</strong> more <em>predictable</em> functions are easier to reason about. And that will reduce state assumption and developers’ cognitive-load.</li><li><strong>Composability: </strong><em>independence</em> of functions and communicating only through input and output, that will allow us to compose functions easily.</li><li><strong>Testability:</strong> <em>self-containment</em> and <em>independence</em> of functions will take testability to the moon.</li></ol><p><strong>In terms of Application Performance:</strong></p><ol><li><strong>Cache-ability (</strong><a href="https://en.wikipedia.org/wiki/Memoization"><strong>Memoization</strong></a><strong>)</strong>: <em>determinism</em> of functions will give us the ability to predict what the output is going to be through the input (since each input will have a defined output), then we can cache functions based on inputs.</li><li><strong>Parallelise-ability</strong>: since functions are now <em>side-effects free</em> and <em>independent</em>, they can be easily parallelised.</li></ol><h3>4096-cores CPUs</h3><p>We’re living in an era of multi-cores machines. The average CPU in hands nowadays has 8-cores, each core is eagerly racing for your computer’s resources. All these cores would be utterly useless if software we build can’t coordinate between them and serve ready-to-consume resources.</p><p>As <a href="https://blog.cleancoder.com/uncle-bob/2012/12/19/Three-Paradigms.html">Uncle Bob asked</a>:</p><blockquote>How are you going to write reliable code with 4096 processors contending for the bus?</blockquote><p>And the answer lies in <strong>pure functions</strong><em> (the beating heart of FP)</em>. Pure functions <strong>do not produce side effects</strong>, <em>thus</em> <strong>do not have concurrency issues</strong>. That is what makes FP the future. It will seamlessly handle the concurrency of our next 4096 cores CPU.</p><h3>Honorship responsibility</h3><blockquote>In the recent years many mainstream languages, like C++, C#, and Java, have adopted the functional style of programming. These languages, however, do not enforce function purity. It is our responsibility to honor that.</blockquote><h3>Recap</h3><ul><li><strong>Pure functions</strong> are <strong><em>Deterministic </em></strong>and<strong><em> don’t produce side effects</em></strong></li><li><strong>Determinism:</strong> for same input x, output should always be the same y</li><li><strong>Side effects:</strong> any use of external dependencies or mutations on any variable.</li></ul><h3>Conclusion</h3><p>Pure functions are living at the core of Functional programming. They are satisfied with a set of rules. The result of applying these rules has tremendous outcomes, which will lead to the future of computing.</p><p><em>Thanks a lot for taking time reading through this article. I’m cooking the next ones in the series. Please feedback me and let me know what you think in the comments about this article or the series.</em></p><h3>This is an article in a series of articles talking about Functional Programming</h3><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h3>This series discusses:</h3><p>0. <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">A Brief Comparison Between Programming Paradigms</a></p><ol><li><a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">First Class functions</a></li><li><em>Pure functions (this article)</em></li><li><a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Currying</a></li><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">Composition</a></li><li>Functors</li><li>Monads</li></ol><h3>Resources</h3><ol><li><a href="https://en.wikipedia.org/wiki/Pure_function">https://en.wikipedia.org/wiki/Pure_function</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/12/19/Three-Paradigms.html">https://blog.cleancoder.com/uncle-bob/2012/12/19/Three-Paradigms.html</a></li><li><a href="https://blog.ploeh.dk/2017/01/27/from-dependency-injection-to-dependency-rejection/">https://blog.ploeh.dk/2017/01/27/from-dependency-injection-to-dependency-rejection/</a></li><li><a href="https://nofluffjuststuff.com/magazine/2016/11/the_duality_of_pure_functions">https://nofluffjuststuff.com/magazine/2016/11/the_duality_of_pure_functions</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85491f3d7190" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-part-2-pure-functions-85491f3d7190">Functional Programming: Pure Functions</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[This Pattern Will Make Your React Hooks Cleaner]]></title>
            <link>https://medium.com/better-programming/this-pattern-will-make-your-react-hooks-cleaner-ca9deba5d58d?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/ca9deba5d58d</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[hooks]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Fri, 11 Mar 2022 15:18:03 GMT</pubDate>
            <atom:updated>2022-04-03T07:28:39.946Z</atom:updated>
            <content:encoded><![CDATA[<h4>So you don’t have to redo work</h4><figure><img alt="Fish hooks" src="https://cdn-images-1.medium.com/max/1024/1*sPptsTjGtwqtiHPSzVhirA.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Anne Nygård</a> on <a href="https://unsplash.com/s/photos/hook?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><h3>Table of Contents</h3><ul><li>How Hooks Are Built</li><li>Can We Combine the Options</li><li>Why Does That Work</li><li>Conclusion</li></ul><h3>How Hooks Are Built</h3><p>When we build a custom hook with complex logic in React, we either return an array or an object that has state and logic. The following shows the process:</p><h4>1. Returning an object</h4><p>The first option is to return an object from the custom hook, like this:</p><pre>const customHook = (configs) =&gt; {<br>  const isLoading = true //logic<br>  const reload    = () =&gt; {/*logic*/}</pre><pre>  return<strong> { isLoading, reload }</strong><br>}</pre><p>The usage would look like this:</p><pre>const <strong>{ isLoading, reload } </strong>= customHook(configs)</pre><p>Where:</p><ul><li>It is developer-friendly, where you don’t need to remember the order of the props</li><li>The IntelliSense will help you know the params</li></ul><p>But when we use multiples of that hook, it doesn’t look nice. It will look like this:</p><pre>const { <br>  <strong>isLoading: isLoadingWidget1, <br>  reload: reloadWidget1 </strong><br>} = customHook(widget1Config)</pre><pre>const { <br> <strong> isLoading: isLoadingWidget2, <br>  reload: reloadWidget2 </strong><br>} = customHook(widget2Config)</pre><pre>const { <br>  <strong>isLoading: isLoadingWidget3, <br>  reload: reloadWidget3 </strong><br>} = customHook(widget3Config)</pre><p>Which is not really nice. We have to rename each key to another one so they don’t clash.</p><h4>2. Returning an array</h4><p>The other option is to return an array from the custom hook, like the following:</p><pre>const customHook = (configs) =&gt; {<br>  const isLoading = true //logic<br>  const reload    = () =&gt; {/*logic*/}</pre><pre>  return <strong>[isLoading, reload]</strong><br>}</pre><p>The usage would look like this:</p><pre>const [<strong>isLoadingWidget1, reloadWidget1] </strong>= customHook(widget1Config)<br>const [<strong>isLoadingWidget2, reloadWidget2] </strong>= customHook(widget2Config)<br>const [<strong>isLoadingWidget3, reloadWidget3] </strong>= customHook(widget3Config)</pre><p>Where:</p><ul><li>It solves the multiple usages problem. You don’t have to rename each key.</li></ul><p>But:</p><ul><li>You have to maintain the order of props</li><li>Doesn’t have the same IntelliSense as in Objects</li></ul><h3>Can We Combine the Options</h3><p>Can we combine these patterns together? In a sense, if you want to use it as an array or as an object for the same hook.</p><p>Yes, that’s possible. Look at this implementation:</p><pre>const customHook = () =&gt; {  <br>  const isLoading = true //logic<br>  const reload    = () =&gt; {/*logic*/}</pre><pre>  <strong>const result = [isLoading, reload]</strong></pre><pre><strong>  result.isLoading = isLoading<br>  result.reload    = reload</strong></pre><pre>  return result<br>}</pre><p>result is an array, yet we add isLoading and reload keys to it.</p><p>That implementation will give us the ability to use the hook’s return value as:</p><ol><li><strong>An object</strong></li></ol><pre>const <strong>{ isLoading, reload }</strong> = customHook(configs)</pre><p>2.<strong> An array</strong></p><pre>const <strong>[isLoading, reload]</strong> = customHook(configs)</pre><p>Both of these options will work. But why…</p><h3>Why Does That Work</h3><p>Why is it possible to use both the Array and Object return types? Why is it possible to attach keys to an array?</p><blockquote>“The Array object, as with arrays in other programming languages, enables <a href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/First_steps/Arrays">storing a collection of multiple items under a single variable name</a>, and has members for <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array#examples">performing common array operations</a>.” — <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">MDN</a></blockquote><p>As mentioned, “The Array object.” That reveals the fact that an array is actually just an object, with a special constructor, and a set of methods performing common array operations.</p><h4>Proof that Array is actually an Object</h4><ol><li><strong>Proof 1</strong></li></ol><pre><strong>typeof []</strong> // &#39;object&#39;</pre><p>Yes, typeof will result in an &#39;object&#39;</p><p>2. <strong>Proof 2</strong></p><pre>const <strong>{0: first, 1: second}</strong> = [1, 2, 3, 4] // first: 1, second: 2</pre><p>We can destruct the array object using the indices because the keys in any array are just the indices and values of the object, and they are what you pass between the brackets []. That’s why we’re able to destruct it and rename keys that way.</p><p>3. <strong>Proof 3</strong></p><pre><strong>const { length } </strong>=<strong> </strong>[1, 2, 3, 4]</pre><p>An array is an object that also has length key in it.</p><p>4. <strong>Proof 4</strong></p><pre><strong>Object.keys([1, 2, 3, 4]) </strong>  // [&#39;0&#39;, &#39;1&#39;, &#39;2&#39;, &#39;3&#39;]<br><strong>Object.values([1, 2, 3, 4])</strong> // [1, 2, 3, 4]</pre><p>Object.keys and Object.values only work on Objects, and Array is an object (a special object).</p><h3>Conclusion</h3><p>We have just seen a pattern that allows us to make hooks’ return value to be destructed as an array or as an object. We’ve seen how that is helpful. And we’ve seen why that is possible because it’s all about the fact that Arrays are just Objects with a cap.</p><h3>Resources</h3><ol><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array">https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ca9deba5d58d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/better-programming/this-pattern-will-make-your-react-hooks-cleaner-ca9deba5d58d">This Pattern Will Make Your React Hooks Cleaner</a> was originally published in <a href="https://betterprogramming.pub/">Better Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: First-Class Functions]]></title>
            <link>https://medium.com/bitsrc/functional-programming-part-1-first-class-functions-791103984dfb?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/791103984dfb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Mon, 07 Feb 2022 08:57:25 GMT</pubDate>
            <atom:updated>2022-12-02T22:28:15.955Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming (Part 1): First-Class Functions</h3><figure><img alt="Twins in a shirt (functions and variables)" src="https://cdn-images-1.medium.com/max/1024/1*J6SAavpu-hyEa8uF7b0cGg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@ron-lach?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Ron Lach</a> from <a href="https://www.pexels.com/photo/two-young-girls-together-in-one-gray-hoodie-sweater-9532902/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In the <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">previous article</a> in this series we discussed main programming paradigms and basic differences. In this article we’ll talk about one of the most important features (maybe the most important one) in a programming language that supports Functional style programming; First-Class functions.</p><h4>Contents</h4><ul><li>What is a First-Class function?</li><li>Why First-Class functions matter</li></ul><h3>What is a First-Class function?</h3><p>A Programming language is considered to have First-Class functions support when it has <strong><em>no</em></strong> <strong><em>restrictions/limits</em></strong> on how functions can be <strong><em>created </em>or <em>used</em>.</strong></p><p><em>“A programming language is said to have </em><strong><em>First-class functions</em></strong><em> when functions in that language are treated like any other variable.” — </em><a href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function"><em>MDN</em></a></p><p>In general, programming languages impose restrictions on the ways in which computational elements can be manipulated. Elements with the fewest restrictions are said to have <strong><em>first-class</em></strong> status. Some of the “rights and privileges’’ of first-class elements:</p><ul><li>Can be <strong>assigned</strong> to regular variables</li><li><strong>Passed</strong> as arguments to functions</li><li><strong>Returned</strong> as results of functions</li><li><strong>Included in any data structures</strong></li></ul><h3>Functions in a programming language are considered First-Class if they can be:</h3><h4><strong>1. A</strong>ssigned to regular variables</h4><p>When functions can be assigned to any variable name, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad537c0322c9a31fa22fc8916cc31472/href">https://medium.com/media/ad537c0322c9a31fa22fc8916cc31472/href</a></iframe><h4>2. Passed as arguments to functions</h4><p>When functions can be passed like any parameter to a function, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/70045f2c1722a56e8760f23737d37197/href">https://medium.com/media/70045f2c1722a56e8760f23737d37197/href</a></iframe><p>We have addOne function that is treated as a variable and passed to .map function. That’s being said, addOne function is indeed a first-class function.</p><h4>3. Returned as results of functions</h4><p>When functions can return another function, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94260a5f827a0d4ad75eeff1dae9917e/href">https://medium.com/media/94260a5f827a0d4ad75eeff1dae9917e/href</a></iframe><p>The makeCounter function returned a function and we assigned it to counter variable. Where counter variable now is holding a regular function.</p><h4>4. Included in <strong>any</strong> data structures</h4><p>When functions can be stored in any data structure, like:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/509ad2fc7b4c8ca7563acb8787712a1b/href">https://medium.com/media/509ad2fc7b4c8ca7563acb8787712a1b/href</a></iframe><p>We can store functions in arrays and as you guessed we can also store them in objects and loop through them as often.</p><h3>Why First-Class functions matter</h3><p>Functional programming (FP) is <strong>highly</strong> influenced by Mathematics realm. FP would love to have all Mathematics included in every line of code.</p><p>Although Math is only built with functions and variables, it’s still very powerful and expressive. That’s what FP is trying to do. Solving every single problem using <strong>functions and functions only</strong> (exactly how the big brother (Maths) would do it).</p><p>That’s why functions’ <strong>freedom</strong> (<em>making them first-class</em>) comes into work. When you can treat a function in a programming language as simple as a variable, that language would be much more flexible and opens a lot of rooms for improvements. Which as we mentioned earlier, FP will make your code more Predictable, Testable, Reusable, Customisable, Cacheable, Maintainable, Composable and Readable.</p><h4>So, you would ask yourself “Ok I understand the relationship between FP and Mathematics, but how first-class functions would make all these benefits possible?”</h4><p>Very nice question. Well, since FP depends all the way on functions’ freedom. first-class functions is the corner stone for all FP concepts, once you have the corner stone then you can build on top of it these awesome concepts (as we’ll try to do in the coming parts of the series).</p><h3>Having first-class functions in a programming language would make it possible to have some awesome patterns, such as:</h3><h4>1. Higher-order functions</h4><p>Functions are considered higher-order functions when they <strong>take functions as arguments, </strong>(like most Array utilities, .map, .filter, .reduce, .every ) and/or<strong> return a function as a result </strong>(Exactly like makeCounter).</p><h4>2. Closures</h4><p>A closure <strong>is a function returned by a “parent” function and has access to the parent function’s internal state</strong>. Like our previous example of makeCounter.</p><p>To elaborate more, let’s give it another example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90af8a65c8bb4bddec04243fd0c5e674/href">https://medium.com/media/90af8a65c8bb4bddec04243fd0c5e674/href</a></iframe><p>Let’s explain that line by line:</p><p><strong>Line 1:</strong> The add is a function that takes the first param x, and returns an anonymous function that takes the second param y, and returns x + y.</p><p><strong>Line 3:</strong> Executing add(5) will return a function with a value of 5 inside it. Compiler/Optimiser will understand it exactly like this:</p><pre>const add5 = (y) =&gt; 5 + y </pre><p><strong>Line 4:</strong> Exactly like line 3. Executing add(10) will return a function with a value of 10 inside it. Compiler/Optimiser will understand it exactly like this:</p><pre>const add10 = (y) =&gt; 10 + y</pre><p><strong>Line 6 &amp; Line 7: </strong>They are just normal function calls to the previously “dynamically” created functions of add5 and add10.</p><p><strong>Ok, that’s cool.</strong> After understanding what each line does, what are the actual technical terms for add, add5 and add10:</p><ul><li>add is a <strong><em>higher-order</em></strong> <strong><em>function. </em></strong>Why? because it returns a function</li><li>But add5 and add10 are <strong>closures</strong>. Why? Because they have values 5 and 10 respectively enclosed (bound) in their parent’s lexical scope and still accessible by them. (That’s why when we add5(1) it will use the the already passed 5 to add)</li></ul><p>(Note 1: The relationship between a closure and a higher-order function, is like parent and child, we will not be able to have a closure without a higher-order function)</p><p>(Note 2: I found something <a href="https://twitter.com/AhmadMHawwash/status/1488066671768215552">interesting</a> about closures while writing this article)</p><h4>3. Currying</h4><p>It’s a mechanism of applying the lazy evaluation concept. Which we’ll discuss it in details later on…</p><h3>Conclusion</h3><p>First-class function is <strong><em>not a pattern</em></strong><em>,</em> it is just <strong><em>a feature</em></strong> in a programming language. That feature would allow treating functions easily as variables, and moved around without restrictions. Having that feature would make the language more powerful and FP-ready. Where we can be build very powerful utilities using that feature, like higher-order functions, closures, currying and more…</p><p><em>Thanks a lot for taking time reading through this article. I’m cooking the next ones in the series. Please feedback me and let me know what you think in the comments about this article or the series.</em></p><h4>This is an article in a series of articles talking about Functional Programming</h4><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h4>This series discusses:</h4><p>0. <a href="https://blog.bitsrc.io/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">A Brief Comparison Between Programming Paradigms</a></p><ol><li><em>First Class functions (this article)</em></li><li><a href="https://medium.com/@ahmad.m.hawwash/functional-programming-part-2-pure-functions-85491f3d7190">Pure functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Currying</a></li><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">Composition</a></li><li>Functors</li><li>Monads</li></ol><h4><strong>Resources</strong></h4><ol><li><a href="https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-12.html">https://mitpress.mit.edu/sites/default/files/sicp/full-text/book/book-Z-H-12.html</a></li><li><a href="https://en.wikipedia.org/wiki/First-class_function">https://en.wikipedia.org/wiki/First-class_function</a></li><li><a href="https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/README.md">https://github.com/getify/You-Dont-Know-JS/blob/2nd-ed/scope-closures/README.md</a></li><li><a href="https://eloquentjavascript.net/">https://eloquentjavascript.net/</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=791103984dfb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-part-1-first-class-functions-791103984dfb">Functional Programming: First-Class Functions</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Programming: A Comparison Between Programming Paradigms]]></title>
            <link>https://medium.com/bitsrc/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6?source=rss-bcbadf464e5d------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ff192cd32b6</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ahmad M. Hawwash]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 11:37:57 GMT</pubDate>
            <atom:updated>2022-12-02T22:27:51.076Z</atom:updated>
            <content:encoded><![CDATA[<h3>Functional Programming (Part 0): A Comparison Between Programming Paradigms</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h1LDUifgUKPJZcHmbC4H7A.png" /><figcaption>Relationship between languages, paradigms and concepts</figcaption></figure><p><strong><em>This article is a part of a series that talks about “Functional Programming”</em></strong></p><p>In this very first part, we’ll talk about Programming paradigms. Touching Imperative and Declarative paradigms. Running on some minimal examples and comparisons. At the end, we’ll take an evolutionary-perspective look at some paradigms.</p><h4>Table of contents</h4><ul><li>Programming paradigms</li><li>Imperative paradigm</li><li>Declarative paradigm</li><li>Extra mile on sum example</li><li>Evolution perspective</li><li>Conclusion</li></ul><h3>Programming paradigms</h3><p>A programming paradigm is a style or a “way” of programming. So some languages<strong> </strong>force us to write in a certain paradigm. Other languages keep options open up to the programmer. where each paradigm follows a set of concepts. (Please take a look at the heading picture -if you haven’t already, so “paradigm” word can make sense).</p><p>In the history of computer programming, engineers have developed different languages. Each language had a paradigm (or more) in mind. These paradigms belong to one of these 2 main categories:</p><h4>1. Imperative Paradigm</h4><p>In which <strong>control flow is<em> explicit</em></strong>, where the programmer instructs the program <strong>how to change its state</strong>. Where it includes more paradigms:</p><ul><li>Structural Paradigm</li><li>Object-Oriented Paradigm</li></ul><h4>2. Declarative Paradigm</h4><p>In which <strong>control flow is <em>implicit</em></strong>, where the programmer instructs the program <strong>what</strong> <strong>should be done without</strong> <strong>specifying how</strong> to it should be done. Where it includes more paradigms:</p><ul><li>Functional Paradigm</li><li>Logical Paradigm</li><li>Mathematical Paradigm</li><li>Reactive Paradigm</li></ul><h4>Summary</h4><p>Most languages belong to either Imperative or Declarative paradigm, where each paradigm has a set of concepts to follow.</p><h3>Let’s talk more about the two main paradigms:</h3><p>The Imperative and Declarative paradigms.</p><h3>1. Imperative Paradigm</h3><p>Imperative paradigm has evolved a bit in terms of <strong>structure </strong>(because of Structural Paradigm), but it still has problems:</p><ul><li>Telling the program <strong>how</strong> to do things (<strong>control flow is<em> explicit)</em></strong></li><li><strong>Sharing state</strong></li></ul><p>To make the idea a bit closer. Let’s take two analogies for the two problems above (if you understand the problems you can skip the next part and jump to the example):</p><h4><strong>Problem 1: T</strong>elling the program how to do things (<strong>control flow is<em> explicit)</em></strong></h4><ul><li><strong>Case:</strong> Imagine 1,000 employees with a lead who’s leading them towards a mission. The lead starts telling the 1000 employees <strong>how</strong> to do things one by one. How bad do you think this is going to be? I am pretty sure you can see that this micro-level management style has major risks, pitfalls and won’t even work.</li><li><strong>Solution:</strong> Grouping people in areas of responsibilities and delegate a team leader to each group. The leader of each group should know <strong>how </strong>to do things for sake of the mission. That’s going to reduce a lot of the complexity, bottleneck and it’s going to be a lot easier to manage.</li><li><strong>In this analogy</strong><br> — Mission leader = Programmer. <br> — Groups’ leaders = Higher level functions<br> — Employees in each group = Lines of code</li><li><strong>Conclusion:</strong> when we apply higher order organisational structure on the program level, our lives are going to be way smoother.</li></ul><h4>Problem 2: <strong>Sharing state</strong></h4><ul><li><strong>Case: </strong>Imagine yourself a father, you have 2 children. You created a shared bank account for them. Each month you put $1000 in that account. Both of your children are unaware that the account is shared. So they both think each have $1000 to spend to him/herself. At the end of the month, you are screwed because you found out that you end up with <strong>-</strong>$1000 in that account.</li><li><strong>Solution: </strong>Each child should have separate account and specified monthly amount</li><li><strong>In this analogy:<br> </strong>— Children = Functions<br> — Shared bank account = shared state.</li><li><strong>Conclusion: </strong>When your functions share the same state. They use it unconsciously. This will mess up your program state even with only 2 functions. So it’s always better that each function has its own independent state to use.</li></ul><h4>Example On Imperative Paradigm</h4><p>Let’s see how sum could be implemented in Imperative Paradigm</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82b433eae01c5bc306807c69b772e8b0/href">https://medium.com/media/82b433eae01c5bc306807c69b772e8b0/href</a></iframe><p><strong>Why is this considered Imperative?</strong></p><ol><li><strong>Telling the program how to do things (control flow is explicit):</strong> We tell the for loop <strong>how</strong> to work explicitly. Also we access each element in the array explicitly.</li><li><strong>Sharing state:</strong> result variable is a shared state, being mutated on every iteration (sharing state in bigger problems will be much harder to deal with).</li></ol><h3>2. Declarative Paradigm</h3><p>Declarative paradigm is when the programmer instructs the program <strong>what</strong> <strong>should be done without</strong> <strong>specifying how.</strong></p><p>In contrast to Imperative paradigm, Declarative paradigm is just not imperative. In other words, in Declarative paradigm we write functions that:</p><ul><li>Describe <strong>what</strong> a program should perform instead of <strong>how </strong>(<strong><em>implicit </em>control flow</strong>).</li><li>Produce <strong>no side effects</strong> (which we’ll discuss more later).</li></ul><h4>Example on Declarative Paradigm</h4><p>We saw how sum function could be implemented in Imperative Paradigm, let’s see how it could be implemented declaratively</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90cb46118208e66d62160599137cc74c/href">https://medium.com/media/90cb46118208e66d62160599137cc74c/href</a></iframe><p>Magical, right? <strong>But why is that considered declarative?</strong></p><ol><li><strong>Described what a program should perform instead of how</strong> (<strong><em>implicit </em>control flow</strong>): There’s no explicit iterator, no explicitly telling the loop how to work or how to access the elements. That was achieved by using reduce.</li><li><strong>Produced no side effects: </strong>Shared state is a form of side effects, that was totally eliminated using the composition of reduce and add function.</li></ol><h3>Extra mile on sum example</h3><p>What if we wanted to sum only even numbers?</p><h4>Imperatively we would do:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8328a6015ac3efdfe23d28ae04ea473b/href">https://medium.com/media/8328a6015ac3efdfe23d28ae04ea473b/href</a></iframe><h4>But Declaratively we would do:</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5df254280a7ef660b943ad375e9a43a9/href">https://medium.com/media/5df254280a7ef660b943ad375e9a43a9/href</a></iframe><p>As we see, if we want to compare both paradigms (Imperative and Declarative), in Declarative paradigm (Functional paradigm in our case) is more like gears ⚙️, you develop your gears as separate units, then you add them wherever you need them. But in Imperative paradigm it’s more like dough 🫓 almost everything is mixed and fused into the same piece of code (unless in fact you did great job doing design patterns).</p><p>In general, Declarative Paradigm is more:</p><ul><li>Predictable</li><li>Testable</li><li>Reusable</li><li>Customisable</li><li>Cacheable</li><li>Maintainable</li><li>Composable</li></ul><p>Some of these points don’t necessarily make sense in context of sum example, but will make sense in future articles.</p><h3>Evolution perspective</h3><p>After understanding that we have 2 main paradigms <em>Imperative</em> and <em>Declarative</em>, where each has sub-paradigms. Let’s talk now more about <strong>Structural, Object-Oriented </strong>and <strong>Functional Paradigms. </strong>from an evolutionary perspective.</p><p>Each paradigm has <strong>restricted </strong>a way of programming by <strong>introducing</strong> something new. Where we can say best leaps happened in:</p><ul><li><strong>Structural Paradigm: </strong>Restricted usage of <strong>goto</strong> and “<em>flow of transfer of control” </em>by introducing <strong>structure</strong> to our code like if/else/then/loop and others. In other words, it <em>constraints the flow of transfer of control</em>.</li><li><strong>Object-Oriented</strong> <strong>Paradigm: </strong>Restricted doing <strong>polymorphism using pointers to functions</strong> by introducing<strong> Polymorphism using inheritance</strong>.</li><li><strong>Functional Paradigm: </strong>Restricted <strong>shared state</strong> and <strong>side effects</strong> by introducing <strong>Immutability</strong>.</li></ul><p>Keep in mind that each paradigm might use one or more of other paradigms’ concepts (for example, both Object-Oriented and Functional paradigms uses Structural Paradigm concepts).</p><h3>Conclusion</h3><p>In real life, we have different paradigms with different styles that needs different levels of proficiency. Practicing more paradigms will give you more superpowers, OO has its superpowers and FP as well. The stronger you become in these paradigms, the more powerful your solutions will be, the more safe people will feel around you.</p><p><em>Thanks a lot for taking time reading through this article. I’m cooking the next ones in the series. Please feedback me and let me know what you think in the comments about this article or the coming ones.</em></p><h4>This is an article in a series of articles talking about Functional Programming</h4><p>In this series of articles we cover the main concepts of Functional Programming. At the end of the series, you’ll be able to tackle problems in a more functional approach.</p><h4>This series discusses:</h4><p><em>0. A Brief Comparison Between Programming Paradigms (this article)</em></p><ol><li><a href="https://blog.bitsrc.io/functional-programming-part-1-first-class-functions-791103984dfb">First Class functions</a></li><li><a href="https://medium.com/@ahmad.m.hawwash/functional-programming-part-2-pure-functions-85491f3d7190">Pure functions</a></li><li><a href="https://blog.bitsrc.io/functional-programming-part-3-the-powers-of-currying-213eb69b234b">Currying</a></li><li><a href="https://blog.bitsrc.io/functional-programming-composition-2e9b863d8bcb">Composition</a></li><li>Functors</li><li>Monads</li></ol><h4>Resources</h4><ol><li><a href="https://blog.cleancoder.com/uncle-bob/2018/04/13/FPvsOO.html">https://blog.cleancoder.com/uncle-bob/2018/04/13/FPvsOO.html</a></li><li><a href="https://cs.lmu.edu/~ray/notes/paradigms/">https://cs.lmu.edu/~ray/notes/paradigms/</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2014/11/24/FPvsOO.html">https://blog.cleancoder.com/uncle-bob/2014/11/24/FPvsOO.html</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2017/07/11/PragmaticFunctionalProgramming.html">https://blog.cleancoder.com/uncle-bob/2017/07/11/PragmaticFunctionalProgramming.html</a></li><li><a href="https://blog.cleancoder.com/uncle-bob/2012/12/19/Three-Paradigms.html">https://blog.cleancoder.com/uncle-bob/2012/12/19/Three-Paradigms.html</a></li><li><a href="https://en.wikipedia.org/wiki/Programming_paradigm">https://en.wikipedia.org/wiki/Programming_paradigm</a></li><li><a href="https://en.wikipedia.org/wiki/Procedural_programming">https://en.wikipedia.org/wiki/Procedural_programming</a></li><li><a href="https://en.wikipedia.org/wiki/Functional_programming">https://en.wikipedia.org/wiki/Functional_programming</a></li><li><a href="https://en.wikipedia.org/wiki/Non-structured_programming">https://en.wikipedia.org/wiki/Non-structured_programming</a></li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ff192cd32b6" width="1" height="1" alt=""><hr><p><a href="https://medium.com/bitsrc/functional-programming-part-0-a-brief-comparison-between-programming-paradigms-3ff192cd32b6">Functional Programming: A Comparison Between Programming Paradigms</a> was originally published in <a href="https://medium.com/bitsrc">Bits and Pieces</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>