<?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 José &#39;Joshi&#39; Ráez Rodríguez on Medium]]></title>
        <description><![CDATA[Stories by José &#39;Joshi&#39; Ráez Rodríguez on Medium]]></description>
        <link>https://medium.com/@joshiraez?source=rss-7fc174796158------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CO9Y3xPPFR9gLV1X.</url>
            <title>Stories by José &amp;#39;Joshi&amp;#39; Ráez Rodríguez on Medium</title>
            <link>https://medium.com/@joshiraez?source=rss-7fc174796158------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 19:25:27 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@joshiraez/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[Make your business logic readable, and your configuration logic extendable]]></title>
            <link>https://medium.com/swlh/make-your-business-logic-readable-and-your-configuration-logic-extendable-ea151d478423?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/ea151d478423</guid>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Mon, 27 Apr 2020 23:40:45 GMT</pubDate>
            <atom:updated>2020-05-31T22:33:26.531Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2Aciic1LjPpw6k6cx3M9w.png" /></figure><p><em>What the hell do you mean with business logic and configuration logic? </em>I swear I have not coined the term and I did read it somewhere that was not Clean Code, but I can’t for my life find it. Yet, with time I have come to see that this piece of info is one of the most useful one liners I usually give for advice.</p><p><strong>Business logic </strong>tells our program <strong>what we want</strong> to do. <em>It tells the story of the use case we are implementing</em>. It’s usually very top level, follows a flow of function calls, and can almost be read as plain text. Does it sound as the best practices for testing? It is! Because <strong>business logic </strong>can be found mostly in tests (where they are a logical implication: we tell what our code does), but I like to extend that to any <strong>top-level access in any use-case: </strong>the entry point of a class, the public functions of a business object, the logic of a component…</p><p><strong>Configuration logic</strong>, in the other hand, tells our program <strong>how to do stuff</strong>. It states paths, relationships and logic. It implements our abstractions and our programming patterns. It, at its core, <strong>stores efficiently how the program should store, retrieve and transform data. </strong>And efficiently means, most of all, maintenable: open close principle, least responsibility principle, inversion of logic principle… SOLID and beyond.</p><p>In a nutshell: business logic is at the top, configuration logic is at the bottom. <strong>Business logic must be readable. Configuration logic must be extendable.</strong></p><p>Let me put a very basic example:</p><pre>public static void main(String[] args) {<br><br>    <em>sayHiShoutingTo</em>(&quot;joshi&quot;)<strong>;<br></strong>}<br><br>private static void sayHiShoutingTo(final String otherPerson) {<br><br>    String greetings = <em>greet</em>(otherPerson)<strong>;<br><br>    </strong>greetings = <em>shouting</em>(greetings)<strong>;<br><br>    </strong><em>sayItOutLoud</em>(greetings)<strong>;<br></strong>}<br><br>private static String greet(final String otherPerson) {<br>    return &quot;Hi &quot;+otherPerson+&quot;!&quot;<strong>;<br></strong>}<br><br>private static String shouting(final String greetings) {<br>    return greetings.toUpperCase()<strong>;<br></strong>}<br><br>private static void sayItOutLoud(final String greetings) {<br>    System.<em>out</em>.println(greetings)<strong>;<br></strong>}</pre><p>We can see that the main implementation could be considered business logic. It is quite readable. We know what it wants to do.</p><p>The bottom part is obviously configuration logic. We are telling how to retrieve the data, transform it, and where to store (or output) it.</p><p>And what about the middle part: <strong>it is business and configuration at the same time! </strong>It acts as configuration to the top layer because it tells how to retrieve that info. But it acts as business for the bottom layer because it tells us what we will do!</p><p>Remember: business is what is in top of <strong>any </strong>abstraction layer. And is not called business for nothing: it’s what interfaces the rest of the application. The public access part. <strong>Is what solves the use case.</strong> (And we don’t care what is behind the counter)</p><p><strong>And that means is the one who is gonna be more visible. <em>The most read during the application life</em>. </strong>And, hence, the one which you should focus more on readability.</p><p>In the other hand, the business logic not only is the part you want to be as readable as you can. It is also the part which is more of a pain to modify, because is the <strong>only one you will be exposing to the application. </strong>This means a few things:</p><ul><li>Every part of the application using it must be tested for regression if it’s changed</li><li>They are hard to generalize, because each use case must do something different. <strong>They are highly specialized</strong></li><li>We don’t want logic in this layer. Seriously. Not. it reduces readability and makes the code tiresome to read. If you have some logic, surely it can be in a much better named function.</li><li>For fuck sake, even just changing the method’s name or paremeters needs a mass refactor and is even impossible in some languages!</li></ul><p>That’s where configuration logic comes. <strong>This is where we implement the logic our business will use.</strong></p><p>And like in any business, behind the counter is where the magic happens. Here is where we will focus on our domain logic. It should be:</p><ul><li>Accessible, so any business logic can use it easily.</li><li>Parametrizable, to allow different behaviours for different cases.</li><li>Extensible, and easily on top of that. Because they are not shared, <strong>we are free to make as much as we need</strong> without fearing overloading the API.</li><li>Efficient, because we can focus on doing abstractions or algorithms without fearing bloating the code.</li></ul><p>But what about business logic? Why doesn’t it be like this? Surely they will need to be parametizable to allow different configurations, or to put together similar code. Right?</p><p><strong>Nope. Because different use cases should be in different methods, <em>even if their code is very similar</em>. Because they are different use cases, they will be maintained <em>separately</em>.</strong></p><p><em>The DRY principle has aged somewhat bad</em>. In the past, the minigame was on how we can lower total line codes by putting together the same code. <strong><em>This became a big problem when applications evolved.</em></strong></p><ul><li>Suddenly, domain items that seemed the same, had to be specialized for different use cases.</li><li>Replicating code meant to have to maintain two different things. And it was only minor details…</li><li>Yet, the details kept creeping in. Suddenly, you have 2/3 different use cases using the same logic just because you didn’t want to break DRY.</li></ul><p>And it’s wrong: <strong>If two methods refer to different use cases, create two different methods for it, even if they end using the same configuration logic behind the scenes! </strong>You can <strong>always create more</strong> configuration methods, and <strong>changing business logic</strong> to point to a different configuration method <strong>is much easier</strong>.</p><p><em>The key is, you can play as much as you want with the inner pieces (configuration), but the external API is much harder to change (business)!</em></p><p>Let’s look again at the previous example, how easy is to make another business flow that doesn’t shout. Or that says goodbye. Can you guess what the code will do only from the method names? Can you see how we use configuration logic to aid us in that?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c86ad0de741046ced9d75cdabd815d0d/href">https://medium.com/media/c86ad0de741046ced9d75cdabd815d0d/href</a></iframe><p>The core idea is to do layers: business-config/business-config and so on. If it’s not enough, then create more layers going down. <strong>There is no limit how much you can create of configuration code!</strong></p><p>And that’s pretty much it. Have you noticed this pattern somewhere else? Do you agree or not? Please, leave it in the comments :)</p><p>4h day of #100DaysOfContent</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ea151d478423" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/make-your-business-logic-readable-and-your-configuration-logic-extendable-ea151d478423">Make your business logic readable, and your configuration logic extendable</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simple patterns explained: the cache]]></title>
            <link>https://medium.com/@joshiraez/simple-patterns-explained-the-cache-5cfb4358dc59?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/5cfb4358dc59</guid>
            <category><![CDATA[cache]]></category>
            <category><![CDATA[memoization]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Sun, 26 Apr 2020 22:31:35 GMT</pubDate>
            <atom:updated>2020-04-26T22:31:35.397Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K2Aciic1LjPpw6k6cx3M9w.png" /></figure><p>If you have read my articles, you will know<a href="https://medium.com/@joshiraez/beating-the-switch-smell-d45f366ffca8?source=your_stories_page---------------------------"> I love maps</a>. They allow to let us transform data into some<a href="https://medium.com/@joshiraez/the-programmer-puzzle-what-is-programming-7f444ab0bd7d?source=your_stories_page---------------------------"> other related data</a>. They are fast, optimized, usually easy to set up, easily readable … many boons and stuff. Maybe also a bit of fanboyism.</p><p>But we (or, rather, I) forget its main use. <strong>And that is storing arbitrarily accessible data by identifier. </strong>But what good is storing data that are not supposed to be used in a vacuum? It has many uses, actually. One of them is what we will be talking about today: <strong><em>caching</em></strong>.</p><p><em>Disclaimer: I use the term caching rather loosely as anything that stores a result in a layer. I dont’ know if there is special terms depending on the case. Please, feel free to tell about it on the comments section :)</em></p><p>So, what is the problem we will be facing today?</p><p>Imagine that you have a very slow operation. For example, retrieving data from a data base. You access the database, retrieve the data, send it to your front… everything’s ok!</p><p>But what happens if you have to access that data 2 times? Now it’s not so good. And 5 times? Huh… That’s not so good.</p><p>But what about if you save the result? Then, you wouldn’t have to check the backend every time you want to use it. You would only have to access the variable containing the result. That, in a nutshell, is caching</p><p>Yet, caching itself is a easy to use, powerful to master, because:</p><ul><li>What happens if the database is updated?</li><li>What happens if we cache too much data?</li><li>What data should we prioritize to cache?</li></ul><p>Despite how much is there to consider, is a widely used technique because of the enormouse benefits it provides, and there are many patterns to alleviate and solve some of those problems.</p><p>One case I want to show is what happens if we can ensure the data wont be updated. For example, if we used pure functions. We could make sure that, given a set of inputs, we will always get the same output.</p><p>In this case, this kind of caching is called “memoized functions”, because you could store the result of the functions and always shortcut to it’s return value because we know <strong>it will always be the same given the same input.</strong> A similar concept can be seen in dynamic programming, where you store intermediate calculations in an algorythm to avoid repeating comprobations or operations.</p><p>As an example, I’ll be using a simple calculating fibonanci problem, and I’ll be using an array instead of a map (because an array behaves similarly to a map mapped to numbers starting from zero to length-1 but with much less overhead)</p><p>Let’s see how fibo behaves with no caching:</p><pre>public static void main(String[] args) {<br><br>    long now = System.<em>nanoTime</em>()<strong>;<br>    </strong><em>fibo</em>(<strong>50</strong>)<strong>;<br>    </strong>long after = System.<em>nanoTime</em>()<strong>;<br>    </strong>System.<em>out</em>.println(&quot;Time passed &quot;+(after - now)+&quot; ms&quot;)<strong>;<br></strong>}<br><br>public static int fibo(int n){<br><br>    if(n == <strong>0</strong>) return <strong>0;<br>    </strong>if(n == <strong>1</strong>) return <strong>1;<br><br>    </strong>return <em>fibo</em>(n-<strong>1</strong>) + <em>fibo</em>(n-<strong>2</strong>)<strong>;<br></strong>}</pre><pre>// Time passed 77852757300 ms ~~ 77,8527573 s</pre><p>😱</p><p>Is taking that long because every call to fibo has to make <strong>THE ENTIRE RECURSION DOWN TO 0.</strong></p><p>But what if we store the value of each fibo? If we have the result stored, we just check it. If we don’t we calculate it and store it.</p><pre>public class Main {<br><br>    public static void main(String[] args) {<br><br>        long now = System.<em>nanoTime</em>()<strong>;<br>        </strong>new MemoizedFibo(<strong>50</strong>).calculate()<strong>;<br>        </strong>long after = System.<em>nanoTime</em>()<strong>;<br>        </strong>System.<em>out</em>.println(&quot;Time passed &quot;+(after - now)+&quot; s&quot;)<strong>;<br>    </strong>}<br>}<br><br>class MemoizedFibo{<br><br>    private final int n<strong>;<br>    </strong>private final Integer[] intermediateFiboCalculations<strong>;<br><br>    </strong>public MemoizedFibo(int n) {<br>        this.n = n<strong>;<br><br>        </strong>intermediateFiboCalculations = new Integer[n+<strong>1</strong>]<strong>;<br>    </strong>}<br><br>    public int calculate() {<br>        return memoizeFibo(n)<strong>;<br>    </strong>}<br><br>    private int memoizeFibo(int n) {<br><br>        if(intermediateFiboCalculations[n] == null)<br>            intermediateFiboCalculations[n] = calculateFibo(n)<strong>;<br><br>        </strong>return intermediateFiboCalculations[n]<strong>;<br>    </strong>}<br><br>    private int calculateFibo(int n){<br><br>        if(n==<strong>0</strong>) return <strong>0;<br>        </strong>if(n==<strong>1</strong>) return <strong>1;<br><br>        </strong>return  memoizeFibo(n-<strong>1</strong>) + memoizeFibo(n-<strong>2</strong>)<strong>;<br>    </strong>}<br>}</pre><pre>//Time passed 538200 ms ~~ 0,0005382</pre><p>😱😱😱 We have a decrease of five orders of magnitude in time. This is a HUGE improvement. Such is the power of caching</p><p><em>(I could have used int primitives to avoid overhead with Integer boxing, but I wanted to let calculateFibo be as close to Fibo as possible so I didn’t want to initialize the array in 0 and 1)</em></p><p>In terms of big O notation, we went from a O(n^n) to O(n) time, but increasing our memory from O(1) to O(n) in the process (<em>tradeoffs…</em>). Even so, I think the improvement is way worth it, right? As long as you consider what to save and how to access it.</p><p>Final comments: most technologies already use these things in one way or another. Caches are used WIDELY in software architecture: down from our CPUs, all the way up to in the cloud. Things like memoization are already used inside languages to improve performance if they constraint the functions to always be pure: such is the case of Haskell. Is a simple concept, yet it has wide implications and uses.</p><p>3rd of #100DaysOfContent</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5cfb4358dc59" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Facing the unknown and thriving]]></title>
            <link>https://medium.com/@joshiraez/facing-the-unknown-and-thriving-b7d859709f0?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/b7d859709f0</guid>
            <category><![CDATA[agile]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[learning]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 22:04:20 GMT</pubDate>
            <atom:updated>2020-04-23T22:04:20.745Z</atom:updated>
            <content:encoded><![CDATA[<p>Something that should work, doesn’t work as expected. Everyone is faced with this situation from time to time in software development. Our decisions and mental schemas depend on understanding a series of rules so we can chain them together and build, and code, our logic, falls apart.</p><p>Some would say that programmers could be classified depending on how they face these problems. Actually, I think this is kind of a harsh and naïve comparison, because facing these mishappennings can go from wishful finding (doing <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=13&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwj3qvv1v__oAhVC2-AKHbDaCeEQFjAMegQIAxAB&amp;url=https%3A%2F%2Fwww.agilealliance.org%2Fglossary%2Fexploratory-testing%2F&amp;usg=AOvVaw0Re0oPeRsB1Ja0o-JDhls7">exploration testing</a>) to absolute terrifing nightmares (edge case in production that you can’t reproduce for the life of you), and there are many kinds of programmers as well — learners, curious, cautious, conservative, disruptors… these factors among a lot others contribute to how one person react to one such situation. So be careful before passing judgement when you see someone not handling this well.</p><p>But, once you find something like that, what can you do?</p><p>For me, there are three key points:</p><ul><li>First, <strong>discover</strong> exactly what is the thing that is not working as expected. You are going into obscure (or undocumented) knowledge territory, so you will want to limit the scope of the research</li><li>Second, <strong>research</strong> what/how/why that happens. Find and fix the “wrong” knowledge. Do be careful, tho, and just do that up to a convenient abstraction level — don’t get down to decompiling stuff if it’s not needed :P (but if you are curious, pray go ahead!)</li><li>Third, <strong>settle</strong> that knowledge. Research why did you have that misunderstanding or look for good practices/how to use it/examples. Then, finally, set a testing strategy (unit are best, but, please, do it even with manual testing), and do your final “exam” breaking the code until you totally understand what it’s actually happening</li></ul><p>This doesn’t only work with misexpectations: this is actually based on a methodology called <a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=2&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwjH7vGpxf_oAhVRzhoKHdVnAygQFjABegQIAhAB&amp;url=https%3A%2F%2Fen.wikipedia.org%2Fwiki%2FProblem-based_learning&amp;usg=AOvVaw3oRqOXciIUIKBfxZ4W96nx">Problem-based Learning</a> where you learn through learning to craft tools and assets that aid you to solve the problem. As you see, <em>we are not so focused on getting it working</em>, but in <strong>making sure we wont ever get it wrong, again</strong>.</p><p>Although only do this if you have the time! <em>If its critical or you have a nearby deadline, use workarounds and make a </em><strong><em>refactoring ticket</em></strong><em> </em><strong><em>to look at it later</em></strong>!</p><p>Day 2 of #100DaysOfContent</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b7d859709f0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RxJs tips: how to refactor chained subscriptions]]></title>
            <link>https://medium.com/@joshiraez/rxjs-tips-how-to-refactor-chained-subscriptions-eb0b5b2ec136?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb0b5b2ec136</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[flatmap]]></category>
            <category><![CDATA[mergemap]]></category>
            <category><![CDATA[rxjs]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Thu, 23 Apr 2020 00:43:26 GMT</pubDate>
            <atom:updated>2020-04-23T00:43:26.701Z</atom:updated>
            <content:encoded><![CDATA[<p>First of all, welcome to my #100DaysOfContent. After being told to <a href="https://twitter.com/ianmiell/status/1252592495390851075?s=20">JFDI</a> and reading an increible post about <a href="http://journal.stuffwithstuff.com/2014/04/22/zero-to-95688-how-i-wrote-game-programming-patterns/">How Game Programming Patterns</a> was born, I realized that if I wanted to start doing something and get some consistency, I had to get on it heads on. And, so, here we are. I dont know how the hell I’ll be doing 100 articles and how much of them will be utter shit, but I’ll try my best.</p><p>Onto the topic, today I bring another in-work lesson. The story is quite simple:</p><ul><li>We had some logic in an Angular component. But that logic used subscriptions with side effects to put the result data into the component.</li><li>It “made sense” to use subscriptions, because we needed for a rest endpoint to finish to use its data for another call.</li><li>We wanted to replicate that behaviour. I decided to move it to a service, to have a single point for that behaviour, instead of copying the logic.</li><li>Alas, the side effect wouldn’t work outside the component. We had to find a way to return the data. And it wouldn’t do inside the subscription: it would return first because is an async operation.</li><li>It wasn’t as easy as returning the observable, either. Because we needed the result of some calls to chain with the next calls (with some coupled logic in between for pushing notifications)</li><li>😱</li></ul><pre>this.s3Service.getUploadLink(asset).subscribe( link =&gt; {<br>  const notificationId = this.notificationService.publish(asset.name);<br>  this.projectService.uploadAsset(asset.id, link).subscribe( project =&gt; {<br>    this.notificationService.remove(notificationId);<br>    <br>    this.project = project;<br>   }<br>});</pre><p>The big point of pain in the refactor were the chained subscriptions. It MIGHT work if we used a subject and emitted from there (although it wouldn’t be the best solution) but it seemed like a hack. And although I was short on time, <a href="https://medium.com/angular-in-depth/when-to-subscribe-a83332ae053">it just felt wrong to do a subscription in a service</a>. So refactoring we go.</p><p>I had to research two things that I didn’t know at a glance how to do:</p><ul><li>How to chain pipes so I can pass the results of one call to do another call?</li><li>How to propagate the notificationId so I could remove the notification after it finishes uploading?</li></ul><p><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwiaruCYo_3oAhVuAWMBHQumCh0QFjAAegQICBAB&amp;url=https%3A%2F%2Fwww.learnrxjs.io%2Flearn-rxjs%2Foperators%2Ftransformation%2Fmergemap&amp;usg=AOvVaw23ZlWkdWqH6YFbkoImUgpW">MergeMap</a> to the rescue! Because what we were getting from the calls were Observables… and we could always chain those merge/flat mapping them to values!</p><p>So instead of <em>subscribing</em> to get the value, we <strong>map our data stream to the result of the call. </strong>This can be further piped to other calls, <strong><em>so we are kept inside the observable without ever having to subscribe</em>.</strong></p><p>As for the other problem, we could use map to propagate the notification id as needed (although, I believe this can still be improved. If you have any suggestions, please comment :D)</p><p>The end result was something like this:</p><pre>uploadFile(asset: Asset) : Observable&lt;Project&gt; {</pre><pre>return this.s3Service.getUploadLink(asset)<br>    .pipe(<br>        map( link =&gt; <br>          ({link, <br>            notificationId: this.notificationService.publish(asset.name)<br>           })),<br>        mergeMap( ({link, notificationId})=&gt; <br>           this.projectService.uploadAsset(asset.id, link)<br>             .pipe(tap( ()=&gt; this.notificationService.remove(notificationId) <br>             )))<br>     );</pre><p>We are returning an observable. No subscriptions. We propagate the notificationId and link down the pipe. Upload the file, then we tap into the second mergeMap to be able to remove the notification once the upload has finished.</p><p>This can be applied as a rule of thumb. If you need a result of a call, flatMap it down the pipe, don’t subscribe!</p><p>And that’s the first day folks! If you have suggestions to improve the code, pray comment please. I still don’t quite like it, and I guess it gets the job done, but I want to learn how do you think would be the “optimal” way to solve this :D</p><p>See you tomorrow!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb0b5b2ec136" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rethinking Interfaces and Abstract Classes]]></title>
            <link>https://medium.com/@joshiraez/rethinking-interfaces-and-abstract-classes-591705b39898?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/591705b39898</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[interfaces]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Wed, 01 Jan 2020 05:04:22 GMT</pubDate>
            <atom:updated>2020-01-01T05:04:22.447Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rethinking Interfaces</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/848/1*OoRuJBvmY2YB1TixQTVKUg.png" /></figure><p><em>This is mostly a dissertation I realized while playing with enums, as a way to make discrete set of behaviours more maintenable. You can find what it looks like to use an Enum to refactor a switch in </em><a href="https://medium.com/@joshiraez/beating-the-switch-smell-d45f366ffca8"><em>Beating the switch smell</em></a><em>.</em></p><p><em>I get to no conclusions. I just want to show what I find a interesting equivalence that can be used to juggle with some of the language restrictions.</em></p><p>I had to rename many times this article, because I couldn’t reach to any conclusion as to “what” I wanted to say. Some of what I wanted to write was already covered in <a href="https://medium.com/@joshiraez/beating-the-switch-smell-d45f366ffca8"><em>Beating the switch smell</em></a><em> </em>so I saw no point on repeating that.</p><p>Yet, there was still some points that I found interesting when I kept working on the technical tests I have had these last months and trying to scratch some itches that I happen upon them. Maybe I don’t have a “what”, but I have a “how” and “why”, so I hope it can be of use to other people.</p><p>Okay, let’s get to the itch: you have n use cases that share a common strategy. So they share a common interface or an abstract class that define the methods needed for that strategy.</p><p>Yet, if I use an interface or an abstract class, I’ll end with n + 1 classes to implement the interface/abstract AND its implementations!</p><p>This always rubbed me the wrong way. Why if we are talking about a common strategy, I end with so many files? Shouldn’t it be one? Or at least, most of the definition should be on one surely?</p><p>It gets even darker when the strategies are simple (and it should be if you try to keep your methods short!). You could always define the subclasses inside the same file, akin to a Sealed Class (<a href="https://openjdk.java.net/jeps/360">which are coming in Java 14</a>!), but makes a lot of boilerplate.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93c281e31f12fdc958e536aa9ce5ec31/href">https://medium.com/media/93c281e31f12fdc958e536aa9ce5ec31/href</a></iframe><p>I could even make an abstract class, but I will get to that later.</p><p>What I noticed is… hey, in reality, these functions are so small. Wouldn’t it be wonderful if I just could lay them in a lambda (which, for me, look more concise and with much less boilerplate). Then I realized.</p><p><strong>I only care about the interface in that I need the instances I’m working with to define those operations for my strategies to work. But I don’t care at ALL about the class itself or whatever extra they might bring.</strong></p><p>So… why use an interface or an abstract? When I really want is an instance that brings those 2 functions!</p><p>Now I don’t need N classes. I can define a set of them on the fly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ad064e5b17c9eb0ea9f5cf4061a21091/href">https://medium.com/media/ad064e5b17c9eb0ea9f5cf4061a21091/href</a></iframe><p>As the comment notes, putting them in the program is an example. Now I can put them in whatever place I like. Putting them in an Enum is my favorite, because it makes for something “almost like” the idea of sealed class, and I can define this Operation class using the enum itself. But you can make it in a Dictionary, in your code, using helper classes, whatever.</p><p>There is only one thing left to make this truly equivalent. This is not still our interface, but getting to the interface from this is trivial.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/88e105b0d50dc7fb06b18304265ed527/href">https://medium.com/media/88e105b0d50dc7fb06b18304265ed527/href</a></iframe><p>So… yeah? We have instantiable interfaces? We have a redefinition on Java interfaces? Something, something? (Although nowhere as near as Go interfaces).</p><p>I was unable to extract conclusions, because this conversion is totally abstract and, while very good for a subset of problems, is not that good for others. The most notorious one is when you actually need the data (because you mix behaviour with data in a pure OOP style) in which case it gets a little unorthodox.</p><p>But some clear advantages for me of this conversion are:</p><ul><li>Freedom on definition. You can still make single Java files for each one of the “classes” that would implement that “interface” if you would need. But you are no longer restricted to only that. Defining them inline, in logic, in configuration files, dictionaries, enums… the choice is yours, to make the code more legible and maintenable.</li><li>Enables single point of modification for polymorphism. No longer we will have to change N classes if we change an interface. Depending on the strategy, we could make static factories that are backwards compatible, configuration files with all the possible cases,… when extending an interface. (Although we already had default method on interfaces in Java9)</li><li>Conciseness, arguably. Depends on the length of the functions. If they are single expressions, sure! If it is a long chain of calls or a block code, not the best solution. But nobody stops you from putting it in another file and referencing it.</li></ul><p>But the big con is that, if someone goes instantiating interfaces wherever, yeah, you could get a big messy unmaintainable code. That’s why I only use this if I explicitly use in some construct/strategy that makes it clear that those are all the possible instances that are implementing the interface.</p><p>I still prefer having the freedom to not have N files and classes which increase cognitive complexity of the application.</p><p>But… I don’t really have a conclusion. Is more like a tool. Sometimes it can be good. Sometimes it can be bad. But, what for? It depends on the case.</p><p>I can totally see it being used in configuration and abstraction libraries (you can do some REALLY cool stuff with generics), and, in my experience, makes both logic code and configuration code just that much more concise.</p><h4>Some interesting cases:</h4><p><strong>Abstract classes:</strong></p><p>I think this conversion even makes more sense for abstract classes. Look at it like those function atributes that need to be instantiated are puzzle pieces that you need to introduce.</p><p>You can actually refactor the former class to an abstract approach, having some part of the implementation already done, while still implementing the interface. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ed580a97c272b06e2fac5f6fdf94c8e2/href">https://medium.com/media/ed580a97c272b06e2fac5f6fdf94c8e2/href</a></iframe><p>This even makes shorter the lambdas we have to pass to complete the abstract class. We avoid inheritance problems inherent to abstract classes too.</p><p><strong>Data classes</strong></p><p>We can do data classes as easily too. Although is uncommon the need for an interface to have to define some attribute accesors, you might need it.</p><p>While I was writing the article I thought that it could also be something to ponder about data encapsulation. Because is the result of a function rather than just accesing a private field through a public method. Food for thought.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3b6923ac1267504bbfc84c8673cd7a56/href">https://medium.com/media/3b6923ac1267504bbfc84c8673cd7a56/href</a></iframe><p><strong>Classic objects (data and behaviour together)</strong></p><p>Like I advanced before, one of the worst cases is when you want to make a classic object instance (and, more so, a mutable one). Up until now all objects we have done <strong>were immutable</strong>, and were clearly separated between logic and data instances.</p><p>Moreover, logic instances were concrete. That means that, like classes, we would keep those instances limited (by using some strategy like discussed earlier).</p><p>But what happens if we want to do some classes that mix behaviour and data using this aproach? Or mutable classes? (Because the Supplier aproach seen before wouldn’t allow for mutability at all)</p><p>You can do it, doing it in two steps. In this case, the class no longer create instances, but factories rather, and we need to create some sort of a builder using a closure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97a13879cf7304e8ca09cdd2e51e5eb8/href">https://medium.com/media/97a13879cf7304e8ca09cdd2e51e5eb8/href</a></iframe><p>But, honestly, if you have to get up to this point, you’d be better rather using a Builder or Factory pattern to take care of all this and just use regular old classes. Still, the option is there.</p><p>I hope you enjoyed the article. It has been a bit different because, for once, I didn’t focus in a particular problem. Rather, I just wanted to share some discoveries with some code samples.</p><p>I would deeply appreciate any kind of feedback. I know this is the usual “clever code but why use it” that is really looked bad upon by some devs, but that’s why I just let it as an option that can greatly simplify some cases.</p><p>Any kind of feedback on what you see it might be wrong (or what you think it might help you) would help me a LOT, because I still have so much to learn and everyday I discover that a lot of things are already invented.</p><p>So, please, if you read this, leave me some feedback here on in my <a href="https://twitter.com/JoshiRaez">twitter</a>! Thanks a lot!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=591705b39898" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting creative with Ruby. Implementing Data Driven Testing on it.]]></title>
            <link>https://medium.com/@joshiraez/getting-creative-with-ruby-implementing-data-driven-testing-on-it-44f55b04683a?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/44f55b04683a</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Sat, 07 Sep 2019 23:12:14 GMT</pubDate>
            <atom:updated>2019-09-07T23:12:14.756Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*E7hL1RjCFPOocpUoj99v7Q.png" /></figure><p>Doing Katas is fun! Is a nice way to improve oneself with sample problems, where you can challenge yourself with you might not find normally, experiment with new ideas or techniques, or just a nice excuse to start coding!</p><p>In this ocassion, I got myself with a nice little Kata about price calculations. I thought it was a good chance to start learning Ruby, so… why not? It was a language I had never used, I might need it sometime in the future and the sooner the better.</p><p>So I spent 1–2 days toying with the Ruby interpreter, trying <a href="https://github.com/edgecase/ruby_koans">Ruby Koans,</a> looking for some good testing frameworks (i settled with <a href="https://rspec.info/">RSpec</a>) and getting my head around <strong>Why and How to Ruby</strong>. I started from scratch, without no previous knowledge whatsoever (oh boy, what I had missed :O) and climbed my way up little by little. Once I got a hang of how stuff worked and felt comfortable doing basic stuff (using RSpec and using RubyMine) I got on with the Kata, and kept learning and trying stuff while solving actual problems.</p><p>I gotta say that this learning experience was fantastic. I’m glad I got the chance and I discovered an amazing language</p><h4>Ruby just scratches that itch</h4><p>First and foremost, I gotta admit my first step with Ruby was reaaaaaaally dense. Its like nothing else I know of! But at the same time, it was just the kind of thing I have always dreamt that should exist!</p><p>If you have read other blog posts, I have a firm conviction about how everything in a program is just data, transformations and wirings. You could theorize that you could make a program where everything is just data being passed to other data/to transformers/to presenters. <strong>And Ruby is just that.</strong></p><p>Everything in Ruby is an object. There are no sentences: instead, Ruby uses “messages”… akin to a function’s parameter. No object receives function calls or attribute access. Rather, they just receive messages. And answer to them. The first part of the message would be the member of the object trying to access to, while the rest would be the parameters needed. Ruby will send the message and do its best for the object to answer it.</p><p>Although some languages get very far with this concept (for example, Python, where mostly everything is also an object), Ruby turns it up a notch. There are no sentences in Ruby (that I know of). Instead, everything are objects being sent messages. Loops, conditionals, operations… are classes or functions and you use them sending them a message with data (numbers, strings, or even code in Ruby’s anonymous function classes ).</p><p>Yes, anything can be sent as a message by the way, meaning that you can do really, reeaaaaaally powerful stuff combining different kinds of code seamlessly.</p><p>Add to it that it comes with a nice variety of syntax sugar, and you get a language that can literally be read like it was english. Some little examples that I liked a lot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/302/1*jEP01Va0dvqT_VX8KI4lKA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*N_lF0vnVBtuL41ylurTjGA.png" /></figure><p>I feel like I just scratched the top of the Ruby’s surface in this week, but it made me fall in love with the language. When you can write logic in such a self-explanatory way, or do some powerfull stuff like I’ll show you next, you really do wonder how far the rabbit hole can go.</p><p>Not everything was the greatest though: I really had a hard time at the start because it is nothing like anything I have ever known. Class definition and access is a thing of its own. Silly mistakes keep appearing (hello “missing_method in Nil:Class”). Even constants have some rules because you need to be careful with namespace collisions. But <strong>once I started thinking on Ruby instead of thinking in other languages, things started going much smoother.</strong></p><p><strong>And that’s because Ruby is <em>much easier</em> to reason than other languages</strong> because there is only a single rule: objects being sent messages; and you have a degree of freedom to program like in any other. In fact, the main issue I had after finishing the Kata is how <strong>I felt that there were so much more I could have done and possibly didn’t even think of </strong>and left me craving to learn more about the language.</p><h4>Getting creative. How does it help our code</h4><p>I want to show you a real example of cool stuff you can do with Ruby if you understand the rules.</p><p>I had a problem when doing some tests: I found out that I ended replicating a lot of code for testing differents cases of the use-case. It was somewhat acceptable at first, but it quickly become downright obvious that it was adding a lot of bloating with no added value to the code. It was to be expected, at least, because some of the behaviours were just calculations functions that computed the price with some special discount and what not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*ap2XuAn_CSVtC3m-WMckkw.png" /><figcaption>Not to mention I could have used a before to set up the Unit under test, but there would be still a lot of repetition</figcaption></figure><p>This was for only one rule, and only for one item. It got to a point that I really wanted to see if the rule worked generically for any kind of configuration or discount. This was only 3 test cases. We could easily get to 15 if I wanted to be confident that I did the math right in the formula…</p><p>BTW this kind of testing where you focus on the data to set the test case is known as Data Driven Testing. Most languages have some kind of tool to let you set different cases for a test. <a href="https://medium.com/@joshiraez/beating-the-switch-smell-d45f366ffca8">I did an article where I introduced Groovy’s framework, Spock, where doing DDT is really easy</a>. But after reading the RSpec specification, I didn’t find anything for DDT.</p><p>At that point, I thought “If I understood correctly, I could message a block to a loop. In fact, the test cases (the it) are nothing more than another function which accepts a title and a block to run(akin to JS jasmine’s), so why not could I just use the same idea to send those blocks to a loop so they are interpreted n-times with different parameters”?</p><p>I was pretty sure that it would work at that point in the Kata, so I just wrote a Hash with the data to fill the tests with, put it in an each loop, and passed to the loop the test template.</p><p>It worked perfectly!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/747/1*KXGt_W0O4Gh8Jpuhq9hN3g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*CvWHGtZOTcaKHZVBj982LQ.png" /><figcaption>Yey</figcaption></figure><p>Not only it reduced the boilerplate enormously, it is arguably easier to read and easier to extend. This concept, as I later learned, can be called “Metaprogramming” where you just program what your program specification would be setting up configurations. I, personally, felt really good when I just wrote it and saw that it worked, because it showed me a glimpse of the possibilities I could do with Ruby.</p><p>But, it felit like a very bizarre technique. For a time I thought this was just me creating little functional monsters again. But I discovered some days ago a post in Stack Overflow where they propose a similar solution for implementing DDT so, at least, it wasn’t that far fetched, and I thought it was kind the thing with ruby, the ability to do things like this.</p><p>Still, I think this power should be used with responsibility, and I would recommend <strong>having the team agree on what style should they use as to avoid wildly different styles making difficult to follow the code, or using knowledge share techniques like Code Reviews.</strong></p><p>In summary,<strong> I fell in love with Ruby. </strong>In fact, shorly after finishing the Kata I <a href="https://www.reddit.com/r/ruby/comments/czmchd/just_started_with_ruby_had_a_heck_of_a_time_any/">went directly to the Ruby subreddit and created a post asking for resources</a> to deepen my understanding on it. Folk were great and they recommended me a bunch of useful resources. Right now I went on with the <a href="https://rubystyle.guide/">Ruby Style Guide</a>, <a href="http://poignant.guide/">Poignant’s guide,</a> The Ruby Way and Metaprogramming Ruby. I also looked for the others recomendations and created some tabs to remind me of getting those books in the future.</p><p>I definitely want to try it some more and will do the <a href="https://www.codewars.com/kata/99-bottles-of-beer-1">99 bottles Kata</a> next, trying to apply what I have learnt while going deeper. I’m really excited about the possibilities and I want to see where it goes. You can expect more articles if I do more cool m̵o̵n̵s̵t̵e̵r̵ stuff.</p><p>And that’s all folks. Did it pick your interest on Ruby? Maybe are you planning on doing some Katas sometime soon? Or maybe was the proposed solution to implement Data Driven Testing useful to you? If you wanna say anything (even just “Hi!”) leave a comment :D</p><p>Remember you can see more in:</p><ul><li><a href="https://www.google.com/url?sa=t&amp;rct=j&amp;q=&amp;esrc=s&amp;source=web&amp;cd=1&amp;cad=rja&amp;uact=8&amp;ved=2ahUKEwitlLK35b_kAhUPAmMBHVi_B5gQFjAAegQIARAB&amp;url=https%3A%2F%2Ftwitter.com%2Fjoshiraez%3Flang%3Des&amp;usg=AOvVaw2AGKRArmuZEQ_VDIGhm8sk">Twitter</a></li><li><a href="https://www.google.com/search?client=firefox-b-d&amp;q=github+joshiraez">Github</a></li><li><a href="https://www.linkedin.com/in/joseraezrodriguez/?originalSubdomain=es">Linkedin</a></li></ul><p>Thank you for reading it, I hope you liked it. See you soon! :D</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=44f55b04683a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Beating the Switch smell]]></title>
            <link>https://medium.com/@joshiraez/beating-the-switch-smell-d45f366ffca8?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/d45f366ffca8</guid>
            <category><![CDATA[java]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[switch]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Sun, 09 Jun 2019 13:43:50 GMT</pubDate>
            <atom:updated>2019-06-09T13:43:50.776Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R26BXaSq9fK8HNiODm5jAg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@tirachard-kumtanom-112571?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Tirachard Kumtanom</a> from <a href="https://www.pexels.com/photo/white-blank-notebook-733857/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>A recent conversation on <a href="https://twitter.com/JoshiRaez/status/1122160996645314560">Twitter</a>, <a href="https://twitter.com/unclebobmartin/status/1122112068201664513">sparked </a>by famous software dev and writer <a href="https://es.wikipedia.org/wiki/Robert_C._Martin">Uncle Bob,</a> left me thinking. It has been a long while since I last used a Switch. I usually don’t feel the need to implement them, and I wondered about the reasons.</p><h3>Uncle Bob Martin on Twitter</h3><p>Switch statements are not intrinsically harmful to software structure; but they cause great harm when the cases depend upon concrete details rather than polymorphic abstractions. Switch statements should invoke constructors not operations.</p><p><strong>Conciseness and maintenability is the main concern</strong>. Personally, I think switchs are terrible to read, easy to mess up, and a clear violation of the single responsibility principle. Some people will usually leave switches in some sort of factory pattern in the depths of the system, but I think we can do better.<strong><em> I’ll show two alternatives I use to refactor switches into more readable patterns.</em></strong></p><p>I have done it in <strong>Java </strong>where I find most useful the use of those patterns because of how limited and verbose java switch statement is (at least until Java 12 new switch comes out), but you could implement these alternatives in any language!</p><p>You could also use Kotlin or Scala, which have much more readable switch <strong>expressions </strong>(Scala’s allows for pattern matching, even). Although you could make the decision to avoid their “switches” altogether and use any of these alternatives instead.</p><p>Let’s begin!</p><blockquote>Did you know? Most switches can be transformed to a data structure while retaining the same behaviour but gaining in readability and maintenability.</blockquote><h4><strong>Strategy</strong></h4><p>So what are we gonna do? Refactor!</p><p>We will start with a simple Switch for a calculator function, who receives an “operation” character, and two integers. This could be our business object for a very simple calculator.</p><p>We will test first, implement it, and then refactor it to other cleaner alternatives.</p><p>You can check the repository for this article on:</p><p><a href="https://github.com/joshiraez/Articles_BeatingTheSwitchSmell/">https://github.com/joshiraez/Articles_BeatingTheSwitchSmell</a></p><h4><strong>Switch implementation</strong></h4><p>Let’s start with the tests for our calculator. It will be a very simple calculator, akin to what you would do in Programming 101. It will accept two ints, and a character operator (+, -, x, /) for the operation. A division by zero will return the expected ArithmeticException and an unknown operation will return InvalidArgumentException.</p><p>I decided to do the tests in<strong><em> groovy with the spock framework</em></strong>. I love how readable they are and that they have data driven testing as a first class feature, allowing for repeated tests with varying inputs to test corner cases.</p><p><em>(Although, I found out that you can’t use Spock with Java 11 because of some bugs :(. It seemed that they were still working on it on their github. If they know how to fix that issue, leave it on the comments! :D)</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76cc21e0b1d926bd0011e508ddc4b628/href">https://medium.com/media/76cc21e0b1d926bd0011e508ddc4b628/href</a></iframe><p>We will have a whole lot of red in these tests. You would usually do a test until it fails, and then go and do the implementation. But for convenience sake I just put them all first (I’ll do a TDD article sometime later. Promise :P)</p><p>Let’s get with the implementation then!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/313416b6986b56b5fe1d81d7572d903e/href">https://medium.com/media/313416b6986b56b5fe1d81d7572d903e/href</a></iframe><p>Quite simple. What you would usually do in the initial courses of programming.</p><p>But is quite hard to read. The switch sentence itself is very verbose, needing to also add all those break statements. We also need to add a variable if we want to maintain the “single point of return” principle. We also have 4 diferent behaviours in one function, which is unavoidable, but, can it be improved to at least make it clearer that a function goes with its respective operation?</p><h4><strong>First alternative: using a data structure to save the relation between case and function</strong></h4><p>I’ll admit this one is quite strange to see, although I don’t know why.</p><p>We are used to use constants to save relations which are not meant to be changed. Not only constants, but also arrays or maps of constants that are specific to our business logic and not meant to change (or to make them easier to configure because they become the single point in the system where that logic is stored).</p><p><strong><em>So why can’t we use this same idea using functions?</em></strong></p><p>Because we have tests, we can refactor the former calculator class without risks. We will convert that nasty switch to something much more readable, extendable and with added meaning on it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7bf415c736a15852eef8165c328eedf5/href">https://medium.com/media/7bf415c736a15852eef8165c328eedf5/href</a></iframe><p><strong>Not only we have reduced enormously the amount of boilerplate code</strong> (the only thing left is that big line 9, and 10 but that could be helped somehow with the var keyword). <strong>We have added an implicit meaning that each operator has an assigned function and that any extension to this should behave in the same way.</strong></p><p>In top of that, we could easily move the map now to another class that would have the single responsibility to choose the correct function. Much better, in my opinion.</p><p>The main disadvantage is that because of java type safety, if we wanted to extend the behaviour of our map, we would forcefully need to create a set of classes with the corresponding needed interface. But we can take another extra step to make that concise, too.</p><h4>Second alternative: using an enum to enable concise polymorphism</h4><p>Among the many advantages of enums, there is one very little known: <strong>every enum acts as an abstract class, with each instance being instances of that abstract class.</strong></p><p>We can couple this with Function variables to get a much greater deal of flexibility, allowing us to modify each instance behaviour in a very concise way. Althour we don’t need it for our current calculator, it will help us a ton in case we need to extend its behaviour.</p><p><em>We can pair this with a data structure like we saw before to allow us to create a very readable factory without ever needing to use a switch.</em></p><p>Just look at the end result in our calculator function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d951705c876674d5f5766e3381f26b3/href">https://medium.com/media/6d951705c876674d5f5766e3381f26b3/href</a></iframe><p>Not only we have reduced our business logic to a single, readable line. Now we have left to its own class the responsibility of choosing operations, and also the implementation of them. In a manner which is easy to read and easy to extend</p><p>In fact, I wish there was some way to override how enums are defined so I could assign the respective character identity to them and save myself the Map, alas, is a good example on how we can combine the two.</p><p>You can run the tests again and see that everyone is green. The refactor was a success!</p><p>—</p><h4>Closing</h4><p>At first, this article was gonna be much larger than this, but I quickly found that it would become too big and the first example with the calculator was nice to bring the point accross. A little bonus I had, how to build a pattern matcher in java using the ideas seen here, I have left it for a future article in which it will be the main focus.</p><p>I haven’t gone too much into the disadvantages of switches or advantages of enum because there are a lot of other resources online which do a really good job. My main point was how we could easily refactor switches to other patterns and I hope it helped you to get some new ideas (or to try those alternatives yourself :) )</p><p>And if you want to say anything about the alternatives, other ways you would have done it yourself or things I might have overlooked… please, do leave a comment! I’ll try to get back to you!</p><p>Thank you for reading, as always, and see you soon. If you want to see more of me, check:</p><ul><li><a href="https://twitter.com/joshiraez">Jose &#39;Joshi&#39; Raez (@JoshiRaez) | Twitter</a></li><li><a href="https://github.com/joshiraez">joshiraez - Overview</a></li><li><a href="https://www.linkedin.com/in/joseraezrodriguez/">José Ráez Rodríguez - Software Engineer y Data Analyst - City Sightseeing Worldwide | LinkedIn</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d45f366ffca8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Playing with data. A bit of functional programming with map, filter and reduce]]></title>
            <link>https://medium.com/@joshiraez/playing-with-data-a-bit-of-functional-programming-with-map-filter-and-reduce-78bf06a19387?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/78bf06a19387</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[data]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Sun, 28 Apr 2019 09:31:00 GMT</pubDate>
            <atom:updated>2019-04-28T09:31:00.894Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/985/1*qmmzKZpjQof7lSFU41xSZg.png" /></figure><p>If you have read my other articles, <a href="https://medium.com/@joshiraez/the-programmer-puzzle-what-is-programming-7f444ab0bd7d">The Programmer puzzle</a> and <a href="https://medium.com/@joshiraez/data-homogenization-how-to-blend-together-use-cases-using-lambdas-2db53cfacc7b">Data Homogenization,</a> you should know by now that Data Manipulation and Higher Order Functions are some of my preferred topics.</p><p>So with the huge hiatus I had (sorry!) and seeing that I was going to make some notes and exercises for a colleague that recently joined our team about this… what better idea than creating a new article just about that!</p><p>So let’s get with it.</p><p>How many times have you dealt with huge serialized data that comes from an external source. Microservice, Restful API, getting data from persistence… you name it.</p><p>How many times have you dealt with Lists/Arrays/Sets/SomethingSomething Iterable (even Maps or Objects)? Extracting info, curating, processing, digesting and a lot of other verbs where we produce and present useful info for our users from our abstract data sets.</p><p>I can tell you without any fear that a huge chunk of our work is managing data in some data structure. Back-end lives from it and modern front-end does to a point.</p><p>But this has some problems, namely:</p><ul><li>What if the data set is accidentaly changed when working on it?</li><li>Is there any simpler way to express those concepts (that we have in languages like SQL) in our programming languages?</li><li>“This works in my computer :)”</li><li>Reusability. Working with data is hardly reusable because every use case will use the data in some way.</li><li>Abstracting from how our data structures work to end in what we want to get.</li></ul><p>And some other. Although is quite the fundamental operation, it can have a miriad of problems and it is often the source of many bugs.</p><blockquote>We produce and present useful info for our users from our abstract data sets.</blockquote><blockquote>I can tell you without any fear that a huge chunk of our work is managing data in some data structure.</blockquote><h4>Here comes functional programming to our help</h4><p>The main idea behind functional programming is to abstract ourselves from how we get the stuff, and instead think about what we want. This is an oversimplification of a very powerful concept, but I can list some of the advantages functional programming brings:</p><ul><li>Immutability: we don’t have to worry with messing with our sources of data.</li><li>Predictability: the same inputs will ALWAYS have the same output.</li><li>Modularity: codes are built around concepts. We can swap the concepts whenever our data fits.</li><li>Brevity: Because of all the above, functional programming is easy to read and quick to write. We have to do less code to avoid errors, we are limited so we avoid some code smells and in the end we have little, succint, blocks of codes that do very clear things.</li></ul><p>Those are some of the advantages, and there are also some disadvantages, so I have summarized the main benefits that bring to us when managing data.</p><blockquote>The main idea behind functional programming is to abstract ourselves from how we get the stuff, and instead think about what we want</blockquote><h4>Pure functions. Higher order functions</h4><p>Our main tool for this is the use of <a href="https://en.wikipedia.org/wiki/Pure_function">Pure Functions</a>. Functions that:</p><ul><li>Always returns the same value for a given input.</li><li>It has no side effects (aka, it doesn’t change any state outside the function).</li></ul><p>Yeah, is as simple as that. And I bet that any programmer that tries to make modularizable, clean code will have realized that functions like this are preferable.</p><p>Why are a simple concept like that so powerful? For example, let’s see our 4 advantages:</p><ul><li>Immutability: No side effects so no mutability.</li><li>Predictability: A given input always returns the same output. (And also no side effects. Yeyness)</li><li>Modularity: Because of no side effects, we are unable to make coupled code (well, not unable, but much harder to do it as least). There are no codependencies, hidden complexity and any of that. This also ensures that pure functions can be reused if we need the same output for a given input.</li><li>Brevity: Not a byproduct of the pure functions, in my opinion, but it comes with the advantages it brings to a coder. Less error prone means less boilerplate. Pure functions can be chained together into bigger pure functions so we can resume concepts in a simple step if necessary. This also means that because it’s not a byproduct, it’s not always true. But in most cases it makes the code more concise, shorter and readable.</li></ul><p>Another tool we have is the concept of <a href="https://en.wikipedia.org/wiki/Higher-order_function">Higher order functions</a>. Worduck for “using functions as another parameter”. What’s so great about this?</p><blockquote>Pure functions are the equivalent to a given data when you are working in an algorithm. <strong>You can substitute a pure function by its result and it will have no effect in our code AT ALL.</strong> This effectively means that we can inject custom behaviours to our code to improve reusability.</blockquote><p>Let’s see an example. All those functions do the same. Is plain js, so copy and paste it into your browser’s console to try them.</p><pre>//Notice we need two functions when the ides is basically the same.<br>//Two points of maintenance solved with... global constants. Sadness</pre><pre>const sayHiInLower = <br>  aString =&gt; &#39;Hola &#39;.concat(aString.toLowerCase());<br>console.log(sayHiInLower(&#39;Jose&#39;));</pre><pre>const sayHiInUpper = <br>  aString =&gt; &#39;Hola &#39;.concat(aString.toUpperCase());<br>console.log(sayHiInUpper(&#39;Jose&#39;));</pre><pre>//But we could decorate it with a function and convert those two //functions in one! In fact, to any number of it.<br>const sayHi =<br>  (aString, withFormat) =&gt; &#39;Hola &#39;.concat(withFormat(aString));</pre><pre>console.log(sayHi(&#39;Jose&#39;, a =&gt; a.toLowerCase()));<br>console.log(sayHi(&#39;Jose&#39;, a =&gt; a.toUpperCase()));</pre><pre>//This works too!! No need for extra functions now.<br>console.log(sayHi(&#39;Jose&#39;, a =&gt; a.concat(&#39; Raez&#39;)));</pre><p><em>Note: That although this concept is conceptually powerful with pure functions, it can be used with any kind of function/procedure to inject custom behaviour to a code, improving the reusability anyway. The decorator pattern drinks from this (although at the object level instead of at function level, but the idea is the same).</em></p><p><strong>The for each madness</strong></p><p>Well, there is one more thing I have to write about.</p><p><em>For loops.</em></p><p>Why? How do we usually deal with collections in any modern language?</p><p><em>For loops</em> (or the more modern<em> for each loop</em>). <em>A lot of them. </em><strong><em>A loooot.</em></strong></p><p>You know the feeling when you have to iterate over a collection and you see like 4 operations done inside, mutating the collection, doing stuff. How bad is the readability? <strong><em>Baaaad</em></strong>.</p><p>Even worse, if you really want to separate every operation, then you end doing 2+ loops. In every loop repeating the same line of code.</p><p>Even worse still, if we want to make it immutable (as to leave the original untouched), we have to instance a new collection and fill it <strong>every-damn-time. </strong>And this is unavoidable, repeatable stuff that you will see in <strong>EVERY</strong> operation.</p><p>Just see this example: we have an array of numbers, from which we want to get the sum of the odd ones. Every function does the same thing, but the mainteinability is much better in later ones (easier to modify and less prone to bugs).</p><pre>//Again, you can test this on your browser&#39;s console<br>const numbers = [1,2,4,7,10,21];</pre><pre>//Usual case. Put together everything in the same loop.<br>//Problem: we couple different actions on a function.</pre><pre>const singleForEach = listNumbers =&gt; {<br>    let total = 0;<br>    for (number of listNumbers) {<br>        if (number%2!=0) total += number;<br>    //This naive line couples two actions!! <br>    //Filtering and acummulation<br>    }<br>    return number;<br>};</pre><pre>console.log(singleForEach(numbers));<br></pre><pre>//Second version where we try to separate the actions.<br>//We create a new list to avoid mutating the original.<br>const filterOdd = listNumbers =&gt; {<br>     let oddNumbers = [];<br>     for (let number of listNumbers) {<br>         if (number%2 != 0) oddNumbers.push(number);<br>     }     <br>     return oddNumbers; <br>} <br>const sum = listNumbers =&gt; <br>{<br>   let sum = 0;<br>     for (let number of listNumbers) {<br>         sum += number;<br>     }<br>     return sum;<br>}</pre><pre>//We have succesfully remove the coupling <br>//and made two pure functions! <br>console.log(sum(filterOdd(numbers)));</pre><p>Please take a look at the second example. Not only are the loops repeated but, if we wanted to do operations like these again (for example, filter even numbers), even more code would be copied. Let’s see what they have in common:</p><ul><li>When we filter, we will always take the result of a boolean expression to know if we want to keep the element.</li><li>When we accumulate, we will always accumulate in a variable the result of a given expression.</li></ul><p>So with the knowledge of higher order functions we saw before, we could take this a step further.</p><pre>//Third version, using higher order functions to <br>//allow us to abstract us to the core idea  <br>//like filtering or accumulating.  </pre><pre>//Notice that the code is mostly the same, but <br>//we can inject now our wanted behaviour.  <br>const filter = (elements, predicate) =&gt; {<br>     let filtered = [];<br>     for (let element of elements) {<br>         if (predicate(element)) filtered.push(element);<br>     }<br>     return filtered;<br>}  </pre><pre>const accumulate = (elements, accumulator, fromInitialValue) =&gt; {<br>   let accumulation = fromInitialValue;<br>     for (let element of elements) {<br>         accumulation = accumulator(element, accumulation);<br>     }<br>     return accumulation;<br>}  </pre><pre>//We can now define our desired behaviours </pre><pre>const oddPredicate = number =&gt; number%2 != 0;<br>const sumF = (number, otherNumber) =&gt; number + otherNumber;</pre><pre>//And magic, we get the above result again. <br>//Realize that the filter and accumulator functions wouldn&#39;t<br>//usually be in the same js, because they are more general use.</pre><pre>//So in the end, we have reduced a 6 lines, coupled, function<br>//to this:<br>console.log(accumulate(filter(numbers, oddPredicate), sumF, 0));</pre><pre>//A 3 liner, and one liner if we used lambdas instead of saving<br>//them in oddPredicate and sumF. Neat, huh?</pre><p>The above example is not far from what is used nowadays. This is the equivalent code using those functions the title speaks of :P.</p><pre>console.log(numbers.filter(oddPredicate).reduce(sumF, 0));</pre><p>And yeah, every piece of code does the same. But every iteration needs fewer and fewer lines with more and more general and reusable tools. This is great!</p><p>And those powerful tools is what I want to tell you about. We just looked at the <strong>Why</strong> use them<strong>.</strong> Now is the time for the <strong>How.</strong></p><p><strong>One last thing before meeting our protagonists…</strong></p><p>I will propose some exercises for the reader. Those functions are better understood when reasoned on paper, drawing diagrams and thinking about the transformations and then implemented. But we need data to practice with.</p><p>So for the data, we will use a public set available at <a href="https://restcountries.eu/rest/v2/all">https://restcountries.eu/rest/v2/all</a>.</p><p>Anyway, those are proposed exercises. Feel free to experiment with your own examples or even leave in the comments any good example or any questions you might have!</p><h4>Map. Transform data</h4><p>Our first protagonist will be Map. The data transformer.</p><p>Map gets a set of data of some length, and returns a <strong>set of data of the same length with the elements transformed.</strong></p><p>A common misconception of map is that it “does a for each”: that is, it executes a function on every element of the code. Although this is true, this is true for every other operation we are gonna talk today :P.</p><ul><li>A map must always return something.</li><li>If you want to run procedures, use forEach instead of doing this monster:</li></ul><pre>//Do not do this. Use forEach</pre><pre>elements.map(x =&gt; {doSomething(x); return x;});</pre><p>Ok, so how do we use map then? Just remember this: It will return the <strong>same elements transformed. </strong>In a more mathematical way: For a set S map will return a new set S’ where for every element a of S there will exist an element a’ that equals f(a) on S’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*BP7prmlliSmXNZSvDaygkA.png" /><figcaption>Map example where we get the double of every number.</figcaption></figure><p>Although the example is good to illustrate map, it doesn’t seem all that useful. But it is. Some of the most typical use cases for map are to transform a set of data to:</p><ol><li>To our desired type/interface, as to adapt the data set to be supplied to a required interface.</li><li>To a simplified object with the data we care about, as to be able to apply other functions on it to get a useful result (like reduce).</li></ol><p>Disclaimer: A simplified object is actually the same as changing to another type, but I think is much simpler to separate the cases between choosing data and transforming to another type.</p><p>Let’s see an example: (formatting could be better, but medium limits me)</p><pre>// We need to gather the total cost of our shopping cart.<br>const shoppingCart = [<br>   {name: &quot;Apple&quot;, amount: 2, unitCost: 1},<br>   {name: &quot;Honey&quot;, amount: 1, unitCost: 4},<br>   {name: &quot;Lettuce&quot;, amount: 4, unitCost: 2}<br>];  </pre><pre>//We only need to know the amount and unit cost of each element.  const usefulData = <br>shoppingCart<br> .map( entry =&gt; ({amount: entry.amount, unitCost: entry.unitCost})); console.log(usefulData);  </pre><pre>//We can&#39;t quite use this yet, because we are still mixing units. <br>//But we can map again to get the total cost for every entry.  <br>const totalCostPerEntry = <br>  usefulData.map(entry =&gt; entry.amount * entry.unitCost); console.log(totalCostPerEntry);  </pre><pre>//Nice, we only have left to aggregate every cost to get our expenses.  <br>const expenses = <br>  totalCostPerEntry.reduce((x,y) =&gt; Number(x) + y, 0); console.log(expenses);  </pre><pre>//Note that because they are pure functions we could just chain. </pre><pre>const theSameExpenses =    <br> shoppingCart<br>  .map( entry =&gt; ({amount: entry.amount, unitCost: entry.unitCost}))<br>  .map( entry =&gt; entry.amount * entry.unitCost )       <br>  .reduce((x,y) =&gt; Number(x) + y, 0); </pre><pre>console.log(theSameExpenses);</pre><blockquote>Just remember this: It will return the <strong>same elements transformed.</strong></blockquote><p><em>Exercises</em>:</p><ul><li>From the rest api, transform every item so it ends being a list of every country code followed by its country. For example, the “American Samoa” object would end being “AS American Samoa”. Format as you will.</li><li>Transform every object so you end with a list formed by the first letter of the country, and the country name, for every object. For example: “American Samoa” object would become [“A”, “American Samoa”]</li></ul><p><strong>Filter. Filter data.</strong></p><p>Next is filter. It filters data. Just that.</p><p>Still, this is often underused or misthought:</p><ul><li>Some think that it will remove elements from their list and want to/dont want to use them for it. Remember: all those functions return a NEW list, they will never touch the original if we use pure functions or expressions.</li><li>Others mix it with map and reduce, because they sort of transform the list (but remember, we transform the elements) and because we can kind of emulate it with reduce (but you should use filter, much more readable).</li><li>There are also other functions like All, None, and others that seem similar as well because they check boolean operations. But although you can emulate the behaviour with filter (checking the size of the list after) you should avoid that (again, because of comprenhension reasons). In fact, the behaviour of those Boolean list operations are more akin to a reduce function than a filter function (you end with one result).</li></ul><p>The trick to use it lies again in the number of elements. Filter will always <strong>return less or the same number of elements as the original, those that fulfill the given condition</strong>. Mathematically, given some condition and a set S, it will return a subset of S which contains all the elements x of S that so x fulfills the condition.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/311/1*298IVBTd1OklC0r1nEmuCw.png" /><figcaption>A graphical example of filter</figcaption></figure><p>I can’t pinpoint to any practical uses because I use it everywhere. Any REST api will bring some data that won’t be of use to us, because is not what we need, because is old, or whatever… any time we need to sanitize our set, we should use it.</p><p><em>Exercises:</em></p><ol><li>Create a filter that so you end only with the countries that start with the A letter.</li><li>Starting from a list with every letter from the A to the Z, try to combine a map and the previous filter so you end with a list containing all the different lists of the countries which share the same starting letter.</li></ol><p><strong>Reduce. Agregate data.</strong></p><p>With reduce we aggregate the data and get a result out of it. We do this providing a starting point and the function to acumulate current result and next element.</p><pre>//Example:</pre><pre>[1,2,3].reduce( (curr, next) =&gt; curr + next, 0);</pre><pre>//This is the same<br>let curr = 0;<br>curr = curr + 1;<br>curr = curr + 2;<br>curr = curr + 3;</pre><p>Although it’s hard to understand at first and seems quite simple at second, it’s actually one of the most powerful functions of them all, effectively being able to emulate most of the other list operators. This is because the rule with reduce is that we get a value from a list, but that value can be anything, including another list, object, or whatever!</p><p>Choosing our starting value and the agregate function cleverly, we can get anything that can be a extracted from a list.</p><pre>//Emulating map<br>elements.reduce((x,y) =&gt; x.concat(someFunction(y)), []);<br>elements.map(y =&gt; someFunction(y));</pre><pre>//Emulating filter<br>elements.reduce((x,y) =&gt; condition(y) ? x.concat(y) : x, []);<br>elements.filter(y =&gt; condition(y));</pre><p>As you can see, using the apropiate function is always shorter and more readable, so you should use them. But still, the point stands. <strong>Reduce can get ANY form of representation from a given data set.</strong></p><p>But it doesn’t stop there. If you have read my previous article, <a href="https://medium.com/@joshiraez/data-homogenization-how-to-blend-together-use-cases-using-lambdas-2db53cfacc7b">Data Homogenization,</a> you will have noticed that reduce can go much further. Because when we say any form of representation, we really mean it, and that extends to inversion of control: <strong>you can build any sequential work flow to operate on any data!</strong></p><p>Such a powerful tool has a lot of practical uses, but it is also really dangerous to use. It is very easy to make it hard to maintain or understand, or as a jack-of-all-trades when there might be better alternatives. Some tips:</p><ul><li>For starters, you should use it only when the logical action is to combine all the elementsof a list to a single result. This rule means that you wouldn’t use it for something like filtering, for example (where you discard some elements).</li><li>Also, you should refrain of using it whenever you wont combine the different elements. For example, creating a dictionary from a list is ok because you end classifying and grouping some elements together, but I wouldn’t use it if just are you putting them without any kind of interaction between them.</li><li>If any of the above are true, is very possible that there exists already a function that does the same but shorter and more readable. Even if you think it makes sense, is good to check in stack overflow if there might exist any function that does what you need without having to resort to reduce.</li><li>Try to keep it simple unless it really helps improve your code mainenability (specific operations, functional workflows, decorators, crazy stuff). If you are in doubt, always try to document what that reduce does.</li><li>And never, ever, use the accumulation as a sort of “state” neither use anything that is not a pure function inside the reduce. This can be said of any of the list operators but I think it is most important on reduce.</li></ul><p>Remember that those rules apply to production code mostly. You should try and experiment with what sort of crazy stuff you imagine. You will come surprised of what can you achieve with it!</p><p>As for examples, well, I want to make someday an article only about reduce and bizarre practical applications it has, so you might have to wait until then :P.</p><p>Exercises:</p><ol><li>Using reduce, get the world’s population.</li><li>Using reduce, try to achieve a dictionary where you classify every country by its letter.</li></ol><blockquote>Such a powerful tool has a lot of practical uses, but it is also really dangerous to use.</blockquote><p><strong>Closing</strong></p><p>This is only the tip of the iceberg of how powerful those functions are. There are many more functions, and then some that only exists on specific languages. They can’t be used for everything, neither they are the most optimized for some operations. But when maintenability and readability are important, they should always be used. They will make coding easier for you and for whoever reads your code.</p><p>There are many important operators I couldn’t show you in this article… mainly because it got too large. But please, if you are interested on this topic, please read about flat map, every, for each, and then take a look to the reactive programming flow operators.</p><p>And don’t be shy to comment below. Any feedback is appreciated, as any questions as well. I’ll try to address everything as soon as possible.</p><p>Thanks for reading</p><p>I haven’t written anything in almost a year! Wow, time flies by and a lot of stuff happened last year. I have tried many times but many ideas were left behind on the paper, unhappy with how they were turning up. I definitely have to finish them sometime, but I’m in no hurry: better a late job well done than a rushed job forever bad (when there is no time constraints, of course :P).</p><p>Also, I might leave Medium soon. I’m not happy with the new business direction Medium is turning and I fear the platform might add new unforeseen rules that further hinder the access to free articles, so I was looking about hosting a blog in github. But I’m still studying it.</p><p>Check more about me on:</p><ul><li>Linkedin: <a href="http://joseraez.com/">http://joseraez.com</a></li><li>Twitter: <a href="http://twitter.com/joshiraez">http://twitter.com/joshiraez</a></li><li>Github: <a href="https://github.com/joshiraez">https://github.com/joshiraez</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=78bf06a19387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Homogenization: How to blend together use cases using lambdas.]]></title>
            <link>https://medium.com/@joshiraez/data-homogenization-how-to-blend-together-use-cases-using-lambdas-2db53cfacc7b?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/2db53cfacc7b</guid>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[lambda]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[python]]></category>
            <category><![CDATA[data-science]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Mon, 29 Jan 2018 15:29:03 GMT</pubDate>
            <atom:updated>2018-01-29T15:29:03.412Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/874/1*28Zdw910YCjCpVv0Dmkq6g.png" /><figcaption>Tl;dr of the post</figcaption></figure><p>Recently, I was undergoing a interviewing process for Ximdex, a product-oriented company in Seville. Their main product is a format-agnostic CMS so it was predictable that their technical interview would be a data manipulation test.</p><p>I was right. Heavily simplified, the test was to apply to some data a JSON with arithmetic functions to get the final value. The data example was short, but it was implied that it could be very long (as one has to expect from almost any data coming from a file, actually).</p><p>My first approach was a typical OOP approach: create an object containing the data model, then get the data into data-model objects, then apply the desired function from the JSON for each object.</p><p>This idea quickly fell out, because I realized that</p><ol><li>I didn’t need most of the data.</li><li>I would have to classify first, then after classifying apply the JSON.</li><li>I didn’t want to save the data in objects in the Heap (because of arbitrary data size).</li></ol><p>Furthermore, <strong>if</strong> <strong>I inferred the type of JSON entry to use for every registry in the data,</strong> <strong>I wouldn’t even need the data model in the first place! </strong>Although for a larger project it would have made sense as to avoid having to extract the data more times.</p><p>There was another problem. The JSON had to be parsed, and the functions extracted and assigned the corresponding values. Although the operations were not complex (only sum and percent), I also had to assume the functions could be as large as whatever they could be and that there could be any number of operations (complex regex). So I wanted to avoid having to parse time and time again the JSON when a category always used the same formula.</p><blockquote><strong>If I inferred the type of JSON entry to use for every registry in the data,</strong> <strong>I wouldn’t even need the data model in the first place!</strong></blockquote><p>I quickly realized I should homogenize the JSON functions as to be callable from a single command.</p><p>The idea came from a previous experience in a reporting app, where I had to put together over 100 documents into a single powerpoint, every document with its own structure, format, whatever you can call it. Up until that point, programmers used to do a complete use case model for every document (as if every KPI is their own object and use case in the business, with is a correct OOP orientation). But it was very problematic: use cases changed almost every day, the documents format changed as well, and every change mean to localize, rewrite, and test the class dedicated to that business object…</p><p>But I quickly realized that what we really <strong>wanted was the result. To abstract ourselves from the data (the document formats, the data contained) and only focus on the desired result.</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/670/0*eVUhXjNbbzubkhuD.jpg" /><figcaption>Let’s get to the point.</figcaption></figure><p>But how. What was the big idea?</p><ol><li>I created a data abstraction class. It was not for a real business object, but a functional object: it’s only purpose was to represent a function, as if the result of that function.</li><li>The data abstraction object had parameters for whatever it was necesary to get the result: position, id of items to get, page number to print, etc.</li><li>At the end, there was a delegate. This is where the magic comes: that delegate returned another function, now with the data we passed to the object set on the function.</li><li>The delegate was who did the homogenization, using the parameters to personalize. If there was a very special use-case that needed extra work, we could create its own delegate. If that extra was used in more use cases, we could just extend the data abstraction class to implement more parameters.</li></ol><p>In the end, what it should have been 120+ classes, ended being a few classes: a static dictionary to the “functions”, the data abstraction class, few classes for the possible formats (with one “general” delegate and extensions of it for the “rare” cases).</p><blockquote><strong>Not only that, but the KPI reporting task was simplified to a for loop over the dictionary!</strong></blockquote><p><strong>The maintenance time was cut</strong>: adding new documents only needed to create new objects (not classes) with the desired paramenters. Creating a rare case was only creating a delegate over the general function that returned the function with the extra behaviour (logic is similar to that of the decorators). What took days before became minutes.</p><p>Adding 5 more documents? No problem. Client wants to have a image in that page? Do another function to extend the general task. You name it.</p><blockquote>The delegate was who did the homogenization, using the parameters to personalize.</blockquote><p>Returning back to our technical exam, I thought of creating something similar. What if I created function generators for each operation? And every function ended in another function that was what it would be finally executed with the data? Wait. I lost you, right?</p><p>Take for example a lambda for a multiplication:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/730/1*ghDCtNUTTyAU2rNhFV6Yvw.png" /></figure><p>If the JSON had a formula that multiplied the data by 3, we would just get the 2 from the data registry and the 3 from the JSON. Mmm. And we would get this data <strong>every </strong>time for the <strong>same </strong>JSON for <strong>every </strong>registry. What? That doesn’t sound ok at all!</p><p>What if we just set the JSON valor and passed that for every type of object?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*OsCV25nl81PE_GlrCHw9dg.png" /><figcaption>This is not working…</figcaption></figure><p>In fact, with OOP you would most likely do the function for the business logic that corresponds to the use case in that object, and in the end you would have something like this. Lots of replicate code, having to manually redo the logic if the use case changes…</p><p>But what if we had a generator of functions? We could give him the JSON value and it would give us the function the data should run. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*gDMLFuPaxag4Kkyl51dRHA.png" /><figcaption>This looks better!</figcaption></figure><p>And what if we had other operations: percents, sums… we could use a dictionary to save the factory and pass the parameter all the same. For example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*WW-ULlFkymsWS-MWE95uNw.png" /><figcaption>From one JSON we created the operation for the specific data set.</figcaption></figure><p>And for complex functions with composition of operations…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/947/1*LKpVJSEJw1hvvsr9XzwXxw.png" /><figcaption>Note that every list comprenhension is a for in any other language, so this can be used anywhere with lambdas</figcaption></figure><p>With this approach I managed to reduce the code to two fragments of around 20 lines of codes (most of them were for readability): one would compile the json to a dictionary of functions, and the other would read the data and acumulate the results of the data with the json in another dict to finally print it.</p><p>It is also efficient. Originally it was an O(n²) in memory/speed. Now, I only have in memory n floats and n functions, with n=number of categories. And it was done in two loops so n complexity. O(n) memory and speed. But most of all, it’s very easy to maintain: just add or modify the JSON dictionary to implement… whatever, really!</p><blockquote>…we really <strong>wanted was the result. To abstract ourselves from the data (the document formats, the data contained) and only focus on the desired result.</strong></blockquote><p><strong>Extra advantages:</strong></p><ul><li>Because of an unified data type on the main program, error finding and solving is much easier. Once found, you only have to check its pipeline.</li><li>Data consistency: the end of magic numbers, strange vars or whatever. You WILL have an abstract type at the end. It makes so much easier for people learning the program to know what to expect at each step, and to implement other functions to the system.</li><li>Design time reduced: you can come up with the abstraction thinking about the functionality (design with pen and paper) or by coding it normally and then refactoring all the repeated code into lambdas. Both come to the same result.</li></ul><p><strong>Limitations</strong>:</p><ul><li>The data homogenization should occur whenever every data has a similar final result. As I told on my earlier article, programming is transforming. The lambdas really are data transformations to a desired type. If there is no common type/result, homogenization is not possible.</li><li>The end result should aways be Data Structures to take advantage of the data homogenization. If you end with single formatted data, don’t complicate your system unless you expect that it will escalate and need to implement other processes.</li><li>Don’t overcomplicate it. If you have different categories of data, use different lambdas for every category, then do another lambda to further abstract those results (like I did: a class for Excel, another for PPT, etz, data, and then I put them together in an abstraction). Remember that if you have too many parameters, maybe you should divide it, just the same as in OOP.</li><li>For very large projects this could be troublesome. But it works great for ad-hoc functionality. In fact, I think it would be interesting to see another architecture where the main objects in the system are the processes (transformations) over some data and you defined process pipelines instead of object relations.</li></ul><p>What do you think? Do you think it could be useful to solve a problem in your projects? Do you think the idea can be improved further? Please, leave your comments below. Thanks for reading :D.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2db53cfacc7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The programmer puzzle: What is programming?]]></title>
            <link>https://medium.com/@joshiraez/the-programmer-puzzle-what-is-programming-7f444ab0bd7d?source=rss-7fc174796158------2</link>
            <guid isPermaLink="false">https://medium.com/p/7f444ab0bd7d</guid>
            <category><![CDATA[puzzle]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[teaching]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[paradigm-shift]]></category>
            <dc:creator><![CDATA[José 'Joshi' Ráez Rodríguez]]></dc:creator>
            <pubDate>Sat, 16 Sep 2017 08:57:00 GMT</pubDate>
            <atom:updated>2017-09-16T13:29:19.664Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pAESF9uFE4lEYgshY_N6Wg.jpeg" /></figure><p><strong><em>Programming is hard</em></strong><em>.</em><strong> </strong>That’s the complain I hear the most whenever I talk with other programming students, technicians or engineers, or while giving private lessons. Whether trying to understand memory, data structures, or just why you need a variable; <em>people struggle</em>.</p><p><strong>But I think that this shouldn’t be the case.</strong> Programming is not inherently hard: it can get really complex, but not at the entry level. The issue I think lays in what we teach as programming. <strong>We teach coding, but we don’t teach what programming actually is</strong>.</p><p>This is sometimes known as understanding the <strong>programming paradigm</strong>, What a word! For the sake of simplicity I say it could be aproximated as the <strong><em>cause </em></strong>and the <strong><em>method</em></strong><em>. The why and the how.</em> And that is what I’ll try to explain.</p><blockquote><strong>We teach coding, but we don’t teach what programming actually is</strong>.</blockquote><p><em>“What is programming?” </em>Would you ask. And I do ask this too to my students. I have heard a lot of answers: developing programs, solving problems, making utilities… yeah, all of those are programming, but they don’t go to the core of the question.</p><blockquote><strong>Programming is transforming data.</strong></blockquote><p>Have a design, and sizes, and you can program a visual interface. Know what a customer likes and you can give him custom adds. Ask for some numbers and a operation and you can give the result. <strong>Our work is to transform data into something useful. </strong><em>This is our cause.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/556/1*dG8MwVwqtJBRsOsM6mmD3w.gif" /><figcaption>A sentence and a few words and numbers and we could get this in our screens.</figcaption></figure><p>But now… how we do it? How can we transform numbers into graphics? Subjective data like customer likes into “choices” that give us the perfect custom add? This is hard.<strong> No. It’s not hard, it’s complex. </strong>Remember…</p><blockquote><strong>Programming is transforming data.</strong></blockquote><p>… and it is so, <strong>always</strong>.</p><p><em>Let’s get to the how then. </em>How do we do this? I’ll start with a basic example: a calculator.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/704/1*5FrClMydusDvRnd9V4TvCQ.jpeg" /><figcaption>It has return, the ever dreaded beginner programming project.</figcaption></figure><p>A calculator is something that makes operations for you. If we put it in more technical terms, it will be a program that will show data (answer) given the user input (problem).</p><p>Let’s forget that and <em>go step by step</em>. We will start with an addition calculator. What does it do?</p><ul><li>It gets two numbers.</li><li>It adds them.</li><li>It shows the user the result.</li></ul><p><strong>This is our program</strong>. And it should be so in any language or framework. <em>Now we can solve them one by one</em><strong>. </strong>But most important: <strong>these problems are far easier than the problem before</strong>. We can even make another program for each one of these if it’s needed, and in each step, these problems will be even easier. For example, our first step could be:</p><ul><li>It gets one number.</li><li>It saves the first number.</li><li>It gets another number.</li><li>It saves the second number.</li></ul><p>Now we have lots of pieces, little problems of easy solution. How do we connect them?</p><blockquote><strong>Our work is to transform data into something useful.</strong></blockquote><p><em>We just transform every tiny bit of data into another tiny bit that is useful for us</em><strong>. </strong>And we know what we need because we know what pieces we have. <strong>We assemble the pieces, the puzzle.</strong></p><ul><li>The user press a button, we get a number. We save it.</li><li>We do this again. We now have two numbers.</li><li>We use these two pieces of data and add them. Now we have a new number: the result.</li><li>We send this number from “our program” to the screen.</li></ul><p>In each step from some info we get new info. We use this new info to go forward into the next step to get new info. We do this until we reach our needs.</p><p><em>But the magic doesn’t stop here. </em>Now we have a program that sums numbers. That makes a <strong>transformation</strong>. We can use it for other things! For example: imagine you have to make a program that calculates the total income from a shop. You need to do it in the Excel or Google sheet where the store’s owner saves the sales benefits. It again sounds complicated. But we can go step by step again:</p><ul><li>We get one sale from the excel. Save it in our program.</li><li>Get the next sale from the excel. Save it in our program.</li><li>Sum those numbers. Save them in the program.</li><li>Get the next number, sum again and save. Repeat with all the sales.</li><li>Write the end number in the excel.</li></ul><p>Is our calculator again! Just that we now repeat the program over and over. But for very different words, very different cases, when you go step by step it becomes very similar. What’s more, you can use your old program again and save some time!</p><p><strong>This is our how. We transform the data for OUR needs, step by step, until we reach our solution.</strong></p><blockquote>For very different words, very different cases, when you go step by step it becomes very similar.</blockquote><p>This is the programmer’s puzzle, <strong>the programmer’s paradigma</strong>. Learning what do we do: transform data. And how we can use it: to transform into useful data for us, which we can then transform again.</p><p>This is what I try to teach my students. When they start seeing the path the data follows from one point to another, they start trying to fit pieces in them until they complete the puzzle. <strong><em>Now they know what they are looking for when they code</em></strong><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/578/1*0vdwKdaqhQXAiTbULrF7zQ.jpeg" /><figcaption>If you see the picture, you can try to fit the pieces</figcaption></figure><p><em>Clossing statements:</em></p><ul><li><strong>The “<em>hard</em>” part of the methodology is being able to predict or identify the pieces you need</strong>. This is what you learn in college/university in theory classes, and you can learn it also from your experience and research. There are ways to speed the process and have some sort of methodology even for the most complex cases. These topics will be discussed in future entries.</li><li>While in one hand programming can be somewhat simplified, <strong>software engineering IS hard</strong>, but not because of programming, but because of the <strong>decisions </strong>we have to make. <strong>One solution can solve a problem and not be optimal for the situation at hand</strong><em>.</em> <strong>Knowing when to use which resources, why and how is critical </strong>in the process to be a good programmer and engineer, <strong>but is not something that an entry level should worry about. </strong>Furthermore, knowing this is, in my opinion, <em>the most critical point to become a </em><strong><em>senior </em></strong><em>engineer and further. </em>But only then.</li></ul><p>Thank you very much for reading it! This is my first post at Medium. I hope you liked it. I was unsure about making this post because of my little experience, but I thought that every one has a first time and I finally got the guts to do it. Also, I have had this topic on top of me for months, and I think it is a very interesting one to share.</p><p>What do you think? Have any insights in how you teach programming or what problems can arise while teaching it? Have any criticism or suggestion which could be of use for this or future entries? Please leave a comment! You can find me too in Linkedin (http://joseraez.com), Twitter and Github (@JoshiRaez). Thank you very much for your attention. Read you soon! :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7f444ab0bd7d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>