<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"
	xmlns:content="http://purl.org/rss/1.0/modules/content/"
	xmlns:wfw="http://wellformedweb.org/CommentAPI/"
	xmlns:dc="http://purl.org/dc/elements/1.1/"
	xmlns:atom="http://www.w3.org/2005/Atom"
	xmlns:sy="http://purl.org/rss/1.0/modules/syndication/"
	xmlns:slash="http://purl.org/rss/1.0/modules/slash/"
	>

<channel>
	<title>Refactoring &#8211; CodePills.com</title>
	<atom:link href="https://codepills.com/category/refactoring/feed/" rel="self" type="application/rss+xml" />
	<link>https://codepills.com</link>
	<description>Helping you make a better code</description>
	<lastBuildDate>Sun, 19 Jun 2022 17:07:30 +0000</lastBuildDate>
	<language>en-US</language>
	<sy:updatePeriod>
	hourly	</sy:updatePeriod>
	<sy:updateFrequency>
	1	</sy:updateFrequency>
	
	<item>
		<title>Small ideas &#8211; quick refactoring of legacy code after couple of years</title>
		<link>https://codepills.com/small-ideas-quick-refactoring-of-legacy-code-after-couple-of-years/</link>
					<comments>https://codepills.com/small-ideas-quick-refactoring-of-legacy-code-after-couple-of-years/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Fri, 22 Nov 2019 19:19:09 +0000</pubDate>
				<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[PHP]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1028</guid>

					<description><![CDATA[Recently I have been working on the refactoring of one method when I realized how much I have skilled up as a developer in the last few years.  <a href="https://codepills.com/small-ideas-quick-refactoring-of-legacy-code-after-couple-of-years/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I have recently been working on a refactoring of a method when I realized how much I have skilled up as a developer in the last few years.</p>
<p><span id="more-1028"></span></p>
<p>Here is a function creating a text snippet describing how to get from the airport to the city, which I wrote approximately three years ago. Immediately I knew how it could be rewritten to a more concise form.</p>
<pre><code class="language-php">public static function howToGetFromCityToAirport(string $airportCode, string $language): string
{
    $title = '';
    $paragraph = '';
    if ($language == 'en') {
        $title = '&lt;h2&gt;How to get on the airport?&lt;/h2&gt;';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    if ($language == 'cz') {
        $title = '&lt;h2&gt;Jak se dostat na letiště?&lt;/h2&gt;';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    if ($language == 'sk') {
        $title = '&lt;h2&gt;Ako sa dostať na letisko?&lt;/h2&gt;';
        $paragraph = self::cityToAirport($language, $airportCode);
        if (empty($paragraph))
        {
            return '';
        }
    }
    return $title . $paragraph;
}</code></pre>
<p>So what I did? I made only few changes:</p>
<ul>
<li>First I extracted the common part and pushed it to <code>$paragraph</code> variable.</li>
<li>Then over ternary decision decided what to return.</li>
<li>If a <code>$paragraph</code> is not zero length then call custom private translation method and build a simple HTML string.</li>
<li>And lastly, I just simplified naming or enforced PHP type safety.</li>
</ul>
<pre><code class="language-php">public static function fromCityToAirport(string $airportCode, string $language): string
{
    $paragraph = self::cityToAirport($language, $airportCode);
    return strlen($paragraph) == 0 ? '' : "&lt;h2&gt;" . self::fromCityToAirport_getTitle($language) . "&lt;/h2&gt;" . $paragraph;
}

private static function fromCityToAirport_getTitle(string $language): string
{
    switch ($language) {
        case 'en':
            return 'How to get on the airport?';
            break;
        case 'cz':
            return 'Jak se dostat na letiště?';
            break;
        case 'sk':
            return 'Ako sa dostať na letisko?';
            break;
    }
}</code></pre>
<p>The result is quite significant. 30 lines of code decreased to 20. Code is not faster. But it is more readable and divided into more cohesive parts reflecting better domain language.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/small-ideas-quick-refactoring-of-legacy-code-after-couple-of-years/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
		<item>
		<title>Refactoring function for the least amount of lines</title>
		<link>https://codepills.com/refactoring-function-for-the-least-amount-of-lines/</link>
					<comments>https://codepills.com/refactoring-function-for-the-least-amount-of-lines/#respond</comments>
		
		<dc:creator><![CDATA[Andrej Buday]]></dc:creator>
		<pubDate>Sat, 22 Jun 2019 16:20:34 +0000</pubDate>
				<category><![CDATA[Refactoring]]></category>
		<category><![CDATA[Angular]]></category>
		<category><![CDATA[dropdown]]></category>
		<category><![CDATA[functional programming]]></category>
		<category><![CDATA[refactoring]]></category>
		<category><![CDATA[TypeScript]]></category>
		<category><![CDATA[user]]></category>
		<guid isPermaLink="false">https://codepills.com/?p=1021</guid>

					<description><![CDATA[I had the opportunity to review a small piece of code. I took code review personally and challenged myself to write the shortest solution possible. <a href="https://codepills.com/refactoring-function-for-the-least-amount-of-lines/">Continue reading <span class="meta-nav">&#8594;</span></a>]]></description>
										<content:encoded><![CDATA[<p>I had the opportunity to review a small piece of code. From the first look, I knew this is a beautiful example ready for refactoring.</p>
<p><span id="more-1021"></span></p>
<p>I took code review little bit personally and challenged myself to write the least amount of line; if I can write the shortest solution possible.</p>
<p>Following code is a method which based on the event input is searching through the list of roles and produce a filtered list of roles in the dropdown selection for Angular form.</p>
<pre><code class="language-typescript">searchRoles(event) {
    let roleList = [];
    this.rolesFiltered = User.ROLES.filter(role =&gt;
        role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase());
    if (this.editForm.value.roles) {
        this.rolesFiltered.forEach(filteredRole =&gt; {
            const isInForm = this.editForm.value.roles.some(formRole =&gt; {
                return filteredRole.value.includes(formRole.value);
            });
            if (!isInForm) {
                roleList.push(filteredRole);
            }
        });
    } else {
        roleList = this.rolesFiltered;
    }
    this.rolesFiltered = roleList;
}</code></pre>
<p>The original code had 18 lines of code. Can you find anything odd with it? Do you think this is the shortest way possible? Read further and if you have any more suggestion or ideas for this piece of code, please share them in comments.</p>
<p>I see at least 3 things which are wrong with this code.</p>
<ol>
<li>There is a loop in a loop. Therefore, finding the roles to display is equal to O(n<sup>2</sup>). I had a hunch that this can be decreased to down O(n).</li>
<li>It seems there is too much unnecessary if-else nesting.</li>
<li>Assigning a value on the end of the code seems also as an inappropriate solution. It is connected with a 2nd point, and I also had another hunch this can be mitigated.</li>
</ol>
<pre><code class="language-typescript">searchRoles(event) {
    this.dropdownRoles = User.ROLES.filter(role =&gt;
        role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase())
    );
    if (this.editForm.value.roles) {
        let tempRoleList = [];
        this.dropdownRoles.forEach(dropdownRole =&gt; {
            if (!this.editForm.value.roles.includes(dropdownRole)) {
              tempRoleList.push(dropdownRole);
            }
        });
        this.dropdownRoles = tempRoleList;
    }
}</code></pre>
<p>First of all, I tried to get rid of the temporary variable. It is necessary now. But only in case if you want to temporary store the case that there is already a role selected and you want to pick up roles from the shortened general list of roles.</p>
<p>The first iteration had 13 lines of code.</p>
<pre><code class="language-typescript">searchRoles(event) {
    this.dropdownRoles = User.ROLES.filter(role =&gt;
        role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase())
    );
    if (this.editForm.value.roles) {
        var i = this.dropdownRoles.length;
        while (i--) {
            if (this.editForm.value.roles.includes(this.dropdownRoles[i])) {
                this.dropdownRoles.splice(i, 1);
            }
        }
    }
}</code></pre>
<p>Then I have decided that looping over all dropdown roles so it can help me save some more instructions if it is made correctly. Looping backward I also cut off all used roles and I was getting back only unselected roles in the dropdown menu.</p>
<p>Looping backward reduced the lines even more into 12 lines of code.</p>
<pre><code class="language-typescript">searchRoles(event) {
    this.dropdownRoles = User.ROLES.filter(role =&gt;
      role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase())
    );
    if (this.editForm.value.roles) {
        for (var i = this.dropdownRoles.length - 1; i &gt;= 0; i--) {
            if (this.editForm.value.roles.includes(this.dropdownRoles[i])) {
                this.dropdownRoles.splice(i, 1);
            }
        }
    }
}</code></pre>
<p>I googled the possibility to make this code shorter and eventually it is possible by refactoring <code>while</code> loop and by using TypeScript syntactic sugar to assign variable for dropdown list in <code>for</code> cycle.</p>
<p>Rewriting <code>while</code> to <code>for</code> in TypeScript brought reduction to 11 lines of code.</p>
<pre><code class="language-typescript">searchRoles(event) {
    function filterRoles(role, editForm) {
        if (!editForm.includes(role)) {
            return role;
        }
    }
    this.dropdownRoles = User.ROLES.filter(role =&gt;
        role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase())
    );
    if (this.editForm.value.roles) {
        this.dropdownRoles = this.dropdownRoles.filter(dropdownRole =&gt; filterRoles(dropdownRole, this.editForm.value.roles));
    }
}</code></pre>
<p>When I didn&#8217;t know how to minimize it further I asked myself a different question &#8211; Is possible to rewrite this code in functional paradigm?</p>
<p>So I turned to functional programming and decided to use the same idea for filtering as in initial querying of user input. I have created a standalone local function which took 2 arguments.</p>
<p>Rewriting the solution in a functional way increased method back to 12 lines of code.</p>
<pre><code class="language-typescript">searchRoles(event) {
    this.dropdownRoles = User.ROLES.filter(role =&gt;
        role.label.toLocaleLowerCase().includes(event.query.toLocaleLowerCase())
    );
    if (this.editForm.value.roles) {
        this.dropdownRoles = this.dropdownRoles.filter(dropdownRole =&gt; {
            if (!this.editForm.value.roles.includes(dropdownRole)) {
                return dropdownRole;
            }
        });
    }
}</code></pre>
<p>However, removing the function and making it anonymous decreased the code length to 11 lines. As a side-effect, the solution is rewritten more robustly and functionally.</p>
<p>While I played with other versions of functional refactoring, I picked up the last one because it was the most readable solution. You know, less code is better (easier maintenance, less prone to errors, etc.). But we need to remember that not every code is readable code.</p>
]]></content:encoded>
					
					<wfw:commentRss>https://codepills.com/refactoring-function-for-the-least-amount-of-lines/feed/</wfw:commentRss>
			<slash:comments>0</slash:comments>
		
		
			</item>
	</channel>
</rss>
