<?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 Johan Martinsson on Medium]]></title>
        <description><![CDATA[Stories by Johan Martinsson on Medium]]></description>
        <link>https://medium.com/@johan_alps?source=rss-b8efc47f5280------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*CIMLbgUTFmA_hhVW.jpg</url>
            <title>Stories by Johan Martinsson on Medium</title>
            <link>https://medium.com/@johan_alps?source=rss-b8efc47f5280------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 14:14:22 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@johan_alps/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[Pour avoir du code propre faut-il consacrer plus de temps?]]></title>
            <link>https://medium.com/@johan_alps/pour-avoir-du-code-propre-faut-il-consacrer-plus-de-temps-4889fd3711c3?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/4889fd3711c3</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Mon, 26 Nov 2018 10:45:04 GMT</pubDate>
            <atom:updated>2019-01-11T15:30:12.307Z</atom:updated>
            <content:encoded><![CDATA[<h3>Faut-il consacrer plus de temps pour avoir du code propre?</h3><p>Quand on code sur un projet nous finissons toujours par produire du code un peu en dessous de notre niveau maximum. Ceci est normal car rendre le code parfait (par à rapport à notre perception) serait trop long. Certes nous devons livrer du code de qualité afin qu’il soit facile à maintenir et c’est ce que nous faisons, mais au final si on peut livrer un résultat qui est à 80% de notre niveau max et qu’il faut 50% plus de temps pour aller à 100% alors on va se contenter de 80.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6Mkq2bSxtzoGazkaUNdgbg.png" /><figcaption>Pousser jusqu`à 100% prends du temps et mets une tension sur le projet difficile à tenir à la longue. Mais désespérons pas, il y a une alternative.</figcaption></figure><p>Maintenant on nous dit qu’il faut relever la qualité du code, car c’est bénéfique, au moins en moyen terme si ce n’est à court terme. Donc bien, nous relevons à 90% et c’est probablement rentable, car le coût de la non qualité s’accumule, c’est pas une imperfection qui cause un problème, mais rustine sur rustine sur rustine qui crée de la complexité inutile. Donc admettons que nous faisons du 90 plutôt que 80 car c’est le trade-off idéale. Bon pas très impressionnant me diriez-vous.</p><p>Nous savons que tout le monde n’a pas le même niveau en développement. Autrement dit le 100% de tout le monde n’est pas le même. Donc ceci n’est pas une limite figée. En effet nous pouvons nous entraîner, et lorsqu’on s’entraîne, on apprend de nouvelles choses et on améliore les connaissances acquises. C’est à dire que nous travaillons au dessus de notre niveau. Avec pour effet de relever notre niveau max. Concrètement nous découvrons des patterns et techniques plus efficaces à appliquer dans notre code qui a pour effet de faire la même chose avec moins de code du code plus simple ou en allant plus directement au but. Bref si au bout de qq séances nous avons relevé notre niveau <em>max</em>, alors notre niveau <em>croisière </em>se trouve alors au dessus de notre niveau max d&#39;avant. Et plus étonnant encore, hormis le temps investi à s’entraîner nous ne passons pas plus de temps par feature, plutôt bien le contraire!</p><p><strong>Avec un peu d’entraînement nous sommes capables, sans investissement de temps supplémentaire, de produire un code de très haute qualité!</strong> Donc on comprends bien que l’enjeu n’est pas de négocier le niveau idéale de code actuelle, mais d’investir du temps pour l’apprentissage!</p><p>On pourrait se dire que le simple fait de développer toujours de nouvelles choses consiste en un entraînement. Bien que ceci est vrai début de carrière, puis parfois quand nous devons nous intégrer avec une nouvelle technologie, cette nouveauté s’estompe rapidement. En effet pratiquement rien ne nous pousse à nous entraîner sur la conception, rien ne nous pousse à devenir meilleur en refactoring. Je le sais, car je passe mon temps à faire découvrir aux des développeurs qui pour la plupart ont de nombreuses années d’expérience qui n’ont jamais pris le temps de s&#39;entraîner à remplacer un Switch par une une Map, encapsuler une primitive dans une classe, remplacer de l’héritage par de la composition etc. Pourtant ces petites choses sont essentielles pour faire des applications de taille.</p><p>La bonne nouvelle est que la plupart de développeurs ayant très peu d’expérience en refactoring, <strong>la progression au début est très impressionnante!</strong></p><p>C’est ainsi que pour avoir du code en état à peu près propre, ce qui manque aux équipes n’est pas tant du temps pour chaque feature, mais du temps consacré à l’entraînement. Créons ce temps pour les équipes! Créons du temps pour que les équipes progressent! Créons du temps pour que notre code puisse nourrir le business au lieu de le plomber.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4889fd3711c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Johan Martinsson]]></title>
            <link>https://medium.com/@johan_alps/johan-martinsson-5ec546eeba2a?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ec546eeba2a</guid>
            <category><![CDATA[career-development]]></category>
            <category><![CDATA[training]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[negotiation]]></category>
            <category><![CDATA[job-search]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Tue, 09 Oct 2018 04:48:00 GMT</pubDate>
            <atom:updated>2018-10-09T12:02:01.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>Obtaining time for training and going to conferences</h3><p>I know some employees that’d like to train more, to go to conferences, present at conferences and train during working hours. Few employers allow that to the extent that the employee would want to, some don’t even feel entitled to order books on behalf of their company. This generates frustration, and to me inefficiency at work, because developers need to continuously learn a lot and learn with a wider perspective than only the working environment can ever offer.</p><h3>John Ⓐ De Goes on Twitter</h3><p>In an ideal world, companies would take responsibility for continuously training every employee. Welcome to the real world. If you want to improve, you&#39;ve got to take responsibility for your future and put in the work.</p><p>I’ve seen this tension and frustration in just about every company, from high profile consulting agencies where training is encouraged and expected, still one or two individuals would prefer to spend even more time training and preparing conference presentations, to some low profile consulting agencies where one boss explained to me:</p><blockquote>I have a problem with letting people train a lot. The company makes an investment through training fees and non billed time. The return on investment is negative, because the more they learn the greater the salary they can get elsewhere, but I can’t pay them much more because developer fees are limited. No matter the skill level I can’t charge above a certain level, so <strong>the more I invest the sooner they’ll leave</strong></blockquote><p>Now that’s sad, really really sad, but what would you do if this was your company?</p><p>Interestingly company owners never have a problem with their personal balance, neither do freelance developers. Why? It’s not because they’re special people in any sense. It’s because they are in a self regulating system. The more they train the less they “<em>produce”</em> in the short term, training is an “<em>investment</em>” in the future and they both reap the benefits and pay the bill. The system will balance without authoritarian decision and consequent frustration.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*VfapMhU8Os4HphmwuXeqKw.jpeg" /><figcaption><a href="https://pxhere.com/en/photo/1435901">https://pxhere.com/en/photo/1435901</a></figcaption></figure><p>Now I have a bold idea both for business owners and for employees negotiating a new job. It came to me several years ago when a client wanted to hire me as an employee instead of as a contractor. The job was interesting so I asked myself what do I value as a freelance, what exactly do I like about it? It became very clear to me that I liked to have the freedom to decide. In particular what conferences I’d go to, what books I’d buy, when I needed to be away from work to train. So I stated <strong>my conditions: 25 days a year of training and going to and/or speaking at conferences with a budget of max 10k€</strong> on training courses and travel expenses. After that we could negotiate salary, making it very easy for the future employer to calculate the total cost, salary, expenses, non-project time etc and compare it to the benefits of my activities. Naturally they had never encountered a demand like it before, nevertheless it was easily accepted. While I never ended up working with them for other reasons, I was confident that I wouldn’t have felt feel frustrated had I ended up working there.</p><p>As you can see I value time for training a lot, but not everyone does to that extent and that’s perfectly OK. We’re not all the same, some people prefer day to day work because lets face it it can be very interesting, and some value maximising salary. The point here is to give the opportunity to everyone to choose how much they’re investing in the future and how much we’re cashing out now.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y4HsNRKrd_bV-kwbQCtWw.jpeg" /></figure><p>Using this clear deal of clearly reserving the expected time and budget for knowledge development, people can even use companies like the low profile consulting agency as trampolines for their career, accepting lower salary in return for greater investment, a productive partnership.</p><blockquote>How much training etc would suit you? We will provide a minimum, but we can also help you if you’d like more.</blockquote><p>I suspect such a question could help people think about it and take responsibility for their future development.</p><p>What do you think? Have you tried something similar? If you know of people and companies who does this or would like to try it yourself, I’d love to hear about it!</p><p><em>Originally published at </em><a href="http://martinsson-johan.blogspot.com/2018/10/obtaining-time-for-training-and-going.html"><em>martinsson-johan.blogspot.com</em></a><em> on October 9, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ec546eeba2a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Vouloir changer les choses]]></title>
            <link>https://medium.com/@johan_alps/vouloir-changer-les-choses-209513244c2d?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/209513244c2d</guid>
            <category><![CDATA[team-collaboration]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[change-management]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Mon, 24 Sep 2018 07:10:48 GMT</pubDate>
            <atom:updated>2018-09-24T21:56:41.642Z</atom:updated>
            <content:encoded><![CDATA[<p>L’une des premières choses qui m’a frappé dans la vie professionnelle est à quel point il est difficile de changer quelque chose, même lorsque ça ne fonctionne pas aujourd’hui. Combien d’entre nous ont apporté une bonne idée, juste pour la voir réfutée sans réelle réflexion ; un jour par un collègue, l’autre par notre manager?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KJbk6Mik-dWBUGydhjyMaw.png" /><figcaption><a href="https://pixabay.com/en/bee-work-hard-insect-digging-dirt-44509/">https://pixabay.com/en/bee-work-hard-insect-digging-dirt-44509/</a></figcaption></figure><p>C’est bien dommage et frustrant! On entend souvent la phrase “<em>Si seulement ils pouvaient écouter</em>” ou une variante “<em>si seulement ils avaient un bon background technique ils comprendraient</em>”. Franchement, combien de fois avons nous buté contre cette résistance au changement? Et pourtant cela aurait tellement de sens de faire du Scrum, tellement de sens de faire du TDD, et d’ailleurs c’est du Kubernetes qu’il nous faut. Si seulement ils pouvaient faire un petit effort pour comprendre…</p><p>Et si on pouvait résoudre ça? Si ce n’était la plupart du temps qu’un malentendu? Si nous regardions de près ce qui se passe quand quelqu’un propose une nouvelle solution, alors peut-être que nous comprendrions mieux pourquoi cela fonctionne pas toujours. En effet proposer une solution est souvent voué à l’échec, parfois pour plusieurs raisons, mais premièrement parce que il n’est pas du tout sur que nous sommes d’accord sur <strong>le problème</strong> que la solution est sensé adresser! Il faut bien se rendre à l’évidence que celui qui n’a pas de problème n’a pas besoin de solution, surtout quand la solution a un coût. Ou comme je dis souvent <strong>Il n’y a pas de solution sans problème</strong>. Effectivement cela est l&#39;inverse du dicton classique, mais il a tout autant de sens.</p><p>Donc la première chose à faire est de se mettre d’accord sur le problème. Cela dit je dois reconnaître que c’est rarement la première chose que je fais… c&#39;est facile d&#39;oublier de passer par là. Par contre dès qu’il y a une résistance ou dès qu&#39;il y a une opposition sur la solution, c’est le moment de ramener la discussion dans le domaine du problème plutôt que la solution, cela permet de voir si tout le monde voit un problème et qu&#39;on parle du même problème. En effet prendre un peu de temps de comprendre le problème est toujours bénéfique car ça permet de l’éclairer sous plusieurs angles et mieux le comprendre, collectivement.</p><p>Une fois que tout le monde est sur la même longueur d&#39;onde, il y a des chances que chacun a un minimum d’énergie pour l’adresser. Certes il se pourrait que la solution adoptée soit totalement différente de la première proposée, mais peu importe l’essentiel est que le problème soit abordé.</p><blockquote>Il n’y a pas de solution sans problème</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=209513244c2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Driven Development pattern -Small types]]></title>
            <link>https://medium.com/@johan_alps/type-driven-development-pattern-small-types-5994482eaca?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/5994482eaca</guid>
            <category><![CDATA[type-design]]></category>
            <category><![CDATA[idris]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Wed, 04 Jul 2018 01:45:00 GMT</pubDate>
            <atom:updated>2018-07-04T08:54:50.554Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*xCs3jFG-TsuozLYQ.jpg" /></figure><p>Small types in type driven development facilitates composability much like small objects do in OO.<br> <br> One of my first experiences in <a href="https://www.idris-lang.org/">Idris</a> was to try to implement a FizzBuzz where the types would be so strong that they’d ensure the code could only be correctly implemented.<br> <br> <a href="https://en.wikipedia.org/wiki/Fizz_buzz">FizzBuzz</a> is a game where the input is a number between 1 and 100. The output is a string, “Fizz” if the number is divisible by 3. “Buzz” if the number is divisible by 5. “FizzBuzz” if it is both divisible by 3 and 5 and just the number otherwise. eg counting from 1<br> <br> 1, 2, fizz, 4, buzz, fizz, 7, 8, fizz, buzz, …<br> <br> My first implemention enforces the correctness by taking as arguments <em>proofs</em> that the given number is either divisible by 3 or a <em>proof</em> that it is not divisible. That way can call the <em>constructor</em> Fizz if and only if you can provide proof of division by 3 and a proof of non division by 5.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4e260a1f13623d73bad20050d7870e/href">https://medium.com/media/ca4e260a1f13623d73bad20050d7870e/href</a></iframe><p>So just by defining a type FizzBuzz and the signatures of the constructors of this type we have no possibility of making a mistake in the implementation. Nice! Here’s are the types and signature of methods.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7be524b397f0284624ae7ca14ce48d13/href">https://medium.com/media/7be524b397f0284624ae7ca14ce48d13/href</a></iframe><p>IF you’re curious about the implementation <a href="https://github.com/martinsson/DDD-and-Dependent-Types/blob/master/fizzbuzz_johan.idr">it’s here</a><br> <br> Besides being a major challenge, for me, in mastering dependent types and understanding that types can act as proofs, it actually worked out quite OK. Certainly it does not allow for incorrect code, so it was a successful experience. Sure it is a bit of verbose and contains a bit of pseudo-duplication.<br> <br> <strong>But not extensible</strong><br> Now there’s an extension to FizzBuzz, namely Bang. Bang is the word for every multiple of 7, for instance given the number 21 we should return FizzBang. Now without Bang there are 4 possible results, Fizz, Buzz, FizzBuzz and the number. Now here’s where things become interesting because with Bang there are 8, so the problem of verbosity and pseudo-duplication gets a lot worse. Clearly the first solution isn’t very extensible<br> <br> <strong>A better solution</strong><br> A different approach is to decompose the type FizzBuzz into smaller orthogonal types. Lets consider the type Fizz (either a IsFizz or a Not IsFizz), the type Buzz, then FizzBuzz can be modeled as a tuple (pair) of Fizz an Buzz (<a href="https://github.com/martinsson/DDD-and-Dependent-Types/blob/master/fizzbuzz-composable.idr">the full code</a>).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d3667231614eb932b069af5c9118f3da/href">https://medium.com/media/d3667231614eb932b069af5c9118f3da/href</a></iframe><p>If we add the functionality of Bang then all we have to do is create a new type Bang, and a new composed type a 3-tuple of Fizz, Buzz and Bang. We don’t have to break the existing type FizzBuzz nor the former function, we could possibly even keep the former method, a good example of the open-closed principle. Open-closed-principle with dependently typed code!<br> <br> Possibly we’d fear that by making the types less <em>closed</em> we’d be able to code an incorrect solution to fizzbuzz. But that’s still not possible.<br> <br> <strong>Learnings</strong><br> Keeping types small in the sense that they <strong>contain little data</strong> (few arguments) and have <strong>few constructors</strong>, favours reuse through composition. It might seem obvious in hindsight, but I discovered this much in the same way that I discovered the use of small objects in OO.<br> <br> Some people say that strongly typed languages like Idris doesn’t allow for extension, that they’d be <em>closed</em> by design. What I learned from this experience is that while that certainly applies to <strong>a</strong> type and functions on existing types, we can still compose types in new ways. Given of course that our types are small enough.</p><p><em>Originally published at </em><a href="http://martinsson-johan.blogspot.com/2018/07/type-driven-development-pattern-small.html"><em>martinsson-johan.blogspot.com</em></a><em> on July 4, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5994482eaca" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bug Generator: Use of indices]]></title>
            <link>https://medium.com/@johan_alps/bug-generator-use-of-indices-83059fa8f041?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/83059fa8f041</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Tue, 01 May 2018 15:29:00 GMT</pubDate>
            <atom:updated>2018-05-02T20:27:32.276Z</atom:updated>
            <content:encoded><![CDATA[<p>Let me just start by stating what I mean by a Bug Generator. It’s a style of code that is likely to contain bugs or produce bugs in the future as the code is extended. This is of course an anti-pattern. There are corresponding Prevention Patterns, basically less error-prone alternatives. That being said, let’s dive into one of the Bug Generators, namely use-of-indices.</p><p>Use of indexed access is low level, off-by-one errors are very common. Also index out of bounds can happen. Usually we can simply avoid this by using higher level constructs such as for-each-loops and higher-order functions such as map and filter.</p><h3>Bug: Off-by-one errors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/1*Yf6amAfBVFk5U3jdHrXatw.jpeg" /><figcaption>Off by one catastrophy, <a href="https://i.imgur.com/gkxMf3F.jpg">https://i.imgur.com/gkxMf3F.jpg</a></figcaption></figure><p>We access the data by some index. The problem can range from some simple error in a loop construct. For instance we use &lt;= instead of &lt; in loop. To harder-to-spot errors like passing the index to some function and using the index while modifying it by a -1 or +1.</p><p>A basic example of this. Say we need to find the first cat in a list of animals. The bug will only occur when there is no cat in the collection</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/437c7729b27a2ca5d3f8b0e807f95bd9/href">https://medium.com/media/437c7729b27a2ca5d3f8b0e807f95bd9/href</a></iframe><p><strong>Bug: Index out of bounds (variation)</strong><br>This is off-by-one where we actually step outside the array.</p><h3>Prevention pattern: use lambdas and higher order functions</h3><p>higher order functions like map, filter, some/first, etc have already implemented the looping and we just have to provide a function that the higher order function will use on each element.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a17b063e52fae7d18409a9f5c277c1c7/href">https://medium.com/media/a17b063e52fae7d18409a9f5c277c1c7/href</a></iframe><h3>Prevention pattern: for-each-loop</h3><p>If we really must use imperative style</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e936364cfc988cf0f94424685a9cb702/href">https://medium.com/media/e936364cfc988cf0f94424685a9cb702/href</a></iframe><h3>Prevention pattern: link the structure length to the index calculation</h3><p>E.g. modulo on length. An example would be picking cards from a deck. Lets assume that whenever we get to the end of the deck we’re supposed to start from the beginning. A naïve implementation would be to</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c33d7b992151b2e9de6a23aad481c8bd/href">https://medium.com/media/c33d7b992151b2e9de6a23aad481c8bd/href</a></iframe><h3>Prevention pattern: Wrap the array and index in a class</h3><p>This is particularly useful when the same calculation is done in several places. Whenever we have a class it is easy to find the code we need to manipulate the date inside. Another advantage is that the behaviour becomes easily testable when isolated in a class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52d643442536a3ecfda7e3450ec8c19c/href">https://medium.com/media/52d643442536a3ecfda7e3450ec8c19c/href</a></iframe><p>It’d be very easy and natural (i.e. likely) that we’d test getNextCard both by calling it many times in a row and with large values of someStep.</p><p>This Prevention Pattern is related to Bug generator <em>Primitive-Obsession</em></p><h3>Conclusion</h3><p>There are less bug-prone alternatives to treating directly with indices, by raising the level of abstraction.</p><p>This post is an attempt at starting to name and classify the anti-patterns that we often find in code where bugs appear. Hence making it easier to find better alternatives. I&#39;d be delighted to know what you think of the content and the form.</p><p>Cheers, I wish you less bugs!</p><p><em>Originally published at </em><a href="https://martinsson-johan.blogspot.fr/2018/05/bug-generator-use-of-indices.html"><em>martinsson-johan.blogspot.com</em></a><em> on May 1, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83059fa8f041" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Bug pattern — Hidden testable code]]></title>
            <link>https://medium.com/@johan_alps/bug-pattern-hidden-testable-code-eb7d261f9f05?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb7d261f9f05</guid>
            <category><![CDATA[bugs]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Mon, 16 Apr 2018 15:36:00 GMT</pubDate>
            <atom:updated>2018-04-18T14:01:40.982Z</atom:updated>
            <content:encoded><![CDATA[<p>When there’s a bug it is very likely the existing design contributed to its existence. This suggests that there are corresponding design anti-patterns, patterns of code that are latent bugs<br> <br> This time lets look at the pattern Hidden testable code</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*62oemiJ73j_JjoPZ.jpg" /><figcaption>By Loveteamin [CC BY-SA 3.0], Wikimedia Commons</figcaption></figure><p><strong>Problem</strong>: Easily testable code is hidden inside hard to test code. For this reason the code is either not tested or the tests are not as thorough as would be needed.<br> <br> Schematically it looks like this</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78cbc96f76ed12070187ed5649a40fb3/href">https://medium.com/media/78cbc96f76ed12070187ed5649a40fb3/href</a></iframe><p><strong>Solution</strong>: It is very very cheap to fix this. Just an Extract Method automatic refactoring in order to extract a Pure Function that can be extremely easily tested.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7c59d5ac6ec7507910789423e9768585/href">https://medium.com/media/7c59d5ac6ec7507910789423e9768585/href</a></iframe><p>Recently I came across an example of this bug generator pattern. It had a first bug that was fixed and tests weren’t added because it was considered too costly to add tests for it. However the idea of testing an extracted function was not even considered. Two weeks later it became clear that this piece of code contained a second similar bug. The code had some very extensive transformation logic between two calls to a web service and two calls to the persistence layer. Below is a shortened version of it. The problems were both errors in the pure transformation logic.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05979efb541a9696277bf0b85df96869/href">https://medium.com/media/05979efb541a9696277bf0b85df96869/href</a></iframe><p>Once extracted and thoroughly tested the logic can be both refactored and extended with confidence. Bugs will have a much harder time hiding in this kind of light.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b74e1a43472064666a098c285bdecffb/href">https://medium.com/media/b74e1a43472064666a098c285bdecffb/href</a></iframe><p>The idea that we can cleanse the system from most of the bugs is called BugsZero. You can learn more about it <a href="https://github.com/martinsson/BugsZero-Kata">here</a>, and by various talks by Arlo Belshee, available on youtube.</p><p><em>Originally published at </em><a href="http://martinsson-johan.blogspot.fr/2018/04/bug-pattern-hidden-testable-code.html"><em>martinsson-johan.blogspot.com</em></a><em> on April 16, 2018.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb7d261f9f05" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Generative fibonacci numbers using reactive streams]]></title>
            <link>https://medium.com/@johan_alps/generative-fibonacci-numbers-using-reactive-streams-31bbe5b98c94?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/31bbe5b98c94</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding-dojo]]></category>
            <category><![CDATA[reactive-programming]]></category>
            <category><![CDATA[fibonacci]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Mon, 12 Mar 2018 22:17:10 GMT</pubDate>
            <atom:updated>2018-03-12T22:17:10.662Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been exploring <a href="http://reactivex.io/">Reactive Streams</a> for a while and the other day it struck me that it’d be possible to use a combination of streams to generate the stream of all fibonacci numbers. Basically all fibonacci numbers are the sum of the two previous numbers, so if we could create the <em>n-2</em> stream and the <em>n-1</em> stream then we could just sum them to create the <em>n</em> stream. Then we’ll feed the <em>n-2 </em>and <em>n-1</em> stream with the results of the n stream.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*5MzGolLNNIc__LpbjxpG-A.jpeg" /><figcaption>fibonacci in real life <a href="https://www.flickr.com/photos/pninsule_acadienne/6086105698">https://www.flickr.com/photos/pninsule_acadienne/6086105698</a></figcaption></figure><p><strong>Learn by pushing the tool to the extreme<br></strong>I initially brought this idea to my hometown Coding Dojo, the skeleton was wrought in that session. Since I’ve been fiddling quite a bit. The result is a lazy stream generating as many elements as you take from it, a bit like a lazy infinite collection in fact. It was a bit harder than I thought to start the streams and I find my code hard to read. On the other hand it was a great exercice as it required several common reactive patterns i a very small amount of code.</p><p><strong>Learning — get the previous value</strong><br>For instance how to get ‘the previous value’ along with the current value — Simply by zipping the stream with itself, one value skipped</p><blockquote>Observable.zip(stream, stream.skip(1))</blockquote><p>Here’s the code anyway</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/244c79357f643206effbfaca05ccf094/href">https://medium.com/media/244c79357f643206effbfaca05ccf094/href</a></iframe><p><strong>Performance</strong><br>One of the typical problems with fibonacci streams is that the definition</p><blockquote>Fn = Fn-1 + Fn-2</blockquote><p>leads to a bad algorithm. If we use recursion we’ll end up calculating <em>Fn-2</em> two times,<em> Fn-3</em> 4 times etc. <a href="https://en.wikipedia.org/wiki/Memoization">Memoization</a> can be used to avoid that, but the above algorithm, building up rather than recurring down, don’t even need that to be optimised.</p><p><strong>Conclusion</strong><br>As I said it was a good exercice, now if I’d actually have that in a project I much prefer the solutions using generators, or a <a href="https://github.com/Reactive-Extensions/RxJS/blob/master/doc/gettingstarted/generators.md">mix of reactive streams and generators</a>, far more elegant.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=31bbe5b98c94" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data structure is key to simplicity]]></title>
            <link>https://medium.com/@johan_alps/data-structure-is-key-to-simplicity-bd31298f35b9?source=rss-b8efc47f5280------2</link>
            <guid isPermaLink="false">https://medium.com/p/bd31298f35b9</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Johan Martinsson]]></dc:creator>
            <pubDate>Mon, 11 Dec 2017 08:41:36 GMT</pubDate>
            <atom:updated>2017-12-11T08:41:36.164Z</atom:updated>
            <content:encoded><![CDATA[<p>If you want a simple solution, find a simple data structure.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sLlW59ToHGpf1EelMDBlJg.jpeg" /></figure><p>A lot of problems have a very simple solution, provided that we use a data structure that reduces the number of necessary operations. Still I find that we often neglect the effort spent in finding the best data structure.</p><p>To me this is a serious problem or a great opportunity for improvement! Every project battles with the complexity of the past. Many systems contain enormous amounts of accidental complexity in addition to the essential complexity that serves the user. If you don’t believe me try to remember the times where it was so hard to understand the existing code that the only solution, given finite time, was to hack it. Which in turn generates even more complexity and eventually will force someone else to hack around that… Stack complex code on top of complex code and very quickly we have a slow and awkward project to work on. What if we got better at finding simple solutions instead? What if we could easily improve on that?</p><p>It’s time for a very simple example of overly complex code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0921774e0493f8db1b550b5581b94b9/href">https://medium.com/media/a0921774e0493f8db1b550b5581b94b9/href</a></iframe><p>A better solution would be</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e125bc06f17d4d4605cda5a3d95970d/href">https://medium.com/media/9e125bc06f17d4d4605cda5a3d95970d/href</a></iframe><p>That’s just to get warmed up and it really doesn’t prove my statement that the right data structure simplifies the code. So let’s look at TicTacToe. In Tic-tac-toe two players compete on a 3x3 board. A player wins if he holds either a line, a column or a diagonal. What would be a good data structure for calculating this? Perhaps a 3x3 array of arrays? That could work out well but it is likely to generate labourious code like</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a111965d8456ced12a4bccf10c8f3379/href">https://medium.com/media/a111965d8456ced12a4bccf10c8f3379/href</a></iframe><p>So perhaps a string instead? That’d optimise readability in tests (you could see the board), however updating the string when a player places a mark is difficult.</p><p>What about a simple map of coordinates to playerMarkers? That comes close to a good solution. Just pay attention to the coordinates used. Is it a pair of [ row, col ]? Or perhaps just the number of the case, 1–9, or better 0–8. But wait, a map indexed by a value from 0-n … That’s an array. So now we could represent a board with something like an array of characters. But wait that’s more or less a string, which is readable. Great!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2fbec1badc984cedb76db034bd121e64/href">https://medium.com/media/2fbec1badc984cedb76db034bd121e64/href</a></iframe><p>Now that we have the board we could just go on with that and solve it with a few ifs</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3270bb969ae2597c789d5762917cd0c6/href">https://medium.com/media/3270bb969ae2597c789d5762917cd0c6/href</a></iframe><p>However those hasXXX() methods will take a few lines to implement. Unless of course we bring out our secret weapon of replacing code with data-structures! We could encode row, column and diagonal as data-structures. Like so</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cda7f08a0799224924a9a68ede54c242/href">https://medium.com/media/cda7f08a0799224924a9a68ede54c242/href</a></iframe><p>From now on every winning combination can be treated equally. You can find <a href="https://gist.github.com/martinsson/a86b301c1e0ab85f92673bbca28b60a9#file-tictactoe-java">a solution using this here</a></p><p>But wait there’s one final simplification to be done. We dont need a board! Actually we’re only interested in the spots that has the players marker on them. We could change the data structure to have a list of spots for each player and the solution becomes a breeze:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41d3e1fee9724e601046d71e6f61a7a9/href">https://medium.com/media/41d3e1fee9724e601046d71e6f61a7a9/href</a></iframe><h3>Disclaimer about primitive obsession</h3><p>I’ve been using primitives extensively here. Actually I’ll almost never expose primitives outside a class, but I will always try to simplify using primitives, then I’ll carefully chose where to encapsulate them. In this case I’d replace the integers with enums which still allows me to use the ordinal to do the above calculations.</p><h3>Conclusion</h3><p>We can write much less and much simpler code if we choose the underlying data-structure wisely. The best data structure is almost always the simplest possible one. Going primitives first helps me a lot.</p><p>I thank Christophe Grand, famous in the Clojure community, for introducing me to the technique of values-first in design.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mSmsjPEHeQwzw6JHwX6p1A.png" /></figure><p><em>Originally published at </em><a href="https://gist.github.com/5828bafe127909d72f0756654bf7efd7"><em>gist.github.com</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bd31298f35b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>