<?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 Fran Iglesias on Medium]]></title>
        <description><![CDATA[Stories by Fran Iglesias on Medium]]></description>
        <link>https://medium.com/@francisco.iglesias_75888?source=rss-9522b5ff0d06------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*YlxSK_oXt8xc3_bpQMSv-Q.jpeg</url>
            <title>Stories by Fran Iglesias on Medium</title>
            <link>https://medium.com/@francisco.iglesias_75888?source=rss-9522b5ff0d06------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 05:04:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@francisco.iglesias_75888/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[Beginner level TDD: the Prime Factors kata]]></title>
            <link>https://medium.com/docplanner-tech/beginner-level-tdd-the-prime-factors-kata-3f5bb95062b1?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5bb95062b1</guid>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[kata]]></category>
            <category><![CDATA[prime-factorization]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Thu, 17 Feb 2022 16:04:17 GMT</pubDate>
            <atom:updated>2022-02-17T16:04:17.993Z</atom:updated>
            <content:encoded><![CDATA[<h3>Beginner level TDD: The Prime Factors Kata</h3><p>– Some time has passed since our last TDD session, my young Padawan.</p><p>– Yes, master. I was busy practicing the exercise you taught me. I even tried it with different programming languages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ieij488llwgF-43eZgJ-dg.jpeg" /></figure><p>– That’s good. I would like to discuss with you another exercise. This time, it’s a bit more of an interesting problem which enable you to decompose a number in its prime factors.</p><p>– Oh, nice! We are going to program the “Eratosthenes sieve”, then.</p><p>– Hum. Something like that, I would say.</p><p>– I’m willing to start… With a test, of course.</p><p>– So…</p><p>– Our first test should be small enough to fail, but only for a good reason. For example, one test that instantiates a class, then requiring us to introduce that minimal code.</p><p>– This sounds right. Show me the code.</p><p>– Sure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/db5d087a1e790e71fe4800f8651b8b92/href">https://medium.com/media/db5d087a1e790e71fe4800f8651b8b92/href</a></iframe><p>– How do you make this test pass?</p><p>– First of all, I execute the test to be sure that it fails for the expected reason: that the class <em>PrimeFactors</em> doesn’t even exist. Once I have checked that, then I simply write enough code to instantiate the class. Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1034ffa4605b7325a2ed7ac793144fa9/href">https://medium.com/media/1034ffa4605b7325a2ed7ac793144fa9/href</a></iframe><p>– Ok, good. And now?</p><p>– Once I have the test in green, I can refactor moving the class to its own file. Thanks to the test, I can be sure that I put it in the right place.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6b2e4420b71bf781f90e7258c870a72/href">https://medium.com/media/a6b2e4420b71bf781f90e7258c870a72/href</a></iframe><p>– I love to see that you listen to my advice, young apprentice. But, don’t you feel that this way of working is slow?</p><p>– Not at all. It seems slow, but I can perform these first steps very fast with the help of my IDE. The fact is that it avoids stupid errors, like typos or putting a class in the wrong namespace, and this sort of thing.</p><p>– Let’s advance a little more, then.</p><p>– Ok. The next thing I need is that <em>PrimeFactors</em> understands a message to decompose a number, so I’m going to test for that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40bcb2143e07d659a2566624b03b2366/href">https://medium.com/media/40bcb2143e07d659a2566624b03b2366/href</a></iframe><p>– Aha. So, you don’t pass an argument yet.</p><p>– That’s right. First of all, I want to be sure that the class can receive the message. After that, I will introduce the argument.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2dc699fb1998a03016fad411325b0952/href">https://medium.com/media/2dc699fb1998a03016fad411325b0952/href</a></iframe><p>– Very nice. We have all that is needed to start developing the behavior. Isn’t it?</p><p>– Almost, master. We should start with a refactor to be ready for that.</p><p>– Can you show me that?</p><p>– Sure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f47fc22152cfe458c66d60176ce8fb02/href">https://medium.com/media/f47fc22152cfe458c66d60176ce8fb02/href</a></iframe><p>– Your progress is impressive, young padawan. You introduce a change in the code that allows us to start introducing parameters without breaking the current tests.</p><p>– Yes. If the language allowed method overloading, I would do it by introducing a second <em>decompose</em> method accepting an integer. But PHP was born this way.</p><p>– I see. What would be our first example?</p><p>– Maybe the number one. It has no factors.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e37967c0bb0bd20957e09ae58623baa1/href">https://medium.com/media/e37967c0bb0bd20957e09ae58623baa1/href</a></iframe><p>– Very interesting. How do you make the test pass?</p><p>– Easy peasy.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9891358525d84a3eee79c42a45b9e226/href">https://medium.com/media/9891358525d84a3eee79c42a45b9e226/href</a></iframe><p>– Well done. What about refactoring?</p><p>– I can see that all of the tests will be decomposing a number and expecting an array of factors, so I think that I can reflect that into the test using this idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9eba8d352f7fb9c3701ca05ca8e42e5d/href">https://medium.com/media/9eba8d352f7fb9c3701ca05ca8e42e5d/href</a></iframe><p>– Ooooh. Very nice. So, you are introducing some domain vocabulary in the test. Clever!</p><p>– Thanks, master.</p><p>– And now, it is very easy to add a new test.</p><p>– That’s right.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08d84e10bb9b81082bb52d40b1bc835f/href">https://medium.com/media/08d84e10bb9b81082bb52d40b1bc835f/href</a></iframe><p>– Let’s make the test pass.</p><p>– I would start doing this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/628861aea1f9ceb7496d1e53d171a6d5/href">https://medium.com/media/628861aea1f9ceb7496d1e53d171a6d5/href</a></iframe><p>– Seems right. But maybe you can refactor something.</p><p>– Hum. Let me see… Instead of returning <em>[2],</em> I should return the variable.</p><p>– Why?</p><p>– If the number is 2, that is a prime number, so the decomposition is the same number. I understand that this better reflects our mental model.</p><p>– Good point. Can we go to the next example?</p><p>– Of course. Number 3 is also a prime.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/717bc6f3584d2bd02852ea4a8f147397/href">https://medium.com/media/717bc6f3584d2bd02852ea4a8f147397/href</a></iframe><p>– It should have a similar solution; is it?</p><p>– Yes, master. Very similar:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6857d3b3b4e02c611cde6b6aef1bd18b/href">https://medium.com/media/6857d3b3b4e02c611cde6b6aef1bd18b/href</a></iframe><p>– This really needs a refactor, young padawan.</p><p>– Yes, of course:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/93230c48ed92578aa0f3554f31a91468/href">https://medium.com/media/93230c48ed92578aa0f3554f31a91468/href</a></iframe><p>– I can see something more.</p><p>– Really?</p><p>– Yes. Numbers are greater than one.</p><p>– Oh. I see.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c07c8a0ece516af524aad427e7e3a97d/href">https://medium.com/media/c07c8a0ece516af524aad427e7e3a97d/href</a></iframe><p>– We are ready for the first not-prime number.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/235798dad5e31c05ef3cf5b8aa62fd6e/href">https://medium.com/media/235798dad5e31c05ef3cf5b8aa62fd6e/href</a></iframe><p>– I would start simple.</p><p>– I agree.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aed6ee739022ec2b1fe3054b0f1ff4f8/href">https://medium.com/media/aed6ee739022ec2b1fe3054b0f1ff4f8/href</a></iframe><p>– Time to think about this. What are you returning here?</p><p>– The array of factors.</p><p>– That’s right, but what type of response is that?</p><p>– Errr. A <strong>constant</strong>?</p><p>– Correct! Why do you return a constant?</p><p>– Because I don’t know exactly how to compute the result. I only have one example and for the moment the test is not asking me for more. This is the minimum amount of code that makes the test pass.</p><p>– Wise answer. So, what do we need to progress?</p><p>– A new example that challenges the current solution.</p><p>– Like five?</p><p>– Let me think… No. Decomposition of five is implemented already, because being a prime number, simply returning the number as the unique factor is the correct solution.</p><p>– Six, then.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f51be4690979b9eb2b8eb8e7e80f739/href">https://medium.com/media/7f51be4690979b9eb2b8eb8e7e80f739/href</a></iframe><p>– And the code to make it pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a0756db371c0041fbc0b60b19e61387/href">https://medium.com/media/0a0756db371c0041fbc0b60b19e61387/href</a></iframe><p>– Do we need more examples to see a general rule and refactor things?</p><p>– I don’t think so. Maybe in other problems, we would need to have some more examples, but not here.</p><p>– So, what do you propose?</p><p>– I can see several things. First of all, both 4 and 6 are divisible by 2. If a number is divisible by 2, the first factor would always be 2. I think I can reflect that in the code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74ecd6eb7686902a004be5bed1d2188c/href">https://medium.com/media/74ecd6eb7686902a004be5bed1d2188c/href</a></iframe><p>– Uh, oh. The example of decomposing 2 fails because we are introducing the number one as a prime factor.</p><p>– I see. The problem is that the remainder of dividing 2 by 2 is 1.</p><p>– I need to change that to prevent it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb85082c195bf20ba715fdfe91ad5324/href">https://medium.com/media/eb85082c195bf20ba715fdfe91ad5324/href</a></iframe><p>– I’m not sure that <em>remaining</em> is a very good name.</p><p>– I agree, but I cannot think of a better one.</p><p>– There is something that bothers me. There are lots of number two’s, there. Also, I think that we could do something with that array. If you were using some kind of collection class it would be easy to spot.</p><p>– Hhhm. Let’s go step by step, master. The number two represents a divisor, or a factor. What do you think?</p><p>– That sounds good enough to me for the moment.</p><p>– Ok. Let me make some changes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e6b52292fb63a99bb2ba57dbb4491908/href">https://medium.com/media/e6b52292fb63a99bb2ba57dbb4491908/href</a></iframe><p>– Now, we got rid of constants and have variables in the response.</p><p>– Aha.</p><p>– What about treating the array as a collection. In PHP we don’t have native collections, but there are some array functions that can do the job.</p><p>– Yes, master. I can see what you are proposing. But using the other notation is faster.</p><p>– I understand, but we shouldn’t care about that yet. I want you to spot something.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51a8b59084fd02b9476171ffd8afea7d/href">https://medium.com/media/51a8b59084fd02b9476171ffd8afea7d/href</a></iframe><p>– Can you see something weird?</p><p>– We have three returns. I don’t worry about having multiple returns, but in this case, they feel like a bad solution, because we start with an empty array or collection of factors, and we push those that we are finding.</p><p>– And…?</p><p>– Ooops. The variable <em>remaining</em>. After guessing the first factor, this remaining is the part of the number that is left without decomposing. In fact, we could keep the name <em>number</em> for that variable.</p><p>– Show me how we can change that.</p><p>– Sure.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cfd0f159dccb73fbfe75a10ffc596d7a/href">https://medium.com/media/cfd0f159dccb73fbfe75a10ffc596d7a/href</a></iframe><p>– Wow!</p><p>– What happened?</p><p>– I have to make some more changes than I expected and move the second $number &gt; 1 condition to a new place - but the code looks clearer now. We remove one level of indentation.</p><p>– That’s good. What about a new example?</p><p>– Ok. The next number is 7, but it is a prime, so the test will pass. I will try with 8.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1a9bf50b17a1c4f13f0d1d70586fb09f/href">https://medium.com/media/1a9bf50b17a1c4f13f0d1d70586fb09f/href</a></iframe><p>– The test fails. It correctly extracts the first factor, but then it puts the remaining 4 as the second factor. We need to force the code to keep trying to decompose the number while it is possible.</p><p>– Isn’t <em>while</em> a generalized form of <em>if</em>?</p><p>– Hhhm. Let me try something.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/20b98ed35fc6017bcd02697bb0d66372/href">https://medium.com/media/20b98ed35fc6017bcd02697bb0d66372/href</a></iframe><p>– Damned! Something is terribly wrong. We’ve got an infinite loop.</p><p>– What’s the problem?</p><p>– Maybe I’m trying to do too much, but if the number is 3, the while loop never ends.</p><p>– Yes. And, why does this happen?</p><p>– Because in that case, we don’t reduce the number. We get the factor right because it is prime, but we are not reducing the number after that, so the loop cannot end.</p><p>– What can we do?</p><p>– Hhhm… I’m stupid.</p><p>– What?</p><p>– I changed the wrong conditional. We should keep trying dividing by 2:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5474e7f9f3c34e77a5154b5f3e9f507a/href">https://medium.com/media/5474e7f9f3c34e77a5154b5f3e9f507a/href</a></iframe><p>– Great! What does this failure teach to us?</p><p>– That I’m stupid?</p><p>– No! The lesson here is that we should concentrate on the example we are testing. You tried to generalize too much and too early, instead of concentrating on the thing that was important at this point: dividing by 2.</p><p>– Yep. I can see it now.</p><p>– Did you spot how a little change from <em>if</em> to <em>while</em> can have a big effect on the program?</p><p>– Yes, indeed.</p><p>– Let’s try with another example. It’s time to try with 9.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f17525e64ae72c1f786df2d9c2b46a5b/href">https://medium.com/media/f17525e64ae72c1f786df2d9c2b46a5b/href</a></iframe><p>– It fails. That’s great. It’s telling us something new. What is it?</p><p>– We need to manage a change in the divisor. But, we can start simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fd6b752ad6ae6c358ba7a83a6db17802/href">https://medium.com/media/fd6b752ad6ae6c358ba7a83a6db17802/href</a></iframe><p>– Now, I can refactor in small steps:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/562a12a2b99e1bb4f050652addded27f/href">https://medium.com/media/562a12a2b99e1bb4f050652addded27f/href</a></iframe><p>– And…</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c0bb49cfc2dddd5cfad9c8c26091180d/href">https://medium.com/media/c0bb49cfc2dddd5cfad9c8c26091180d/href</a></iframe><p>– And… what?</p><p>– Now, I can see that I need to increase the divisor when I exhaust it… and do that until the number is 1, so no more factors could be found. But I need to do some preparatory refactor before and initialize the divisor outside of the first condition.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b09ca35d32c03c0035fb5b1c66b0105/href">https://medium.com/media/7b09ca35d32c03c0035fb5b1c66b0105/href</a></iframe><p>– I wonder if we could change that if to while, so we get the same structure and remove that ugly duplication.</p><p>– You could do that provided it doesn’t break the tests.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a572719ace0e49f7a1a052bac2685ae/href">https://medium.com/media/5a572719ace0e49f7a1a052bac2685ae/href</a></iframe><p>– Now, it is clear how to remove duplication.</p><p>– Yes.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/796e730b1dbb93c6a7efc8be4c882f39/href">https://medium.com/media/796e730b1dbb93c6a7efc8be4c882f39/href</a></iframe><p>– This fails.</p><p>– That’s because the remaining <em>if</em> condition should be removed.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a03c7976e599032f7018da603765264/href">https://medium.com/media/0a03c7976e599032f7018da603765264/href</a></iframe><p>– And that’s all.</p><p>– All? What do you mean?</p><p>– Let’s try another example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b6f077983fa74e1e8206b4c44a52f0b/href">https://medium.com/media/7b6f077983fa74e1e8206b4c44a52f0b/href</a></iframe><p>– It works</p><p>– Try 30 and 900</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe9f138b0c31922b71ae117e5a61b326/href">https://medium.com/media/fe9f138b0c31922b71ae117e5a61b326/href</a></iframe><p>– All of them pass.</p><p>– I can’t imagine another test that can fail. The exercise is mostly completed. You will need to clean some details, and maybe do some optimization here and there.</p><p>– Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8aac6349f94696202e79622c5aaef604/href">https://medium.com/media/8aac6349f94696202e79622c5aaef604/href</a></iframe><p>– This is the end of our lesson for today.</p><p>– Thanks, master. I will practice this exercise.</p><p>– I hope you do. There are some important takeaways from this exercise. First, you should follow the three laws and the red-green-refactor cycle. Second, make small changes secured by the tests. Third, try to concentrate on the example at hand and work only to fulfill it. Fourth: avoid generalizing too early. And Fifth: don’t try to optimize code until you have defined the behavior.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5bb95062b1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/beginner-level-tdd-the-prime-factors-kata-3f5bb95062b1">Beginner level TDD: the Prime Factors kata</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Choosing and managing examples in your tests]]></title>
            <link>https://medium.com/docplanner-tech/choosing-and-managing-examples-in-your-tests-56cb0de10d52?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/56cb0de10d52</guid>
            <category><![CDATA[test-examples]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[object-mother-pattern]]></category>
            <category><![CDATA[qa]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Fri, 17 Dec 2021 15:20:24 GMT</pubDate>
            <atom:updated>2021-12-17T15:20:24.408Z</atom:updated>
            <content:encoded><![CDATA[<p>It is very important to wisely choose the examples we use to write our tests so that they are useful and meaningful. In this article, I will explain how to achieve that using basic techniques.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Pk6hH22523wYIUBq0VyNfw.jpeg" /><figcaption>Choosing examples for tests</figcaption></figure><p>On the other hand, it is frequent to need the same examples in different tests. When we work with an object-oriented approach, it is easy to refer to certain objects according to their properties. For example, you’ll want to work with an example of a logged user, or of a booked appointment, or of a canceled order, etc., in different scenarios across the test suite. In those cases, you can copy-paste them, but there is a better solution for that - one that ensures that you have a coherent set of examples, with a unique creation point for them: object mothers.</p><p>So, let’s go first with how to choose examples.</p><h3>Choosing examples</h3><h4>Unique discrete values: test them all</h4><p>When we have a limited number of possible discrete cases, we can simply test all of them.</p><p>Example: applying some kind of promotional code to a price. Suppose that there are only three promotional code types: low, medium, and high. They provide a discount of 10%, 20%, and 30%, respectively. So we write a test using each one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Y_CrW7zM1U7HJ--8Dk4YFA.jpeg" /><figcaption>Test all cases if you have a limited set of them</figcaption></figure><h4>Values that you can group by some criteria: equivalence class partitioning</h4><p>It is frequent to have infinite values for a variable, but they can be easily classified in categories based on a property of the data that is relevant for the test. These categories are <em>equivalence classes </em>and all of their members are equally representatives of the class.</p><p>You are not going to try all the possible values, so you select one representative from each category, and that’s enough.</p><p>Let’s consider the Leap Year problem. There are the following categories:</p><ul><li><em>Common years</em>: those which number is not divisible by four.</li><li><em>Leap years</em>: those which number is divisible by four, but not by 100.</li><li><em>Special common years</em>: those which number is divisible by 100.</li><li><em>Special leap years</em>: those which number is divisible by 400.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NqmI552bHLPAUDmc1fEmcw.jpeg" /><figcaption>You only need to test an example of each category</figcaption></figure><p>So, we only will need four examples to prove all of the possible scenarios. Well… maybe we could add a special scenario for dates before 1582, given it marks the invention of the Gregorian calendar, but I think that this is not relevant for most current businesses.</p><h4>We can classify values, but we care about what happens in the boundaries between categories: boundary value analysis</h4><p>Some variables can accept continuous values; we can partition this continuous into categories. Nevertheless, we are worried about how the behaviour applies to the values in the boundaries.</p><p>In other terms: categories are intervals of values ​​whose extremes can be open or closed. Open extremes are excluded from the interval, while closed extremes are included.</p><p>We can consider the Museum Ticket Price problem. It’s common practice to segment the price of these tickets based on age. Categories are defined by age intervals, like this:</p><ul><li>Toddlers: Less than 3 years old.</li><li>Children: Between 3 and 12 years old.</li><li>General: Between 12 and 65 years old.</li><li>Retired: More than 65 years old.</li></ul><p>The point to consider here is in which category is included each boundary. We need a precise definition from business people. For example:</p><ul><li>Toddlers: Less than 3 years old.</li><li>Children: More or equal than 3 and less than 12 years old.</li><li>General: More or equal than 12 and less than 65 years old.</li><li>Retired: More than 65 years old.</li></ul><p>So: how many examples do we need? If we want to be sure about the boundaries we would need to pick two values in each category - which are the values in both extremes. For the categories with only one boundary, we can pick only one example.</p><ul><li>Toddlers: 2</li><li>Children: 3, 11</li><li>General: 12, 64</li><li>Retired: 65</li></ul><p>This way, we will be well served with six examples. Note that each example is a good representative of its category.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KHZFW7L8CQXRz2shIrgDVw.jpeg" /><figcaption>We use boundary analysis when it is important to be sure about the behaviour across different categories</figcaption></figure><h4>We need to create scenarios based on several variables: decision table</h4><p>If we need to combine several variables to create a test scenario we apply a combinatory strategy.</p><p>First, we choose examples for each variable, applying the equivalence class partitioning or the boundary value analysis strategy.</p><p>Second, we combine all using a combinatory tree and represent the combinations in a table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*nzBE9npe1JNy5ubm5NN00w.jpeg" /><figcaption>Decision tables can be huge</figcaption></figure><h4>We are not sure about the values that we need to try: basic path</h4><p>The previous techniques are used for <em>black-box testing.</em> This is the kind of test that we write considering the subject under test as a black-box, for which we don’t know anything about how it is implemented.</p><p>Sometimes, we don’t have a clue about the values that we could use for testing, but we can examine the algorithm in order to ensure that all the possible branches of the flow are executed. With this knowledge, we can define the different scenarios. Usually, the different execution paths are controlled by a variety of variables, so the black-box techniques don’t fit well.</p><p>This type of testing is what we refer to as <em>white-box testing</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hQicXVobNo0ir6KouA4LcQ.jpeg" /><figcaption>We can see some of the possible paths of this algorithm.</figcaption></figure><p>We can use graphical code coverage tools to discover the paths not tested yet.</p><h3>Managing examples in tests</h3><p>Making our selection of examples understandable in the tests can be a tricky problem. When we write the tests we know why we choose certain values as examples for a concrete test, but another developer that is not familiar with the subject can feel a bit lost.</p><p>Test examples fall easily in the <em>Magic numbers</em> code smell: arbitrary values in the code of the test without meaning nor explanation.</p><h4>Name your examples by applying the introduce constant refactor (or introduce variable)</h4><p>The best way to solve this problem is by introducing constants or variables with meaningful names instead of the raw values. This way, the reader can understand what’s going on without the need to know the exact values, but they can always access them.</p><p>Using constants or variables is up to you, and can be determined by the programming language. It depends on the scope in which you need to use the example.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/122e3cfc8582d7107032852cb87e258f/href">https://medium.com/media/122e3cfc8582d7107032852cb87e258f/href</a></iframe><h4>Apply extract method when it is complex to create the example</h4><p>Naming examples using constants or variables works fine for scalar values and simple objects, but if creating an example requires some complexity it becomes easy to entangle the code, making it difficult to understand.</p><p>In those cases, we can extract the complexity to a factory method in the test case, so instantiating an example becomes a one-liner. You can parametrize the method to be able to customize the example for different cases.</p><p>In the following example, you can see how we extract the instantiation of the Request object to a private method, making it easier to create all examples that we need.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/55cf3cdd7875c36ed01c355147806308/href">https://medium.com/media/55cf3cdd7875c36ed01c355147806308/href</a></iframe><p>Maybe you need to use builders or factories for this.</p><h4>Apply the object mother pattern if you want to use the same examples in different tests</h4><p>Many times you will want to use the same example across different unrelated tests, because you would like to have a way to reuse or share it in some way.</p><p>To achieve that, you can apply the <em>Object Mother</em> pattern. An Object Mother is similar to a limited factory that can create valid examples of certain objects. Usually, they are completely configured, but you can allow some parametrization - you could say that they provide archetypical examples of objects.</p><p>Here is an example. I’d prefer to name these objects as Examples, but the pattern is the same.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/09d6985504c32adedbec422b4b193db5/href">https://medium.com/media/09d6985504c32adedbec422b4b193db5/href</a></iframe><p>Remember that Object Mothers are not builders. A builder is an object that knows how to instantiate other objects that have complex construction. An Object Mother is only concerned about a very reduced set of parameters, keeping the rest constant, default, or even random. So, if your Object Mothers need to be builders, that’s an indicator that you are trying to test too much at once or that the object is too simple, as happens in our example.</p><p>Some tips with Object Mothers.</p><p><strong>Allow them to be used statically;</strong> granting a unique place to gather examples of a class. It’s safe to do so as they only provide this creational behaviour and they will be only used in tests.</p><p><strong>Name methods meaningfully</strong>. Each factory method must describe the type of example it creates, so the team will be able to talk and reason about them. For example, I usually have a <em>dummy</em> method, of which returns an arbitrary configured object for use in examples in which the result doesn’t depend on particular properties of the object.</p><p>Another example: you can have a <em>ContractMother::signed</em> to provide a <em>Contract</em> object that is signed to compare against an <em>unsigned</em> one.</p><p>This allows the team to have conversations about the tests and their examples.</p><p><strong>Limit parametrization to only one or two variables,</strong> if needed by the tests. Keep constant or randomize the rest of the required parameters; if there are only a few values, create a factory method specific for each one.</p><h3>Stochastic examples?</h3><p>You can think that randomness and tests don’t mix well. This is generally true, but you can use some randomness to increase the reliability and trust in your test suites.</p><p>How can you do that? By introducing random examples in the tests instead of using fixed ones. The point is to not test based on single values for a category, but instead, you try randomly with a lot of values that belong to the category.</p><p>The random method in the following snippet generates a completely random <strong>Task</strong> object every time it is called. Using these examples your test will run with a completely new set of examples, and the code under test should be able to manage them properly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba806dae45cd91d97bfef08cce63a68b/href">https://medium.com/media/ba806dae45cd91d97bfef08cce63a68b/href</a></iframe><p>So, tests using this approach could fail at a random execution but this is the intended behaviour. Your task is to avoid that a failure can happen even when we are providing random examples, something that resembles real production situations.</p><h3>Summarizing</h3><p>There are several techniques that you can use to choose examples for tests in a systematized way:</p><ul><li>The limited set of examples</li><li>Equivalence class partitioning</li><li>Boundary analysis</li><li>Decision table</li><li>Basic path</li></ul><p>Also, you can manage all those examples in your test by using simple practices:</p><ul><li>Use constants and variables to give them meaning</li><li>Extract creation of examples to private methods</li><li>Use the Object Mother pattern to have a limited set of examples, for using in tests and to reason about</li></ul><p>Happy testing!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=56cb0de10d52" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/choosing-and-managing-examples-in-your-tests-56cb0de10d52">Choosing and managing examples in your tests</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[null is something … to care about]]></title>
            <link>https://medium.com/docplanner-tech/null-is-something-to-care-about-abb515e92d73?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/abb515e92d73</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[null-safety]]></category>
            <category><![CDATA[it]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Mon, 25 Oct 2021 16:29:47 GMT</pubDate>
            <atom:updated>2021-10-25T16:29:47.995Z</atom:updated>
            <content:encoded><![CDATA[<h3>null is something … to care about</h3><p>In case you feel familiar with the title … You’re right. I’ve shamelessly stolen it from a talk by Sandi Metz:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F9lv2lBq6x4A%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D9lv2lBq6x4A&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F9lv2lBq6x4A%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b5df86e3b29651ed395960f0fee8e84/href">https://medium.com/media/8b5df86e3b29651ed395960f0fee8e84/href</a></iframe><p>I’ve found myself recently in a situation in which using <em>null</em> was a bad decision, so I decided to research ideas about how to avoid it and model with a better approach. <a href="https://www.arhohuttunen.com/avoiding-unnecessary-null-checks/">This article by Arho Huttunen</a> about avoiding <em>null</em> checks helped a lot and also provided me with some useful links, as well as this <a href="https://www.yegor256.com/2014/05/13/why-null-is-bad.html">other article by Yegor Bugayenko</a>.</p><figure><img alt="Two cups, one filled with water and the other empty" src="https://cdn-images-1.medium.com/max/1024/1*7uuyoArQ9i84CI5khOcBCA.png" /><figcaption>Even the empty cup is something</figcaption></figure><p>The <em>null reference</em> was introduced by Tony Hoare in 1965 when he was developing the type system for ALGOL W. <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">And he regretted it</a>:</p><blockquote>This has led to innumerable errors, vulnerabilities, and system crashes, which have probably caused a billion dollars of pain and damage in the last forty years. (Tony Hoare (2009): <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/">Null References: The Billion Dollar Mistake</a>, QCon, 2009)</blockquote><p>So, in this post we will try to discuss why <em>null</em> can be a really big problem, and how to avoid it.</p><h3>What is <em>null</em> anyway?</h3><blockquote>It is a strange fate that we should suffer so much fear and doubt over so small a thing. (Boromir in The fellowship of the Ring, J.R.R.Tolkien)</blockquote><p>What is <em>null</em>? <em>null</em> is a pointer that doesn’t refer to a valid object. This is similar to saying that <em>null</em> points to nothing. Or, in simpler words: <em>null</em> is nothing.</p><p>For example, if we consider a <em>linked list</em>, in which every item in the list keeps a pointer to the next one, <em>null</em> is used to mark the end of the list. <em>If this item points to nothing, then the list ends.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e1dc4b90a61cf0af8f3a536862e4646d/href">https://medium.com/media/e1dc4b90a61cf0af8f3a536862e4646d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22b2b64daa7507aa891c1352dbf0a4aa/href">https://medium.com/media/22b2b64daa7507aa891c1352dbf0a4aa/href</a></iframe><p>Also, one typical use of <em>null</em> is to signal that a certain object has not been initialized and is waiting to have a value. We have to put something there, at some moment. The sooner, the better. For example, when we define the properties of a class, we usually initialize them at construction time. Type systems can prevent us from not initializing them by failing when we try to use an uninitialized property. The code above shows some examples.</p><p>Those were situations in which <em>null</em> is <em>nothing</em>. Also, they have some traits in common:</p><ul><li>Usually, we don’t explicitly set them as <em>null</em>.</li><li>Those <em>nulls</em> are internal to the object or data structure. The outer world doesn’t need to know about them.</li></ul><p>But, sometimes <em>null</em> is <em>something</em>. And that’s very important when communicating with other objects in the system.</p><h3><em>Null</em> as “<em>no result”</em></h3><p>One frequent use of <em>null</em> is to represent that something is not found. This can happen in several situations.</p><p>Let’s consider a repository of entities. There are two main ways to get an entity from such a repository:</p><ul><li><strong>by its identifier</strong>: we get one entity providing its identifier.</li><li><strong>by specification</strong>: we can get a set of entities that match certain criteria.</li></ul><h4>To be or not to be</h4><p>In a first way, what we can expect is that one entity with that identifier exists or not. If it exists is not a problem at all. We retrieve it and do whatever we need.</p><p>But if the entity doesn’t exist we get <em>nothing</em>. It makes sense. If the entity with that identifier was never stored, then you will never find it. There are two big possible reasons: something happened that prevented the entity from being stored in the first place, or someone is trying to fool the system by using a non-existent identifier.</p><p>So, we get nothing and the temptation to represent it as <em>null</em> is strong.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/daf861c36ef71f96185547762e6642c5/href">https://medium.com/media/daf861c36ef71f96185547762e6642c5/href</a></iframe><p>But it is also wrong because it forces us to check if there is something in the response. It seems kind of ridiculous to verify if my partner has given me something I asked her for. If she cannot give it to me, she simply will say “I don&#39;t have it”. I don’t need to check my hand to be sure that I don’t have the damn thing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08a3922f36536d1e82080d98b179ad2b/href">https://medium.com/media/08a3922f36536d1e82080d98b179ad2b/href</a></iframe><p>The repository should fail with an exception, because an entity that we hope does exist does not exist; this is something that shouldn&#39;t happen. The consumer only has to deal with that problem or pass it to a higher level until the exception finds a proper handler.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c04a602d3d52b9abe99d3c4110a6aec/href">https://medium.com/media/6c04a602d3d52b9abe99d3c4110a6aec/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e038323f4ef2a143e1febff5615662e9/href">https://medium.com/media/e038323f4ef2a143e1febff5615662e9/href</a></iframe><h4>Sorry, we don’t find any of those</h4><p>In the specification way, the problem is slightly different. In this case, we can expect that there are no entities that fulfill the specification, thus the result can be <em>nothing</em>.</p><p>If there are entities that meet the conditions of the specification, then you will get a set of entities. Maybe in the form of an array, a set, a collection, or a similar container data structure. Possibly you will get the set and iterate over it to provide some functionality.</p><p>Here, <em>nothing</em> means <em>empty</em>. And that’s because this time <em>nothing</em> is <em>something</em>: the result is a set or collection that happens to be <em>empty</em>. If you iterate an empty collection, nothing will happen, but also, nothing would break. You simply inform the consumer that no results were found.</p><p>So, you don’t usually need to check if the result set is empty.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d0ae4ce91a71be782a0adf21e7e3be30/href">https://medium.com/media/d0ae4ce91a71be782a0adf21e7e3be30/href</a></iframe><h3>Null as “maybe…”</h3><p>Sometimes we use <em>null</em> to express that something is optional and it can be there or not. Consider this situation:</p><p>We have a student assessment system that allows us to assess their tasks. A grade is mandatory, but you can also add feedback with a customizable message and one standard label.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a5fe287a25a4e74c762701759946053d/href">https://medium.com/media/a5fe287a25a4e74c762701759946053d/href</a></iframe><p>Ok. Feedback is optional, so we can have an Assessment class with a mandatory Grade and nullable Feedback property. It sounds reasonable, but it leads to several problems.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5470e373e7619d6e1361d2015951c61/href">https://medium.com/media/b5470e373e7619d6e1361d2015951c61/href</a></iframe><p>Most of the time you have to check if Feedback is present. If you forget that, you will find a situation in which you will be sending a message to <em>nothing</em>, and the system will complain, throwing a <em>Null pointer exception</em> or its equivalent.</p><p>For example, if you want to show a list view of the assessments for a student, you will have to add a conditional to check if the Feedback exists and render something in the affirmative case and render something different in the opposite one.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c12127c34b2598b116cb3dec5fe1da49/href">https://medium.com/media/c12127c34b2598b116cb3dec5fe1da49/href</a></iframe><p>The problem here is that <em>No Feedback</em> is also a <em>Feedback</em> and <em>null</em> doesn’t represent that properly, because <em>null</em> is <em>nothing,</em> and not having feedback is something.</p><p>You can avoid that by introducing the <strong>Null Object</strong> pattern instead. A Null Object is an object with the same interface that does nothing or provides some kind of default behaviour. The Null Object can even fail with exceptions if it makes sense for your domain at some point.</p><p>Let’s see an example. We define an interface for Feedback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e9779916c9cadb7c8dcfa59f0e0510ed/href">https://medium.com/media/e9779916c9cadb7c8dcfa59f0e0510ed/href</a></iframe><p>This is the standard feedback object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f46a27d5bde28c727c95b4521349c3a/href">https://medium.com/media/5f46a27d5bde28c727c95b4521349c3a/href</a></iframe><p>And this is the Null Object implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/46fb9d12f17e07eb8b5f3bf1309b62c4/href">https://medium.com/media/46fb9d12f17e07eb8b5f3bf1309b62c4/href</a></iframe><p>This way, you can communicate with the Null Object the same way you do with any standard objects of the same type, sending the same messages and expecting a proper response from it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5190c18e0136010fbb3f63c9f62e6bf/href">https://medium.com/media/b5190c18e0136010fbb3f63c9f62e6bf/href</a></iframe><p>And not having to worry about checking for <em>null</em>.</p><h3>Null as “I can’t do this in that way”</h3><p>Related to the previous topic, sometimes you query an object for some data to perform an operation with the object itself.</p><p>The point here is that if the data we asked for is <em>null</em>, the consumer has to decide how to manage the situation. For example, gathering more data from the object and trying to call again the same method or another one.</p><p>This problem comes from a code smell known as an <strong>anemic object</strong>. An anemic object is mostly a container of data with little or no behaviour at all. In OOP we expect that objects combine data and processes, in such a way that you don’t need to ask them for data. You tell them to do things, instead.</p><p>A typical example is sending notifications to users in our systems. They usually have several ways to be notified (email, SMS, etc), but it is possible that they don’t have a defined destination for one, or even several of them. So, you need to ask the User or Customer object about every possible communication channel and decide if you can use one or another.</p><p>This is our anemic Customer model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a82d33eb20a2a586485b6e83b8a37cf/href">https://medium.com/media/6a82d33eb20a2a586485b6e83b8a37cf/href</a></iframe><p>And this is a service suffering the consequences:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10f04567861f5475acc2e0f116358432/href">https://medium.com/media/10f04567861f5475acc2e0f116358432/href</a></iframe><p>One of the possible solutions is to apply the <em>Tell, don’t ask</em> principle. This way, you can tell the User object to perform the notification and it will do it using the preferred or configured channel.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/056923a0fecfc792879d9e40a5d8cf29/href">https://medium.com/media/056923a0fecfc792879d9e40a5d8cf29/href</a></iframe><p>This way, the problems of managing the <em>nulls</em> are hidden to other components. So, NotificationService could do something like this, using a Double Dispatch:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/991871c76d5be950f617624e23878254/href">https://medium.com/media/991871c76d5be950f617624e23878254/href</a></iframe><p>Another solution is to re-think the problem and the solution design. If the User object cannot manage the communication, because it is the responsibility of another object, then the User object can provide the preferred communication channel or a Null Object if none is available. This way, the notification service won’t need to worry about checking if they are valid or not.</p><h3>Trust-driven programming</h3><p>While I was writing this post I started to think about <em>defensive programming</em> techniques. In general, defensive programming considers all inputs as dangerous, so you shouldn’t trust them. This way, you need to validate all inputs to your system from the outside, but also to your functions, applying sanitization and validation rules to accept them.</p><p>Instead of that, object-oriented programming proposes something that we could call <em>trust-driven programming</em>. Objects in the system are created valid and complete, and we should expect them to provide valid data, in the form of valid objects that will properly manage their concerns. Objects <em>cooperate</em> for the benefit of others.</p><p>When an object answers with a <em>null</em>, it introduces mistrust into the system. Mistrust leads to fear, and fear leads to the dark side… And bad programming.</p><h3>Don’t force checking for null</h3><p>Most of the time, the problem with <em>null</em> is the need to check if some object response is <em>null</em>. That means that you cannot trust in that response, and the lack of trust is always a problem.</p><p>Having to check for <em>null</em> requires the insertion of a conditional clause that increases cyclomatic complexity and introduces risks. What will happen if you forget the check for <em>null</em>? Or worse: What can happen if you pass along the <em>null</em> to an indirection chain?</p><p>So, in conclusion, as a general rule, you should not return <em>null</em>. Instead, try to manage it inside the objects using one or several of these techniques:</p><ul><li><strong>Fail with an exception</strong>. This is the way to go when it is possible that the response doesn’t exist at all.</li><li><strong>Return Null Objects</strong>. This allows the consumer to interact with an object that can have some kind of neutral or default behaviour. Empty containers, such as collections, can be considered <em>null objects</em> in the sense that they represent empty sets of data.</li><li><strong>Apply the “<em>Tell, don’t ask”</em> principle.</strong> Sometimes, having to deal with <em>null</em> is a design flaw. If you have to <em>ask</em> an object for some information to do something with the same object, there is a lot of chance that you can <em>tell</em> the object to do all the process itself, providing adequate behaviour in the case that something is not there.</li><li><strong>Re-think your design</strong>. Maybe <em>“Tell, don’t ask”</em> doesn’t apply, but you can consider other options or patterns to redesign the code.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=abb515e92d73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/null-is-something-to-care-about-abb515e92d73">null is something … to care about</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Entry-level TDD with the Leap Year Kata]]></title>
            <link>https://medium.com/docplanner-tech/entry-level-tdd-with-the-leap-year-kata-9fbf0f60c3be?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/9fbf0f60c3be</guid>
            <category><![CDATA[it]]></category>
            <category><![CDATA[test-driven-development]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[tdd]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Mon, 21 Jun 2021 10:04:47 GMT</pubDate>
            <atom:updated>2021-10-24T15:57:27.845Z</atom:updated>
            <content:encoded><![CDATA[<p>Maybe you have heard about the wonders of practicing TDD to develop your software. Or maybe you have read one of those rants about TDD being death. Never mind, if you want to learn how to inaugurate your TDD journey, you are at the right place. Let’s start from the very beginning.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t0iZlYhuIY4ulvRHdnaJCQ.png" /><figcaption>Mastering TDD with the Leap Year kata</figcaption></figure><h3>What is TDD</h3><p>TDD is a development technique based on the idea of writing tests before the production code. It was invented by KentBeck in the nineties as part of Extreme Programming. It basically works this way:</p><ul><li>You decide the new piece of functionality you want to add and write a test that describes it</li><li>You write production code until the test pass, indicating that the functionality is working</li><li>You refactor the code for a better design</li><li>Repeat the steps until you have developed the full functionality</li></ul><p>Key points to take into account are:</p><ul><li>You only write one test on each iteration. That is: you don’t define the complete functionality up-front.</li><li>Each test asks you to write a part of the functionality that the production code currently lacks.</li><li>Every test should be as small as possible, and the changes in production code should be also as small as possible. This is what we call “baby steps”.</li></ul><p>Other authors contributed to refining the technique. Namely, Robert C. Martin developed the <a href="http://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html">Three Laws of TDD</a>. They help us to decide how much test and code we should write. Here they are:</p><ol><li>You must write a failing test before you write any production code.</li><li>You must not write more of a test than is sufficient to fail or fail to compile.</li><li>You must not write more production code than is sufficient to make the currently failing test pass.</li></ol><p>We will return to these laws in the examples of this post.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xAaf8Nng5M4JlmFIaCAHGg.png" /><figcaption>Let’s make these tests pass, young padawan</figcaption></figure><h4>The TDD cycle</h4><p>One of the characteristics of TDD is the red-green-refactor cycle.</p><p>The cycle starts with a test that fails because no code makes it pass yet. Usually, testing frameworks represent failing tests in red color, so we say that we are in the red phase of the cycle.</p><p>Our goal is to make the test pass, something that is represented with the green color. So, we can say that our goal is to put the tests in green adding enough production code, but no more.</p><p>At this point, we should start with the most simple or obvious implementation that can work. Even if it seems too obvious or rough, we only want to make the test pass as soon as possible, establishing the desired behavior.</p><p>When we have all the tests passing in green, it is time to refactor the current implementation to a better design. This includes, among other actions:</p><ul><li>Remove code duplication if possible</li><li>Improve naming of variables, functions, classes, constants</li><li>Improve code organization by extracting parts of it to private methods or new classes as responsibilities emerge</li><li>Improve code design as applicable conditions appear</li></ul><h4>What TDD is not</h4><p>TDD uses tests as a development tool, but tests in TDD are not the same as Quality Assurance tests, although they overlap a lot.</p><p>The main differences between the TDD style of testing and QA are:</p><ul><li>Some TDD tests are redundant for a QA suite. Usually, you start writing a lot of tests that are not needed for QA and should be removed after they fulfilled their purpose of driving development.</li><li>In general, the goal of TDD tests is to challenge the current production code to add new behavior. QA tests are meant to verify that behavior is the expected one.</li></ul><p>Nevertheless, one of the outcomes of working using TDD is that we get a nice regression suite of unitary tests after cleaning it a bit.</p><h4>Code quality and TDD</h4><p>TDD is not a guarantee of code quality or good code design. It is a tool that helps to build software with better quality and design, preventing lots of defects and providing us with a methodology to add new functionality or improve design, without breaking anything.</p><p>This is possible because once we make a test pass, these very same tests become a regression test that ensures that the developed behavior stays untouched.</p><p>The refactor phase in the TDD cycle is the moment that we use to increase code quality, migrating from simple, naive, implementation to better-structured ones.</p><h4>Benefits of TDD</h4><p>TDD helps us to develop a discipline when writing software. Every test defines a short-test goal and helps us to keep focused on a single task. <a href="https://dev.to/franiglesias/improve-your-life-with-tdd-a5d">Using TDD you work relaxed, one step at a time</a>. In fact, some studies show<a href="https://api.semanticscholar.org/CorpusID:16559803"> evidence that teams</a> doing TDD spent less time debugging, have fewer bugs after deployment, and write a lot more tests.</p><h3>Hands-on</h3><p>Let’s start learning how to develop using Test Driven Development with a pretty simple exercise known as The Leap Year Kata. A Kata is a coding exercise that we should repeat frequently to gain automation of certain thought processes and steps. Kata is a term borrowed from a kind of exercise in martial arts.</p><p>The Leap Year Kata consists of developing a simple class or function to calculate if a given year is a leap year or not. The point of the exercise is to learn how the TDD cycle works, thus the simplicity of the problem.</p><p>For this post, I will develop a Year class, with a method isLeap that returns a bool value indicating if the year is a leap year or not. Let’s suppose a pairing session between an expert TDD practitioner and an entry-level developer.</p><p>– Ok, let’s do this. — said the expert. We are going to write this Year class guided by tests. First of all, we should take a look at the rules for calculating if a year is a leap year.</p><p>– Yes. All years that can be divided by 4, but not by 100, are Leap years.</p><p>– Good. So, years that can be divided by 100 are not leap ones. Except for years divisible by 400 that are leap years.</p><p>– Then, maybe we can start by writing a test to verify that a year is not a leap year. – Said the newbie developer.</p><p>– No, my friend. Those are a lot of steps at once. – Replied the expert.</p><p>– A lot? But, it’s only a single thing.</p><p>– Let’s see. What do you need to check that a year is or is not a leap year?</p><p>– Well, I only need a class called Year, with a method isLeap. I can instantiate it with an example of a known common year and verify that the isLeap method returns false. Something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/462588df2ac1418fd3093ef2ecb6e9e1/href">https://medium.com/media/462588df2ac1418fd3093ef2ecb6e9e1/href</a></iframe><p>– I can see that we need no less than three things: a class named year, a method in thas class named isLeap, and that the method can return false if the year is not a leap year.</p><p>– And are you suggesting writing a test for every single one of them?</p><p>– Exactly, my little padawan.</p><p>– How is that possible?</p><p>– By applying the TDD rules. What is the first one of them?</p><p>– Hum… We cannot write production code unless we have a failing test.</p><p>– So…</p><p>– So, we need to write a test.</p><p>– And… what does the second law say?</p><p>– It says that you cannot write more than one test enough to fail or not compile.</p><p>– That’s correct. And if we write that test you show me before, we will find that it can fail for a lot of reasons. The first thing we need is to be able to instantiate the class, so our first test should force us to define the class to the point that we can instantiate one object.</p><p>– So, that’s a baby step!</p><p>– Sure! Like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57fa0f9334bb3f999f034181e3962ea9/href">https://medium.com/media/57fa0f9334bb3f999f034181e3962ea9/href</a></iframe><p>– But, but, but… you are not even passing an argument to instantiate the class.</p><p>– I know. But this test is enough to fail and to tell us exactly what we need to do next. See what happens if we execute it:</p><blockquote>Error : Class ‘Year’ not found</blockquote><p>– We should write the class, I guess.</p><p>– Yes, but how much code should we write.</p><p>– Well, we can create a new file named year.php, and define a class named Year, containing a meth…</p><p>– Hold! We only need to write enough code to make this test pass. We don’t even need to create a new file for that.</p><p>– But, that’s not a correct practice. You should separate classes in files.</p><p>– I know that, but we will have the refactoring phase for that. In the meantime, we need to make the test pass, and we can achieve that by doing the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f49ce6f82e407c3b4b5cfa95dae63d3/href">https://medium.com/media/1f49ce6f82e407c3b4b5cfa95dae63d3/href</a></iframe><p>– See? The test passes.</p><p>– All right, all right, teacher. But now, we should move the class to its own file.</p><p>– Of course, but now we are protected by a test. If we move the class to the wrong file, the test will not pass, indicating our mistake.</p><p>– Really?</p><p>– For sure! Let&#39;s move it and finish our first iteration.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2cbbafb3019482defb8b750999d7792/href">https://medium.com/media/f2cbbafb3019482defb8b750999d7792/href</a></iframe><p>– So, we have moved the class and the test is still passing. That’s great. We have completed a cycle. What should we do the next, little padawan developer?</p><p>– We could write a test that invokes the “isLeap” method, but we should instantiate the class before.</p><p>– You’re right. However, we can refactor our current test to have an instance of the class before writing the test. What do you think?</p><p>– I can’t see how useful that would be, but I trust you.</p><p>We prepare ourselves for the next iteration by doing this, leaving the code easy to change as needed, while the test is green. See the code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9bb9e081a49d0d8f1c9b9b4648e748dd/href">https://medium.com/media/9bb9e081a49d0d8f1c9b9b4648e748dd/href</a></iframe><p>– That’s not a huge change.</p><p>– No, it isn’t. But it is an enabler for our next step.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7eb51c44646e5571227b74ba1dc7fb0a/href">https://medium.com/media/7eb51c44646e5571227b74ba1dc7fb0a/href</a></iframe><p>– Now, if we run the test, it fails because of a new reason:</p><blockquote>Error : Call to undefined method App\Katas\LeapYear\Year::isLeap()</blockquote><p>– Yes, little padawan. And the reason is that we don’t have the required method.</p><p>– I see. But… you are writing all in the same test. Is that right?</p><p>– At this point, it is fine. We could write each iteration in a different test, but we will remove these simple tests at the end of the process, so…</p><p>– Wait! Are we going to remove this test at the end? Are you kidding me?</p><p>– No, I’m not kidding. The point is that some of the tests that we write in TDD are useless or redundant out of this context, so we’ll remove them, leaving those that can act as regression tests.</p><p>– Oh!</p><p>– Let’s continue. We need to write our “isLeap” method.</p><p>– Yes, we can then pass the year as a parameter and check if we can divide it by four or not.</p><p>– My dear padawan: what is the minimum piece of code that will make the test pass?</p><p>– Hum… Let me think… Oh! I know: it will be enough with the method definition.</p><p>– That’s correct.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56df3593ab47f5ff0900fe2b95c89fae/href">https://medium.com/media/56df3593ab47f5ff0900fe2b95c89fae/href</a></iframe><p>– So, we have the test passing again. Could we improve the code in some way?</p><p>– Is there code to improve?</p><p>– Maybe.</p><p>– Ufff. Let me think. Possibly we can declare the return type but it will force us to return a value, and we don’t know what to return at this moment.</p><p>– Any other improvement that can help us with the next steps?</p><p>– Errr… We could introduce the parameter needed in the constructor even if we don’t use it. This will break the test but… we can prevent that by changing the test first, and then modifying the production code to use it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7dc2a56495cec2b684f62089091cd15/href">https://medium.com/media/a7dc2a56495cec2b684f62089091cd15/href</a></iframe><p>– Fantastic, my padawan! You learn fast. Now the production code, please.</p><p>– Yes. Here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b5159334fb589bb3a007a5ac3a41cf6/href">https://medium.com/media/7b5159334fb589bb3a007a5ac3a41cf6/href</a></iframe><p>– Great! Now we are ready to start testing behavior. Maybe your first test makes sense now.</p><p>– Do you mean that we have been doing this workaround only to return to my first test? Seriously?</p><p>– Don’t get angry. Anger leads to the dark side. You should practice those baby steps until you automate and perform them in a few seconds. That will help you avoid many silly errors, like typos, putting the wrong file in the wrong folder, and using wrong names... Let’s see your test now and run it. What should happen?</p><p>– Easy. It will fail.</p><p>– Because…</p><p>– Because… we don’t have any code that checks that the value of the year can be divided by four, so we will need to add code that can do exactly that.</p><p>– Can you see my point? If we had executed your first test, we would have found that it failed because we have neither the class nor the method. Now, we are sure that the unique valid reason for the test to fail is not having code that performs the behavior that we want.</p><p>– So, let’s consider the test again:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0593a78e04fa663d1903290867f1bd0f/href">https://medium.com/media/0593a78e04fa663d1903290867f1bd0f/href</a></iframe><p>– Fine. If we execute it, it fails this way:</p><blockquote>Failed asserting that null is false.</blockquote><p>– Yes. And it fails because of a good reason: the behavior is not implemented.</p><p>– Then we now can check if the year is divisible by…</p><p>– I have a better idea, for now, we can simply do the following:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0d0c97f86d63555b534f8233f81de1b/href">https://medium.com/media/e0d0c97f86d63555b534f8233f81de1b/href</a></iframe><p>– Now, I know you’re fooling me.</p><p>– Not at all. Run the test, please.</p><p>– It passes. But, this will not detect leap years.</p><p>– Yes. It’s pretty obvious. But that’s exactly the behavior that we want at this moment as defined by our tests. Now, our goal is to challenge the current implementation with a new test.</p><p>– Let me guess. We should write a test that verifies that if we instantiate the class with a genuine leap year it will be detected.</p><p>– You are right. And here is such a test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf014887c44e286f9b7f7c883549becc/href">https://medium.com/media/cf014887c44e286f9b7f7c883549becc/href</a></iframe><p>– And it fails because of the right reason:</p><blockquote>Failed asserting that false is true.</blockquote><p>– True. We need to implement something that makes it pass.</p><p>– Yesssss. Finally!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/587003f73daa2964ce6ffd1ab1aed07e/href">https://medium.com/media/587003f73daa2964ce6ffd1ab1aed07e/href</a></iframe><p>– Great job, young padawan. Now the test passes and the code identifies most of the leap years. But maybe we can refactor it a bit, don’t you think?</p><p>– Yes, let’s do it. I see that we can eliminate the <strong>if</strong> and return the result of the boolean expression. Also, we can declare the return type as boolean.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9a32b537d4410e0776ecbe76a1d7b077/href">https://medium.com/media/9a32b537d4410e0776ecbe76a1d7b077/href</a></iframe><p>– Nice. But we need to detect special no leap years, like 1900 or 1800.</p><p>– We need a test for that, teacher.</p><p>– And here it is:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6971c6fb522d0f3a1c0b399d988167dc/href">https://medium.com/media/6971c6fb522d0f3a1c0b399d988167dc/href</a></iframe><p>– If we run it, it fails.</p><blockquote>Failed asserting that true is false.</blockquote><p>– I‘ve noted that you are running all of the tests. Why?</p><p>– Because I want to be sure that we don’t break a test that was passing before. This would mean that we have altered the behavior in some way. If this happens, we should stop and fix the code to make that test pass again.</p><p>– Ok, so every test that we make pass becomes a regression test.</p><p>– Exactly. That’s mandatory to be able to refactor. While refactoring, tests must be passing. All of them. That guarantees that we preserve the behavior.</p><p>– But right now, we have a test in red, so it’s time to implement something new, isn’t it?</p><p>– Yes. We should manage the situation in which a year is divisible by 100.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/671f6252f5738143bfca822197b289c6/href">https://medium.com/media/671f6252f5738143bfca822197b289c6/href</a></iframe><p>– That was pretty simple, but it does the job.</p><p>– It is fine enough. Maybe we can refactor something.</p><p>– Let me see... We have this idea of <em>divisible by</em> in the code, perhaps we can make it explicit in code extracting the calculation to a private method.</p><p>– Interesting. I like it. Let’s do it. But don’t forget to check that tests keep passing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d3515d5e3b692c17c55de86742b64cc/href">https://medium.com/media/4d3515d5e3b692c17c55de86742b64cc/href</a></iframe><p>– Wow! We are near to completing the development. We need a new test so we can implement the management of the special leap years every 400 years.</p><p>– For example, the year 2000.</p><p>– That’s right. Let’s write the test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d8450b03d5761e2bc9a16d2c855733d/href">https://medium.com/media/5d8450b03d5761e2bc9a16d2c855733d/href</a></iframe><p>– As expected, this test doesn’t pass.</p><p>– We are on the right track to implement production code that makes it green:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e978b8b5b38d693c3e45afc2dfaa880/href">https://medium.com/media/4e978b8b5b38d693c3e45afc2dfaa880/href</a></iframe><p>– So, my dear padawan, we are mostly done. Do you think we could refactor something here?</p><p>– I can’t see a good opportunity for that. The code is pretty simple and clean. Perhaps we could combine the two last conditions, because if a year number is divisible by four, but not by 100, then the year is a leap year and common if not.</p><p>– Yes. I agree. So, we can refactor the code to reflect that and finish here our first lesson.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a96d228d1cda1f776b23f91ad86e77e/href">https://medium.com/media/7a96d228d1cda1f776b23f91ad86e77e/href</a></iframe><p>– It’s nice, but I’m not sure if it is better. Anyway, having tests has allowed us to try this new approach being sure that the behavior is not broken. TDD allows for that and to decide if you can refactor to a better design, or experiment with different options.</p><p>– This approach has surprised me. It seems slow, but I liked the process a lot.</p><p>– You should practice TDD exercises, every day if possible. By doing so, you will gain experience, speed, and trust. Now, you should practice this kata several times, until you perform it fluidly and fast.</p><p>– I will do.</p><p>– Next time, I will propose you a slightly more complex exercise, and you’ll see that the process is exactly the same.</p><p>– Thank you. I’m looking forward to a new session.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9fbf0f60c3be" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/entry-level-tdd-with-the-leap-year-kata-9fbf0f60c3be">Entry-level TDD with the Leap Year Kata</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Test doubles]]></title>
            <link>https://medium.com/docplanner-tech/test-doubles-eeacc380e049?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/eeacc380e049</guid>
            <category><![CDATA[docplannerit]]></category>
            <category><![CDATA[test-automation]]></category>
            <category><![CDATA[test-doubles]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Mon, 31 May 2021 10:17:34 GMT</pubDate>
            <atom:updated>2021-05-31T10:17:34.827Z</atom:updated>
            <content:encoded><![CDATA[<p>When you need to test an object using collaborators and want to be sure that the tested behavior is provided only by the code in the object, you probably will need test doubles.</p><p>Using test doubles, you can suppress or keep under control the behavior of the collaborators. This way you isolate the object from any other influence. Also, by using test doubles, you can avoid costly dependencies that can be out of your control or that introduce indetermination or performance penalties.</p><p>But, let’s start from the beginning.</p><h3>How we test a piece of software</h3><p>We test a piece of software by comparing the result of executing it against some defined criteria. We usually name this piece of software the <em>subject under test</em> or <em>SUT.</em></p><p>These pieces of software can be one of these two types, but not both:</p><p>A <strong>query</strong> retrieves some information about the system&#39;s state but doesn’t produce any side effects.</p><p>A <strong>command</strong> produces a change in the state of the system but doesn’t return a response.</p><p>Yes: This is the Command Query Separation principle by Bertrand Meyer.</p><h4>Testing queries</h4><p>Queries are pretty easy to test because we only need to get the response and compare it with the expected outcome.</p><p>When testing queries we could use test doubles to replace expensive dependencies and to define their behaviors for the different scenarios. Usually, we will be using stubs or fakes for that.</p><h4>Testing commands</h4><p>Commands, instead, are a bit harder for testing. We need to verify that we get the expected outcome by looking for their effect on the system. Nevertheless, sometimes we don’t have the possibility to do that because we can’t use the real dependency and we use a test double.</p><p>We will need doubles to define the collaborators&#39; behavior and verify that we produce the desired effect, expecting that we send the proper messages to them. These kinds of doubles are called spies or mocks.</p><p>An example is when we need to test a service that sends an email. There is no way to check that we send a real email. Even if we could do it, looking in some specific mailbox, the performance and reliability of the test would be a complete disaster. So, instead of that, we ensure that we call the appropriate methods of the mailer library with the correct message. We can see an example here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f6cfa0aac0cb0f61eae0dab2b57d45ff/href">https://medium.com/media/f6cfa0aac0cb0f61eae0dab2b57d45ff/href</a></iframe><p>The side-effect of the command is tested in the last two lines, where we interrogate the MailerSpy about the calls performed and the receiver of the message</p><h3>Introducing test doubles</h3><p>We will be using a test example to introduce the different types of test doubles. Imagine that we are building a feature to greet our customers for their birthday, sending them an email, maybe with a promo code or another goodie. Here is the <em>setUp</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e75668f0378b889b2f7cf7f3e95cf49/href">https://medium.com/media/7e75668f0378b889b2f7cf7f3e95cf49/href</a></iframe><p>To unit test the use case <em>GreetCustomerForBirthday</em>, we will need to double all of its collaborators.</p><h4>Dummies</h4><p><strong>Dummies</strong> are test doubles that have no behavior, all their methods return null or nothing. We use them because we need to comply with some interface and we are not particularly interested in what they do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FW3SgCxbtKGiWzRknD51dg.png" /><figcaption>Dummy (top) model</figcaption></figure><p>Let’s start with the Logger. We may want a logger in the use case but we are not worried about how it is used, but we need it to instantiate the <em>GreetCustomerForBirthdayHandler</em>. This is the case for a dummy.</p><h4>Stubs</h4><p>Stubs are test doubles that should have a predefined behavior that we want to control. Imagine that we need to test a service that gets some information talking to an external API. We have an adapter to talk with this API so we will need to double it instead of calling the real API.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZnnNpB7t7Cpr47EpmIs9fg.png" /><figcaption>We nailed it with this unicorn stub</figcaption></figure><p>In one of the possible scenarios, we can simulate that the API returns a correct value. In another, we can simulate that the API is down, so we test that our service can manage that situation gracefully. In every possible scenario, we define a stubbed behavior so we can verify our piece of software.</p><p>The use case in our example needs to get the current date to find the customers celebrating a birthday. Working with dates is always a tricky question, so, instead of access to the real system clock, we abstract it in the form of a <em>ClockService</em>. This way. we simply need to stub a fixed date and store a crafted <em>Customer</em> in the test repository.</p><h4>Fakes</h4><p>Sometimes we need a collaborator that has the same behavior as the real dependency but in a cheaper way. For example, instead of having a database-backed repository, we could use memory storage to provide the same functionality without the performance penalty. This kind of double is called a Fake.</p><p>Fakes should pass the same tests that the original collaborator, they are alternative implementations.</p><p>We decided to use a FakeCustomerRepository for this test using a memory collection implementation.</p><h4>Spies</h4><p>When we are testing commands we need to verify that they produce the expected outcome. If we need to double the dependency we won’t be able to check that outcome. Alternatively, we will need to verify that we send the right message to the collaborator in the object-oriented programming sense.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1QC0NN6OHh4T95_hvYnlTg.png" /><figcaption>She wears sunglasses, she must be a spy</figcaption></figure><p>Spies are test doubles that can register how they are used so we can interrogate them after executing the subject under test and make assertions about that.</p><p>The side effect of this use case is to send an email. We need to create a Spy that can verify that we call the send method of the MailerService with the appropriate data.</p><h4>Mocks</h4><p>Mocks resolve the same problem as spies: we use them to verify that the correct message is sent to the collaborator. The difference is that a mock expects to be used in a certain way so you could say that it carries the assertion with it.</p><p>The problem with spies and mocks is that they introduce a certain degree of fragility given that they couple the test with the implementation of the code under test.</p><p>Also, tests using mocks are more difficult to understand because they hide the assertion into the expectation. It is preferable to use spies, instead.</p><h3>But, do we really need to use doubles?</h3><p>There is some controversy about using or not doubles in tests. Most of the concerns are with spies and mocks because of the coupling they introduce. Other objections have to do with the fact that we could consider the behavior of an object as a composition of the behaviors of its collaborators, and test that through the public API of the subject under test. Those are valid points, but using doubles is a trade-off we need to accept in several circumstances.</p><h4>Doubles as boundaries</h4><p><em>Functional tests</em> are those that verify the behavior of the subject under test. We can have different types of functional tests according to the scope of the test:</p><p><strong>Unitary test</strong>: check a unit of software in isolation. We should double any collaborator of the unit to ensure that the outcome is produced only by the code of the unit. Nevertheless, you can use real collaborators instead of doubling them if they have no external dependencies.</p><p><strong>Integration tests</strong>: check subsystems to verify that their components communicate properly. We need to double the dependencies used by the subsystems that don’t belong to it.</p><p><strong>End-to-end tests</strong>: check the behavior of a system from the outside, using its entry and output points. We should double things that we don’t own, that are expensive in terms of performance, or that have undefined behavior, such as external services, mostly via fakes or crafted versions.</p><p>As you can see, doubles help to define the boundaries of the test scope. You use a double whenever you need to set a boundary that you don’t want to cross in testing.</p><h4>Isolation</h4><p>Those boundaries seldom match architectural boundaries that put your tests at risk if you cross them.</p><p>You don’t want to include in your test the performance penalty of talking to a real database at the unitary level, so you will double the database adapter to achieve this.</p><p>You don’t want the risk of having pre-existing data that will make unpredictable the behavior of the subject under test and the overload of having to manage to keep the database state clean.</p><p>You don’t want to cross your fingers trusting some external API to be up and running or returning the expected responses for your tests. In consequence, you will need to fake it in some way.</p><p>You don’t want to be dependent on the machine or the concrete set-up on which the test runs, so you use doubles to isolate from those. A typical situation is when a test has to manage dates or times, you should stub the behavior of the system clock to avoid tests that fail or pass depending on the machine, the timezone, or even the date or time when you run them.</p><p>So, doubles are one of the tools that we count on to isolate tests from all the details that we don’t own or cannot control.</p><h4>Outside-in test-driven development</h4><p>The so-called London school of TDD uses doubles as first-class citizens in the outside-in approach to test-driven development.</p><p>In the inner unitary test loops, mocks are used extensively as design tools, doubling the collaborators used by the component under development to define and refine their interfaces and the communication between units. The drawbacks of this approach, such as the test-implementation coupling, are compensated by the fact that we are designing the implementation and it probably won’t change.</p><h3>Best practices with doubles</h3><h4>You don’t share doubles behavior between tests, except fakes.</h4><p>Shared doubles can introduce dependencies between tests, something that leads to low reliability and low trustfulness. The needs of one test are not the same as another, and they should be able to evolve separately.</p><p>So, you can share doubles when:</p><ul><li>They are fakes in the sense of alternative, low-cost fully-owned implementations of a given dependency.</li><li>They are dummies, so they have no behavior, and, therefore, they don’t introduce cross dependency.</li><li>They are configurable stubs, so you can control the behavior from the test.</li></ul><h4>You only stub the behavior that is interesting for the current test.</h4><p>In addition, you don’t want to have one-size-fits-all doubles. You only stub the behavior you need for the test at hand, forgetting about other possible scenarios. Remember that you want to have isolated tests, even inside the same test case.</p><h4>You set the minimum expectations needed to verify a side effect in mocks.</h4><p>Expectations are useful to assert side effects in mocks, but you don’t use them to verify calls to stubs.</p><p>I mean: in a query, you could need to stub some behavior in a collaborator, the test will execute the call to that collaborator and get the stubbed response. The test will pass if the code under test manages the collaborator response the right way returning the correct response. In this situation, you don’t need to assert that the message was issued to the collaborator: it is implied in the successful test execution.</p><p>When testing a command, you will need to verify the side-effect of calling a specific collaborator, so an expectation should be set to check that this really happens, and only for that.</p><p>Ideally, you will have only one expectation by test except when you need some triangulation.</p><h3>How to create doubles</h3><p>There are several techniques to create doubles:</p><h4>Using real objects</h4><p>This technique is specially used when creating fakes, but you can use it for other types of doubles you would like to share between tests, like dummies.</p><p>It’s pretty straightforward: create and use a new implementation for the interface you need to double. The following example is a pretty simple example of a CustomerRepository implementation only for tests:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36590150b4ea5428db01ebe2360a70b1/href">https://medium.com/media/36590150b4ea5428db01ebe2360a70b1/href</a></iframe><p>To use it, we only need to do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59f18affe2e1346a8cd3a1fbb828ae79/href">https://medium.com/media/59f18affe2e1346a8cd3a1fbb828ae79/href</a></iframe><p>Let’s see an example of a spy:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37c94607a36ae3451cd97a29bcfe8bd9/href">https://medium.com/media/37c94607a36ae3451cd97a29bcfe8bd9/href</a></iframe><p>The main problem with this type of implementation is that it is not Liskov Substitution Principle compliant given we add some query methods to be able to verify the expected outcomes. This is a trade-off that we can accept because their use is limited to the test environment.</p><h4>Using anonymous classes</h4><p>Anonymous classes are a great way to create disposable doubles for a specific test without using a mocking framework and keeping the advantages of real objects. Here, you have an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b278dd8b5087c7568532a9a8c6b89f43/href">https://medium.com/media/b278dd8b5087c7568532a9a8c6b89f43/href</a></iframe><p>The previous example violates Liskov Substitution Principle, so you can be stricter:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2a5998e2fd6fd6ecab575161fb2cea5e/href">https://medium.com/media/2a5998e2fd6fd6ecab575161fb2cea5e/href</a></iframe><p>As you can see, we don’t even need to extract the class to another file, but you could use a factory if makes sense for your use case.</p><h4>Using mocking frameworks</h4><p>Mocking frameworks can be an easy way to build doubles that are expensive to double using the other techniques. For example, in PHP, the PSR Logger Interface is huge, with no less than nine methods to implement. It is way simpler to use the mocking framework like this and get a dummy double:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4d9d268422b14f20fe5f2ec8ce9d040/href">https://medium.com/media/a4d9d268422b14f20fe5f2ec8ce9d040/href</a></iframe><p>Every mocking framework has its own syntax. I will be using the native PHPUnit one in these examples, but you will get the point.</p><p>To build a stub, you only have to define a response to a method call, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/77d2b5d459060a50d546f6d85193a87e/href">https://medium.com/media/77d2b5d459060a50d546f6d85193a87e/href</a></iframe><p>This is an example of a <em>MailerService</em> mock that expects the method <em>send</em> to be called with a message.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9b6340a1ba4a794cced8fa6cf3c04ce/href">https://medium.com/media/d9b6340a1ba4a794cced8fa6cf3c04ce/href</a></iframe><p>In this snippet we have defined a mock of the <em>MailerService</em> interface, setting the expectation that we will be calling its send method once with a <em>Message</em> object.</p><p>We can create a spy, instead of a pure mock:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60c5ca74be19645a0f21fd8f8c6f241f/href">https://medium.com/media/60c5ca74be19645a0f21fd8f8c6f241f/href</a></iframe><p>In this example, you inject the <em>$mailerMock</em> as a dependency, but you check the outcomes asking to the <em>$mailerSpy</em>. It is pretty weird, but other mocking frameworks offer better interfaces for this feature.</p><p>In fact, you probably will be better served by crafting your own doubles instead of using a mocking library.</p><h3>Summing up…</h3><p>Test doubles are a tool that we will need to use sooner or later. Their purpose is to help us isolate the code under test replacing their dependencies.</p><p>We can use several techniques to create them ranging from implementing our own doubles to use a mocking library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eeacc380e049" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/test-doubles-eeacc380e049">Test doubles</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring conditionals]]></title>
            <link>https://medium.com/docplanner-tech/refactoring-conditionals-38c9e7367c82?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/38c9e7367c82</guid>
            <category><![CDATA[refactor]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[conditional]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Tue, 20 Apr 2021 07:58:15 GMT</pubDate>
            <atom:updated>2021-04-20T07:58:15.858Z</atom:updated>
            <content:encoded><![CDATA[<p>Conditionals are supposed to add intelligence to code, but they can be a nightmare to understand.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LGVAs3dCGgdUhbVdmlf_5w.png" /><figcaption>You need to decide which one</figcaption></figure><h3>Why refactor conditionals</h3><p>Our targets when refactoring conditionals are:</p><p><strong>Making it easy to understand the conditions that we are checking</strong>: conditions can be hard to understand if we check for specific values that are meaningfully related to the concept they try to evaluate. See this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa61b38c7f8401f4931cc68af118e86a/href">https://medium.com/media/fa61b38c7f8401f4931cc68af118e86a/href</a></iframe><p>The condition is fairly easy to describe in human terms: select documents that have too long names. But its code expression is really hard to understand. Let’s simplify this a bit, extracting the conditional expression to a method with a meaningful name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b66b60104e5848428d898214524aaec/href">https://medium.com/media/9b66b60104e5848428d898214524aaec/href</a></iframe><p><strong>Reduce the cognitive complexity when following the execution flow through their branches</strong>. When you read a conditional structure you need to keep track of the main flow. If you introduce conditionals inside the branch of another conditional you are creating new breaking points that need to be tracked. At a certain level, you will overflow the ability of your working memory to handle all that tracking.</p><p>You can easily spot this by looking at the indentation levels of the code. The more indented it is, the more difficult it to understand and the easier it for bugs to appear.</p><p>You can manage this with several refactors. The most simple and easy to apply is to extract code in branches to methods. That opens new refactoring opportunities inside the private methods.</p><h3>Conditions with meaning</h3><h4>You don’t always need conditions</h4><p>We use conditionals to control the execution flow of a program: go this way if a condition is met. If not, go this other. But, sometimes, we can avoid that. Let’s look at this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cba492227b42193bde96bdcce58c075/href">https://medium.com/media/5cba492227b42193bde96bdcce58c075/href</a></iframe><p>We don’t need the flow control part here, we are served with the response from the object. Also, it’s pretty confusing that you return false in the true leg of the conditional.</p><p>To be precise, we can simply return the negation of that response:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469857a594d58b6efc34998fe8f3bc11/href">https://medium.com/media/469857a594d58b6efc34998fe8f3bc11/href</a></iframe><p>This kind of refactor helps to avoid some potential points of failure. With the original code, you have to ensure no less than three things:</p><ul><li>The method invoked provides the correct value</li><li>The conditional expression evaluates to the correct value</li><li>Each leg of the conditional returns the correct value</li></ul><p>Now, you only have to check one thing:</p><ul><li>The method invoked provides the correct value</li></ul><h3>Ternary operator instead of if/then</h3><p>The ternary operator is pretty convenient under certain conditions. You should use it carefully because it can bring more problems than solutions. But it is perfect for this situation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/48d066cefd45f03a13184e578d2eae98/href">https://medium.com/media/48d066cefd45f03a13184e578d2eae98/href</a></iframe><p>When we have two possible ways of calculating a value depending on a simple condition, the ternary operator is perfectly fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ce0bd3421d573ec7a0f12e10d5cf8bc/href">https://medium.com/media/8ce0bd3421d573ec7a0f12e10d5cf8bc/href</a></iframe><p>The conditions to use the ternary operator are:</p><ul><li>We need to choose between two ways of calculating something</li><li>We don’t nest ternary operators.</li></ul><p>The benefit here is that we state clearly that we are calculating something (the <strong>$event</strong> that we want to send in some next step).</p><h4>If it’s complicated, extract a method</h4><p>The ternary operator works pretty fine in the simple situations exposed before. But if the calculation is more complex or can’t be reduced to clean construction, you’d better extract a method and hide the conditional inside of it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/25896058fc42c2d18d5a544a8abfee1b/href">https://medium.com/media/25896058fc42c2d18d5a544a8abfee1b/href</a></iframe><h4>Replace type checking with type safety</h4><p>Take a look at this code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dde4104085053b87f0ea699531b027d5/href">https://medium.com/media/dde4104085053b87f0ea699531b027d5/href</a></iframe><p>This code reveals a big <em>bad smell</em>. If you need to check for type to perform a task, then you have a design problem. Probably, you are trying to ensure that the <strong>Visit</strong> has a related <strong>Patient</strong>, so you can do something with it.</p><p><em>Does it make sense that a visit has no patient-related?</em> If not, you probably should have to fail with an exception. In fact, you should ensure that when instantiating the <strong>Visit</strong> object. Anyway, the <strong>Visit::getVisitPatient</strong> method should be typed to state that the expected outcome is a <strong>VisitPatient</strong>. By doing that, you can enclose the code block in a <strong>try/catch</strong> to manage the situation.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/172a223f9b565797bbef5afb1654e2d7/href">https://medium.com/media/172a223f9b565797bbef5afb1654e2d7/href</a></iframe><p><strong>Visit::getVisitPatient()</strong> guarantees that it only will return a <strong>VisitPatient</strong>. Otherwise, something is wrong.</p><p>If not having a <strong>VisitPatient</strong> is fine for <strong>Visit</strong>, then you should use <strong>nullable</strong> return type. This way, instead of checking for type, you will check for object existence, making code cleaner:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5f12d56ea4cf644488560b25e05c2ede/href">https://medium.com/media/5f12d56ea4cf644488560b25e05c2ede/href</a></iframe><p>You can do this because <strong>getVisitPatient</strong> guarantees that it will return a <strong>VisitPatient</strong> or a <strong>null</strong>, keeping consumers safe about the type, but having to manage the situation of empty value. So you simply need to check that <strong>$visitPatient</strong> has a value.</p><p>Also, remember that this example could reveal a violation of the <strong>Tell, don’t ask</strong> principle or <strong>Demeter’s law</strong>. It is possible that code related to <strong>VisitPatient</strong> can be happily encapsulated in <strong>Visit</strong>. You can take a look at <a href="https://medium.com/docplanner-tech/refactor-for-better-knowledge-allocation-ef83be9d44fe">this previous article on the topic</a>.</p><h4>Give combined conditions a meaning</h4><p>Sometimes combined conditions represent a concept that is not explicitly put in code. Let’s see a pretty simple example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c085272040cf5dc5729f6fde5b9205ff/href">https://medium.com/media/c085272040cf5dc5729f6fde5b9205ff/href</a></iframe><p>This line of code makes you think about what it is actually checking for. This line is in the context of an SMS notification service, so it makes sense to think about the idea of <em>a patient can be notified via SMS or not</em>. This can be achieved if both two conditions are met:</p><ul><li>The patient has a phone number (that can receive SMS)</li><li>The patient chose to allow being notified with SMS</li></ul><p>So, instead of asking about these two things to the same object, we can encapsulate both questions into only one, inside <strong>VisitPatient,</strong> because both conditions belong to the object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cbe2cd08b35f0bc1d9c67f0b8a3e8b7e/href">https://medium.com/media/cbe2cd08b35f0bc1d9c67f0b8a3e8b7e/href</a></iframe><p>If we don’t have a better place to move the combined conditions, we can simply create a private method. This is the proper way when we are using values from different origins.</p><h3>Managing the flow</h3><p>Conditionals are control flow structures and we use them to take different actions when certain requirements are met. We’ve been talking about the conditions, but now we will focus on their <em>branches</em>.</p><p>We can have different problems with the branches of conditional expressions:</p><ul><li><strong>Too large branches</strong>: too much code in the body of a branch makes it easy to lose track of the context.</li><li><strong>Unbalanced branches</strong>: one of the branches is comparatively larger than the other, making the latter <em>invisible</em>.</li><li><strong>Nested conditionals</strong>: conditions inside conditions are especially difficult to understand and are a perfect place for intricated bugs to hide.</li></ul><h4>Too large branches</h4><p>The best approach is to extract branches to their own method with a descriptive name for the abstraction level. This will make it easier to understand the overall flow, and you always be able to dig into details if needed.</p><p>Look at this code. The branch is remarkably long:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b37ffeaf7d1ccfe383876b30420f7603/href">https://medium.com/media/b37ffeaf7d1ccfe383876b30420f7603/href</a></iframe><p>We move all the code in the branch to a new method, taking care of managing how we return the data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b8cd9e81924e4864e00a14df9c87555c/href">https://medium.com/media/b8cd9e81924e4864e00a14df9c87555c/href</a></iframe><p>Now, the main flow is far easier to read. We can dive into details by jumping into the extracted method. We even have a chance to extract this code to a collaborator in the future if we need to reuse this particular piece.</p><h4>Unbalanced branches</h4><p>When one of the legs of a conditional structure is a oneliner and the other is huge, it is good practice to invert the conditional, so the shortest branch appears in the first place. This avoids missing it:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0dd2aae8d3ca0c45cc38eaa421f8404b/href">https://medium.com/media/0dd2aae8d3ca0c45cc38eaa421f8404b/href</a></iframe><p>It’s much better to extract both branches to methods with a significant name. This way you stress the fact that two flows are depending on the <strong>province</strong> variable having value or not.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/86e44425e1898a631d5566bb1b1535b3/href">https://medium.com/media/86e44425e1898a631d5566bb1b1535b3/href</a></iframe><p>You should consider eliminating the <strong>else</strong> branch. Sometimes you won’t need it. For example, because you can perform an <em>early return</em>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4eb7b067b0302fefe9261c4e76baf18c/href">https://medium.com/media/4eb7b067b0302fefe9261c4e76baf18c/href</a></iframe><h4>Nested conditionals</h4><p>Nested conditionals are a source of frustration and pain. They are difficult to follow and unsafe to modify when needed. How can we avoid them?</p><p>First of all, try to ensure that nesting is needed. In the following example, we can see that the inner conditional should be moved to another place. We can guess that by putting next, things that are related to each other. For example, the calculation of <strong>validSince</strong>.</p><p>The value of <strong>validSince</strong> can be calculated before, instead of waiting until being in the conditional. And we can introduce the <strong>null coalesce operator</strong> to simplify the assignment using the first value among all possible that it’s not null.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1abecfbad12d7c280321d1455791246c/href">https://medium.com/media/1abecfbad12d7c280321d1455791246c/href</a></iframe><p>Our first approach will be to extract the main branches into private methods. Then, you repeat this extraction iteratively so all methods have a maximum of one indentation level in each one. This opens opportunities for further refactors that are pretty difficult, or impossible, in the nested structure. In fact, part of nested structure complexities relies on the fact that you have to carefully manage the execution flow to make sure you don’t overwrite variables or introduce some other bugs.</p><p>Let’s take a look at this code extracted from the famous <a href="https://github.com/emilybache/GildedRose-Refactoring-Kata">GildedRose kata</a>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8fe0216777c1f5f0a4f405dc4502a85e/href">https://medium.com/media/8fe0216777c1f5f0a4f405dc4502a85e/href</a></iframe><p>This is only half of the code and has a lot of nesting.</p><p>For this example, we extract the legs to their methods. Note that this kata deserves an object-oriented approach, but I want to illustrate a different point this time:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b15354489a6794dc079d7f3936a11a25/href">https://medium.com/media/b15354489a6794dc079d7f3936a11a25/href</a></iframe><p>We can see that in the extracted methods the body is inside a conditional. We can apply a <em>return early</em> refactor that will reduce the nesting. We need to invert the conditional expressions first. As you can see, the readability has increased a lot.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0936eff94e310be9a075a38984ffe731/href">https://medium.com/media/0936eff94e310be9a075a38984ffe731/href</a></iframe><p>We can apply <em>return early</em> again in the <strong>increaseQuality</strong> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37742df0178def96aea269bcb8218182/href">https://medium.com/media/37742df0178def96aea269bcb8218182/href</a></iframe><p>At this point, we can spot some remaining code duplication that we could refactor. It can be argued that the nesting is there yet. Nevertheless, the takeaway here is that with pretty simple steps we have structured the code so it is much more readable and easier to understand.</p><h3>Final words</h3><p>Conditionals can be tricky to manage, but we can improve their readability a lot by using simple refactoring techniques and thinking twice about why we need them.</p><p>Of course, we could go further by applying a good object-oriented design that can even avoid the need for conditional structures. But that should be the topic for another post. In the meantime, you can watch <a href="https://www.youtube.com/watch?v=8bZh5LMaSmE">this talk by Sandi Metz about how and why to achieve this using the Gilded Rose example</a>.</p><p>Keep an eye on our blog for more tips about refactoring and testing to keep your code healthy.</p><p>Do you enjoy the article? Follow our profile and visit our other channels:<a href="https://docplanner.tech/"> Docplanner.tech website</a>, <a href="https://www.facebook.com/docplannerTech/?__tn__=%2Cd%2CP-R&amp;eid=ARCMkTULxdIBTOyout0irGzXnbLcnwj_n_n2_RY5mQGdpLjCbKM_VpAqBhN0B_FQD3ygzsJnYWK_Uf_1">Facebook</a>, <a href="https://twitter.com/DocplannerTech">Twitter</a>, and<a href="https://www.linkedin.com/showcase/26236889/admin/"> LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38c9e7367c82" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/refactoring-conditionals-38c9e7367c82">Refactoring conditionals</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactor for better knowledge allocation]]></title>
            <link>https://medium.com/docplanner-tech/refactor-for-better-knowledge-allocation-ef83be9d44fe?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef83be9d44fe</guid>
            <category><![CDATA[refactor]]></category>
            <category><![CDATA[php]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[docplannerit]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Thu, 04 Mar 2021 08:58:00 GMT</pubDate>
            <atom:updated>2021-03-04T08:58:00.447Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the ongoing problems inside all organizations is documentation. From an agile perspective, code can document a good part of the knowledge about the business when written in an expressive, well organized, fashion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bmxDE8w69sXb0G43Kf8fYw.png" /><figcaption>Where does this knowledge belong to?</figcaption></figure><p>But this frequently does not happen due to several reasons. Poor communication, too much emphasis in implementation details, <em>framework driven development</em>, among others. So, many code bases present problems when you try to understand how they express the domain of the business.</p><p>In our previous post we talked about some tips to refactor code to be a better storyteller. This time we will continue digging into the same idea, but from a slightly different point of view: how to better structure the knowledge.</p><p>Knowledge means a lot of things. In every software project there are both business knowledge (how to book a visit with a doctor, for example), but also technical knowledge (how to connect to some database server). The problems arise when different domains of knowledge appear mixed in code. It can be technical concerns entangled with business concerns, different areas of the business sharing pieces of code or huge levels of coupling between different parts of the code.</p><h3>Object-Oriented Software… or not so much</h3><p>There are lots of code bases in the wild written in object oriented languages, using classes and objects, that doesn’t really apply well the OO paradigm. They consist of procedural code with an object-oriented costume. In this code bases, knowledge is something global and objects are usually only containers for data, behavior or both, but they are not really self-consistent, well encapsulated objects.</p><p>In the OO paradigm, objects are experts that encapsulate knowledge and behavior, communicating and cooperating to fulfill the tasks.</p><blockquote>The most difficult problem in teaching object- oriented programming is getting the learner to give up the global knowledge of control that is possible with procedural programs, and rely on the local knowledge of objects to accomplish their tasks. Novice designs are littered with regressions to global thinking: gratuitous global variables, unnecessary pointers, and inappropriate reliance on the implementation of other objects. (<a href="http://c2.com/doc/oopsla89/paper.html">Beck &amp; Cunningham: A Laboratory For Teaching Object-oriented Thinking</a>)</blockquote><p>Object-oriented design is guided by a plethora of principles that serve as guidelines to make decisions about how to allocate knowledge and how objects should interact. We can benefit from applying this principles to improve the quality of our code, moving from a procedural style to a more object-oriented one.</p><p>So, in this post we will review some of these principles and we will try to show them in action.</p><h3>Separation of concerns principle</h3><p>This is pretty simple, and the basement for most architectural and code organization decisions: different parts of the code addresses different concerns.</p><p>We can understand this principle from another perspective: a unit of code should not address more than one concern. If so, it needs to be broken into parts. We can apply this to different levels: the methods in a class, the different class in a software module, the different modules in a software application, or the different layers.</p><p>This basic principle, enunciated by Dijsktra, is in the roots of the well know <em>Single Responsibility Principle</em>, the <em>S</em> in SOLID, and most of the patterns and principles that help us to put knowledge where it belongs.</p><p><strong>Single Responsibility Principle</strong> states that software units should have one unique responsibility, defined as a unique reason to change. It doesn’t mean to do only one thing, that could lead us to a convoluted design. Instead of that, this principle is better applied if we consider the reasons that could force us to change that unit. Let’s see an example.</p><p>Price is a common concept for most business. It could be modelled initially with this class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e3472f9ff5b386f46f9a10a7577c5832/href">https://medium.com/media/e3472f9ff5b386f46f9a10a7577c5832/href</a></iframe><p>Pretty anemic, huh? But it is a starting point. Now, the Finance team asks for a way to add VAT to the price. We honor immutability and add a factory method that returns the price with added VAT. Well done!</p><p>Also, the Front-End crew asks for a price representation that includes the currency information. We add a simple format method to the class.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/363b9a7ef0731b2d5f1e2644736c39eb/href">https://medium.com/media/363b9a7ef0731b2d5f1e2644736c39eb/href</a></iframe><p>Hey! Different currencies requires different representation formats. Also, our beloved Marketing team asks for a feature to add discounts and promotions to our Price objects. Wait a moment! This poor little class has a lot of reasons to change. We are asking it to hold a lot of responsibilities.</p><p>We need a change to address that.</p><p>First, Price should be only responsible for holding information about… price. We can model Taxes and Discounts as Price decorators, so we always will be able to recover the base price. Here is an example. It’s not perfect, but now we have separated some of the responsibilities.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9213a48b3459363d7e7c2452517f49a7/href">https://medium.com/media/9213a48b3459363d7e7c2452517f49a7/href</a></iframe><p>The method addVat in Price will become unnecessary but if it is being used we can remove it iteratively.</p><p>So, do you need a discount? No problem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba0b564cc02ce57d42075a6182957a54/href">https://medium.com/media/ba0b564cc02ce57d42075a6182957a54/href</a></iframe><p>Now, you can use it like in the following test. Price is now a compounded object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e24a6fdf6371d2e67e6e6f5cffd18e/href">https://medium.com/media/22e24a6fdf6371d2e67e6e6f5cffd18e/href</a></iframe><p>Now, if the Finance team asks us to apply another Tax to our price, or one different because we need prices for several countries with different laws, we only need to add classes accordingly without touching Price itself.</p><p>Also, if Marketing asks us to apply new discounts and promotions, we only need to add classes for each one.</p><p>All of those new classes may change for one unique reason, so we are honoring the Single Responsibility Principle… at least in this area. Remember that we need to address the format concern. But we can apply a similar solution.</p><p>Oh, and another benefit is that by doing this approach, we also are honoring the <em>Open for extension, closed for modification principle</em>. This principle states that we should avoid to modify existing code in order to add or modify behavior. Instead, we should provide means to extend object behavior without touching that existing code.</p><p>Let’s return to the format problem. It exposes an interesting problem that requires us to talk about segregating interfaces.</p><h3>Interface Segregation Principle</h3><p>If you look at our Decorators you can see that they have to carry the <strong>format</strong> method, and they really don’t need it. Price and their Decorators are having two reasons for change: one related to their business meaning, and one related to their presentation. Also, you have to duplicate it in every type you need to create, multiplying the problems with the format variations.</p><p>When working with legacy objects, it is very easy to find classes that hold too many responsibilities and had huge public interfaces with lots of methods serving different kinds of consumers.</p><p>The <em>Interface Segregation Principle</em>, states that an object should not depend on methods that it will not use. We should design narrower interfaces based on the needs of its consumers.</p><p>In our example, PriceInterface has methods that obey to different kinds of consumers: one is interested in the amount concerns, and one is interested in the presentation concerns. So, we should separate those concerns in different interfaces.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0092636ddee7c1bf4514c12b77e47be5/href">https://medium.com/media/0092636ddee7c1bf4514c12b77e47be5/href</a></iframe><p>Now, the old Price class implements two interfaces, but our decorators only implement one of them: the one that relates with amount modifications. They are free about presentation concerns.</p><p>We can solve these concerns with another family of decorators using the PriceFormatterInterface:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c444597de299a04aebad7fcb7a4b7172/href">https://medium.com/media/c444597de299a04aebad7fcb7a4b7172/href</a></iframe><p>Now, you can compose them:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dea7ee367e7cc380e40135cdd27a1368/href">https://medium.com/media/dea7ee367e7cc380e40135cdd27a1368/href</a></iframe><p>It looks nice. And it is because we now have separated responsibilities in different classes, with pretty narrow interfaces.</p><p>An extra benefit is that we removed some duplication. Let’s talk about being DRY.</p><h3>The DRY principle</h3><p>The Don’t Repeat Yourself principle, by Hunt and Thomas, states that “Every piece of knowledge must have a single, unambiguous, authoritative representation within a system”.</p><p>The principle doesn’t refer to code duplication, it talks about knowledge duplication. This is an important distinction, because trying to apply DRY to any code duplication can lead us to tough problems. Sandi Metz has a post that worth the reading: <a href="https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction">The wrong abstraction</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tlFFL3_QlZOd1f9P7EM7Rw.png" /><figcaption>Can you spot the abstraction here?</figcaption></figure><p>Anyway, code duplication can be a symptom of knowledge duplication, it could mean that there is an interesting concept emerging. But you should consider this carefully. Code duplication can:</p><ul><li><em>Be unavoidable</em>: three or more fragments of code look similar, but they don’t represent the same knowledge.</li><li><em>Be unnecessary</em>: three or more fragments of code can be reconciled extracting the parts that are different for economy. For example, blocks of code that can be extracted to one method or function.</li><li><em>Represent knowledge duplication</em>: three or more fragments of code are examples of a more general concept or abstraction.</li></ul><p>Have you notice the <em>three</em>? There is an heuristic called <em>The Rule of Three</em> that advises to not refactor duplication unless you have three or more occurrences of the same code. It is a simple rule to prevent <em>premature abstraction</em> if we don’t have enough information to decide what kind of duplication we are spotting.</p><p>But, is there a similar rule to find knowledge duplication that we should refactor? Yes. If you need to make the very same change in several parts of the code at once, in order to introduce or modify a behavior, then you have a candidate.</p><p>I will try to show you some examples of when to apply DRY and when don’t with our Price Decorators family.</p><p>Does it make sense that both decorators share a common ancestor in order to avoid duplications? No, it doesn’t. Taxes and Discounts are two different concepts, two different pieces of knowledge with their own business rules and they are also managed by different teams in the company. Instead, we could model Taxes and Discounts as different abstractions.</p><h3>The tell, don’t ask principle</h3><p>The basic idea is that if you are getting information from an object to operate with it, you should encapsulate the whole operation in that object because it is where it belongs. Instead of asking the object about the data needed for the calculation, it is better to tell the object to calculate that itself.</p><p>In a more formal definition: if you need to ask an object about its state in order to change the state itself, you are violating both the information hiding and encapsulation principles. Then, you should encapsulate the operation in a method.</p><p>This principle is very useful to start moving knowledge to the objects to which belongs. Objects should be information experts about themselves. Also, objects are the solely responsibles about its state and consistency. You should be able to trust your objects in that concern. This will make your life easier.</p><p>Let’s see an example. Imagine you have a concept TimeSlot to allocate, ahem…, time slots in a Calendar application. If you want to know if two slots overlap you could do this <em>beauty</em>:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8afd6252798748d6d0015b0e28dfb0c1/href">https://medium.com/media/8afd6252798748d6d0015b0e28dfb0c1/href</a></iframe><p>You are asking time slots about data to perform a calculation in order to guess something about the state of both slots, among other code quality violations. But this is a knowledge that belongs to the TimeSlot object itself: to know if it overlaps with another TimeSlot:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/368ba2fd02689c10e34c7027c189a1e2/href">https://medium.com/media/368ba2fd02689c10e34c7027c189a1e2/href</a></iframe><p>So you can tell a TimeSlot to calculate if another one is overlapping or not, because it has all the knowledge about itself.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12b7efe58e12b8b5fcfd0c6ae6b81c9c/href">https://medium.com/media/12b7efe58e12b8b5fcfd0c6ae6b81c9c/href</a></iframe><h4>Anemic object smell</h4><p>This principle is related with the <em>anemic object smell</em>. An anemic object, or more specifically an <em>anemic model</em>, is an object that has only state, but no behavior. There are several objects that are designed to only contain data, for example Data Transfer Objects, but we are referring here to objects that model entities or values that should also have domain behavior.</p><p>In our example, the first implementation of TimeSlot was an anemic object. It only had properties and accessors to those properties.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0f4a693f28f3d33b047ecc3b364b42a7/href">https://medium.com/media/0f4a693f28f3d33b047ecc3b364b42a7/href</a></iframe><p>As we have shown above, TimeSlot can, and must, encapsulate its own knowledge in the form of properties and behavior. Rich objects also can attract more behavior needed by the application. Imagine that you need a way to get a new TimeSlot just exactly after a given one. Here is the dirty way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63e7863cdc6321ed6b0c744ba4f7dc42/href">https://medium.com/media/63e7863cdc6321ed6b0c744ba4f7dc42/href</a></iframe><p>But, TimeSlot could be able to create them for us:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/469a031b6e3b81bffd3909420ef414f5/href">https://medium.com/media/469a031b6e3b81bffd3909420ef414f5/href</a></iframe><p>Because it knows how:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/67bd661b91c922b619c03a913fae07be/href">https://medium.com/media/67bd661b91c922b619c03a913fae07be/href</a></iframe><p>This way, you know that if you need to learn about time slots, your first stop should be the TimeSlot class.</p><h3>The minimum knowledge principle or Demeter’s law</h3><p>This principle states that a unit of software, usually a function or method, should not talk with objects that they don’t know directly. What objects are those?</p><ul><li>Objects instantiated inside the unit.</li><li>Object passed to the unit as parameters.</li><li>The object that owns the unit (its methods and attributes)</li></ul><p>The application of this principle helps a lot to avoid coupling. Coupling is the degree of dependency between software units. Some level of coupling is unavoidable but you can keep it under control. The secret for a healthy coupling is that objects know the minimum about other objects.</p><p>An object should not rely in having intimate knowledge about the internal structure of another. For example, an object should not perform calls on an object inside another one. This is a smell called <em>inappropriate intimacy</em>.</p><p>You should talk with an object using only its public interface. If you really need to access to some property or internal, you should consider to add a method that exposes it. But also, you should ask yourself if that knowledge should be available in another object.</p><p>Consider this piece of code. We have a PricingCalculator that allows us to calculate product pricing applying different rules. This is a new way to model some of the behaviors of our previous examples.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae199ee27cc1a92622cbdc11f2037381/href">https://medium.com/media/ae199ee27cc1a92622cbdc11f2037381/href</a></iframe><p>As you can see, base price of Product is defined in its product Family. Let’s see what happen inside the calculator:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/269f6ad289ef81bd2f716da5ab3f2ea0/href">https://medium.com/media/269f6ad289ef81bd2f716da5ab3f2ea0/href</a></iframe><p>This works, but PricingCalculator has to know that, in order to get the product price, it has to ask first for the Family and then for the price. Now, that’s tight coupling: PricingCalculator must know intimate details of the internal structure of Product. Nevertheless, It shouldn’t need to know how the price is built or where it come from. It only should know that Product has a price.</p><p>In the future, if you change Product to have its price defined in a different way, the program could break. For example, imagine that Family is no longer responsible of the Product price:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cf2e23e8e7e880fedaa3da595541a11/href">https://medium.com/media/6cf2e23e8e7e880fedaa3da595541a11/href</a></iframe><p>If we don’t change PricingCalculator, the program will fail, because it expects to find the price in the Family object. It depends on talking with an object of which it doesn’t know about.</p><p>In this case, Product should be the source of truth about its price:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5a20f695a977174ea87e616ad3707959/href">https://medium.com/media/5a20f695a977174ea87e616ad3707959/href</a></iframe><p>Now, PricingCalculator only depends on Price, a known object because it is passed as a parameter in the method forProduct.</p><p>In this case, applying Demeter’s Law helps us to decouple and to make our code more resilient to changes, allowing objects to change its internals without affecting others unnecessarily. So, every time you find those chained calls for access objects contained in another object, take a time to encapsulate that logic or event consider if that knowledge belongs to another place.</p><h3>More refactoring tips coming</h3><p>We expect that with this post you have some food for thought about how to allocate knowledge and behavior in your code.</p><p>Object-oriented design principles are a very good guide to help us to move and organize concepts in our codebase, allowing for a better modelling of the domain knowledge. We didn’t address all of them, of course. The lesson here is to take them into consideration when refactoring.</p><p>There are a lot of things about refactoring, so stay tuned to learn about managing complex and nested conditionals and more ways to improve the health of your code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef83be9d44fe" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/refactor-for-better-knowledge-allocation-ef83be9d44fe">Refactor for better knowledge allocation</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactor for better comprehension]]></title>
            <link>https://medium.com/docplanner-tech/refactor-for-better-comprehension-4f55e1a8be3b?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/4f55e1a8be3b</guid>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[software-architecture]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[docplannerit]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Wed, 10 Feb 2021 10:21:07 GMT</pubDate>
            <atom:updated>2021-02-10T11:00:56.919Z</atom:updated>
            <content:encoded><![CDATA[<p>You are in front of a long-lived codebase and you understand… Well, not so much.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SaGipdnWbcQkM9iMhUDMUA.jpeg" /><figcaption>Reading and understanding code can be hard</figcaption></figure><p>You want the code to tell you its story in order to add your own part to it. Nevertheless, you may find a code base, or some piece of it, that is a little pandemonium, where you cannot obtain too much information easily. You need to interpret how some concepts are represented and how some processes are reflected. Maybe, you try to read the documentation, but it can be outdated, redundant, useless, or non-existent.</p><p>You need to refactor for better comprehension before your start implementing a new feature or fixing that bug.</p><p><strong>Refactor for comprehension</strong> is the process we perform to evolve present code structure to another one that is more understandable. One that reflects better the state of business knowledge and one that is easier to operate with.</p><p>In fact, we should consider code as an executable representation of the business or domain knowledge. Tests, on the other hand, are another representation of the same knowledge, built around the outcomes of the production code.</p><p>When we need to work with a messy piece of code, we surely will need to introduce some changes that should improve our ability to understand what’s going on. We have three areas in which to intervene:</p><ul><li>Production code itself</li><li>Test covering that production code</li><li>Comments and documentation</li></ul><p>Before we start talking about how to make code easier to understand, we should first learn about the “two hats metaphor”.</p><h3>Two hats to rule them all</h3><p>The two hats metaphor by Kent Beck helps us to understand something very important about refactoring.</p><p>The basic idea is that you must not mix refactoring with changing the behavior of a piece of code.</p><p>So, you work on preparatory refactoring crafting structural changes wearing the <em>refactor hat</em>. Then, you commit that set of modifications as a whole. Once committed, you work in the behavioral change and commit it wearing the <em>change behavior hat</em>. After that, you may need to put on the <em>refactor hat</em> again to tidy up things.</p><p>Beck says that the preparatory refactoring consists on reorganizing code to make the change of behavior easy and safe to apply:</p><h3></h3><p>for each desired change, make the change easy (warning: this may be hard), then make the easy change</p><p>You can’t wear two hats at the same time… Well, you shouldn’t. So, we ask you to put the <em>refactor hat</em> right now because we are going to introduce some nice ideas about how to improve the storytelling abilities of the code.</p><h3>Refactor for better names</h3><p>The first tool to make code explain itself is to choose names wisely.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TDxIgKPJ7lUonP6Qad8YCA.jpeg" /><figcaption>Naming things is also a teamwork</figcaption></figure><p>Naming is reputed as one of the most difficult things in computer science, along with invalidating the cache, but you don’t have the obligation to spot on the first try. You can rename things for very good reasons, among others:</p><ul><li>A concept that is represented in code with a name that doesn’t describe it accurately from the start.</li><li>A concept that could have evolved and its name became obsolete.</li><li>A name that could be too general or too narrow for the concept that it describes.</li></ul><p>We can apply a <em>rename refactor</em> in these situations. Let’s see some examples.</p><h4>Name coupled to implementation</h4><p>Consider this variable name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4241c3cddf9cc64d8532804b79390d1b/href">https://medium.com/media/4241c3cddf9cc64d8532804b79390d1b/href</a></iframe><p>Leaving aside other questions about the code, what is the problem with this name? As we can see, the name mentions the current specific time limits decided by the business.</p><p>So, if those limits change someday, we could end with something like the first line of the following example, so we should change the variable name in order to keep it consistent with business requirements.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/499a10a08e5ee4f531b3c73e0310c14d/href">https://medium.com/media/499a10a08e5ee4f531b3c73e0310c14d/href</a></iframe><p>We will need to do the same every time those limits are changed. Nevertheless, it’s easy to forgot updating the name at some point, and that will cause some moments of anxiety to the future developer.</p><p>We can see that a more abstract concept is arising: the idea that there is a period of time (<em>overnight</em>) that requires a special treatment and that is defined by certain time limits. Probably, when talking about this feature with the business people or users, someone asked something similar to “What if the appointment is cancelled <em>overnight</em>?“. As programmers we need to define that with some kind of temporal marks, but the concept itself isn’t tied to a precise hour range.</p><p>We could express it this way:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/282f4f072fab4642ab4d2478d8868b5b/href">https://medium.com/media/282f4f072fab4642ab4d2478d8868b5b/href</a></iframe><p>Now, we have a more expressive name that doesn’t depend on implementation details. The concept <em>overnight</em> is an abstraction easier to understand than an arbitrary time interval, so its name doesn’t need to change frequently.</p><p>This very same idea can be applied to function and method names.</p><h4>How to rename things</h4><p>You can use the tools provided by your IDE, taking into account some safety measures.</p><p>You will have no problems when:</p><ul><li>changing a variable name inside a method or function.</li><li>changing a private method name inside a class.</li></ul><p>Most IDEs offer the rename refactor. At the end, it’s a <em>find and replace</em>, but IDEs can work at the syntax tree level, so it is usually more precise than us to complete this refactor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/287/1*LyvJuw3q8fdk3rQflsrS9g.png" /><figcaption>The refactor menu in PHPStorm</figcaption></figure><p>For example, in the JetBrains IDEs you select the variable or function you want to rename, select Refactor, then Rename (caps-F6), type the new name, and you’re done.</p><p>If you change a public function name, you may find that there are a lot of places affected, so we will use a more conservative approach.</p><p>Let’s see an example: Imagine that you have this method in a class that you want to rename because its current naming doesn’t help too much. Sure, it’s funny, but a bit misleading. Nevertheless, the method is called in a lot of places, so a bulk rename involves risks:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2493fd8cdee0e00f74e00f24cfb0ae19/href">https://medium.com/media/2493fd8cdee0e00f74e00f24cfb0ae19/href</a></iframe><p>First of all, <strong>duplicate the function and rename the copy</strong>. All calls to the original name are preserved and now you have a method with the better name that has the very same behavior.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d804eee90257d0f69eae216aa5f6ad/href">https://medium.com/media/83d804eee90257d0f69eae216aa5f6ad/href</a></iframe><p>Now, delete the body of the old function and write a call to the new one instead. This way, you avoid the code duplication without hurting existing uses of the old name.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/07ba5184b3597f24edfb395d9be6a143/href">https://medium.com/media/07ba5184b3597f24edfb395d9be6a143/href</a></iframe><p>Progressively, change the calls to the old method to the new one every time you find them and has something to do with your current task.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8443f715570cefbb3ea71fd4790065fd/href">https://medium.com/media/8443f715570cefbb3ea71fd4790065fd/href</a></iframe><p>When there are no calls to the old method remaining, delete it.</p><p>Alternatively, you can use <em>extract method </em>refactor provided by the IDE selecting the body of the method you want to rename and extracting it with the new name.</p><h4>Where the things had no name</h4><p>There is a well-known code smell called <em>magic numbers</em>. It refers to primitive values that are present in the code but you don’t have any clue about what they mean.</p><p>In the same line we have used in the previous example about the overnight period. the limits of this period are represented by numbers.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/282f4f072fab4642ab4d2478d8868b5b/href">https://medium.com/media/282f4f072fab4642ab4d2478d8868b5b/href</a></iframe><p>Those numbers were decided by business people. From the code point of view they are arbitrary values, and with the passing of time, their meaning can be forgotten. So, it is a good idea to give them names.</p><p>The simplest way to do that is to convert these values into constants with a name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dcec546fafa4d40fd0cff7f19317560d/href">https://medium.com/media/dcec546fafa4d40fd0cff7f19317560d/href</a></iframe><p>There are other potential improvements for this line, but we will leave them for future articles about refactoring for better design.</p><p>This refactor can be applied to any arbitrary value you could find in a code fragment and needs explanation. But there are some more advantages:</p><ul><li>If those values change you don’t need to touch the code that uses them, lowering the chances to break something by accident.</li><li>If they are used in several places, you will have only one point to change them, guaranteeing consistency.</li></ul><h4>Break expressions into meaningful parts</h4><p>Complex expressions should be broken into parts in order to improve readability, but also to avoid potential errors. Tangled expressions with a lot of elements are a good place for bugs to hide, specially when we need to modify them.</p><p>We can use the <em>extract variabl</em>e refactor, that consists of replacing part of a expression with a variable. A good rule of thumb is to apply this refactor to parts wrapped in brackets. Let’s see a typical example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a35aa3a3f1fda98bf6d83b1dbebac539/href">https://medium.com/media/a35aa3a3f1fda98bf6d83b1dbebac539/href</a></iframe><p>Ok. This looks like a very simple expression, but it should help us to understand the intent of the refactor and how to proceed.</p><p>The <strong>$this-&gt;amount * vat </strong>subexpression represents the concept of <em>tax or VAT amount</em>. That concept could be expressed in a variable:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/65de4fb3d205b587b2ccf025d90f0dcc/href">https://medium.com/media/65de4fb3d205b587b2ccf025d90f0dcc/href</a></iframe><p>Now, the expression is easier to read. Imagine the same applied to more complex calculations.</p><p>Sometimes, these kind of extractions reveal the need for a behavior, even for a public one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/581d4b928ef00ede9995513cdaf7e5c7/href">https://medium.com/media/581d4b928ef00ede9995513cdaf7e5c7/href</a></iframe><p><em>Extract variable</em> helps us abstracting concepts inside the scope of a method or function. <em>Extract method</em>, instead, is useful when we identify public or reusable behaviors.</p><h4>Explain conditional expressions</h4><p>Every conditional expression that is a combination of two or more single conditions is a good candidate to be encapsulated in a method with a name that provides a meaning.</p><p>Imagine that we have a pricing schema that allow us to offer different prices to different age ranges.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9b15f6a8840d63092395e8267bfee49c/href">https://medium.com/media/9b15f6a8840d63092395e8267bfee49c/href</a></iframe><p>The conditions in this method apply the price for each age range. Let’s take a look at line 12. This condition expresses an age interval for adults. We could extract this to a method that explicitly states that idea:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c78e547dddb0e7e74cd7d0f67fedfa64/href">https://medium.com/media/c78e547dddb0e7e74cd7d0f67fedfa64/href</a></iframe><p>Even single conditions could need to be extracted if they are not expressive enough or easy to understand. We can do the same for line 17:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8666e45ef5ca7f990617a25f2965053a/href">https://medium.com/media/8666e45ef5ca7f990617a25f2965053a/href</a></iframe><p>This is especially true when the condition is negated, because this kind of expression is more difficult to process when reading.</p><p>Not to mention <em>negated negations</em>. In that case, introduce a new method in the class being tested or a function that doesn’t need to be negated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ced8acaae317c59df8fae24eb59bb12c/href">https://medium.com/media/ced8acaae317c59df8fae24eb59bb12c/href</a></iframe><p>Introducing new methods is pretty cheap because they are not used in any other part of the code and you are not removing existing code. You can introduce progressively the use of the new code.</p><p>By the way, we want to mention that this kind of boolean properties are usually best represented by positive names that are easy to process even when they are being negated. Nevertheless, you should pay attention to the business value of that property in order to choose the best name.</p><p>We will back to conditional expressions in future articles about moving knowledge to the right place.</p><h4>Refactor to guard clause</h4><p>Conditionals can be tricky. And sometimes, in subtle ways. Take a look at this code, for example. It works perfectly, but can you spot the problem?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/47298a7f2df6dd62f78c1d056eee2895/href">https://medium.com/media/47298a7f2df6dd62f78c1d056eee2895/href</a></iframe><p>The problem is that the main responsibility of this method is under a condition. That makes the method name and body contradict each other in a way.</p><p>As a general rule is better to check requisites first and <em>fail fast</em> if they are not met. Or, as in this example, to <em>return early</em> doing nothing.</p><p>This kind of conditional is called a <em>guard clause</em> and its purpose is to avoid invalid data to reach the main processing. Guard clauses are used to ensure preconditions are met before proceed with the job in that method. We can use assertions or throw an exception if we prefer to fail.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f83ab9249b2c5c5d1c0f9a5e7b3981e1/href">https://medium.com/media/f83ab9249b2c5c5d1c0f9a5e7b3981e1/href</a></iframe><h4>Attack on the block</h4><p>Not only magic values need names. A lot of parts of the code will benefit from having good intent revealing names.</p><p>In general, every cohesive code block could be extracted to a private method, giving it an expressive name. Let’s return to the <em>extract method</em> refactor in a future post about long methods and classes, so we will pay attention for now to some refactor opportunities in which <em>extract method</em> contributes to better understability.</p><p><strong>Body of loops</strong>. It is a good practice to separate iterations from actions in loops. To do this, extract the body of the loop to its own method. You can see an example here:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ba9c7c1d2e20dacc33edb7ccbba363fb/href">https://medium.com/media/ba9c7c1d2e20dacc33edb7ccbba363fb/href</a></iframe><p>Of course, in this example you could go functional, but take into account that this approach could be way more difficult to understand at first sight:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca4915b56a3458c82f17bd9066453d43/href">https://medium.com/media/ca4915b56a3458c82f17bd9066453d43/href</a></iframe><p><strong>Conditional legs.</strong> This extraction can also be applied to the legs of conditionals, making them easier to understand at a higher level. You simply has to extract legs to private methods. Let’s consider this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f8ab0d341f0ad9ccd3570da522c624a2/href">https://medium.com/media/f8ab0d341f0ad9ccd3570da522c624a2/href</a></iframe><p>We can extract the body of the true branch to its own method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a1f92b97c7195f4078597276a06602b4/href">https://medium.com/media/a1f92b97c7195f4078597276a06602b4/href</a></iframe><p>Now, we are hiding the details in the extracted method and can scan the conditional structure faster, digging deeper if we need.</p><p>This also paves the way for applying further refactors. If you look at the code you will see that this part is pretty strange and it will need more work to get a better organization.</p><p>Extracting the branches of conditionals to methods reduces the indentation level and makes it easier to tidy things.</p><h3>To be continued…</h3><p>In this post your have seen some techniques that can help your code to be a better storyteller, for you and for future developers.</p><p>In new posts we will talk about other areas of improvement. For example, how to deal with long classes and methods. Those long code blocks usually mix responsibilities and are difficult to manage and test.</p><p>Also, we will address the problem of moving knowledge and responsibilities to their proper places, applying some well known design principles.</p><p>Keep an eye on our blog for this series and other interesting posts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4f55e1a8be3b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/refactor-for-better-comprehension-4f55e1a8be3b">Refactor for better comprehension</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping code healthy with refactoring]]></title>
            <link>https://medium.com/docplanner-tech/keeping-code-healthy-with-refactoring-2b1b4f0c9d73?source=rss-9522b5ff0d06------2</link>
            <guid isPermaLink="false">https://medium.com/p/2b1b4f0c9d73</guid>
            <category><![CDATA[code]]></category>
            <category><![CDATA[docplannerit]]></category>
            <category><![CDATA[it]]></category>
            <category><![CDATA[refactoring]]></category>
            <dc:creator><![CDATA[Fran Iglesias]]></dc:creator>
            <pubDate>Wed, 13 Jan 2021 13:13:58 GMT</pubDate>
            <atom:updated>2021-01-20T11:47:58.283Z</atom:updated>
            <content:encoded><![CDATA[<p>Making the healthcare experience more human is our motto here at DocPlanner. To achieve this as developers, we contribute implementing useful features for doctors and patients, but we are also in charge of the health of our own code.</p><figure><img alt="A really messed up code fragment" src="https://cdn-images-1.medium.com/max/1024/0*I_8AqrkTAz7K7qAy" /><figcaption>Photo by <a href="https://unsplash.com/@markusspiske?utm_source=medium&amp;utm_medium=referral">Markus Spiske</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>In this first article we would like to talk about our main tool to keep code healthy, clean, and in good shape to meet business expectations: refactoring. So, yes, this is an introductory piece for a series about what we like to call <em>everyday refactoring.</em></p><p>Code health is somewhat similar to the health of you and me: you need to take care every day, developing good habits and avoiding obvious risks. If those habits fail to be kept, software entropy starts to grow.</p><p><em>Software entropy</em> is a term coined by <a href="https://en.wikipedia.org/wiki/Ivar_Jacobson">Ivar Jacobson</a> and refers to a measure of the disorder of a software system. Software entropy increases every time a developer adds or modifies features on top of the existing ones. In large, monolithic applications, this can lead to a situation in which code can become a big ball of mud, where all things are tightly coupled in all sorts of unexpected and magical ways. Messy code is difficult to maintain and is harder and harder to add new features at the pace desired by the business.</p><p>This happens due to several reasons. We would like to stress two of them:</p><ul><li>Code is not ready to be extended with ease, so we eventually end up with tangled and confusing code each time we add or modify an existing feature.</li><li>We don’t perform a continuous tidying and fixing of those problems, before and after working in our features.</li></ul><p>This continuous code tidying is what we refer to <em>Everyday </em>r<em>efactoring</em>.</p><h3>What is refactoring</h3><p>Refactoring is both the action, and the effect, of applying limited and focused changes to code without altering its behavior, yet improving its structure, making it more readable, expressive and sustainable in the long term. You should use tests to guarantee that refactoring doesn’t break anything in the software, but you also can pretty safely rely on some provable or safe refactors specially if they are performed with the help of automated tools.</p><figure><img alt="Hen developer reading Refactoring by Martin Fowler" src="https://cdn-images-1.medium.com/max/1024/1*4-XV2XV_JPvswsFR4l2qyw.jpeg" /><figcaption>Learning from those who know</figcaption></figure><p>Refactoring opposes to the idea of redesign or rewriting. Rewriting happens when we act on large chunks of code, even entire modules, in order to modify its design. This, of course, is considerably more risky, because we will have to change tests and a lot of files. Not only can be unsafe, but it is also problematic from the business perspective because we could end up breaking or stopping new features.</p><h3>Why refactoring</h3><p>The goal of refactoring is to improve the way that code reflects domain knowledge in a progressive way. The better the code expresses the domain, the easier it is to add new features or improve the existing ones. So, the main reason to refactor continuously is economics.</p><figure><img alt="Hen developer thinking how to refactor a messy codebase" src="https://cdn-images-1.medium.com/max/1024/1*gJ6Tf53Ib0BoYBLydXPnaw.jpeg" /><figcaption>Let’s refactor this mess</figcaption></figure><p>For example, imagine that you are surfing a certain file in a project, looking for the best place to introduce a change. In the process you could find some variable that represents a concept in the domain, but it is using a poorly crafted name that is imprecise or even misleading, and you don’t understand what it is doing there. After several minutes reading and thinking, you came up with the meaning of that variable and its role in the code.</p><p>If you do nothing, another developer, that could be your future self, will need to spend a good amount of time trying to decipher that line again. Nevertheless, if you change its name for another one that expresses the intent with more clarity, that future developer will have a better experience with that part of the code, and they will be in a better position to act on it.</p><p>This kind of refactoring is an application of the <strong>Camp Rule</strong>, which says that you should leave the code in a better situation than you found it.</p><p>When all developers in the team do this, code will evolve to better standard of quality at a faster and more sustainable pace. Also, most relevant parts of the code will receive more care, especially the more business critical parts of the codebase. Those parts that are less central for the business will receive less caring. You can find more about this approach in the outstanding book <a href="https://pragprog.com/titles/rjnsd/the-nature-of-software-development/"><em>The nature of software development</em></a>, by Ron Jeffreys.</p><p>We need to keep an eye on two general goals:</p><ul><li><strong>Reduce coupling</strong>. When refactoring one of our objectives is to help loosing coupling. So, a first step will be to isolate dependencies, minimize calls to them, and in the mid to long term, invert them and inject.</li><li><strong>Increase cohesion</strong>. This means keep together the things that belong together and separate the things that do not. In other words, make units of software to handle only one responsibility and break complex units into smaller units.</li></ul><h3>When to refactor</h3><p>To identify what parts of the code need refactor we can learn to discover <em>code smells</em>. Code smells are certain patterns in the software that make it difficult to understand or to modify. You can find catalogs of smells and how to identify them in places like <a href="https://refactoring.guru/refactoring/smells">Refactoring Guru</a> or in the canonical book <a href="https://martinfowler.com/articles/refactoring-2nd-ed.html">Refactoring, by Martin Fowler</a>.</p><figure><img alt="Hen developer surfing refactoring guru" src="https://cdn-images-1.medium.com/max/1024/1*7FLtrkxL6ubxqxJSAgIHKQ.jpeg" /><figcaption>Surfing refactoring.guru</figcaption></figure><p>In general, you can identify refactoring opportunities in every place of the code where you feel that some idea is badly expressed. As a rule of thumb: if you need to read some block of code several times in order to understand what’s going on, you have found a refactoring candidate.</p><p>Being more systematic, there are four main moments for refactoring, <a href="https://www.youtube.com/watch?v=vqEg37e4Mkw">according to Martin Fowler</a>:</p><ul><li><strong>Litter-picking</strong>: we refactor when we see the need to clean or reduce litter in some piece of code: bad naming, unnecessary nested conditionals, complex expressions, liar comments, etc.</li><li><strong>Comprehension</strong>: we refactor to gain understanding of a piece of code. We could change code or could only add comments, to document the new knowledge for a future time when we have a better opportunity to make changes. That’s what Eric Evans calls <em>refactor for insight</em>.</li><li><strong>Preparatory</strong>: when we refactor before we start working in a feature, in order to ease its development, or to improve its extensibility.</li><li><strong>Planned refactoring</strong>: this matches with the idea of redesigning, so it should be avoided unless we have a real need for it.</li></ul><h3>How to refactor</h3><p>The ideal situation is having tests that verify the behavior of the piece of code we want to refactor. This way, we can be safe that the structure changes what we want to apply are neutral to that behavior and can be happily merged and deployed to production.</p><figure><img alt="Hen developer with a book about working with legacy code" src="https://cdn-images-1.medium.com/max/1024/1*vGyLAgOypqExopTxpwzjTA.jpeg" /><figcaption>Eventually, you will need this</figcaption></figure><p>If not, we should try to write tests that describe the current behavior. There are several techniques to achieve this, but we will describe them in future articles. The general idea is to provide a batch of examples of input data to establish a baseline of the response to assert against it. Once we have this safety net, we can proceed to refactoring.</p><p>The less than ideal situation is when we cannot write any test for that piece of code, something that will surely happen in projects with badly managed dependencies, highly coupled components and low cohesive code.</p><p>In this case, we can use several safe refactoring techniques, also called <a href="https://www.youtube.com/watch?v=1Ao_000oF5U">provable refactors</a> because it can be proved that they won’t affect behavior. Many of them can be performed easily with the help of automated tools, so they are fast and easy to apply. To perform others, we need to follow a series of steps to make changes with safety.</p><h3>What/where to refactor</h3><p>We apply refactors in the pieces of code that we need to touch in order to develop a User Story or fix some bug. Refactor should be part of the normal development process and it doesn’t need dedicated moments. Refactor is one of the tools we use to work, along with testing.</p><figure><img alt="Hen developer next to button for applying refactor" src="https://cdn-images-1.medium.com/max/1024/1*zL1Zbt0CRVy1KCB6uNPd5w.jpeg" /><figcaption>OK. Let’s do it!</figcaption></figure><p>That refactor can be preparatory, improving things before we start working in the new feature. On the other hand, after we introduce the new code, we could improve its quality and its extendability for the future. But don’t confuse that with developing unsolicited features.</p><p>Some places are safer than others. For example, we can refactor the body of public functions and methods as long as we don’t change their signature. We can touch variable names and private methods, inline or extract variables from expressions, extract blocks of code to other functions or private methods, etc.</p><p>When we need to change public interfaces or signatures, we can apply migration techniques to avoid backwards compatibility problems. One of them is to move the body of the method to a new one with the new signature, then replace the old method body with a call to the new one and progressively replace old method calls to the new one. This way, we can have both methods at the same time.</p><h3>Coming soon…</h3><p>This article is a general introduction to refactor but it will be incomplete without some examples. Stay tuned for future instalments in which we will talk about some frequent refactor opportunities and techniques to work with them.</p><p>If you enjoyed this post and this series of articles, please hit the clap button below and follow us on <a href="https://www.facebook.com/docplannerTech/?__tn__=%2Cd%2CP-R&amp;eid=ARCMkTULxdIBTOyout0irGzXnbLcnwj_n_n2_RY5mQGdpLjCbKM_VpAqBhN0B_FQD3ygzsJnYWK_Uf_1">Facebook</a>, <a href="https://twitter.com/DocplannerTech">Twitter</a>, and<a href="https://www.linkedin.com/showcase/26236889/admin/"> LinkedIn</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2b1b4f0c9d73" width="1" height="1" alt=""><hr><p><a href="https://medium.com/docplanner-tech/keeping-code-healthy-with-refactoring-2b1b4f0c9d73">Keeping code healthy with refactoring</a> was originally published in <a href="https://medium.com/docplanner-tech">Docplanner Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>