Write a code that endures endless business requirements: Part-2 On Code Refactoring!
Tags: codequality, refactorit, productivity, csharp
Published: 2020-02-16 15:11:00

<!-- wp:paragraph -->
<p>So, you got to know
what are the consequences of bad code (<a href="https://www.smartercode.io/19-why-you-should-aggressively-invest-in-your-coding-skills/">here</a>
&amp; <a href="https://www.smartercode.io/19-why-you-should-aggressively-invest-in-your-coding-skills/">here</a>).
You also got to understand how you can objectively decide if a particular piece
of code is horrible or not (<a href="https://www.smartercode.io/write-a-code-that-endures-business-endless-requirements-part-1-on-code-quality-metrics/">here</a>).
Then comes the question:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Ok, I have inherited this devilish system. What should I do
to improve it aside from nagging to my manager?</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Luckily, again, the software industry is experienced in dealing with such <a href="https://en.wikipedia.org/wiki/Brownfield_(software_development)">Brownfield</a> projects. But before discussing how we can improve a brownfield project, let us explain why I believe it is a <strong>must skill </strong>to able to fix and refactor legacy projects. Let’s discuss what refactoring is, and then we make a case for it.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":479,"width":392,"height":634,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://www.smartercode.io/wp-content/uploads/2020/02/why-refactoring.jpg" alt="" class="wp-image-479" width="392" height="634"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":1} -->
<h1>What is Refactoring?</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><strong>Refactoring</strong> is the process of restructuring existing
computer code—changing the factoring—without changing its external behavior</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Simply put, make my code easier to understand and change without
changing its business behavior. <a href="https://en.wikipedia.org/wiki/Robert_C._Martin">Uncle Bob</a> made it on
the spot!</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":480,"width":431,"height":201,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://www.smartercode.io/wp-content/uploads/2020/02/bob.png" alt="" class="wp-image-480" width="431" height="201"/></figure></div>
<!-- /wp:image -->

<!-- wp:heading {"level":1} -->
<h1>Why Refactoring? </h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Since I love philosophy and theoretical discussions, I
always find it interesting -and also useful- to start with the why question.
Let us discuss why we need refactoring in the first place. From WHY questions,
we build wisdom!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Being a good citizen</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>I always believe in “<strong>Make Your Code Cleaner than Your
Found</strong> <strong>It</strong>.” Refactoring and cleaning code is a healthy sign of a
professional developer; it tells that you care about the product, your employer,
and, most importantly, your work quality and professional standards. Not only
that, it will put you in a position to be a leader by doing, which is a way
stronger position than leading by fluffing or talking all day about quality and
so. Remember: Actions are louder than words.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>You will work with legacy systems MOST of your careers</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Software systems are expensive; we all know. And when they
are developed, they are meant to stay for years to come until they recover
their <a href="https://en.wikipedia.org/wiki/Return_on_investment">ROI</a>. If
it is an HR system, the company wants to make sure that they save money on
automating manual processes, having fewer errors, and obtaining a better
experience. If it is integration, the company wants to save time on less data
quality errors, centralized management, and quicker processes. At the end of
the day, business is just a simple math game, and every software system must
comply with it; otherwise, it does not worth it!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, if you read studies about the total cost of ownership (<a href="https://en.wikipedia.org/wiki/Total_cost_of_ownership">TCO</a>), you will
find that research suggests that 80% of the software life cycle costs are
actually maintenance costs, while the 20% is the development or acquisition
cost. Dump math will tell you that out of each five projects you work on, only
one will be a <a href="https://en.wikipedia.org/wiki/Greenfield_project">Greenfield
project</a>. If you managed to find such a project, believe me, you are fortunate!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Therefore, the fact that you will most probably work on a
legacy project simply means that you need to learn how to read a lousy code
someone else wrote, and most importantly, how to improve it!</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Reducing technical debt</h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p><a href="https://en.wikipedia.org/wiki/Technical_debt">Technical
debt</a> is one of the most dangerous things that the business is usually
unaware of. The more complex and rigid the code is, the more expensive it is to
change. We have discussed that extensively in&nbsp;
(<a href="https://www.smartercode.io/19-why-you-should-aggressively-invest-in-your-coding-skills/">here</a>
&amp; <a href="https://www.smartercode.io/19-why-you-should-aggressively-invest-in-your-coding-skills/">here</a>).
So, if you refactor and optimize your code so that it becomes easier to change
and extend, you are doing a big favor for the business! It means better growth
opportunities, better customer reaction, and better time to market.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>What are the common Refactoring techniques?</h1>
<!-- /wp:heading -->

<!-- wp:heading -->
<h2>Red-Green-Refactor</h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":482,"width":366,"height":191,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://i2.wp.com/www.smartercode.io/wp-content/uploads/2020/02/Refactoring.png?fit=1024%2C538&amp;ssl=1" alt="" class="wp-image-482" width="366" height="191"/><figcaption> Figure 1 Source <a href="http://bit.ly/31ZIGB1">http://bit.ly/31ZIGB1</a> </figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>One common refactoring technique is inspired from the test-driven
development approach (<a href="https://technologyconversations.com/2013/12/20/test-driven-development-tdd-example-walkthrough/">TDD</a>)
and follows three simple steps. It can be thought of as a general refactoring
guideline.</p>
<!-- /wp:paragraph -->

<!-- wp:list {"ordered":true} -->
<ol><li>Green: Write just
enough unit tests to make a small piece of the current code passes. This will
give you the confidence in your code so that if something breaks, you can
detect it.</li><li>Refactor: Since you
have backed-up yourself, refactor your code with confidence. If you break your
code, your unit tests will hopefully fail (given that you have good enough <a href="https://en.wikipedia.org/wiki/Code_coverage">code coverage</a>).</li><li>Red: The changes you
introduced during the refactoring phase will likely break your currently
working code, thanks to unit tests. You can repeat the cycle from here to fix
the code and go again to the green state.</li></ol>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>This process continues iteratively through the code base
until we reach an acceptable level of code quality.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Composing Methods</h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":483,"width":330,"height":246,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://www.smartercode.io/wp-content/uploads/2020/02/extract-code-scope-selection1.png" alt="" class="wp-image-483" width="330" height="246"/><figcaption> Figure 2 Source <a href="http://bit.ly/2SueSJA">http://bit.ly/2SueSJA</a> </figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>A simple and conventional way to do abstraction is by
composing methods, that is, by identifying repetitive pieces of logic and
extract them to separate methods. Common pieces of logic I have seen that need
to be refactored are logging logic, file reading logic, and printing logic. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Abstraction</h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":484,"width":426,"height":223,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://i1.wp.com/www.smartercode.io/wp-content/uploads/2020/02/by-abstraction.png?fit=1024%2C538&amp;ssl=1" alt="" class="wp-image-484" width="426" height="223"/><figcaption> Figure 3 Source <a href="http://bit.ly/31ZIGB1">http://bit.ly/31ZIGB1</a> </figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>A common way to do refactoring by introducing a refactoring
layer. Either in cross-systems integration scenarios or even within the same
code base. A refactoring layer is typically introduced to protect developers
against ugly, yet necessary code bases. A common scenario I have seen across
systems is when integrating with banking systems. Most banks have introduced an
API wrapper against complex mainframe interfaces that almost no one understands
how it works. Other ways to do abstraction within the same code base is through
class inheritance and extraction.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Moving Features Between Objects</h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":485,"width":428,"height":208,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://www.smartercode.io/wp-content/uploads/2020/02/moving-objects-1.jpg" alt="" class="wp-image-485" width="428" height="208"/><figcaption> Figure 4 Source <a href="http://bit.ly/2vFKe6N">http://bit.ly/2vFKe6N</a> </figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>An essential principle in object-oriented design is the
single responsibility principle: That is, a specific class, method, or piece of
logic should be responsible for the only thing. Therefore, having classes that
do too many different things (e.g., calculating employee salary and printing
it) is considered against ODD. There are a strong case and reason why this is
unacceptable: Simply because it introduces unnecessary dependencies across the
code and makes it difficult to change. </p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Simplifying conditionals</h2>
<!-- /wp:heading -->

<!-- wp:image {"align":"center","id":486,"width":249,"height":365,"sizeSlug":"large"} -->
<div class="wp-block-image"><figure class="aligncenter size-large is-resized"><img src="https://i1.wp.com/www.smartercode.io/wp-content/uploads/2020/02/Simplified-illustration-of-the-main-conditional-expressions-controlling-the-life-death.png?fit=697%2C1024&amp;ssl=1" alt="" class="wp-image-486" width="249" height="365"/><figcaption> Figure 5 Source <a href="http://bit.ly/3bGSXGq">http://bit.ly/3bGSXGq</a> </figcaption></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Is this image very confusing to understand right? Hhhh, yes,
this is on purpose! Do not spend your time digesting it. We won’t go through
it. The complexity you are facing to understand this diagram is too excessive
conditional complexity. Many techniques help in reducing conditional complexity,
such as replacing nested conditions with guard clauses and replacing conditions
with polymorphism.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>Convincing business to refactor?</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Justifying refactoring to business is one of the most challenging
tasks I have been into. The thing is that the business perception is that they are
paying for something that does not deliver a “tangible” functional requirement
from their point of view of course. The trick to this situation is to convince
businesses with the language they understand, NUMBERS. Try to make a comparison
on how long it takes to modify a specific feature with well-written code and
another feature with ugly code and show them the percentage of productivity
improvement. Yes, a tough and detailed task, but this is what it takes to
convince non-technical people.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Moreover, I would like to ask to use refactoring
responsibility not to overengineer your solution (have you heard of <a href="https://en.wikipedia.org/wiki/Analysis_paralysis">analysis-paralysis</a>?)
and focus only on refactoring critical, and most moving parts in your codebase.
One excellent candidate for that would be an invoicing engine logic that
requires to be adapted a lot to the market needs. Avoid refactoring
non-changing parts such as CRUD logic areas unless you have a clear business
justification. At the end of the day, remember, we are at dollars business!</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>Important Resources</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Finally, I would like to conclude this post by sharing some
resources that I believe help a lot in improving your refactoring skills.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://amzn.to/325ei8b"><strong>https://amzn.to/325ei8b</strong></a><strong> The well-known refactoring book by
Martin Fowler, highly recommended</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://sourcemaking.com/"><strong>https://sourcemaking.com/</strong></a><strong> Excellent website that teaches
refactoring in an interactive way</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://www.udemy.com/course/refactoring-to-patterns/"><strong>https://www.udemy.com/course/refactoring-to-patterns/</strong></a><strong> Excellent course that teaches you
design pattern by doing</strong></p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://app.pluralsight.com/library/courses/refactoring-csharp-developers/table-of-contents"><strong>https://app.pluralsight.com/library/courses/refactoring-csharp-developers/table-of-contents</strong></a><strong> A good course that teaches basic
concepts of refactoring</strong></p>
<!-- /wp:paragraph -->