Write a code that endures endless business requirements: Part-1 On Code Quality Metrics!
Tags: programming, codequality, productivity, beginners
Published: 2020-02-03 19:00:36

<!-- wp:paragraph -->
<p>Hi everyone!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Here I am back after a long vacation (one month and a half!)
in my home country, Sudan. It was an amazing vacation where I met many old
friends, relatives and enjoyed our local food!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Returning to blogging. I discussed why you should
aggressively invest in your coding skills in <a href="https://www.smartercode.io/19-why-you-should-aggressively-invest-in-your-coding-skills/">Part-1</a>
and <a href="Why%20you%20should%20aggressively%20invest%20on%20your%20clean%20coding%20skills-Part%202">Part-2</a>.
I hope that I made a clear case and convinced you that writing good code is not
a luxury but rather a necessity in a world full of <a href="https://en.wikipedia.org/wiki/Cowboy_coding">coding cowboys</a>.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Now, I will shift the focus from the problem to the solution.
We will take a three parts series that will give some insights on how to write better
code. In the first post, we will learn how we can measure our code complexity.
In the second post, we will learn how can we design a proper greenfield
solution. Finally, in the last part, we will learn how to refactor a brownfield
solution.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Ready? Let us start our storytelling in the first part.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>Oops, it is another incident!</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Usually, you start your day as a developer with a cup of
coffee after having your standup meeting. Then, you run into your computer
fully energized and ready to implement a new future the business requested. But
unfortunately, it does not always go smoothly!</p>
<!-- /wp:paragraph -->

<!-- wp:image {"align":"center","id":467,"width":326,"height":325,"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/incident-800.jpg" alt="" class="wp-image-467" width="326" height="325"/></figure></div>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>You get an email from an operation manager that there is a
critical application feature that is down and he requests your urgent
intervention to fix it. There is no other option, as this critical system is a
money cow for the company and the incident is affecting thousands of users who
pay your collogues payroll! You are asked straight away to prioritize new
developments down and focus on this incident. Even worse, the feature has been
developed by a friend who left the company years ago in a codebase you are not
familiar with 😊 Sounds familiar, huh?</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>The curse is coming …</h1>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>You got the heat and decided to navigate the codebase and
understand what is going on. You open your Visual Studio (Read IntelliJ,
PyCharm, whatever!). You found the code area that you suspect is the root cause
of the issue and decide to troubleshoot. And here is how it looks.</p>
<!-- /wp:paragraph -->

<!-- wp:image {"id":468,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://www.smartercode.io/wp-content/uploads/2020/02/Picture1.png" alt="" class="wp-image-468"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>Trrrrra!!! This ladder-style coding is well recognized for
us since the early days we started learning how to program. It is called <a href="https://en.wikipedia.org/wiki/Spaghetti_code">Spaghetti Code</a>; it is a horrible, disgusting, foolish and terrible
coding style!</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>You curse the developer who wrote the code as you are
receiving huge pressure from the project manager and the business stakeholders
to fix the issue and restore the normal application operation.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>Away from the emotional reaction towards a spaghetti code,
let us try and analyze the objective disasters with it:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Would you feel safe
modifying this code?</li><li>Can you make it readable?</li><li>Can you write unit tests
against this code?</li><li>Do you think it would be
flexible against future business requirements?</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>For an organization, such code means:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Low time to Market</li><li>High maintenance cost</li><li>Lower system availability</li><li>Less business agility</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Thus, Decreased overall organization competitiveness.
Therefore, such a coding style is a business threat, and we should have the
proper forensic measures to deal with it.</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>Introducing Code Complexity Metrics</h1>
<!-- /wp:heading -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>What gets measured gets done</p></blockquote>
<!-- /wp:quote -->

<!-- wp:paragraph -->
<p>Fortunately, our understanding of software development
methodologies has developed to the extent that it made us develop some
objective metrics to measure the code quality. These metrics serve as a vehicle
to assess different aspects of code quality, such as:</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Depth of Inheritance:
This metric tells us how deep a certain class goes in the inheritance tree.</li><li>Cyclomatic Complexity
(CC): My favorite metric! It tells us how difficult it is to test our code;
it relies mainly on measuring the number of branching we have on our code.
Industry recommendations are to make it below 10; it only matters on the method
level.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Refer to this <a href="http://bit.ly/2YhtAVx">academic paper</a> for a more in-depth analysis of
Cyclomatic Complexity.</p>
<!-- /wp:paragraph -->

<!-- wp:list -->
<ul><li>Maintainability Index:
A percentage indicating how difficult it is to maintain a certain piece of code.</li><li>Class Coupling: According
to <a href="https://docs.microsoft.com/en-us/visualstudio/code-quality/code-metrics-values?view=vs-2019">MSDN</a>,
“Measures the coupling to unique classes through parameters, local variables,
return types, method calls, generic or template instantiations, base classes,
interface implementations, fields defined on external types, and attribute
decoration.” This metric works best to assess the code from an OOP point of
view.</li><li>Cognitive Complexity:
A new measure introduced by Sonar Source in their <a href="https://www.sonarsource.com/docs/CognitiveComplexity.pdf">White Paper</a>.
Unlike the Cyclomatic Complexity, which aims to tell how difficult the code is
to test, cognitive complexity aims to tell how difficult the code is to
understand. However, not many tools support cognitive complexity.</li></ul>
<!-- /wp:list -->

<!-- wp:paragraph -->
<p>Depth of Inheritance, Cyclomatic Complexity,
Class Coupling, and Maintainability index are the most common metrics in the
industry.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>Why do we have very bad programming experience?</h2>
<!-- /wp:heading -->

<!-- wp:image {"id":469,"sizeSlug":"large"} -->
<figure class="wp-block-image size-large"><img src="https://i0.wp.com/www.smartercode.io/wp-content/uploads/2020/02/Picture2.png?fit=1024%2C407&amp;ssl=1" alt="" class="wp-image-469"/></figure>
<!-- /wp:image -->

<!-- wp:paragraph -->
<p>If we look at the code quality metrics in Visual Studio (<a href="https://docs.microsoft.com/en-us/visualstudio/code-quality/code-metrics-values?view=vs-2019">Click
to learn how to do it</a>), we will end up with the image shown above. The
arrows point clearly on the metrics for the method “<strong>VeryComplexCode</strong>” we
see that it has Maintainability Index of 60 and Cyclomatic Complexity of 8. The
numbers tell us we have some problematic parts in the code. Such metrics are
extremely useful to quickly analyze big projects and decide on critical parts,
which, if fixed, will result in the greatest ROI on the project.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>So, the conclusion I would like to draw here is:</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>The more
nesting we have in our code, the more complex it will be. Therefore, we should
strive to minimize nesting.</p>
<!-- /wp:paragraph -->

<!-- wp:heading -->
<h2>More reads around improving Cyclomatic Complexity </h2>
<!-- /wp:heading -->

<!-- wp:paragraph -->
<p>Attaining the skill to write an excellent code takes time,
effort and education. However, it is a long term strategic skill I would highly
recommend learning. Here are some resources I would recommend based on my
experience.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="http://www.codinghelmet.com/articles">15 Articles
series by Zoran Horvat on how to reduce Cyclomatic Complexity</a>: An extremely
useful blog posts series by Zoran Horvat on how to improve code complexity, he
starts from a dirty, ugly code and reasons towards better-refactored design.
Useful post to understand the thought process behind design patterns.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://app.pluralsight.com/library/courses/patterns-library/table-of-contents">Design
Patterns Library</a>: A must to have skill for any decently developed code is
the proper usage of design patterns. Pluralsight has an extensive course that
covers a wide range of design patterns by many world-class authors.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p><a href="https://ardalis.com/measuring-aggregate-complexity-in-software-applications">Aggregate
Complexity</a>: Cyclomatic Complexity has certain limitations when it comes to
large codebases, Steve Smith, has developed a unique metric called aggregate
complexity to overcome that; it will be interesting to read on that.</p>
<!-- /wp:paragraph -->

<!-- wp:paragraph -->
<p>If the guy who developed the previously presented
problematic code has read the previous courses and applied them, the business application
would be in better shape in terms of agility, maintainability, and stability!
Your life as a succeeding developer will be easier too!</p>
<!-- /wp:paragraph -->

<!-- wp:heading {"level":1} -->
<h1>Final Words</h1>
<!-- /wp:heading -->

<!-- wp:quote -->
<blockquote class="wp-block-quote"><p>No matter how good and recent your platform/infrastructure stack is (e.g., Kubernetes, clustering, HA, etc.), bad code will always beat good hardware.</p><p>A bad code for me is like a careless student you sent to MIT (1st world-ranked engineering school), they will never learn, not because of MIT, but because of the student. Good code is like a hardworking student from very underprivileged school; he succeeds at the end (e.g., Google CEO)</p><cite> Mohammed Osman </cite></blockquote>
<!-- /wp:quote -->