<?xml version="1.0" encoding="utf-8"?>
<feed xmlns="http://www.w3.org/2005/Atom">
  <title>Seeing Sharply</title>
  
  
  <link href="/atom.xml" rel="self"/>
  
  <link href="https://blog.jamesmichaelhickey.com/"/>
  <updated>2022-09-07T01:11:18.496Z</updated>
  <id>https://blog.jamesmichaelhickey.com/</id>
  
  <author>
    <name>James Hickey</name>
    
  </author>
  
  <generator uri="http://hexo.io/">Hexo</generator>
  
  <entry>
    <title>Modular Monoliths And Composite UIs With .NET Core Razor Class Libraries</title>
    <link href="https://blog.jamesmichaelhickey.com/How-To-Build-Modular-Monoliths-With-NETCore-Razor-Class-Libraries/"/>
    <id>https://blog.jamesmichaelhickey.com/How-To-Build-Modular-Monoliths-With-NETCore-Razor-Class-Libraries/</id>
    <published>2019-12-10T00:19:00.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p><strong>Microservices are all the rage now.</strong> </p><p>But, many are (finally) realizing that it’s not for everyone. Most of us aren’t at the scale of Netflix, LinkedIn, etc. and therefore don’t have the organizational manpower to offset the overhead of a full-blown microservices architecture.</p><p>An alternative to a full-blown microservices architecture that’s been getting a lot of press lately is called “modular monoliths.”</p><a id="more"></a><blockquote><p>Shouldn’t well-written monoliths be modular anyways?</p></blockquote><p>Sure. But modular monoliths are done in a <strong>very intentional</strong> way that usually follows a domain-driven approach.</p><h2 id="Summary-Table-Of-Contents"><a href="#Summary-Table-Of-Contents" class="headerlink" title="Summary / Table Of Contents"></a>Summary / Table Of Contents</h2><p>This is part of the 2019 C# Advent! <a href="https://crosscuttingconcerns.com/The-Third-Annual-csharp-Advent" target="_blank" rel="noopener">Take a look at all the other awesome articles for this year!</a></p><p>Here are the main sections in the article in case you would like to skip certain parts:</p><ul><li><a href="#Why-Modular-Monoliths">Introduction / Why Modular Monoliths?</a></li><li><a href="#Creating-Our-Skeleton">Building A Modular Monolith With .NET Core Razor Class Libraries</a></li><li><a href="#Composite-UIs-With-Blazor-Components">Building A Composite UI With Blazor/Razor Components</a></li></ul><p><strong>The GitHub repo for everything in this article <a href="https://github.com/jamesmh/net-core-modular-monolith-razor-lib" target="_blank" rel="noopener">is here</a>.</strong></p><h2 id="Why-Modular-Monoliths"><a href="#Why-Modular-Monoliths" class="headerlink" title="Why Modular Monoliths?"></a>Why Modular Monoliths?</h2><p>The biggest benefits that microservices give us (loose coupling, code ownership, etc.) can be had in a well-designed modular monolith. By leveraging the domain-driven concept of bounded contexts, we can treat each context as an isolated application. </p><p>But, instead of hosting each context as an independent process (like with microservices), we can extract each bounded context as a module within a larger system or web of modules. </p><p>For example, each module might be a .NET project/assembly. These assemblies would be combined at run-time and hosted within one main process.</p><p>Each module would own everything from UI components, back-end business/domain logic to persistence.</p><p>Compared to microservices, the benefits of modular monoliths include:</p><ul><li>In-memory communication between contexts are more performant and reliable than doing it on the network</li><li>A much simpler deployment process for smaller teams</li><li>Retain boundaries and ownership around specific contexts</li><li>Simplified upgrades to contexts/services</li><li>Modules are “ready” to be extracted as services if needed</li></ul><p>I see modular monoliths as a step within the potential evolution of a system’s architecture:</p><p><img src="/img/architecture/ArchitectureSpectrum.png" alt="spectrum"></p><p>For domain-driven approaches, starting with a modular monolith might make the most sense and is definitely worth considering.</p><p>Here’s a more in-depth <a href="https://www.kamilgrzybek.com/design/modular-monolith-primer/" target="_blank" rel="noopener">primer on modular monoliths</a> by Kamil Grzybek if you’re interested.</p><h2 id="How-Can-I-Build-Them"><a href="#How-Can-I-Build-Them" class="headerlink" title="How Can I Build Them?"></a>How Can I Build Them?</h2><p>There are many ways to build modular monoliths!</p><p>For example, Kamil Grzybek has created <a href="https://github.com/kgrzybek/modular-monolith-with-ddd" target="_blank" rel="noopener">a production-ready modular monolith sample</a>.</p><p>I personally prefer less separation within each bounded context / module, but his example is super detailed and worth looking at!</p><p>And, of course, Kamil says it well in his repo’s disclaimer:</p><blockquote><p>The architecture and implementation presented in this repository is one of the many ways to solve some problems</p></blockquote><p>In this article, we’ll be looking at a much simpler approach to building modular monoliths. Again, the direction and implementation depends on your needs (business requirements, team experience, time-to-market required, etc.)</p><p>We’ll be looking at one way that’s unique to .NET Core by using a new-ish feature of .NET Core called <a href="https://docs.microsoft.com/en-us/aspnet/core/razor-pages/ui-class?view=aspnetcore-3.0&amp;tabs=visual-studio" target="_blank" rel="noopener">razor class libraries</a>. Razor class libraries allow you to build entire UI pages, controllers and components inside of a sharable library! It’s the approach I’ve used for <a href="https://www.pro.coravel.net/" target="_blank" rel="noopener">Coravel Pro</a> and enables some exciting possibilities.</p><h2 id="Life-Insurance-Application"><a href="#Life-Insurance-Application" class="headerlink" title="Life Insurance Application"></a>Life Insurance Application</h2><p>I recently wrote <a href="https://www.blog.jamesmichaelhickey.com/DDD-Use-Case-Life-Insurance-Platform/" target="_blank" rel="noopener">an article</a> about using some domain-driven approaches to think about and re-design an insurance selling platform I once worked on.</p><p>To keep things simple for now, let’s imagine we’ve determined two bounded contexts from this domain:</p><ul><li>Insurance Application</li><li>Medical Questionnaire</li></ul><p>The specific details are not so important since the remainder of this article will look at implementation and code.</p><p>The structure of our solution will roughly look like the following - with a .NET Core web application as the host:</p><p><img src="/img/razormodules/modules.png" alt="modules"></p><h2 id="Creating-Our-Skeleton"><a href="#Creating-Our-Skeleton" class="headerlink" title="Creating Our Skeleton"></a>Creating Our Skeleton</h2><p>Let’s implement the skeleton for our modular monolith and use razor class libraries as a way to implement our bounded contexts.</p><p>First, create a new root host process:</p><p><code>dotnet new webapp -o HostApp</code></p><p>Next, we’ll create our two modules as razor class libraries:</p><p><code>dotnet new razorclasslib -o Modules/InsuranceApplication</code></p><p><code>dotnet new razorclasslib -o Modules/MedicalQuestions</code></p><p><img src="/img/razormodules/folders1.png" alt="folder structure"></p><p>Then, we’ll reference our modules from the host project.</p><p>From within the host project:</p><p><code>dotnet add reference ../Modules/InsuranceApplication/InsuranceApplication.csproj</code></p><p><code>dotnet add reference ../Modules/MedicalQuestions/MedicalQuestions.csproj</code></p><h2 id="Building-Our-First-Module"><a href="#Building-Our-First-Module" class="headerlink" title="Building Our First Module"></a>Building Our First Module</h2><p>Navigate to the Insurance Application module at <code>Modules/InsuranceApplication</code>.</p><p>Your razor class library will have some sample Blazor files, <code>www</code> folder, etc. You can remove all those generated files.</p><p>Let’s build a couple of Razor Pages that will be used as this bounded context’s UI:</p><p><code>dotnet new page -o Areas/InsuranceApplication/Pages -n ContactInfo</code></p><p><code>dotnet new page -o Areas/InsuranceApplication/Pages -n InsuranceSelection</code></p><blockquote><p>You might have to go into your razor pages and adjust the generated namespaces. In my example, I changed them to <code>InsuranceApplication.Areas.InsuranceApplication.Pages</code>.</p></blockquote><h2 id="Oops-It-Doesn’t-Work"><a href="#Oops-It-Doesn’t-Work" class="headerlink" title="Oops! It Doesn’t Work!"></a>Oops! It Doesn’t Work!</h2><p>Navigate back to the <code>HostApp</code> web project and try to build it. </p><p><em>It will fail!</em></p><p>Our razor class libraries are trying to use razor pages - which is a web function. This requires referencing the appropriate reference assemblies.</p><p>Before .NET Core 3.0, we would have added a reference to some extra NuGet packages like <code>Microsoft.AspNetCore.Mvc</code>, etc. As of .NET Core 3.0, many of these ASP related packages are actually included in the .NET Core SDK.</p><blockquote><p>For some projects, this breaking change can cause issues and confusion! For more details, check out Andrew Lock’s <a href="https://andrewlock.net/converting-a-netstandard-2-library-to-netcore-3/" target="_blank" rel="noopener">in-depth look at this issue.</a></p></blockquote><p>So, let’s change the project files of our two razor class libraries to the following:</p><pre class=" language-xml"><code class="language-xml"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>Project</span> <span class="token attr-name">Sdk</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>Microsoft.NET.Sdk.Razor<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>PropertyGroup</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>TargetFramework</span><span class="token punctuation">></span></span>netcoreapp3.0<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>TargetFramework</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>AddRazorSupportForMvc</span><span class="token punctuation">></span></span>True<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>AddRazorSupportForMvc</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>PropertyGroup</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ItemGroup</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>FrameworkReference</span> <span class="token attr-name">Include</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>Microsoft.AspNetCore.App<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>ItemGroup</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>Project</span><span class="token punctuation">></span></span></code></pre><blockquote><p>Yes, I removed all the boilerplate Blazor code since the appropriate references are included in the <code>FrameworkReference</code>.</p></blockquote><h2 id="It’s-Alive"><a href="#It’s-Alive" class="headerlink" title="It’s Alive!"></a>It’s Alive!</h2><p>Go into the razor pages you created and add some dummy HTML.</p><p>For example:</p><pre class=" language-html"><code class="language-html">@page@model InsuranceApplication.Areas.InsuranceApplication.Pages.ContactInfoModel@{}<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Insurance Contact Info<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span></code></pre><p>Try running your host application and navigate to <code>/InsuranceApplication/ContactInfo</code> and <code>/InsuranceApplication/InsuranceSelection</code>.</p><p>Both pages should display. Cool!</p><h2 id="UI-Flow-Beginning-The-Insurance-Application"><a href="#UI-Flow-Beginning-The-Insurance-Application" class="headerlink" title="UI Flow: Beginning The Insurance Application"></a>UI Flow: Beginning The Insurance Application</h2><p>Let’s look at building out a basic flow between our two modules.</p><p>First, in the <code>HostApp</code> project, in your <code>Pages/Index.cshtml</code> file add the following HTML:</p><pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>/InsuranceApplication/ContactInfo<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Begin Your Application!<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>a</span><span class="token punctuation">></span></span></code></pre><p>That will give us a link to click from our home screen to begin the flow through our application logic.</p><p><img src="/img/razormodules/flow1.png" alt="screen 1"></p><h2 id="UI-Flow-Inside-The-Insurance-Application-Module"><a href="#UI-Flow-Inside-The-Insurance-Application-Module" class="headerlink" title="UI Flow: Inside The Insurance Application Module"></a>UI Flow: Inside The Insurance Application Module</h2><p>In your <code>ContactInfo.cshtml</code> file within the <code>InsuranceApplication</code> project, insert the following:</p><pre class=" language-html"><code class="language-html">@page@model InsuranceApplication.Areas.InsuranceApplication.Pages.ContactInfoModel@addTagHelper *, Microsoft.AspNetCore.Mvc.TagHelpers<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Insurance Contact Info<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>form</span> <span class="token attr-name">method</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>post<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>label</span><span class="token punctuation">></span></span>Email:<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>label</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>input</span> <span class="token attr-name">asp-for</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>EmailAddress<span class="token punctuation">"</span></span> <span class="token attr-name">required</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>email<span class="token punctuation">"</span></span> <span class="token punctuation">/></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">type</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>submit<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>submit<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>form</span><span class="token punctuation">></span></span></code></pre><p>In <code>ContactInfo.cshtml.cs</code>, add the following:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">using</span> System<span class="token punctuation">;</span><span class="token keyword">using</span> System<span class="token punctuation">.</span>Collections<span class="token punctuation">.</span>Generic<span class="token punctuation">;</span><span class="token keyword">using</span> System<span class="token punctuation">.</span>Linq<span class="token punctuation">;</span><span class="token keyword">using</span> System<span class="token punctuation">.</span>Threading<span class="token punctuation">.</span>Tasks<span class="token punctuation">;</span><span class="token keyword">using</span> Microsoft<span class="token punctuation">.</span>AspNetCore<span class="token punctuation">.</span>Mvc<span class="token punctuation">;</span><span class="token keyword">using</span> Microsoft<span class="token punctuation">.</span>AspNetCore<span class="token punctuation">.</span>Mvc<span class="token punctuation">.</span>RazorPages<span class="token punctuation">;</span><span class="token keyword">namespace</span> InsuranceApplication<span class="token punctuation">.</span>Areas<span class="token punctuation">.</span>InsuranceApplication<span class="token punctuation">.</span>Pages<span class="token punctuation">{</span>  <span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ContactInfoModel</span> <span class="token punctuation">:</span> PageModel  <span class="token punctuation">{</span>    <span class="token punctuation">[</span>BindProperty<span class="token punctuation">]</span>    <span class="token keyword">public</span> <span class="token keyword">string</span> EmailAddress <span class="token punctuation">{</span> <span class="token keyword">get</span><span class="token punctuation">;</span> <span class="token keyword">set</span><span class="token punctuation">;</span> <span class="token punctuation">}</span>    <span class="token keyword">public</span> IActionResult <span class="token function">OnPostAsync</span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">{</span>      Console<span class="token punctuation">.</span><span class="token function">WriteLine</span><span class="token punctuation">(</span>$<span class="token string">"Email Address is {this.EmailAddress}."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>      <span class="token keyword">return</span> <span class="token function">RedirectToPage</span><span class="token punctuation">(</span><span class="token string">"./InsuranceSelection"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>  <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>This will allow us to enter an email address and move to the next page in our flow.</p><p><img src="/img/razormodules/flow2.png" alt="screen 2"></p><p>In the <code>InsuranceSelection.cshtml</code> page - just add a link to keep things simple:</p><pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>/MedicalQuestionnaire/Questions<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Next<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span><span class="token punctuation">></span></span></code></pre><blockquote><p>You can imagine that this page would allow the user to select a specific insurance plan they want to apply for.</p></blockquote><h2 id="UI-Flow-Medical-Questionnaire-Module"><a href="#UI-Flow-Medical-Questionnaire-Module" class="headerlink" title="UI Flow: Medical Questionnaire Module"></a>UI Flow: Medical Questionnaire Module</h2><p>You might have noticed that we never created any razor pages in the Medical Questionnaire module. Let’s do that now.</p><p>Navigate to the root of the <code>MedicalQuestions</code> project and enter the following from your terminal:</p><p><code>dotnet new page -o Areas/MedicalQuestionnaire/Pages -n Questions</code></p><blockquote><p>Again, you might need to adjust the generated namespaces.</p></blockquote><p>Within the <code>Questions.cshtml</code> file, add a link:</p><pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h1</span><span class="token punctuation">></span></span>Medical Questionnaire<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h1</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span> <span class="token attr-name">href</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>/<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Finish<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>a</span><span class="token punctuation">></span></span></code></pre><p>Try running your host project with <code>dotnet run</code> and run through the entire UI!</p><h2 id="Composite-UIs-With-Blazor-Components"><a href="#Composite-UIs-With-Blazor-Components" class="headerlink" title="Composite UIs With Blazor Components"></a>Composite UIs With Blazor Components</h2><p>When working with these kinds of loosely coupled modules a question arises: </p><p><strong>What happens when we need to display information from multiple bounded contexts on the same screen?</strong></p><p>Usually, we resort to building composite UIs. </p><p>These are UIs where various parts of the UI are rendered and controlled by components owned by a specific bounded context, service or module.</p><p><img src="/img/razormodules/compositeui.png" alt="composite ui"></p><p>As you can see in the image above, each component might be owned by a different back-end module and would be isolated from and loosely coupled to the other modules.</p><p>Let’s build a simple composite UI using some exciting new .NET Core 3.0 technologies!</p><h3 id="Configure-Blazor-Components"><a href="#Configure-Blazor-Components" class="headerlink" title="Configure Blazor Components"></a>Configure Blazor Components</h3><p>We need to configure our host application to support the new blazor/razor components.</p><ol><li>Add the following script to <code>Pages/Shared/_Layout.cshtml</code>:</li></ol><pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>script</span> <span class="token attr-name">src</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>_framework/blazor.server.js<span class="token punctuation">"</span></span><span class="token punctuation">></span></span><span class="token script language-javascript"></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>script</span><span class="token punctuation">></span></span></code></pre><ol start="2"><li>In <code>Startup.cs</code> in <code>ConfigureServices</code> add:</li></ol><pre class=" language-csharp"><code class="language-csharp">services<span class="token punctuation">.</span><span class="token function">AddServerSideBlazor</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><ol start="3"><li>In the <code>Configure</code> method:</li></ol><pre class=" language-csharp"><code class="language-csharp">app<span class="token punctuation">.</span><span class="token function">UseEndpoints</span><span class="token punctuation">(</span>endpoints <span class="token operator">=</span><span class="token operator">></span><span class="token punctuation">{</span> endpoints<span class="token punctuation">.</span><span class="token function">MapRazorPages</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> endpoints<span class="token punctuation">.</span><span class="token function">MapBlazorHub</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// Add this one.</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><h3 id="Create-Insurance-Application-Component"><a href="#Create-Insurance-Application-Component" class="headerlink" title="Create Insurance Application Component"></a>Create Insurance Application Component</h3><p>Navigate to the <code>InsuranceApplication</code> project’s root directory and execute the following:</p><p><code>dotnet new razorcomponent -o ./Components -n ApplicationDashboard</code></p><p>Replace the contents of your new razor component with the following:</p><pre class=" language-html"><code class="language-html">@using Microsoft.AspNetCore.Components.Web<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>h3</span><span class="token punctuation">></span></span>Application Dashboard<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>h3</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>p</span><span class="token punctuation">></span></span>    Time: @currentTime<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>p</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>button</span> <span class="token attr-name">@onclick</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>Update<span class="token punctuation">"</span></span><span class="token punctuation">></span></span>Update<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>button</span><span class="token punctuation">></span></span>@code {    private string currentTime = DateTime.Now.ToString();    private void Update()    {        currentTime = DateTime.Now.ToString();           }}</code></pre><h3 id="Create-Medical-Questions-Component"><a href="#Create-Medical-Questions-Component" class="headerlink" title="Create Medical Questions Component"></a>Create Medical Questions Component</h3><p>Do the same steps within the <code>MedicalQuestions</code> module to create a dummy razor component (but change the title of the component).</p><h3 id="Putting-It-Together"><a href="#Putting-It-Together" class="headerlink" title="Putting It Together"></a>Putting It Together</h3><p>Now, back in your host application project, within the <code>Pages/Index.cshtml</code> page, add the following to the top of the file:</p><pre class=" language-csharp"><code class="language-csharp">@page@<span class="token keyword">using</span> InsuranceApplication<span class="token punctuation">.</span>Components <span class="token comment" spellcheck="true">// Add this.</span>@<span class="token keyword">using</span> MedicalQuestions<span class="token punctuation">.</span>Components <span class="token comment" spellcheck="true">// Add this.</span>@model IndexModel</code></pre><p>Then, in the middle of your HTML page, add:</p><pre class=" language-html"><code class="language-html"><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>row<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>col-6<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> @(await Html.RenderComponentAsync<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>ApplicationDashboard</span><span class="token punctuation">></span></span>(RenderMode.ServerPrerendered)) <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span> <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>div</span> <span class="token attr-name">class</span><span class="token attr-value"><span class="token punctuation">=</span><span class="token punctuation">"</span>col-6<span class="token punctuation">"</span></span><span class="token punctuation">></span></span> @(await Html.RenderComponentAsync<span class="token tag"><span class="token tag"><span class="token punctuation">&lt;</span>QuestionsDashboard</span><span class="token punctuation">></span></span>(RenderMode.ServerPrerendered)) <span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span><span class="token tag"><span class="token tag"><span class="token punctuation">&lt;/</span>div</span><span class="token punctuation">></span></span></code></pre><p>Finally… start your host project using <code>dotnet run</code>!</p><p><img src="/img/razormodules/compositeuiscreenshot.png" alt="composite ui"></p><p>Any time one of the components needs to be changed, the host application will (most likely) not need to change. Both bounded contexts are still isolated from each other but our architecture allows us to be smart about how we display that information.</p><p><em>Note: There are other ways to build these types of components: <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1" target="_blank" rel="noopener">view components</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/intro?view=aspnetcore-3.1" target="_blank" rel="noopener">tag helpers</a>, <a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/tag-helpers/th-components?view=aspnetcore-3.1" target="_blank" rel="noopener">tag helper components</a>, javascript components, etc.</em></p><h2 id="Other-Considerations"><a href="#Other-Considerations" class="headerlink" title="Other Considerations"></a>Other Considerations</h2><ol><li><p>Modules can be deployed as NuGet packages so that they ultimately can be managed by independent teams and be isolated as true modules.</p></li><li><p>Each bounded context can:</p><ul><li>Use its own isolated database</li><li>Have its own self-contained business logic</li><li>Communicate with other bounded contexts by using messaging and domain events</li><li>etc.</li></ul></li><li><p>In terms of service/module interaction, any calls between modules could use a shared abstractions library which would be configured in DI at run-time to use the concrete service from the appropriate bounded context:</p></li></ol><p><img src="/img/razormodules/references.png" alt="references"></p><p>It doesn’t show on the diagram, but the Medical Questions context might need to get some information from the Insurance Application context in some scenarios where using messaging isn’t appropriate.</p><p>In this case, the Medical Questions code would use the <code>IInsuranceApplicationService</code> interface (from DI) to make those calls.</p><p>Then, at run-time, the host process would configure the concrete implementation (<code>InsuranceApplicationFacade</code>) to be given to anyone who asks for the interface.</p><p>This technique keeps each module loosely coupled and enforces a strict contract in terms of what one bounded context can be explicitly be “asked for”.</p><p><em>However, some might say the need to make direct calls to another bounded context is a sign that the boundaries are incorrect…a topic for another day.</em></p><h2 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h2><p>I hope you found this article helpful and informative. I’m sure you can see that razor class libraries are a really exciting feature of .NET Core that hasn’t been talked about too much.</p><p>This is one way to use them and for some cases it might work really well!</p><p>Here are some resources about the topics we covered:</p><ul><li><a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/?view=aspnetcore-3.1" target="_blank" rel="noopener">Blazor</a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/blazor/components?view=aspnetcore-3.1" target="_blank" rel="noopener">Razor Components</a></li><li><a href="https://docs.microsoft.com/en-us/aspnet/core/mvc/views/view-components?view=aspnetcore-3.1" target="_blank" rel="noopener">View Components</a></li><li><a href="https://www.youtube.com/watch?v=kbKxmEeuvc4" target="_blank" rel="noopener">Modular Monoliths Talk By Simon Brown</a></li><li><a href="https://jimmybogard.com/composite-uis-for-microservices-a-primer/" target="_blank" rel="noopener">Composite UIs for Microservices - A Primer By Jimmy Bogard</a></li><li><a href="https://docs.microsoft.com/en-us/dotnet/architecture/microservices/architect-microservice-container-applications/microservice-based-composite-ui-shape-layout" target="_blank" rel="noopener">Microsoft: Creating composite UI based on microservices</a></li></ul><h1 id="My-Book"><a href="#My-Book" class="headerlink" title="My Book"></a>My Book</h1><p>Check out my book about keeping your code healthy!</p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on:</p><ul><li><a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">Twitter</a></li><li><a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;&lt;strong&gt;Microservices are all the rage now.&lt;/strong&gt; &lt;/p&gt;
&lt;p&gt;But, many are (finally) realizing that it’s not for everyone. Most of us aren’t at the scale of Netflix, LinkedIn, etc. and therefore don’t have the organizational manpower to offset the overhead of a full-blown microservices architecture.&lt;/p&gt;
&lt;p&gt;An alternative to a full-blown microservices architecture that’s been getting a lot of press lately is called “modular monoliths.”&lt;/p&gt;
    
    </summary>
    
    
      <category term="microservices, domain-driven design, modular monoliths" scheme="https://blog.jamesmichaelhickey.com/tags/microservices-domain-driven-design-modular-monoliths/"/>
    
  </entry>
  
  <entry>
    <title>Domain-Driven Design Use Case: Improving A Life Insurance Selling Platform</title>
    <link href="https://blog.jamesmichaelhickey.com/DDD-Use-Case-Life-Insurance-Platform/"/>
    <id>https://blog.jamesmichaelhickey.com/DDD-Use-Case-Life-Insurance-Platform/</id>
    <published>2019-10-31T22:34:12.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>Years ago, I lead the web development of a new platform for selling life insurance online (which provided white-label abilities).</p><p>This was one of my biggest professional accomplishments given the many technical and political constraints. But that’s a whole other topic for another day.</p><p>This was before I understood domain-driven design. Since then, I’ve wondered: what this might have looked like using a domain-driven approach?</p><a id="more"></a><p>Here are a few points we’ll cover:</p><ul><li>Event storming: what it is and how to start modelling a business domain</li><li>How thinking of a system or business domain in terms of domain events can <em>really</em> help clarify things</li><li>Some important problems that life insurance businesses might face</li><li>How to tackle interactions with external systems/APIs better</li><li>How certain distributed patterns can improve the UX of a system</li></ul><h1 id="Event-Storming"><a href="#Event-Storming" class="headerlink" title="Event Storming"></a>Event Storming</h1><p>Event storming is a workshop that is usually held to discover and learn about how a business works. You invite all relevant stakeholders and use sticky notes to discover what domain events occur, and what impact or additional processes they might lead to.</p><p>I’ve also found event storming to be helpful even in smaller settings and within smaller team discussions or design discussions.</p><p>For more, see <a href="https://leanpub.com/introducing_eventstorming" target="_blank" rel="noopener">the book by its creator on leanpub</a>.</p><p>In this article, I’ll be using a simple version of event storming so we can focus on the important points.</p><h1 id="Overview-Of-Past-Design"><a href="#Overview-Of-Past-Design" class="headerlink" title="Overview Of Past Design"></a>Overview Of Past Design</h1><p>This system was designed for (a) the main insurance provider and (b) 3rd party insurance providers to allow their customers to apply for life insurance online. It was configurable in that 3rd party providers could choose which parts of the general application process would be included, where the entry point would be, and other customizations.</p><p>Generally speaking, the process went like this when dealing with applications on behalf of 3rd party providers:</p><ol><li><p>Accept some HTTP POST data from an initial form filled out by a third-party provider’s customer.</p></li><li><p>The user continues to fill out the online life insurance application (with multiple steps).</p><ol><li>First, general contact information.</li><li>Next, information about beneficiaries, etc.</li><li>Then, a medical questionnaire.</li><li>Etc.</li></ol></li><li><p>Once done, the user would provide their banking information.</p></li><li><p>It would then process the application by calling a remote API (synchronously - while the user waited for the UI to refresh).</p></li><li><p>Finally, it would display whether the application was accepted or not (with the next steps for the user to take).</p></li></ol><p>Everything was done in one massive code-base. All the web UI and business logic were all together.</p><p>Some of the problems with this approach were:</p><ul><li>Lack of code quality</li><li>Difficulty in terms of maintainability</li><li>Lack of business processes documented in how the code was structured</li><li>Long-running synchronous HTTP POSTs could time-out and cause processing errors</li><li>And more…</li></ul><h1 id="Exploring-Our-Domain"><a href="#Exploring-Our-Domain" class="headerlink" title="Exploring Our Domain"></a>Exploring Our Domain</h1><p>Let’s start to look at the business flow in terms of the events that occur in the domain to give us an overview of what we’re dealing with.</p><p>Keep in mind that this is <em>not</em> an exhaustive look at all the domain events, but a very simplified look:</p><p><img src="/img/insurance/events1.png" alt="events"></p><p><code>PersonalInformationProvided</code> is considered a domain event because other stuff happens in response.</p><p>For example, the insurance company insisted that the system send an e-mail with a token so the proposed insured (i.e. the applicant) could resume their application at a later date.</p><p>The results of <code>MedicalQuestionsProvided</code> may lead to the disqualification of the applicant, disqualification of the selected insurance product, enable an entirely different path throughout the rest of the form, etc. These would be domain events too, but they aren’t shown for simplicity’s sake.</p><h2 id="The-Interesting-Parts…"><a href="#The-Interesting-Parts…" class="headerlink" title="The Interesting Parts…"></a>The Interesting Parts…</h2><p>After the application is completed, we get into the next steps:</p><p><img src="/img/insurance/events2.png" alt="events"></p><p>As you can see, this is where things get interesting.</p><p>Right after <code>BankingInfoProvided</code> the system would remotely call the insurance company’s “special” API that would look at past applicant history, banking history, medical history, etc. and make a decision. This decision was returned via the same HTTP POST (🙃).</p><p>In some cases, the proposed insured had to undergo a physical medical examination at a later date. Their application was kept in a pending state. </p><p>If the application passed, then then the insurance policy would be created (<code>PolicyCreated</code>). Otherwise, a failure just meant there was no policy created and everyone could be on their merry way.</p><p>Upon the first payment of the policy (<code>FirstPolicyPaymentReceived</code>), the policy would “activate.” If a policy was not activated within the first 30 days (or some arbitrary duration), it would be immediately cancelled.   </p><h1 id="Bounded-Contexts"><a href="#Bounded-Contexts" class="headerlink" title="Bounded Contexts"></a>Bounded Contexts</h1><p>In the design of the existing system, there was no concept of bounded contexts. Everything was stored in one massive XML file (yes…the things we have to deal with in outdated industries).</p><p>We know that we need to split this up though. How should we?</p><h2 id="Pivotal-Events"><a href="#Pivotal-Events" class="headerlink" title="Pivotal Events"></a>Pivotal Events</h2><p>One of the kinds of events to watch out for is what Alberto Brandolini (the creator of event storming) calls “pivotal events.” These are the most important events because they are drivers for major transitions within a domain.</p><p>In this scenario, the most important event is <code>PolicyCreated</code>. This is when the application has officially transitioned into a real insurance policy. <strong>That’s the end goal of what the user wants in the first place.</strong></p><p>Interestingly, this is also where the user-facing web application ended and the backend office policy management began.</p><h2 id="Sub-Domains"><a href="#Sub-Domains" class="headerlink" title="Sub-Domains"></a>Sub-Domains</h2><p>Another interesting area (that you might not be aware of unless you’re familiar with the industry) is that the medical questionnaire is <em>very</em> complex. Depending on how you answer certain questions, many different things could happen. </p><p>The code and business logic around this specific area is a hotspot. </p><p>Because of the complexity contained within this area, I’d be interested in exploring this area as a sub-domain and treating it as a bounded context.</p><blockquote><p>Sub-domains are not the same as bounded contexts. Sub-domains are still business related divisions, whereas bounded contexts are about what boundaries our software has. Many times, though, they do match - especially at the beginning of modelling, like we are doing. But, if the business structure changes then the sub-domains might change (with the business) while the bounded contexts are still baked into the software.</p></blockquote><p>Definitely, from the business’ perspective, the <code>MedicalQuestionsProvided</code> is a pivotal event. It’s the main driver for whether a proposed insured is eligible for coverage or qualifies for additional “bonus” insurance add-on products.</p><blockquote><p>In the existing system, this part of the system was the hardest to build and maintain!</p></blockquote><p>This is where the main concept of bounded contexts shines - you can draw a bubble around a specific area or problem space that’s complex and keep that complexity isolated. No one else needs to know <em>how</em> it works. It just needs to know what happens at the end of the questionnaire.</p><p>Keeping in mind though that we can’t just create bounded contexts wherever we want. In this case, we’ve identified (what seems to be for the moment) a pivotal event. </p><h2 id="Language"><a href="#Language" class="headerlink" title="Language"></a>Language</h2><p>Also, if we dig deeper with domain experts, we would find that the (ubiquitous) language used in context of the medical questions is very specific to the medical questionnaire.</p><p>For example, in this context, when speaking about the applicant, it’s in terms of their health, physical well-being, etc.</p><p>This is the only place in the entire domain where this language is used about the applicant.</p><h2 id="Transitions-Between-Sub-Domains"><a href="#Transitions-Between-Sub-Domains" class="headerlink" title="Transitions Between Sub-Domains"></a>Transitions Between Sub-Domains</h2><p>What you’ll notice is that the flow of data is from one context, into another, and then back out into the same one again.</p><p><img src="/img/insurance/events3.png" alt="events"></p><p>Usually, in typical DDD examples, you see data flow from one context into another and the flow never returns to the original context again. </p><p>My gut feeling is that these kinds of complex sub-domains that are smack in the middle of some over-arching business process or other parent domains are common in real-world domains.</p><h2 id="Naive-API-Calls-Vs-Sagas"><a href="#Naive-API-Calls-Vs-Sagas" class="headerlink" title="Naïve API Calls Vs. Sagas"></a>Naïve API Calls Vs. Sagas</h2><p>One of the major issues with the existing system was that it would issue an HTTP POST directly from the web application to the insurance provider’s “special” API that would approve or decline an application.</p><p>Again, this easily leads to issues like:</p><ul><li>HTTP timeouts due to network issues</li><li>Errors when the endpoint was down</li><li>The request just took too long and timed-out…</li></ul><p>Since this was a white-label product, that API would not necessarily be controlled by the insurance provider who we were building this for. So, we had no control over the performance and availability of that API.</p><p>How would I do this today? </p><p>To re-cap more clearly, here are the steps needed (barebones):</p><ul><li>Submit the application (via HTTP POST)</li><li>Wait…</li><li>Make sure to retry on errors…</li><li>Abort if the external system never responds</li><li>If it does respond, then give the results to the user</li></ul><p>This type of long-running job/process is usually best done using the <a href="https://microservices.io/patterns/data/saga.html" target="_blank" rel="noopener">saga pattern</a>.</p><blockquote><p>Other considerations when dealing with these type of long-running jobs might be the <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/RoutingTable.html" target="_blank" rel="noopener">routing slip pattern</a> or the <a href="https://www.enterpriseintegrationpatterns.com/patterns/messaging/ProcessManager.html" target="_blank" rel="noopener">process manager pattern</a> - both of which are similar to the saga pattern.</p></blockquote><p>With the saga pattern, here’s roughly what I would envision:</p><p><img src="/img/insurance/saga1.png" alt="saga"></p><p>This looks a lot more complicated, but please bear with me for a moment.</p><p>Notice that instead of issuing the HTTP POST “plain-and-simple”, the <code>BankingInfoProvided</code> event will kick-off a long-running background job. Specifically, the <code>ApplicationSubmissionSaga</code>.</p><p>This saga has two handlers:</p><ol><li>The first will attempt to call the API and submit the application.</li><li>The second will receive an asynchronous event informing it of the submission status and issue further events or logic.</li></ol><p>Why? What does this give us?</p><h3 id="Resilient-Systems"><a href="#Resilient-Systems" class="headerlink" title="Resilient Systems"></a>Resilient Systems</h3><p>In the original design (direct HTTP POST) - what happens if the external API is <strong>not even running?</strong></p><p>Oh…</p><p>I guess the user is out of luck. They can’t even submit their application…</p><p>What if this happens when using the saga pattern?</p><p>The saga would fail, then go to sleep and re-try at a later date (since it is a background process). If the external system comes back up the next day then the saga will succeed in submitting the application and continue! </p><p><em>Note: This re-try process is indicated in the diagram above by the orange gear on the <code>SubmitApplicationForApprovalStep</code>.</em></p><p>This way of dealing with a distributed transaction or long-running business process (even if the external API isn’t owned by you) helps you to build systems that <strong>can fail and are expected to fail well.</strong></p><h3 id="Implications-For-UX"><a href="#Implications-For-UX" class="headerlink" title="Implications For UX"></a>Implications For UX</h3><p>Let’s compare the two designs in terms of impact on UX. <strong>Yes, this difference in modelling impacts UX in a huge way.</strong></p><p>With the naïve original design, if the external system is down, <strong>the user cannot complete his application.</strong> So… the user will have to come back to the website at a later date and “try again!”</p><p>What about with the saga?</p><p>Here’s where using this pattern shines: the user will “complete” his/her application and we will tell them, “You will receive an e-mail within the next 24 hours once we’ve finished processing your application.”</p><p>The user goes home and eventually, at some point in the near future, will get an e-mail telling them everything they need to know.</p><p><em>Note: In the diagram above, you’ll see that I’ve added the commands around this part of the process.</em></p><p>But, what if the external system is down now? </p><p><em>The user doesn’t know</em>. They’re gone. We’ve designed our system such that the user isn’t needed for us to communicate with the external API and deal with failures. </p><p><strong>What is the user’s experience?</strong></p><p><strong>Awesome.</strong></p><p>The implications of this are huge. This is the difference between systems that are easy to use and annoying and difficult to use.</p><p><strong>This can affect the branding and reputation of the insurance company.</strong></p><p>If users can’t even complete their application because they need to have their web browser open so that our system can communicate with the insurance providers API… that’s crazy. Really bad.</p><h2 id="The-Importance-Of-Modelling-Your-Domain-Well"><a href="#The-Importance-Of-Modelling-Your-Domain-Well" class="headerlink" title="The Importance Of Modelling Your Domain Well"></a>The Importance Of Modelling Your Domain Well</h2><p>This comes back to the idea of modelling your domain well. This is all modelling. We haven’t written any code, but conceptually we can know what would happen with both designs.</p><p>This is why it’s important for companies who want to succeed and give their users the best experience possible to hire developers and engineers who are good at modelling business domains and processes like this.</p><p>It literally could be the difference between a company’s success and failure!</p><p>And it’s one look at why learning to model with these tools is important as a developer/engineer.</p><h2 id="Problem-Business-Stakeholders-Disagree"><a href="#Problem-Business-Stakeholders-Disagree" class="headerlink" title="Problem! Business Stakeholders Disagree"></a>Problem! Business Stakeholders Disagree</h2><p>Everything is fine and dandy now. Except: they do not like the fact that the user cannot get immediate feedback of the application’s approval status on the web site.</p><p>Yes, the applicant will get an e-mail.</p><p>But, the stakeholders also want to keep the web site able to display the results to the customer.</p><p>What do we do? Say no?</p><p>Our new design means that the results of the application approval/denial is a background process now - it’s disconnected from our web application.</p><p>Here’s one solution you might have thought about: the web application can also subscribe to the <code>ApplicationAccepted</code>, <code>ApplicationDenied</code> and <code>ApplicationPending</code> events and use web-sockets (using SignalR, etc.) to “push” the results back to the user’s browser. </p><p>This might even include showing a browser notification (even though we all hate them)?</p><p>Either way, it’s one way to satisfy all the requirements we have so far:</p><p><img src="/img/insurance/saga2.png" alt="saga2"></p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>This was a somewhat primitive look at this domain. There’s <em>so much more to it</em>.</p><p>Hopefully you did learn something about modelling business processes though. Sometimes, just by changing how we process one step in a business flow we can make a huge impact!</p><p>If enough people enjoy this and provide feedback then I might just dig into some more specific problems and do some more intense modelling 😉.</p><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Years ago, I lead the web development of a new platform for selling life insurance online (which provided white-label abilities).&lt;/p&gt;
&lt;p&gt;This was one of my biggest professional accomplishments given the many technical and political constraints. But that’s a whole other topic for another day.&lt;/p&gt;
&lt;p&gt;This was before I understood domain-driven design. Since then, I’ve wondered: what this might have looked like using a domain-driven approach?&lt;/p&gt;
    
    </summary>
    
    
      <category term="domain-driven design, event storming" scheme="https://blog.jamesmichaelhickey.com/tags/domain-driven-design-event-storming/"/>
    
  </entry>
  
  <entry>
    <title>Unhealthy Code: Null Checks Everywhere!</title>
    <link href="https://blog.jamesmichaelhickey.com/Unhealthy-Code-Null-Checks-Everywhere/"/>
    <id>https://blog.jamesmichaelhickey.com/Unhealthy-Code-Null-Checks-Everywhere/</id>
    <published>2019-09-04T23:08:14.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<h1 id="Identifying-The-Problem"><a href="#Identifying-The-Problem" class="headerlink" title="Identifying The Problem"></a>Identifying The Problem</h1><h2 id="Billion-Dollar-Mistake"><a href="#Billion-Dollar-Mistake" class="headerlink" title="Billion Dollar Mistake"></a>Billion Dollar Mistake</h2><p>Did you know that the inventor of the concept of “null” has called this his <a href="https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/" target="_blank" rel="noopener">“Billion Dollar Mistake!”</a></p><p>As simple as it seems, once you get into larger projects and codebases you’ll inevitably find some code that goes “off the deep end” in its use of nulls.</p><a id="more"></a><hr><p><em>Note: This is an excerpt from my book <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript: Keeping Your Code Healthy.</a></em></p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><br><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><hr><p>Sometimes, we desire to simply make a property of an object optional:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">class</span> <span class="token class-name">Product</span><span class="token punctuation">{</span>  <span class="token keyword">public</span> id<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">;</span>  <span class="token keyword">public</span> title<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span>  <span class="token keyword">public</span> description<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>In TypeScript, a <code>string</code> property can be assigned the value <code>null</code>. </p><p>But… so can a <code>number</code> property!</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> chocolate<span class="token punctuation">:</span> Product <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>chocolate<span class="token punctuation">.</span>id <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>chocolate<span class="token punctuation">.</span>description <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span></code></pre><p><em>Hmmm….</em></p><h2 id="Another-Example"><a href="#Another-Example" class="headerlink" title="Another Example"></a>Another Example</h2><p>That doesn’t look so bad at first glance.</p><p>But, it can lead to the possibility of doing something like this:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> chocolate<span class="token punctuation">:</span> Product <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Product</span><span class="token punctuation">(</span><span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">,</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>What’s wrong with that? Well, it allows your code (in this case, the <code>Product</code> class) to get into an inconsistent state.</p><p>Does it ever make sense to have a <code>Product</code> in your system that has no <code>id</code>? Probably not. </p><p>Ideally, as soon as you create your <code>Product</code> it should have an <code>id</code>.</p><p>So… what happens in other places that have to deal with logic around dealing with Products?</p><p>Here’s the sad truth:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">let</span> title<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>product <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span>product<span class="token punctuation">.</span>id <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">if</span><span class="token punctuation">(</span>product<span class="token punctuation">.</span>title <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            title <span class="token operator">=</span> product<span class="token punctuation">.</span>title<span class="token punctuation">;</span>        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>            title <span class="token operator">=</span> <span class="token string">"N/A"</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span>    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>        title <span class="token operator">=</span> <span class="token string">"N/A"</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>    title <span class="token operator">=</span> <span class="token string">"N/A"</span><span class="token punctuation">}</span></code></pre><p><em>Is that even real code someone would write?</em></p><p><strong>Yes.</strong></p><p>Let’s look at why this code is unhealthy and considered a “code smell” before we look at some techniques to fix it.</p><h2 id="Is-It-That-Bad"><a href="#Is-It-That-Bad" class="headerlink" title="Is It That Bad?"></a>Is It That Bad?</h2><p>This code is hard to read and understand. Therefore, it’s very prone to bugs when changed.</p><p>I think we can agree that having code like this scattered in your app is not ideal. Especially when this kind of code is inside the important and critical parts of your application!</p><hr><h2 id="A-Side-Note-About-Non-Nullable-Types-In-TypeScript"><a href="#A-Side-Note-About-Non-Nullable-Types-In-TypeScript" class="headerlink" title="A Side-Note About Non-Nullable Types In TypeScript"></a>A Side-Note About Non-Nullable Types In TypeScript</h2><p>As a relevant side note, someone might raise the fact that TypeScript supports <a href="https://www.typescriptlang.org/docs/handbook/advanced-types.html#nullable-types" target="_blank" rel="noopener">non-nullable types</a>.</p><p>This allows you to add a special flag to your compilation options and will prevent, by default, any variables to allow <code>null</code> as a value.</p><p>A few points about this argument:</p><ul><li><p>Most of us are dealing with existing codebases that would take <strong>tons</strong> of work and time to fix these compilation errors.</p></li><li><p>Without testing the code well, and carefully avoiding assumptions, we could <strong>still</strong> potentially cause run-time errors by these changes.</p></li><li><p>This article (taken from <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">my book</a>) teaches you about solutions that can be applied to other languages - which may not have this option available.</p></li></ul><hr><p>Either way, it’s always safer to apply smaller more targeted improvements to our code. Again, this allows us to make sure the system still behaves the same and avoids introducing a large amount of risk when making these improvements.</p><h1 id="One-Solution-Null-Object-Pattern"><a href="#One-Solution-Null-Object-Pattern" class="headerlink" title="One Solution: Null Object Pattern"></a>One Solution: Null Object Pattern</h1><h2 id="Empty-Collections"><a href="#Empty-Collections" class="headerlink" title="Empty Collections"></a>Empty Collections</h2><p>Imagine you work for a company that writes software for dealing with legal cases. </p><p>As you are working on a feature, you discover some code:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> legalCases<span class="token punctuation">:</span> LegalCase<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> await <span class="token function">fetchCasesFromAPI</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">const</span> legalCase of legalCases<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span>legalCase<span class="token punctuation">.</span>documents <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token function">uploadDocuments</span><span class="token punctuation">(</span>legalCase<span class="token punctuation">.</span>documents<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Remember that we should be wary of null checks? What if some other part of the code forgot to check for a <code>null</code> array?</p><p>The Null Object Pattern can help: you create an object that represents an “empty” or <code>null</code> object.</p><h3 id="Fixing-It-Up"><a href="#Fixing-It-Up" class="headerlink" title="Fixing It Up"></a>Fixing It Up</h3><p>Let’s look at the <code>fetchCasesFromAPI()</code> method. We’ll apply a version of this pattern that’s a very common practice in JavaScript and TypeScript when dealing with arrays:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> fetchCasesFromAPI <span class="token operator">=</span> async <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">const</span> legalCases<span class="token punctuation">:</span> LegalCase<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> await $http<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'legal-cases/'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">const</span> legalCase of legalCases<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Null Object Pattern</span>        legalCase<span class="token punctuation">.</span>documents <span class="token operator">=</span> legalCase<span class="token punctuation">.</span>documents <span class="token operator">||</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">return</span> legalCases<span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Instead of leaving empty arrays/collections as <code>null</code>, we are assigning it an actual empty array.</p><p>Now, no one else will need to make a null check!</p><p>But… what about the entire legal case collection itself? What if the API returns <code>null</code>?</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> fetchCasesFromAPI <span class="token operator">=</span> async <span class="token keyword">function</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">const</span> legalCasesFromAPI<span class="token punctuation">:</span> LegalCase<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> await $http<span class="token punctuation">.</span><span class="token keyword">get</span><span class="token punctuation">(</span><span class="token string">'legal-cases/'</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">// Null Object Pattern</span>    <span class="token keyword">const</span> legalCases <span class="token operator">=</span> legalCasesFromAPI <span class="token operator">||</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>    <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">const</span> <span class="token keyword">case</span> of legalCases<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Null Object Pattern</span>        <span class="token keyword">case</span><span class="token punctuation">.</span>documents <span class="token operator">=</span> <span class="token keyword">case</span><span class="token punctuation">.</span>documents <span class="token operator">||</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">return</span> legalCases<span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Cool!</p><p>Now we’ve made sure that everyone who uses this method does not need to be worried about checking for nulls.</p><h2 id="Take-2"><a href="#Take-2" class="headerlink" title="Take 2"></a>Take 2</h2><p>Other languages like C#, Java, etc. won’t allow you to assign a mere empty array to a collection due to rules around strong typing (i.e. <code>[]</code>).</p><p>In those cases, you can use something like this version of the Null Object Pattern:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">class</span> <span class="token class-name">EmptyArray</span><span class="token operator">&lt;</span>T<span class="token operator">></span> <span class="token punctuation">{</span>    <span class="token keyword">static</span> create<span class="token operator">&lt;</span>T<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">Array</span><span class="token operator">&lt;</span>T<span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token comment" spellcheck="true">// Use it like this:</span><span class="token keyword">const</span> myEmptyArray<span class="token punctuation">:</span> <span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> EmptyArray<span class="token punctuation">.</span>create<span class="token operator">&lt;</span><span class="token keyword">string</span><span class="token operator">></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><h2 id="What-About-Objects"><a href="#What-About-Objects" class="headerlink" title="What About Objects?"></a>What About Objects?</h2><p>Imagine that you are working on a video game. In it, some levels might have a boss.</p><p>When checking if the current level has a boss, you might see something like this:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">if</span><span class="token punctuation">(</span>currentLevel<span class="token punctuation">.</span>boss <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    currentLevel<span class="token punctuation">.</span>boss<span class="token punctuation">.</span><span class="token function">fight</span><span class="token punctuation">(</span>player<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>We might find other places that do this null check:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">if</span><span class="token punctuation">(</span>currentLevel<span class="token punctuation">.</span>boss <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    currentLevel<span class="token punctuation">.</span>completed <span class="token operator">=</span> currentLevel<span class="token punctuation">.</span>boss<span class="token punctuation">.</span><span class="token function">isDead</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>If we introduce a null object, then we can simply remove all these null checks.</p><p>First, we need an interface to represent our <code>Boss</code>:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">interface</span> <span class="token class-name">IBoss</span> <span class="token punctuation">{</span>    <span class="token function">fight</span><span class="token punctuation">(</span>player<span class="token punctuation">:</span> Player<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token function">isDead</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Then, we can create our concrete boss class:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">class</span> <span class="token class-name">Boss</span> <span class="token keyword">implements</span> <span class="token class-name">IBoss</span> <span class="token punctuation">{</span>    <span class="token function">fight</span><span class="token punctuation">(</span>player<span class="token punctuation">:</span> Player<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Do some logic and return a bool.</span>    <span class="token punctuation">}</span>    <span class="token function">isDead</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Return whether boss is dead depending on how the fight went.</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Next, we’ll create an implementation of the <code>IBoss</code> interface that represents a “null” <code>Boss</code>:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">class</span> <span class="token class-name">NullBoss</span> <span class="token keyword">implements</span> <span class="token class-name">IBoss</span> <span class="token punctuation">{</span>    <span class="token function">fight</span><span class="token punctuation">(</span>player<span class="token punctuation">:</span> Player<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Player always wins.</span>    <span class="token punctuation">}</span>    <span class="token function">isDead</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">return</span> <span class="token keyword">true</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>The <code>NullBoss</code> will automatically allow the player to “win”, and we can remove all our null checks!</p><p>In the following code example, if the boss is an instance of <code>NullBoss</code> or <code>Boss</code> there are no extra checks to be made.</p><pre class=" language-typescript"><code class="language-typescript">currentLevel<span class="token punctuation">.</span>boss<span class="token punctuation">.</span><span class="token function">fight</span><span class="token punctuation">(</span>player<span class="token punctuation">)</span><span class="token punctuation">;</span>currentLevel<span class="token punctuation">.</span>completed <span class="token operator">=</span> currentLevel<span class="token punctuation">.</span>boss<span class="token punctuation">.</span><span class="token function">isDead</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p><em>Note: This section in the book contains more techniques to attack this code smell!</em></p><h1 id="How-To-Keep-Your-Code-Healthy"><a href="#How-To-Keep-Your-Code-Healthy" class="headerlink" title="How To Keep Your Code Healthy"></a>How To Keep Your Code Healthy</h1><p>This post was an excerpt from <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript</a> which is designed as an approachable and practical tool to help developers get better at building quality software. </p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0 20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div><h2 id="You-Might-Also-Enjoy"><a href="#You-Might-Also-Enjoy" class="headerlink" title="You Might Also Enjoy"></a>You Might Also Enjoy</h2><ul><li><a href="https://www.blog.jamesmichaelhickey.com/why-should-you-refactor-your-code/" target="_blank" rel="noopener">Why Should You Refactor Your Code?</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-first-steps/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 1: First Steps</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/Unhealthy-Code-Primitive-Overuse/" target="_blank" rel="noopener">Unhealthy Code: Primitive Overuse</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;h1 id=&quot;Identifying-The-Problem&quot;&gt;&lt;a href=&quot;#Identifying-The-Problem&quot; class=&quot;headerlink&quot; title=&quot;Identifying The Problem&quot;&gt;&lt;/a&gt;Identifying The Problem&lt;/h1&gt;&lt;h2 id=&quot;Billion-Dollar-Mistake&quot;&gt;&lt;a href=&quot;#Billion-Dollar-Mistake&quot; class=&quot;headerlink&quot; title=&quot;Billion Dollar Mistake&quot;&gt;&lt;/a&gt;Billion Dollar Mistake&lt;/h2&gt;&lt;p&gt;Did you know that the inventor of the concept of “null” has called this his &lt;a href=&quot;https://www.infoq.com/presentations/Null-References-The-Billion-Dollar-Mistake-Tony-Hoare/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;“Billion Dollar Mistake!”&lt;/a&gt;&lt;/p&gt;
&lt;p&gt;As simple as it seems, once you get into larger projects and codebases you’ll inevitably find some code that goes “off the deep end” in its use of nulls.&lt;/p&gt;
    
    </summary>
    
    
      <category term="refactoring, code quality, clean code" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring-code-quality-clean-code/"/>
    
  </entry>
  
  <entry>
    <title>Unhealthy Code: Primitive Overuse</title>
    <link href="https://blog.jamesmichaelhickey.com/Unhealthy-Code-Primitive-Overuse/"/>
    <id>https://blog.jamesmichaelhickey.com/Unhealthy-Code-Primitive-Overuse/</id>
    <published>2019-08-30T10:02:36.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>One of the classic “code smells” is called Primitive Overuse.</p><p>It’s deceptively simple.</p><a id="more"></a><hr><p><em>Note: This is an excerpt from my book <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript: Keeping Your Code Healthy.</a></em></p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><br><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><hr><h1 id="Identification-Of-Primitive-Overuse"><a href="#Identification-Of-Primitive-Overuse" class="headerlink" title="Identification Of Primitive Overuse"></a>Identification Of Primitive Overuse</h1><p>Take this code, for example:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> email<span class="token punctuation">:</span> <span class="token keyword">string</span> <span class="token operator">=</span> user<span class="token punctuation">.</span>email<span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>email <span class="token operator">!==</span> <span class="token keyword">null</span> <span class="token operator">&amp;&amp;</span> email <span class="token operator">!==</span> <span class="token string">""</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token comment" spellcheck="true">// Do something with the email.</span><span class="token punctuation">}</span></code></pre><p>Notice that we are handling the email’s raw data?</p><p>Or, consider this:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> firstname <span class="token operator">=</span> user<span class="token punctuation">.</span>firstname <span class="token operator">||</span> <span class="token string">""</span><span class="token punctuation">;</span><span class="token keyword">const</span> lastname <span class="token operator">=</span> user<span class="token punctuation">.</span>lastname <span class="token operator">||</span> <span class="token string">""</span><span class="token punctuation">;</span><span class="token keyword">const</span> fullName<span class="token punctuation">:</span> <span class="token keyword">string</span> <span class="token operator">=</span> firstname <span class="token operator">+</span> <span class="token string">" "</span> <span class="token operator">+</span> lastname<span class="token punctuation">;</span></code></pre><p>Notice all that extra checking around making sure the user’s names are not <code>null</code>? You’ve seen code like this, no doubt.</p><h2 id="What’s-Wrong-Here"><a href="#What’s-Wrong-Here" class="headerlink" title="What’s Wrong Here?"></a>What’s Wrong Here?</h2><p>What’s wrong with this code? There are a few things to think about:</p><ul><li><p>That logic is not sharable and therefore will be duplicated all over the place</p></li><li><p>In more complex scenarios, it’s hard to see what the underlying business concept represents (which leads to code that’s hard to understand)</p></li><li><p>If there is an underlying business concept, it’s implicit, not explicit</p></li></ul><h2 id="Business-Concepts-By-Chance"><a href="#Business-Concepts-By-Chance" class="headerlink" title="Business Concepts By Chance"></a>Business Concepts By Chance</h2><p>The business concept in the code example above is something like a user’s <em>display name</em> or <em>full name</em>.</p><p>However, that concept only exists temporarily in a variable <em>that just happened to be named correctly.</em> Will it be named the same thing in other places? If you have other developers on your team - <strong>probably not</strong>. </p><p>We have code that’s potentially hard to grasp from a business perspective, hard to understand in complex scenarios and is not sharable to other places in your application.</p><p>How can we deal with this?</p><h1 id="Deceptive-Booleans"><a href="#Deceptive-Booleans" class="headerlink" title="Deceptive Booleans"></a>Deceptive Booleans</h1><p>Primitive types should be the building blocks out of which we create more useful business-oriented concepts/abstractions in our code.</p><p>This helps each specific business concept to have all of its logic in one place (which means we can share it and reason about it much easier), implement more robust error handling, reduce bugs, etc.</p><p>I want to look at the most common cause of primitive overuse that I’ve experienced. I see it <em>all the time</em>.</p><h2 id="Scenario"><a href="#Scenario" class="headerlink" title="Scenario"></a>Scenario</h2><p>Imagine we’re working on a web application that helps clients to sell their used items online.</p><p>We’ve been asked to add some extra rules around the part of our system that authenticates users.</p><p>Right now, the system only checks if a user was successfully authenticated.</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> isAuthenticated<span class="token punctuation">:</span> <span class="token keyword">boolean</span> <span class="token operator">=</span> await <span class="token function">userIsAuthenticated</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>isAuthenticated<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><h2 id="New-Business-Rules"><a href="#New-Business-Rules" class="headerlink" title="New Business Rules"></a>New Business Rules</h2><p>Our company now wants us to check if users are active. Inactive users will not be able to log in.</p><p>Many developers will do something like this:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> user<span class="token punctuation">:</span> User <span class="token operator">=</span> await <span class="token function">userIsAuthenticated</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">const</span> isAuthenticated<span class="token punctuation">:</span> <span class="token keyword">boolean</span> <span class="token operator">=</span> user <span class="token operator">!==</span> <span class="token keyword">null</span><span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>isAuthenticated<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span>isActive<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>        <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"User is not active."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Oh no. We’ve introduced code smells that we know are going to cause maintainability issues!</p><p>We’ve got some null checks and nested conditions in there now (which are both signs of unhealthy code that are addressed in the <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript</a> book.)</p><p>So, let’s refactor that first by applying (a) the special case pattern and (b) guard clauses (both of these techniques are explained at length in <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">the book</a> too.)</p><pre class=" language-typescript"><code class="language-typescript"><span class="token comment" spellcheck="true">// This will now always return a User, but it may be a special case type</span><span class="token comment" spellcheck="true">// of User that will return false for "user.isAuthenticated()", etc.</span><span class="token keyword">const</span> user<span class="token punctuation">:</span> User <span class="token operator">=</span> await <span class="token function">userIsAuthenticated</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true">// We've created guard clauses here.</span><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>user<span class="token punctuation">.</span><span class="token function">isAuthenticated</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>user<span class="token punctuation">.</span><span class="token function">isActive</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"User is not active."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Much better.</p><h2 id="More-Rules…"><a href="#More-Rules…" class="headerlink" title="More Rules…"></a>More Rules…</h2><p>Now that your managers have seen how fast you were able to add that new business rule, they have a few more they need.</p><ol><li><p>If the user’s session already exists, then send the user to a special home page.</p></li><li><p>If the user has locked their account due to too many login attempts, send them to a special page.</p></li><li><p>If this is a user’s first login, then send them to a special welcome page.</p></li></ol><p><strong>Yikes!</strong></p><blockquote><p>If you’ve been in the industry for a few years, then you know how common this is!</p></blockquote><p>At first glance, we might do something naïve:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token comment" spellcheck="true">// This will now always return a User, but it may be a special case type</span><span class="token comment" spellcheck="true">// of User that will return false for "user.isAuthenticated()", etc.</span><span class="token keyword">const</span> user<span class="token punctuation">:</span> User <span class="token operator">=</span> await <span class="token function">userIsAuthenticated</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token comment" spellcheck="true">// We've created guard clauses here.</span><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>user<span class="token punctuation">.</span><span class="token function">isAuthenticated</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>user<span class="token punctuation">.</span><span class="token function">isActive</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"User is not active."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span><span class="token function">alreadyHadSession</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToHomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span><span class="token function">isLockedOut</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToUserLockedOutPage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>user<span class="token punctuation">.</span><span class="token function">isFirstLogin</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToWelcomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Notice that because we introduced guard clauses, it’s much easier to add new logic here? That’s one of the awesome benefits of making your code high-quality - it leads to future changes being <em>much</em> easier to change and add new logic to.</p><p>But, in this case, there’s an issue. Can you spot it?</p><p><strong>Our <code>User</code> class is becoming a dumping ground for all our authentication logic.</strong></p><h2 id="Is-It-Really-That-Bad"><a href="#Is-It-Really-That-Bad" class="headerlink" title="Is It Really That Bad?"></a>Is It Really That Bad?</h2><p>Is it that bad? <em>Yep.</em></p><p>Think about it: what other places in your app will need this data? Nowhere - it’s all authentication logic.</p><p>One refactoring would be to create a new class called <code>AuthenticatedUser</code> and put only authentication-related logic in that class.</p><p>This would follow the Single Responsibility Principle.</p><p>But, there’s a much simpler fix we could make for this specific scenario.</p><h2 id="Just-Use-Enums"><a href="#Just-Use-Enums" class="headerlink" title="Just Use Enums"></a>Just Use Enums</h2><p>Any time I see this pattern (the result of a method is a boolean or is an object that has booleans which are checked/tested immediately), it’s a much better practice to replace the booleans with an enum.</p><p>From our last code snippet above, let’s change the method <code>userIsAuthenticated</code> to something that more accurately describes what we are trying to do: <code>tryAuthenticateUser</code>.</p><p>And, instead of returning either a <code>boolean</code> or a <code>User</code> - we’ll send back an enum that tells us exactly what the results were (since that’s all we are interested in knowing).</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">enum</span> AuthenticationResult <span class="token punctuation">{</span>    InvalidCredentials<span class="token punctuation">,</span>    UserIsNotActive<span class="token punctuation">,</span>    HasExistingSession<span class="token punctuation">,</span>    IsLockedOut<span class="token punctuation">,</span>    IsFirstLogin<span class="token punctuation">,</span>    Successful<span class="token punctuation">}</span></code></pre><p>There’s our new enum that will specify all the possible results from attempting to authenticate a user.</p><p>Next, we’ll use that enum:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> result<span class="token punctuation">:</span> AuthenticationResult <span class="token operator">=</span> await <span class="token function">tryAuthenticateUser</span><span class="token punctuation">(</span>username<span class="token punctuation">,</span> password<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>result <span class="token operator">===</span> AuthenticationResult<span class="token punctuation">.</span>InvalidCredentials<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>result <span class="token operator">===</span> AuthenticationResult<span class="token punctuation">.</span>UserIsNotActive<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"User is not active."</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>result <span class="token operator">===</span> AuthenticationResult<span class="token punctuation">.</span>HasExistingSession<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToHomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>result <span class="token operator">===</span> AuthenticationResult<span class="token punctuation">.</span>IsLockedOut<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToUserLockedOutPage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">if</span><span class="token punctuation">(</span>result <span class="token operator">===</span> AuthenticationResult<span class="token punctuation">.</span>IsFirstLogin<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token function">redirectToWelcomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Notice how much more readable that is? And, we aren’t polluting our <code>User</code> class anymore with a bunch of extra data that is unnecessary!</p><p>We are returning <em>one value</em>. This is a great way to simplify your code. </p><p>This is one of my favorite refactorings! I hope you will find it useful too.</p><h2 id="Bonus-Strategy-Pattern"><a href="#Bonus-Strategy-Pattern" class="headerlink" title="Bonus: Strategy Pattern"></a>Bonus: Strategy Pattern</h2><p>Whenever I use this refactoring, I know automatically that the strategy pattern may help us some more.</p><p>Imagine the code above had <em>lots</em> more business rules and paths.</p><p>We can further simplify it by using a form of the strategy pattern:</p><pre class=" language-typescript"><code class="language-typescript"><span class="token keyword">const</span> strategies<span class="token punctuation">:</span> <span class="token keyword">any</span> <span class="token operator">=</span> <span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>InvalidCredentials<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"Credentials are not valid."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>UserIsNotActive<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">returnErrorOnLoginPage</span><span class="token punctuation">(</span><span class="token string">"User is not active."</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>HasExistingSession<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">redirectToHomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>IsLockedOut<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">redirectToUserLockedOutPage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>IsFirstLogin<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">redirectToWelcomePage</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>AuthenticationResult<span class="token punctuation">.</span>Successful<span class="token punctuation">]</span> <span class="token operator">=</span>     <span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> <span class="token function">redirectToUserDashboard</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>strategies<span class="token punctuation">[</span>result<span class="token punctuation">]</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><h1 id="How-To-Keep-Your-Code-Healthy"><a href="#How-To-Keep-Your-Code-Healthy" class="headerlink" title="How To Keep Your Code Healthy"></a>How To Keep Your Code Healthy</h1><p>This post was an excerpt from <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript</a> which is designed as an approachable and practical tool to help developers get better at building quality software. </p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0 20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div><h2 id="You-Might-Also-Enjoy"><a href="#You-Might-Also-Enjoy" class="headerlink" title="You Might Also Enjoy"></a>You Might Also Enjoy</h2><ul><li><a href="https://www.blog.jamesmichaelhickey.com/why-should-you-refactor-your-code/" target="_blank" rel="noopener">Why Should You Refactor Your Code?</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-first-steps/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 1: First Steps</a></li><li><a href="https://builtwithdot.net/blog/where-do-i-put-my-business-rules-and-validation" target="_blank" rel="noopener">Where Do I Put My Business Rules And Validation?</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;One of the classic “code smells” is called Primitive Overuse.&lt;/p&gt;
&lt;p&gt;It’s deceptively simple.&lt;/p&gt;
    
    </summary>
    
    
      <category term="refactoring, code quality, clean code" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring-code-quality-clean-code/"/>
    
  </entry>
  
  <entry>
    <title>Why Should You Refactor Your Code?</title>
    <link href="https://blog.jamesmichaelhickey.com/why-should-you-refactor-your-code/"/>
    <id>https://blog.jamesmichaelhickey.com/why-should-you-refactor-your-code/</id>
    <published>2019-08-29T08:43:10.000Z</published>
    <updated>2022-09-07T01:11:18.500Z</updated>
    
    <content type="html"><![CDATA[<p><strong>Refactoring</strong> is just a fancy term that means improving your code without changing how it behaves. </p><p>Let’s look at some reasons for why you should learn about when and how to refactor effectively.<br><a id="more"></a></p><p><em>Note: This is an excerpt from my book <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript: Keeping Your Code Healthy.</a></em></p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><br><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><h1 id="Slow-Development"><a href="#Slow-Development" class="headerlink" title="Slow Development?"></a>Slow Development?</h1><p>Ever work in a software system where your business asked you to build a new feature - but once you started digging into the existing code you discovered that it’s not going to be so easy to implement?</p><p>Many times, this is because our existing code is not flexible enough to handle new behaviors the business wants to include in your application.</p><p>Why? </p><p><em>Well, sometimes we take shortcuts and hack stuff in.</em></p><p>Perhaps we don’t have the knowledge and skills to know how to write healthy code?</p><p>Other times, timelines need to be met at the cost of introducing these shortcuts.</p><p>This is why refactoring is so important:</p><p><strong>Refactoring can help your currently restrictive code to become flexible and able/easy to extend once again.</strong></p><p>It’s just like a garden. Sometimes you just need to get rid of the weeds!</p><blockquote><p>I’ve been in a software project where adding a checkbox to a screen was not possible given the system’s set up at the time! Adding a button to a screen took days to figure out! And this was as a senior developer with a good number of years under my belt. Sadly, some systems are just very convoluted and hacked together.</p></blockquote><blockquote><p>This is what happens when we don’t keep our code healthy!</p></blockquote><h1 id="Saving-Money"><a href="#Saving-Money" class="headerlink" title="Saving Money"></a>Saving Money</h1><p>It’s a practical reality that you need to meet deadlines and get a functioning product out to customers. This could mean having to take shortcuts from time-to-time, depending on the context. Bringing value to your customers is what makes money for your company after-all.</p><p>Long-term, however, these “quick-fixes” or shortcuts lead to code that can be rigid, hard to understand, more prone to contain bugs, etc.</p><p>Improving and keeping code quality high leads to:</p><ul><li>Fewer bugs</li><li>Ability to add new features faster</li><li>Able to keep changes to existing code isolated</li><li>Code that’s easier to reason about</li></ul><p>All of these benefits lead to less time spent on debugging, fixing problems, developers trying to understand how the code works, etc.</p><p><em>E.g. It saves your company real money!</em></p><h2 id="Aside-Navy-SEALS-Get-It"><a href="#Aside-Navy-SEALS-Get-It" class="headerlink" title="Aside: Navy SEALS Get It"></a>Aside: Navy SEALS Get It</h2><p>There’s an adage that comes from the Navy SEALs which many have noticed also applies to creating software:</p><blockquote><p>Slow is smooth. Smooth is fast.</p></blockquote><p>Taking time to build quality code upfront will help your company move faster in the long-term. But even then, we don’t anticipate all future changes to the code and still need to refactor from time-to-time.</p><h1 id="Being-A-Craftsman"><a href="#Being-A-Craftsman" class="headerlink" title="Being A Craftsman"></a>Being A Craftsman</h1><p>Software development is a critical part of our society.</p><p>Developers build code that controls:</p><ul><li>Vehicles</li><li>Power Grids</li><li>Government Secrets</li><li>Home Security</li><li>Weapons</li><li>Banking Accounts</li><li>Etc.</li></ul><p>I’m sure you can think of more cases where the software a developer creates is tied to the security and well-being of an individual or group of people.</p><p>Would you expect your doctor to haphazardly prescribe you medications without carefully ensuring that he/she knows what your medical condition is?</p><p>Wouldn’t you want to have a vehicle mechanic who takes the time to ensure your vehicle’s tires won’t fall off while you are driving?</p><p>Being a craftsman is just another way to say that we should be professional and care about our craft. </p><p>We should value quality software that will work as intended!</p><blockquote><p>I’ve had it happen before that my car’s axel was replaced and, while I was driving away, the new axel fell right out of my car! Is that the kind of mechanic I can trust my business to? Nope!</p></blockquote><blockquote><p>Likewise, the quality of software that we build can directly impact people’s lives in real ways.</p></blockquote><h1 id="Case-Study-1"><a href="#Case-Study-1" class="headerlink" title="Case Study #1"></a>Case Study #1</h1><p>You might be familiar with an incident from 2018 where <a href="https://www.bloomberg.com/news/articles/2019-06-28/boeing-s-737-max-software-outsourced-to-9-an-hour-engineers" target="_blank" rel="noopener">a Boeing 737 crashed and killed all people on board</a>. </p><p>It was found that Boeing had outsourced its software development to developers who were not experienced in this particular industry: </p><blockquote><p>Increasingly, the iconic American planemaker and its subcontractors have relied on temporary workers making as little as $9 an hour to develop and test software, often from countries lacking a deep background in aerospace.</p></blockquote><p>Also, these developers were having to redo improperly written code over and over again:</p><blockquote><p>The coders from HCL were typically designing to specifications set by Boeing. Still, “it was controversial because it was far less efficient than Boeing engineers just writing the code,” Rabin said. Frequently, he recalled, “it took many rounds going back and forth because the code was not done correctly.”</p></blockquote><p>One former software engineer with Boeing is quoted as saying:</p><blockquote><p>I was shocked that in a room full of a couple hundred mostly senior engineers we were being told that we weren’t needed.</p></blockquote><p>While I have no beef with software developers from particular countries, it does concern me when a group of developers are lacking the knowledge or tools to build quality software in such critical systems.</p><p>For Boeing in general, what did this overall lack of quality and craftsmanship lead to?</p><p><strong>The company’s stocks took a huge dip a couple of days after the crash.</strong></p><p>Oh, and don’t forget - <strong>people died.</strong> No one can undo or fix this.</p><p>After it’s all said and done, Boeing did not benefit from cutting costs, trying to rush their software development and focus on speed rather than quality.</p><p>As software development professionals, we should seek to do our part and value being software craftsmen and craftswomen who focus on creating quality software.</p><h1 id="Case-Study-2"><a href="#Case-Study-2" class="headerlink" title="Case Study #2"></a>Case Study #2</h1><p>Do you still think that because airplanes can potentially kill people that the software built is going to be quality? Nope.</p><p>Here’s another example of software quality issues in the aviation field: <a href="https://gizmodo.com/turn-it-off-and-on-again-every-149-hours-is-a-concernin-1836818094" target="_blank" rel="noopener">$300 million Airbus software bug solved by “turning it off and on again every 149 hours.”</a></p><p>Sound’s kind of like a memory leak? You know, when you have a web application that starts getting slow and clunky after keeping it opened for a while. Just refresh the page and <em>voila</em>! Everything’s fine again!</p><p>Sadly, we are building airplanes like that too…</p><p>Quoting the article:</p><blockquote><p>Airlines who haven’t performed a recent software update on certain models of the Airbus A350 are being told they must completely power cycle the aircraft every 149 hours or risk “…partial or total loss of some avionics systems or functions,” according to the EASA.</p></blockquote><p>Do <strong>you</strong> want to fly on those planes?</p><p>Quality matters. And the fact is, many developers are <strong>not</strong> writing quality software. </p><h1 id="How-To-Keep-Your-Code-Healthy"><a href="#How-To-Keep-Your-Code-Healthy" class="headerlink" title="How To Keep Your Code Healthy"></a>How To Keep Your Code Healthy</h1><p>This post was an excerpt from <a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener">Refactoring TypeScript</a> which is designed as an approachable and practical tool to help developers get better at building quality software. </p><p><a href="https://leanpub.com/refactoringtypescript" target="_blank" rel="noopener"><img src="/img/refactoringts.png" alt="Refactoring TypeScript book"></a></p><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0 20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div><h2 id="You-Might-Also-Enjoy"><a href="#You-Might-Also-Enjoy" class="headerlink" title="You Might Also Enjoy"></a>You Might Also Enjoy</h2><ul><li><a href="https://www.blog.jamesmichaelhickey.com/Do-You-Struggle-Naming-Your-Classes-Well/" target="_blank" rel="noopener">Do You Struggle Naming Your Classes Well?</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-first-steps/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 1: First Steps</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/Unhealthy-Code-Primitive-Overuse/" target="_blank" rel="noopener">Unhealthy Code: Primitive Overuse</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;&lt;strong&gt;Refactoring&lt;/strong&gt; is just a fancy term that means improving your code without changing how it behaves. &lt;/p&gt;
&lt;p&gt;Let’s look at some reasons for why you should learn about when and how to refactor effectively.&lt;br&gt;
    
    </summary>
    
    
      <category term="refactoring, code quality, clean code" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring-code-quality-clean-code/"/>
    
  </entry>
  
  <entry>
    <title>.NET Core Worker Services: Background Job Scheduler With Coravel</title>
    <link href="https://blog.jamesmichaelhickey.com/NET-Core-Worker-Services-Background-Job-Scheduler-With-Coravel/"/>
    <id>https://blog.jamesmichaelhickey.com/NET-Core-Worker-Services-Background-Job-Scheduler-With-Coravel/</id>
    <published>2019-06-12T16:06:23.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>The .NET Core CLI comes with tons of pre-built project templates! One of the new templates that will be included with <a href="https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0" target="_blank" rel="noopener">.NET Core 3</a> will be for building worker services.</p><p>Combining .NET Core worker services with <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> can help you build lightweight background job scheduling applications very quickly. Let’s take a look at how you can do this in just a few minutes!</p><a id="more"></a><p><em>Note: Worker services are lightweight console applications that perform some type of background work like reading from a queue and processing work (like sending e-mails), performing some scheduled background jobs from our system, etc. These might be run as a daemon, windows service, etc.</em></p><h1 id="Installing-NET-Core-3-Preview"><a href="#Installing-NET-Core-3-Preview" class="headerlink" title="Installing .NET Core 3 Preview"></a>Installing .NET Core 3 Preview</h1><p>At the writing on this article, .NET Core 3 is in preview. First, you must <a href="https://dotnet.microsoft.com/download/dotnet-core/3.0" target="_blank" rel="noopener">install the SDK</a>. You can use Visual Studio Code for everything else in this article 👍.</p><h1 id="Coravel’s-Task-Scheduling"><a href="#Coravel’s-Task-Scheduling" class="headerlink" title="Coravel’s Task Scheduling"></a>Coravel’s Task Scheduling</h1><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> is a .NET Core library that gives you advanced application features out-of-the-box with near-zero config. <a href="https://www.blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/" target="_blank" rel="noopener">I was inspired by Laravel’s ease of use</a> and wanted to bring that simple and accessible approach of building web applications to .NET Core.</p><p>One of those features is a task scheduler that is configured 100% by code.</p><p>By leveraging Coravel’s ease-of-use with the simplicity of .NET Core’s worker service project template, I’ll show you how easily and quickly you can build a small back-end console application that will run your scheduled background jobs!</p><h1 id="Worker-Service-Template"><a href="#Worker-Service-Template" class="headerlink" title="Worker Service Template"></a>Worker Service Template</h1><p>First, create an empty folder to house your new project.</p><p>Then run:</p><p><code>dotnet new worker</code></p><p>Your worker project is all set to go! 🤜🤛</p><p>Check out <em>Program.cs</em> and you’ll see this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">Main</span><span class="token punctuation">(</span><span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token function">CreateHostBuilder</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">public</span> <span class="token keyword">static</span> IHostBuilder <span class="token function">CreateHostBuilder</span><span class="token punctuation">(</span><span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>    Host<span class="token punctuation">.</span><span class="token function">CreateDefaultBuilder</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span>        <span class="token punctuation">.</span><span class="token function">ConfigureServices</span><span class="token punctuation">(</span>services <span class="token operator">=</span><span class="token operator">></span>        <span class="token punctuation">{</span>            services<span class="token punctuation">.</span><span class="token generic-method function">AddHostedService<span class="token punctuation">&lt;</span>Worker<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><h1 id="Configuring-Coravel"><a href="#Configuring-Coravel" class="headerlink" title="Configuring Coravel"></a>Configuring Coravel</h1><p>Let’s add Coravel by running <code>dotnet add package coravel</code>.</p><p>Next, in <em>Program.cs</em>, we’ll modify the generic code that was generated for us and configure Coravel:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">Main</span><span class="token punctuation">(</span><span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span><span class="token punctuation">{</span>    IHost host <span class="token operator">=</span> <span class="token function">CreateHostBuilder</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    host<span class="token punctuation">.</span>Services<span class="token punctuation">.</span><span class="token function">UseScheduler</span><span class="token punctuation">(</span>scheduler <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// We'll fill this in later ;)</span>    <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    host<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">public</span> <span class="token keyword">static</span> IHostBuilder <span class="token function">CreateHostBuilder</span><span class="token punctuation">(</span><span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>    Host<span class="token punctuation">.</span><span class="token function">CreateDefaultBuilder</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span>        <span class="token punctuation">.</span><span class="token function">ConfigureServices</span><span class="token punctuation">(</span>services <span class="token operator">=</span><span class="token operator">></span>        <span class="token punctuation">{</span>            services<span class="token punctuation">.</span><span class="token function">AddScheduler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token punctuation">;</span></code></pre><p>Since Coravel is a native .NET Core set of tools, it <em>just works™</em> with zero fuss!</p><h1 id="Adding-An-Invocable"><a href="#Adding-An-Invocable" class="headerlink" title="Adding An Invocable"></a>Adding An Invocable</h1><p>One of Coravel’s fundamental concepts is <a href="https://docs.coravel.net/Invocables/" target="_blank" rel="noopener">Invocables</a>.</p><p>Each invocable represents a self-contained job within your system that Coravel leverages to make your code much easier to write, compose and maintain.</p><p>Next, then, create a class that implements <code>Coravel.Invocable.IInvocable</code>:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">MyFirstInvocable</span> <span class="token punctuation">:</span> IInvocable<span class="token punctuation">{</span>    <span class="token keyword">public</span> Task <span class="token function">Invoke</span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">{</span>        Console<span class="token punctuation">.</span><span class="token function">WriteLine</span><span class="token punctuation">(</span><span class="token string">"This is my first invocable!"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">return</span> Task<span class="token punctuation">.</span>CompletedTask<span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Since we are going to simulate some async work, we’ll just log a message to the console and then return <code>Task.CompletedTask</code> to the caller.</p><h1 id="Scheduling-Your-Invocable"><a href="#Scheduling-Your-Invocable" class="headerlink" title="Scheduling Your Invocable"></a>Scheduling Your Invocable</h1><p>Here’s where Coravel really shines 😉. </p><p>Let’s schedule our new invocable to run every 5 seconds. Inside of our <em>Program.cs</em> main method we’ll add:</p><pre class=" language-csharp"><code class="language-csharp">host<span class="token punctuation">.</span>Services<span class="token punctuation">.</span><span class="token function">UseScheduler</span><span class="token punctuation">(</span>scheduler <span class="token operator">=</span><span class="token operator">></span> <span class="token punctuation">{</span>    <span class="token comment" spellcheck="true">// Yes, it's this easy!</span>    scheduler        <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>MyFirstInvocable<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>        <span class="token punctuation">.</span><span class="token function">EveryFiveSeconds</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Don’t forget to register your invocable with .NET Core’s service container:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token punctuation">.</span><span class="token function">ConfigureServices</span><span class="token punctuation">(</span>services <span class="token operator">=</span><span class="token operator">></span><span class="token punctuation">{</span>    services<span class="token punctuation">.</span><span class="token function">AddScheduler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">// Add this 👇</span>    services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>MyFirstInvocable<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>In your terminal, run <code>dotnet run</code>.</p><p>You should see the output in your terminal every five seconds!</p><h1 id="Real-World-Invocable"><a href="#Real-World-Invocable" class="headerlink" title="Real-World Invocable"></a>Real-World Invocable</h1><p>Sure, writing to the console is great - but you are going to be making API calls, database queries, etc. after all.</p><p>Let’s modify our invocable so that we can do something more interesting:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">SendDailyReportEmailJob</span> <span class="token punctuation">:</span> IInvocable<span class="token punctuation">{</span>    <span class="token keyword">private</span> IMailer _mailer<span class="token punctuation">;</span>    <span class="token keyword">private</span> IUserRepository _repo<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">SendDailyReportEmailJob</span><span class="token punctuation">(</span>IMailer mailer<span class="token punctuation">,</span> IUserRepository repo<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_mailer <span class="token operator">=</span> mailer<span class="token punctuation">;</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_repo <span class="token operator">=</span> repo<span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task <span class="token function">Invoke</span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">var</span> users <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_repo<span class="token punctuation">.</span><span class="token function">GetUsersAsync</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">foreach</span><span class="token punctuation">(</span><span class="token keyword">var</span> user <span class="token keyword">in</span> users<span class="token punctuation">)</span>        <span class="token punctuation">{</span>            <span class="token keyword">var</span> mailable <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">DailyReportMailable</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>            <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_mailer<span class="token punctuation">.</span><span class="token function">SendAsync</span><span class="token punctuation">(</span>mailable<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Since this class will hook into .NET Core’s service container, all the constructor dependencies will be injected via dependency injection.</p><p>If you wanted to build a lightweight background application that processes and emails daily reports for all your users then this might be a great option.</p><h1 id="Configuring-As-A-Windows-Service"><a href="#Configuring-As-A-Windows-Service" class="headerlink" title="Configuring As A Windows Service"></a>Configuring As A Windows Service</h1><p>While beyond the scope of this article, you can take a look at how .NET Core 3 will <a href="https://docs.microsoft.com/en-us/aspnet/core/host-and-deploy/windows-service?view=aspnetcore-3.0&amp;tabs=visual-studio-code#app-configuration" target="_blank" rel="noopener">allow configuring your worker as a windows service</a>.</p><p>And, apparently, <a href="https://github.com/aspnet/Extensions/pull/1804" target="_blank" rel="noopener">there’s upcoming support for systemd too!</a></p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>What do you guys think about .NET Core’s worker services? </p><p>I find they are so easy to get up-and-running. Coupled with the accessibility designed into Coravel, I find these two make an awesome pair for doing some cool stuff!</p><p>All of Coravel’s features can be used within these worker services - such as <a href="https://docs.coravel.net/Queuing/" target="_blank" rel="noopener">queuing tasks</a>, <a href="https://docs.coravel.net/Events/" target="_blank" rel="noopener">event broadcasting</a>, <a href="https://docs.coravel.net/Mailing/" target="_blank" rel="noopener">mailing</a>, etc.</p><p>One thing I’d love to try is to integrate <a href="https://www.pro.coravel.net/" target="_blank" rel="noopener">Coravel Pro</a> with a worker service. One step at a time though 🤣.</p><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on:</p><ul><li><a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">Twitter</a></li><li><a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;The .NET Core CLI comes with tons of pre-built project templates! One of the new templates that will be included with &lt;a href=&quot;https://docs.microsoft.com/en-us/dotnet/core/whats-new/dotnet-core-3-0&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;.NET Core 3&lt;/a&gt; will be for building worker services.&lt;/p&gt;
&lt;p&gt;Combining .NET Core worker services with &lt;a href=&quot;https://github.com/jamesmh/coravel&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Coravel&lt;/a&gt; can help you build lightweight background job scheduling applications very quickly. Let’s take a look at how you can do this in just a few minutes!&lt;/p&gt;
    
    </summary>
    
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core/"/>
    
      <category term="Coravel" scheme="https://blog.jamesmichaelhickey.com/tags/Coravel/"/>
    
      <category term=".NET Core Job Scheduler" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core-Job-Scheduler/"/>
    
  </entry>
  
  <entry>
    <title>Do You Struggle Naming Your Classes Well?</title>
    <link href="https://blog.jamesmichaelhickey.com/Do-You-Struggle-Naming-Your-Classes-Well/"/>
    <id>https://blog.jamesmichaelhickey.com/Do-You-Struggle-Naming-Your-Classes-Well/</id>
    <published>2019-06-05T12:10:06.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>Ever find yourself scratching your head while wondering what you should name that new class?</p><a id="more"></a><p>We all struggle with this!</p><p>In fact, <a href="https://www.martinfowler.com/bliki/TwoHardThings.html" target="_blank" rel="noopener">it’s one of the two hardest parts of programming!</a></p><p>Sometimes it’s easy because you have a clear business concept in mind. </p><p>Other times you might be creating classes that aren’t necessarily tied to a business concept.</p><p>You might decide to split a class into several classes (for maintainability’s sake). </p><p>Or, you may need to use a design pattern.</p><p>🤦‍♂️</p><h1 id="Tips-To-The-Rescue"><a href="#Tips-To-The-Rescue" class="headerlink" title="Tips To The Rescue!"></a>Tips To The Rescue!</h1><p>Writing code usually involved some specific scenario(s) that you are trying to solve. Here are some tips for tackling these kinds of business scenarios by naming your classes well:</p><ol><li>Be as specific as possible!</li><li>Don’t be afraid to be verbose at first. You can refactor later.</li><li>Try pretending that you are writing the outline for an article that explains your business process to a non-programmer. Start by naming things with the terms from this.</li></ol><h2 id="Example"><a href="#Example" class="headerlink" title="Example"></a>Example</h2><p>Here’s what a sample of using tip #3 might look like:</p><blockquote><p>Once an order is submitted by the customer, we need to make sure that all the order’s items are in stock. If some are not in stock, then we need to send them an email to let them know what items are on back-order.</p></blockquote><blockquote><p>Next, we will pass the information to the shipping department for further handling.</p></blockquote><p>We can use this description to create some classes from the nouns. Sometimes, depending on how you want to organize your code, it’s very worthwhile to use the adjectives too!</p><ul><li><code>Order</code> or <code>SubmittedOrder</code></li><li><code>Customer</code> or <code>OrderCustomer</code></li><li><code>OrderItems</code></li><li><code>OrderItemsOnBackOrderEmail</code></li><li><code>ShippingDepartmentOrderHandler</code></li></ul><p>Keep in mind that the nouns/terms are all applicable to the specific context (see <a href="https://www.martinfowler.com/bliki/BoundedContext.html" target="_blank" rel="noopener">bounded contexts from DDD</a>) you are trying to solve for.</p><p>The code we write might look like this at first pass:</p><pre class=" language-js"><code class="language-js"><span class="token keyword">class</span> <span class="token class-name">OrderSubmittedHandler</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> <span class="token function">handle</span><span class="token punctuation">(</span>order<span class="token punctuation">:</span> Order<span class="token punctuation">,</span> customer<span class="token punctuation">:</span> Customer<span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">const</span> submitted<span class="token punctuation">:</span> SubmittedOrder <span class="token operator">=</span> order<span class="token punctuation">.</span><span class="token function">submitOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">if</span><span class="token punctuation">(</span>submitted<span class="token punctuation">.</span><span class="token function">hasItemsOnBackOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            <span class="token keyword">const</span> mail <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">OrderItemsOnBackOrder</span><span class="token punctuation">(</span>submitted<span class="token punctuation">)</span><span class="token punctuation">;</span>            mail<span class="token punctuation">.</span><span class="token function">sendTo</span><span class="token punctuation">(</span>customer<span class="token punctuation">)</span><span class="token punctuation">;</span>            <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_mailer<span class="token punctuation">.</span><span class="token function">send</span><span class="token punctuation">(</span>mail<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span>        <span class="token keyword">const</span> shipping <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">ShippingDepartmentOrderHandler</span><span class="token punctuation">(</span>submitted<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">await</span> shipping<span class="token punctuation">.</span><span class="token function">sendOrderInfo</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Points of interest:</p><ul><li><p>Notice that we explicitly model the transition from an <code>Order</code> to a <code>SubmittedOrder</code>. Since a <code>SubmittedOrder</code> has different behaviours than an <code>Order</code>, this will keep your classes way smaller and manageable by following the <a href="https://www.weeklydevtips.com/episodes/049" target="_blank" rel="noopener">Single Responsibility Principle</a>.</p></li><li><p>We introduced cross-cutting objects like the <code>_mailer</code> variable. In this example, I already know that I am going to use dependency injection to supply the <code>Mailer</code>. But that can be something you decide to refactor later on.</p></li><li><p>The entire scenario itself is captured by a meaningful noun as a new class!</p><p> Of course, this can be refactored after-the-fact. But as a first pass, this technique can really help to solidify what to name things and how they ought to interact.</p></li><li><p>Being verbose actually works well!</p></li></ul><h1 id="Some-More-Guidelines"><a href="#Some-More-Guidelines" class="headerlink" title="Some More Guidelines"></a>Some More Guidelines</h1><p>Here are some guidelines that might help you when dealing with specific kinds of classes that may or may not be obvious from a business scenario.</p><p>For example, sometimes you need to introduce a design pattern. What do you name your class then?</p><table><thead><tr><th>Intent</th><th>Formula</th><th>Examples</th></tr></thead><tbody><tr><td>Authorization</td><td><code>Can{Entity}{Action}</code></td><td><code>CanAdminViewThisPage</code>, <code>CanManagerUpdateUserInfo</code></td></tr><tr><td>Validation</td><td><code>Is{Target}{State}{Test}</code></td><td><code>IsAddressUpdateAllowed</code>, <code>IsUserCreationValid</code></td></tr><tr><td>Interfaces</td><td><code>ICan{Action}</code></td><td><code>ICanSendMail</code>, <code>ICanBeValidated</code></td></tr><tr><td>Concrete Business Concept</td><td><em>“What is it?” (nouns + adjectives)</em></td><td><code>Student</code>, <code>EmployeeUserProfile</code>, <code>ShippingAddress</code></td></tr><tr><td>Use Cases</td><td><code>{Action}{Target}</code></td><td><code>ApproveOrder</code>, <code>SendWelcomeEmail</code></td></tr><tr><td>Design Pattern</td><td><code>{Name}{Pattern}</code></td><td><code>IShippingAddressStrategy</code>, <code>HomeAddressStrategy</code>, <code>TemporaryAddressStrategy</code></td></tr></tbody></table><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on:</p><ul><li><a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">Twitter</a></li><li><a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a></li></ul><p>You can also find me at my web site <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">www.jamesmichaelhickey.com</a>.</p><h1 id="Navigating-Your-Software-Development-Career-Newsletter"><a href="#Navigating-Your-Software-Development-Career-Newsletter" class="headerlink" title="Navigating Your Software Development Career Newsletter"></a>Navigating Your Software Development Career Newsletter</h1><p>An e-mail newsletter that will help you level-up in your career as a software developer! Ever wonder:</p><p>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br>✔ Is there someone willing to walk with me and answer my questions?</p><p>Sound interesting? <a href="https://eepurl.com/gdIV5X" target="_blank" rel="noopener">Join the community!</a></p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Ever find yourself scratching your head while wondering what you should name that new class?&lt;/p&gt;
    
    </summary>
    
    
      <category term="software design" scheme="https://blog.jamesmichaelhickey.com/tags/software-design/"/>
    
  </entry>
  
  <entry>
    <title>Practical Coding Patterns For Boss Developers #1: Special Case</title>
    <link href="https://blog.jamesmichaelhickey.com/Practical-Coding-Patterns-For-Boss-Developers-Special-Case/"/>
    <id>https://blog.jamesmichaelhickey.com/Practical-Coding-Patterns-For-Boss-Developers-Special-Case/</id>
    <published>2019-05-08T08:00:00.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>Design patterns are necessary (in my opinion) for you to start gaining an advanced understanding and ability to design and refactor software.</p><p>These patterns also give developers a common language to speak about certain code structures.</p><a id="more"></a><p><em>E.g. If you are facing a certain problem, and I say “Try the strategy pattern…” then I don’t have to spend an hour explaining what you should do.</em></p><p>You can go look it up or, if you already know the pattern, go implement it!</p><h1 id="Not-Your-Typical-Design-Patterns"><a href="#Not-Your-Typical-Design-Patterns" class="headerlink" title="Not Your Typical Design Patterns"></a>Not Your Typical Design Patterns</h1><p>Everyone is talking about the design patterns found in the famous gang of four book <a href="https://amzn.to/2WP2P8w" target="_blank" rel="noopener">Design Patterns</a>:</p><ul><li>Strategy</li><li>Builder</li><li>Factory</li><li>Adapter</li><li>etc.</li></ul><p>But, there are <strong>way more</strong> software design patterns not found in this book which I’ve found super helpful.</p><p>Some of them I’ve learned from <a href="https://www.martinfowler.com" target="_blank" rel="noopener">Martin Fowler</a>, others from <a href="https://amzn.to/2ZBH1yO" target="_blank" rel="noopener">Domain Driven Design</a>, and other sources.</p><p>I figured I’d start to catalogue some of these by sharing them!</p><p>As a general rule, I’m going to use TypeScript for my code samples.</p><h1 id="A-Close-Relative…"><a href="#A-Close-Relative…" class="headerlink" title="A Close Relative…"></a>A Close Relative…</h1><p>The pattern I want to start with is a close relative to the null object pattern that I’ve tweeted about before:</p><p><blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr"><a href="https://twitter.com/hashtag/csharp?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#csharp</a> <a href="https://twitter.com/hashtag/dotnet?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#dotnet</a> <br><br>C# tip 🔥 - a form of the null object pattern 👇 <a href="https://t.co/fLpO5ibLhO" target="_blank" rel="noopener">pic.twitter.com/fLpO5ibLhO</a></p>&mdash; James Hickey 🇨🇦👨‍💻 (@jamesmh_dev) <a href="https://twitter.com/jamesmh_dev/status/1067605234653061120?ref_src=twsrc%5Etfw" target="_blank" rel="noopener">November 28, 2018</a></blockquote></p><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><p>The null object pattern is a way of avoiding issues around <code>null</code> states (like all the extra <code>null</code> checking you need to do 😒).</p><p>You create a specialized version of a class to represent it in a “null” state, which exposes the same API or interface as the base object.</p><p>In other words, it’s kinda like a stub.</p><p>Here’s an example off the top of my head, in TypeScript:</p><pre class=" language-ts"><code class="language-ts"><span class="token comment" spellcheck="true">// Concrete Order</span><span class="token keyword">class</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">private</span> _items<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">;</span>    <span class="token keyword">constructor</span><span class="token punctuation">(</span>items<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_items <span class="token operator">=</span> items<span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// API call or whatever...</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token comment" spellcheck="true">// Null "version" of the Order</span><span class="token keyword">class</span> <span class="token class-name">NullOrder</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// We just do nothing!</span>        <span class="token comment" spellcheck="true">// No errors are thrown!</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token comment" spellcheck="true">// Usage:</span><span class="token keyword">const</span> orders<span class="token punctuation">:</span> Order<span class="token punctuation">[</span><span class="token punctuation">]</span> <span class="token operator">=</span> <span class="token punctuation">[</span>    <span class="token keyword">new</span> <span class="token class-name">Order</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token string">'fancy pants'</span><span class="token punctuation">,</span> <span class="token string">'t-shirt'</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">,</span> <span class="token keyword">new</span> <span class="token class-name">NullOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">]</span><span class="token punctuation">;</span><span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">const</span> order of orders<span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token comment" spellcheck="true">// This won't throw on nulls since we've</span>    <span class="token comment" spellcheck="true">// used the null object pattern.</span>    order<span class="token punctuation">.</span><span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><h1 id="An-Example-Scenario"><a href="#An-Example-Scenario" class="headerlink" title="An Example Scenario"></a>An Example Scenario</h1><p>Imagine we had a scheduled background process that fetches multiple orders and tries to place them. </p><p>Like Amazon, we might have a complex process around placing orders that isn’t as linear as we might think it would be.</p><p>We might want a buffer period between the time when you click “place order” and when the order is <strong>really</strong> placed. This will make cancelling an order an easy process (it avoids having to remove credit card charges, etc.)</p><p><em>Note: I might write about this pattern later.</em> 😉</p><p>In this scenario, we might be trying to process orders that have already been changed:</p><ul><li>Cancelled order</li><li>Payment declined</li><li>The payment gateway is not responding so we need to wait…</li><li>etc.</li></ul><p>The null object pattern can help with this kind of scenario.</p><p><strong>But even better, when you have multiple versions of these kinds of “special” cases, the special case pattern is here to save the day!</strong></p><h1 id="Special-Case-Pattern"><a href="#Special-Case-Pattern" class="headerlink" title="Special Case Pattern"></a>Special Case Pattern</h1><p>The special case pattern is essentially the same in implementation, but instead of modelling specific “null” states, we can use the same technique to model <em>any</em> special or non-typical cases.</p><p>Using the code example above, instead of having “null” versions of our <code>Order</code>, by using the special case pattern we can implement more semantic and targeted  variants of our <code>Order</code> class:</p><pre class=" language-ts"><code class="language-ts"><span class="token keyword">class</span> <span class="token class-name">IncompleteOrder</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Do nothing...</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">class</span> <span class="token class-name">CorruptedOrder</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Try to fix the corruption?</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">class</span> <span class="token class-name">OrderOnFraudulentAccount</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">super</span><span class="token punctuation">(</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Notify the fraud dept.?</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>As you can see, this pattern helps us to be very specific in how we model special cases in our code.</p><h1 id="Benefits"><a href="#Benefits" class="headerlink" title="Benefits"></a>Benefits</h1><p>Some benefits are:</p><ul><li>Avoiding <code>null</code> exception issues</li><li>Having classes with more targeted single responsibilities</li><li>Ability to handle special cases without our <code>Order</code> class blowing up with tons of logic</li><li>The semantics of the class names makes our code much more understandable to read</li><li>Introducing new cases involves creating new classes vs. changing existing classes (<a href="https://en.wikipedia.org/wiki/Open%E2%80%93closed_principle" target="_blank" rel="noopener">see open-closed principle</a>)</li></ul><h1 id="Refactoring-To-The-Special-Case-Pattern"><a href="#Refactoring-To-The-Special-Case-Pattern" class="headerlink" title="Refactoring To The Special Case Pattern"></a>Refactoring To The Special Case Pattern</h1><p>So, when should you use the pattern?</p><h3 id="Constructor"><a href="#Constructor" class="headerlink" title="Constructor"></a>Constructor</h3><p>You might consider this pattern whenever you see this type of logic in a class’ constructor:</p><pre class=" language-ts"><code class="language-ts"><span class="token keyword">constructor</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">fraudWasDetected</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_fraudDetected <span class="token operator">=</span> <span class="token keyword">true</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>fraudWasDetected <span class="token operator">=</span> <span class="token keyword">false</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p><em>Note: The refactoring for this will begin in the <a href="#oops-too-many-responsibilities">Oops, Too Many Responsibilities</a> section below.</em></p><h3 id="Outside-“Asking”"><a href="#Outside-“Asking”" class="headerlink" title="Outside “Asking”"></a>Outside “Asking”</h3><p>When you see something like the following, then you may want to consider the special case pattern:</p><pre class=" language-ts"><code class="language-ts"><span class="token keyword">const</span> order <span class="token operator">=</span> <span class="token function">getOrderFromDB</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">if</span><span class="token punctuation">(</span>order<span class="token punctuation">.</span><span class="token function">fraudWasDetected</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    order<span class="token punctuation">.</span><span class="token function">doFraudDetectedStuff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span>order<span class="token punctuation">.</span><span class="token function">hasItems</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>    order<span class="token punctuation">.</span><span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span> <span class="token comment" spellcheck="true">// ... and more ...</span></code></pre><p>Focusing on this example, why is this potentially a “code smell”?</p><p>At face value, this type of logic should be “baked into” the Order class(es).</p><p>Whoever is using the order shouldn’t have to know about this logic. This is all order specific logic. It shouldn’t be “asking” the <code>Order</code> for details and then deciding how to use the <code>Order</code>.</p><p>For more, see the <a href="https://www.martinfowler.com/bliki/TellDontAsk.html" target="_blank" rel="noopener">tell don’t ask principle</a> - which, most times, does indicate that your logic might be better suited inside the object you are using.</p><p>The first fix then is to move this logic to the <em>inside</em> of the <code>Order</code> class:</p><pre class=" language-ts"><code class="language-ts"><span class="token keyword">class</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_fraudWasDetected</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_doFraudDetectedStuff</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span><span class="token punctuation">(</span><span class="token operator">!</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_hasItems</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span>     <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><h3 id="Oops-Too-Many-Responsibilities"><a href="#Oops-Too-Many-Responsibilities" class="headerlink" title="Oops, Too Many Responsibilities!"></a>Oops, Too Many Responsibilities!</h3><p>But, now we run into some issues: we are dealing with different responsibilities (placing orders, fraud detection, item corruption, etc.) in one class! 😓</p><p><em>Note: What follows can be applied to the constructor refactor too.</em></p><p><strong>Special case pattern to the rescue!</strong></p><pre class=" language-ts"><code class="language-ts"><span class="token comment" spellcheck="true">// Note: I'm just highlighting the main parts, this won't compile 😋</span><span class="token keyword">class</span> <span class="token class-name">CorruptedOrder</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_fixCorruptedItems</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">super</span><span class="token punctuation">.</span><span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">class</span> <span class="token class-name">OrderOnFraudulentAccount</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_notifyFraudDepartment</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">class</span> <span class="token class-name">IncompleteOrder</span> <span class="token keyword">extends</span> <span class="token class-name">Order</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">placeOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Do nothing...</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><h3 id="Combining-Patterns"><a href="#Combining-Patterns" class="headerlink" title="Combining Patterns"></a>Combining Patterns</h3><p>Great! But how can we instantiate these different classes?</p><p>The beauty of design patterns is that they usually end up working together. In this case, we could use the factory pattern:</p><pre class=" language-ts"><code class="language-ts"><span class="token keyword">class</span> <span class="token class-name">OrderFactory</span> <span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token function">makeOrder</span><span class="token punctuation">(</span>accountId<span class="token punctuation">:</span> <span class="token keyword">number</span><span class="token punctuation">,</span> items<span class="token punctuation">:</span> <span class="token keyword">any</span><span class="token punctuation">[</span><span class="token punctuation">]</span><span class="token punctuation">)</span><span class="token punctuation">:</span> Order <span class="token punctuation">{</span>        <span class="token keyword">if</span> <span class="token punctuation">(</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">_fraudWasDetected</span><span class="token punctuation">(</span>accountId<span class="token punctuation">)</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">OrderOnFraudulentAccount</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span> <span class="token keyword">else</span> <span class="token keyword">if</span> <span class="token punctuation">(</span>items <span class="token operator">===</span> <span class="token keyword">null</span> <span class="token operator">||</span> items<span class="token punctuation">.</span>length <span class="token operator">===</span> <span class="token number">0</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>            <span class="token keyword">return</span> <span class="token keyword">new</span> <span class="token class-name">EmptyOrder</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token punctuation">}</span>        <span class="token comment" spellcheck="true">// and so on....</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p><em>Note: This is a pretty clear example of when you would really want to use the factory pattern - which I do find can be easily over-explained. Hopefully, this helps you to see why you would want to use a factory in the first place.</em></p><p>We have split our <code>Order</code> class into a few more special classes that can each handle one special case.</p><p>Even if the logic for, let’s say, processing a suspected fraudulent account/order is very complex, we have isolated that complexity into a targeted and specialized class.</p><p>As far as the consumers of the <code>Order</code> class(es) go - they have no idea what’s going on under the covers! They can simply call <code>order.placeOrder()</code> and let each class handle its own special case.</p><h1 id="Resources"><a href="#Resources" class="headerlink" title="Resources"></a>Resources</h1><ul><li><a href="https://amzn.to/2MZYQGr" target="_blank" rel="noopener">Patterns of Enterprise Application Architecture</a></li><li><a href="https://www.martinfowler.com/eaaCatalog/specialCase.html" target="_blank" rel="noopener">Special case pattern by Martin Fowler</a></li><li><a href="https://sourcemaking.com/design_patterns/null_object" target="_blank" rel="noopener">Null object design pattern</a></li></ul><h1 id="Thoughts"><a href="#Thoughts" class="headerlink" title="Thoughts?"></a>Thoughts?</h1><p>Have you ever encountered the special case pattern? Or perhaps any of the others I’ve mentioned?</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on:</p><ul><li><a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">Twitter</a></li><li><a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a></li></ul><p>You can also find me at my web site <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">www.jamesmichaelhickey.com</a>.</p><h1 id="Navigating-Your-Software-Development-Career-Newsletter"><a href="#Navigating-Your-Software-Development-Career-Newsletter" class="headerlink" title="Navigating Your Software Development Career Newsletter"></a>Navigating Your Software Development Career Newsletter</h1><p>An e-mail newsletter that will help you level-up in your career as a software developer! Ever wonder:</p><p>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br>✔ Is there someone willing to walk with me and answer my questions?</p><p>Sound interesting? <a href="https://eepurl.com/gdIV5X" target="_blank" rel="noopener">Join the community!</a></p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Design patterns are necessary (in my opinion) for you to start gaining an advanced understanding and ability to design and refactor software.&lt;/p&gt;
&lt;p&gt;These patterns also give developers a common language to speak about certain code structures.&lt;/p&gt;
    
    </summary>
    
    
      <category term="design patterns" scheme="https://blog.jamesmichaelhickey.com/tags/design-patterns/"/>
    
      <category term="refactoring" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring/"/>
    
  </entry>
  
  <entry>
    <title>Introducing Gate Classes</title>
    <link href="https://blog.jamesmichaelhickey.com/Introducing-Gate-Classes/"/>
    <id>https://blog.jamesmichaelhickey.com/Introducing-Gate-Classes/</id>
    <published>2019-04-10T16:11:10.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>Have you ever heard of guard clauses? Steve Smith discusses them in one of his Weekly Dev Tips <a href="https://www.weeklydevtips.com/004" target="_blank" rel="noopener">here</a>.</p><p>Today I want to show you a technique that I’ve been using which is similar to the guard clause pattern but is used in more advanced scenarios. These scenarios include when you have problems due to external dependencies or complex logic that is required in your guard clauses.</p><a id="more"></a><p>With guard clauses, we would take code that has nested conditional logic like this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">if</span><span class="token punctuation">(</span>order <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span>order<span class="token punctuation">.</span>Items <span class="token operator">!=</span> <span class="token keyword">null</span><span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">PlaceOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">else</span> <span class="token punctuation">{</span>        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ArgumentNullException</span><span class="token punctuation">(</span><span class="token string">"Order is null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">else</span> <span class="token punctuation">{</span>    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ArgumentNullException</span><span class="token punctuation">(</span><span class="token string">"Order is null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Then we would invert the conditional logic and try to “fail fast”:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">if</span><span class="token punctuation">(</span>order<span class="token operator">?</span><span class="token punctuation">.</span>Items <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ArgumentNullException</span><span class="token punctuation">(</span><span class="token string">"Order is null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">PlaceOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Notice that right-off-the-bat we will try to make the method fail? That’s what I mean by “failing fast”.</p><p>Next, we might create a reusable method out of this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">IsNullGuardClause</span><span class="token punctuation">(</span><span class="token keyword">this</span> <span class="token keyword">object</span> me<span class="token punctuation">,</span> <span class="token keyword">string</span> message<span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">if</span><span class="token punctuation">(</span>me <span class="token operator">==</span> <span class="token keyword">null</span><span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">ArgumentNullException</span><span class="token punctuation">(</span>message<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Finally, we can use this guard clause anywhere we need:</p><pre class=" language-csharp"><code class="language-csharp">order<span class="token operator">?</span><span class="token punctuation">.</span>Items<span class="token punctuation">.</span><span class="token function">IsNullGuardClause</span><span class="token punctuation">(</span><span class="token string">"Order is null"</span><span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">this</span><span class="token punctuation">.</span><span class="token function">PlaceOrder</span><span class="token punctuation">(</span>order<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>This will keep our code much cleaner, avoid any nested conditions, and be <em>way</em> easier to reason about!</p><h1 id="What-If-You-Have-Dependency-Baggage"><a href="#What-If-You-Have-Dependency-Baggage" class="headerlink" title="What If You Have Dependency Baggage?"></a>What If You Have Dependency Baggage?</h1><p>I love this pattern. </p><p>But, sometimes you might find yourself trying to build a type of guard clause which has certain external dependencies, like a repository or <code>HttpClient</code>. Perhaps the logic for the actual guard is quite complex too.</p><p>Examples might include determining if:</p><ul><li>A user has proper permissions to view a certain resource in your system</li><li>A potential order is capable of being purchased (in a simple retail system)</li><li>An insurance claim is capable of being approved</li><li>etc.</li></ul><p>What I like to do in these cases is use what I’ve been calling “Gate Classes.” They’re like guard clauses, but they are classes… Go figure.</p><p>Think of these as a series of gates which each request in the system has to go through (just like middleware). If any of them fail, the gate is closed and the request cannot proceed any further.</p><p>Let me show you what I mean.</p><h1 id="Checking-If-We-Can-Approve-An-Insurance-Claim"><a href="#Checking-If-We-Can-Approve-An-Insurance-Claim" class="headerlink" title="Checking If We Can Approve An Insurance Claim"></a>Checking If We Can Approve An Insurance Claim</h1><p>Imagine we are building part of an insurance processing system. </p><p>Next, we have to check whether the claim is able to be approved, and if so, approve it.</p><p>Here’s our use case (Clean Architecture) or, as some might know it, our Command (CQRS):</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ApproveInsuranceClaimCommand</span> <span class="token punctuation">:</span> IUseCase<span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IInsuranceClaimRepository _claimRepo<span class="token punctuation">;</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IUserRepository _userRepo<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">ApproveInsuranceClaimCommand</span><span class="token punctuation">(</span>        IInsuranceClaimRepository claimRepo<span class="token punctuation">,</span>         IUserRepository userRepo    <span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo <span class="token operator">=</span> claimRepo<span class="token punctuation">;</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_userRepo <span class="token operator">=</span> userRepo<span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task <span class="token function">Handle</span><span class="token punctuation">(</span>Guid claimId<span class="token punctuation">,</span> <span class="token keyword">int</span> approvingUserId<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">var</span> user <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_userRepo<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>approvingUserId<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">// 1. Figure out if the user has permission to approve this...</span>        InsuranceClaim claim <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>claimId<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">// 2. Figure out if the claim is approvable...</span>        claim<span class="token punctuation">.</span><span class="token function">Approve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo<span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span>claim<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>For the logic that will go into the comments I made, what if we required <strong>more</strong> repositories to make those checks?</p><p>Also, what if other use cases in our system needed to make those same checks?</p><p>Perhaps we have another use case called <code>ApproveOnHoldInsuranceClaimCommand</code> that will approve an insurance claim that was, for some reason, placed on hold until further documentation was supplied by the customer?</p><p>Or, perhaps in other use cases we need to check if users are able to have permission to change a claim?</p><p>This will lead to messy code and a lot of copy and pasting!</p><h1 id="The-Solution-From-The-Outside"><a href="#The-Solution-From-The-Outside" class="headerlink" title="The Solution From The Outside"></a>The Solution From The Outside</h1><p>Just like the guard clause refactoring pattern, why don’t we do the same thing but convert each guard clause into an entirely new class?</p><p>The benefits are that we can use dependency injection to inject any dependencies like repositories, <code>HttpClient</code>s, etc. that <strong>only</strong> each gate class will require.</p><p>Now, our use case might look like this (keeping in mind that each gate class may do some complex logic inside):</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">ApproveInsuranceClaimCommand</span> <span class="token punctuation">:</span> IUseCase<span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IInsuranceClaimRepository _claimRepo<span class="token punctuation">;</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> CanUserApproveInsuranceClaimGate _canUserApprove<span class="token punctuation">;</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> CanInsuranceClaimBeApprovedGate _claimCanBeApproved<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">ApproveInsuranceClaimCommand</span><span class="token punctuation">(</span>        IInsuranceClaimRepository claimRepo        CanUserApproveInsuranceClaimGate canUserApprove<span class="token punctuation">,</span>         CanInsuranceClaimBeApprovedGate claimCanBeApproved    <span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo <span class="token operator">=</span> claimRepo<span class="token punctuation">;</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_canUserApprove <span class="token operator">=</span> canUserApprove<span class="token punctuation">;</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_claimCanBeApproved <span class="token operator">=</span> claimCanBeApproved<span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task <span class="token function">Handle</span><span class="token punctuation">(</span>Guid claimId<span class="token punctuation">,</span> <span class="token keyword">int</span> approvingUserId<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_canUserApprove<span class="token punctuation">.</span><span class="token function">Invoke</span><span class="token punctuation">(</span>approvingUserId<span class="token punctuation">)</span><span class="token punctuation">;</span>        InsuranceClaim claim <span class="token operator">=</span> <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo<span class="token punctuation">.</span><span class="token function">Find</span><span class="token punctuation">(</span>claimId<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_claimCanBeApproved<span class="token punctuation">.</span><span class="token function">Invoke</span><span class="token punctuation">(</span>claim<span class="token punctuation">)</span><span class="token punctuation">;</span>        claim<span class="token punctuation">.</span><span class="token function">Approve</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_claimRepo<span class="token punctuation">.</span><span class="token function">Update</span><span class="token punctuation">(</span>claim<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Notice that there’s no more need for the <code>IUserRepository</code> since it will be handled by the <code>CanUserApproveInsuranceClaimGate</code> gate class (and DI).</p><p><em>Note: Why didn’t I make an interface for each gate class? Just for simplicity. But yes, by using interfaces instead of a concrete class you may mock them much easier for testing.</em></p><h1 id="Creating-A-Gate-Class"><a href="#Creating-A-Gate-Class" class="headerlink" title="Creating A Gate Class"></a>Creating A Gate Class</h1><p>Let’s look at how we might build the <code>CanInsuranceClaimBeApprovedGate</code> gate class:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CanInsuranceClaimBeApprovedGate</span><span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IInsuranceClaimAdjusterRepository _adjusterRepo<span class="token punctuation">;</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IInsuranceClaimLegalOfficeRepository _legalRepo<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">CanInsuranceClaimBeApprovedGate</span><span class="token punctuation">(</span>        IInsuranceClaimAdjusterRepository adjusterRepo<span class="token punctuation">,</span>        IInsuranceClaimLegalOfficeRepository legalRepo    <span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_adjusterRepo <span class="token operator">=</span> adjusterRepo<span class="token punctuation">;</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_legalRepo <span class="token operator">=</span> legalRepo<span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task <span class="token function">Invoke</span><span class="token punctuation">(</span>InsuranceClaim claim<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Do some crazy logic from the data returned from each repository!</span>        <span class="token comment" spellcheck="true">// On failure, throw a general gate type exception that can be handled </span>        <span class="token comment" spellcheck="true">// by middleware or a global error handler somewhere at the top of your stack.</span>        <span class="token keyword">throw</span> <span class="token keyword">new</span> <span class="token class-name">GateFailureException</span><span class="token punctuation">(</span><span class="token string">"Insurance claim cannot be approved."</span><span class="token punctuation">)</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Each gate class will either succeed or fail. </p><p>On failure, it will throw an exception that will be caught up the stack. In web applications, there is usually some global exception handler or middleware that can convert these into specific HTTP error responses, etc.</p><p>If we do need to use this logic in other places, as mentioned above, then we don’t need to re-import all the dependencies required for this logic. We can just simply use the gate class as-is and allow the DI mechanism to plug in all the dependencies for us.</p><h1 id="Some-Caveats"><a href="#Some-Caveats" class="headerlink" title="Some Caveats"></a>Some Caveats</h1><p>It’s worth mentioning, that in some cases your use cases and your gate classes <em>may need to call the same repository method</em>. You don’t want to be fetching that data twice (once in your gate class and once in your use case).</p><p>In this event, there are ways to fix it.</p><p>One is to build a <strong>cached repository using the Decorator pattern</strong>. </p><p>You might rig this up as a scoped dependency (in .NET Core) so the cached data will only be cached for the lifetime of the HTTP request. Or you might just set a timeout on the cache.</p><p>Another way is to <strong>allow the use case to inject the raw data into the gate class as a dependency</strong>.</p><p>In any event, this pattern is very helpful in making your code much easier to test, use and maintain!</p><hr><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div><h2 id="You-Might-Also-Enjoy"><a href="#You-Might-Also-Enjoy" class="headerlink" title="You Might Also Enjoy"></a>You Might Also Enjoy</h2><ul><li><a href="https://builtwithdot.net/blog/where-do-i-put-my-business-rules-and-validation" target="_blank" rel="noopener">Where Do I Put My Business Rules And Validation?</a> (Guest post on <a href="https://builtwithdot.net" target="_blank" rel="noopener">builtwithdot.net</a>)</li><li><a href="https://www.blog.jamesmichaelhickey.com/NET-Core-Dependency-Injection/" target="_blank" rel="noopener">.NET Core Dependency Injection: Everything You Ought To Know</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/keeping-ado-sql-connections-safe/" target="_blank" rel="noopener">Keeping Your ADO Sql Connections Safe</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Have you ever heard of guard clauses? Steve Smith discusses them in one of his Weekly Dev Tips &lt;a href=&quot;https://www.weeklydevtips.com/004&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;here&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;Today I want to show you a technique that I’ve been using which is similar to the guard clause pattern but is used in more advanced scenarios. These scenarios include when you have problems due to external dependencies or complex logic that is required in your guard clauses.&lt;/p&gt;
    
    </summary>
    
    
      <category term="software design" scheme="https://blog.jamesmichaelhickey.com/tags/software-design/"/>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/tags/C/"/>
    
  </entry>
  
  <entry>
    <title>How To Stand-Out Among Your Peers As A Software Developer</title>
    <link href="https://blog.jamesmichaelhickey.com/How-To-StandOut-Among-Your-Peers/"/>
    <id>https://blog.jamesmichaelhickey.com/How-To-StandOut-Among-Your-Peers/</id>
    <published>2019-02-19T23:14:56.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>I started my career working for an organization that was building a platform for vehicle manufacturers to consolidate and run analytics on their sales.</p><p>I started off having to use technologies and frameworks I had no experience with yet (ASP.NET, T-SQL, etc.)</p><p>For the first few months, I felt <strong>overwhelmed.</strong></p><p>I took forever to do simple things like adding a checkbox to a web page that would get stored in the database!</p><p>Maybe you’ve been there too!</p><a id="more"></a><div style="padding:40px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:50px">This is based on an article from my email newsletter <strong>Navigating Your Software Development Career</strong>. If you would like to get up-to-date articles similar to this then you can <a href="https://eepurl.com/gdIV5X" target="_blank" rel="noopener">join the community here</a>!<br></div><h1 id="My-First-“Specialization”"><a href="#My-First-“Specialization”" class="headerlink" title="My First “Specialization”"></a>My First “Specialization”</h1><p>After a few months, from time-to-time, I would build SQL scripts to migrate large sets of data from one vehicle manufacturer’s old platform to this new one.</p><p>Think something like ALL of Mercedes-Benz USA’s data (sales figures, inventory, etc.) for ALL dealerships in the United States over a period of a decade. Lots of data.</p><p>One of the core problems with migrating the data was that, for example, certain codes (for financial accounts, SKUs, etc.) in one system might look totally different in another. It might not even exist at all!</p><p>We had to extract the proper code by parsing patterns or manipulating old codes.</p><p>Now, while in college, I fell in love with regular expressions. So I was really good at them (not so much anymore! 😂).</p><p>My colleagues - peers with over a decade in the industry - would get really surprised when they would see my scripts. I was basically just using regular expressions and SQL to manipulate these data sets. My scripts would typically take just a few SQL statements to do the job.</p><p>My colleagues, on-the-other-hand, were building individual command-line executables with C# that would first fetch some data from the database, loop through them and do some stuff and put some data back into the database.</p><p>My solutions would take a few hours or minutes to run, while theirs would take days to run.</p><p>Quickly, I became the “go-to” guy for whenever the team had encountered some really hard pieces of data to extract! All because I knew regular expressions really well! </p><p>Go figure!</p><h1 id="How-This-Relates-To-You"><a href="#How-This-Relates-To-You" class="headerlink" title="How This Relates To You"></a>How This Relates To You</h1><p>So, what came out of that?</p><p><strong>Trust.</strong></p><p><strong>Respect.</strong></p><p><strong>Confidence.</strong></p><p><strong>Opportunities.</strong></p><p><strong>That placed me in the minds of my peers as someone who was a skilled programmer.</strong></p><p>Sure, I was known for doing something well in a <em>very specific situation</em>.</p><p>But, our minds usually don’t place significance on people who are good at doing the general day-to-day stuff. The people who are remarkable at something always stick out.</p><blockquote><p>The people who are remarkable at something always stick out.</p></blockquote><p>Where does this lead?</p><p>When new opportunities arise to learn something new or jump onto some new projects, you’ll be at the top of everyone’s mind.</p><p><strong>You’ll simply be viewed as someone who can do remarkable things.</strong></p><h1 id="Some-Tips"><a href="#Some-Tips" class="headerlink" title="Some Tips"></a>Some Tips</h1><p>Now, I’m <em>not</em> going to tell you to learn regular expressions 😂.</p><p>But, for me, it started with regular expressions. Then it was front-end development. Then it was modelling business rules and system architecture.</p><p><strong>Here’s my advice: Find a gap within your team or company that could help solve some important problems your company is facing.</strong></p><p>But you’re thinking - <em>“Easier said than done!”</em></p><p>Practically speaking, if you are early in your career, <em>just keep an eye out for whenever your peers seem surprised at some skill or way of doing things you have.</em> </p><p>This might indicate a gap that could be helpful to your organization!</p><p>For those more seasoned developers, it should be more apparent what gaps need to be filled. And, the more experienced you are, the more you should naturally drift into a position of mentoring others.</p><p>Once you are seasoned, you can use this principle and apply it to the global community - not just your internal company. Try to figure out where there is a need or where certain trends seem to be pointing.</p><h1 id="A-Few-Examples"><a href="#A-Few-Examples" class="headerlink" title="A Few Examples"></a>A Few Examples</h1><p>Here are some diverse examples that are taken off the top of my head (not all devs):</p><ul><li><a href="https://martinfowler.com/" target="_blank" rel="noopener">Martin Fowler</a>: Enterprise software</li><li><a href="https://ardalis.com/" target="_blank" rel="noopener">Steve Smith</a>: DDD and architecture in .NET</li><li><a href="https://twitter.com/mijustin" target="_blank" rel="noopener">Justin Jackson</a>: Teaching devs to market stuff</li><li><a href="https://twitter.com/theChrisDo" target="_blank" rel="noopener">Chris Do</a>: Helps designers become entrepreneurs</li><li><a href="https://twitter.com/sarah_edo" target="_blank" rel="noopener">Sarah Drasner</a>: Vuejs and web animations</li></ul><h1 id="The-End"><a href="#The-End" class="headerlink" title="The End"></a>The End</h1><p>Yes, it’s hard. </p><p>If you can’t find anything <em>yet</em>, then just pick something! You need to stick out!</p><p>You can always move into other areas of specialization later if you find something else too! </p><p><a href="https://twitter.com/dan_abramov" target="_blank" rel="noopener">Dan Abramov</a> used to be a .NET developer - now he’s known as one of the top react.js developers!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;I started my career working for an organization that was building a platform for vehicle manufacturers to consolidate and run analytics on their sales.&lt;/p&gt;
&lt;p&gt;I started off having to use technologies and frameworks I had no experience with yet (ASP.NET, T-SQL, etc.)&lt;/p&gt;
&lt;p&gt;For the first few months, I felt &lt;strong&gt;overwhelmed.&lt;/strong&gt;&lt;/p&gt;
&lt;p&gt;I took forever to do simple things like adding a checkbox to a web page that would get stored in the database!&lt;/p&gt;
&lt;p&gt;Maybe you’ve been there too!&lt;/p&gt;
    
    </summary>
    
    
      <category term="career" scheme="https://blog.jamesmichaelhickey.com/tags/career/"/>
    
  </entry>
  
  <entry>
    <title>The Importance Of Solving Real-World Problems</title>
    <link href="https://blog.jamesmichaelhickey.com/The-Importance-Of-Solving-Real-World-Problems/"/>
    <id>https://blog.jamesmichaelhickey.com/The-Importance-Of-Solving-Real-World-Problems/</id>
    <published>2019-01-29T11:18:57.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>Being a software developer is <strong>much more</strong> than simply knowing everything about mastering programming languages.</p><p>You need to know how to deal with people, understand how software is best built from a high-level, best practices and trade-offs between them, etc.</p><p>We’ll look at a question I received from someone who is struggling with the fact that he just graduated from university - but has no idea how to apply everything he’s learned to solve real-world problems.</p><a id="more"></a><div style="padding:40px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:50px">This is based on an excerpt from my email newsletter <strong>Navigating Your Software Development Career</strong>. If you would like to get up-to-date articles similar to this then you can <a href="https://eepurl.com/gdIV5X" target="_blank" rel="noopener">join the community here</a>!<br></div><p>Here’s the question I was given:</p><blockquote><p>“Does knowing how to code in a particular language makes one a developer? I just graduated from the university and want to be a professional developer, what must I learn, I’m learning C# and Python now. I’m confused because I don’t even know how to apply the coding I’m learning in solving real life problems?”</p></blockquote><h1 id="I-don’t-know-how-to-apply-what-I’ve-learned-in-University-to-solve-real-life-problems"><a href="#I-don’t-know-how-to-apply-what-I’ve-learned-in-University-to-solve-real-life-problems" class="headerlink" title="I don’t know how to apply what I’ve learned in University to solve real-life problems."></a>I don’t know how to apply what I’ve learned in University to solve real-life problems.</h1><p>This is a problem 😋 </p><p>This is why I prefer community college vs. universities. Usually, a 2-year college program will give you much more practical experience and knowledge than a university usually gives in 4-years! </p><p>Anyways - a topic for another day.</p><p><strong>The answer:</strong> <em>You need to build some real-life projects that you can show off!</em></p><h2 id="Solving-Real-Problems"><a href="#Solving-Real-Problems" class="headerlink" title="Solving Real Problems"></a>Solving Real Problems</h2><p>Companies want to hire people who can demonstrate that they can solve real problems. The questioner understands this - otherwise, they wouldn’t be asking the question. 😜</p><p>You need to be a problem solver - who just happens to know how to build software to solve <em>some</em> of these problems.</p><p>Your task then is to find some problem - big or small. Then build something to solve it. </p><p>Let me give you a couple examples.</p><h3 id="Coravel"><a href="#Coravel" class="headerlink" title="Coravel"></a>Coravel</h3><p>I had the idea one day <em>“I wish .NET development could be as easy as using Laravel”.</em></p><p>.NET is very robust but lacks some of the ease-of-use that frameworks for other languages have - like <a href="https://laravel.com/" target="_blank" rel="noopener">Laravel</a>.</p><p>So, I created a solution to that problem! That was why <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> was born.</p><p>If you turn something like this into a GitHub repo then you can showcase things like:</p><ul><li>Understanding how to solve a real-life problem by building software</li><li>Ability to write very clear documentation</li><li>Initiative and passion to build this in the first place</li></ul><h3 id="Build-An-App"><a href="#Build-An-App" class="headerlink" title="Build An App!"></a>Build An App!</h3><p>Another option is to build an entire app!</p><p>I did this when I was learning how to build web apps using Laravel <em>years ago</em>. <a href="https://social.jamesmichaelhickey.com/" target="_blank" rel="noopener">It’s just a small social media spoof app.</a></p><p>This app uses Vue.js and SASS for the front-end and Laravel for the back-end.</p><p>In this case, I demonstrated that I could do front-end and back-end development, among other things.</p><p>If you can’t make up your mind then just do this. Just make something that will demonstrate you <em>can</em> solve problems with code!</p><h1 id="Does-knowing-X-number-of-programming-languages-make-you-a-developer"><a href="#Does-knowing-X-number-of-programming-languages-make-you-a-developer" class="headerlink" title="Does knowing X number of programming languages make you a developer?"></a>Does knowing X number of programming languages make you a developer?</h1><p>No. It just means you can make something that someone else told you to build.</p><p>Sadly, many companies will interview based on irrelevant technical knowledge alone (which doesn’t test if you can think for yourself, etc.)</p><p>You need to be someone who can first identify problems within a company or community. Then, you can decide whether or not building software is a good fit for solving it. </p><p>What are some other skills and qualities that will help you become a quality developer?</p><ul><li>Ability to work with a team in a positive and encouraging manner</li><li>Experience connecting different systems together<ul><li>Back-end to database</li><li>Front-end to API</li><li>Back-end to API</li></ul></li><li>Understanding of general programming principles and best practices<ul><li>SOLID</li><li>Recognizing and knowing fixes for “code smells”</li></ul></li><li>Code organization<ul><li>How the business/product should influence your code’s structure</li><li>Knowing the different ways to organize code and the trade-offs between them</li></ul></li><li>Architectural patterns<ul><li>MVC</li><li>MVVM</li><li>Onion architecture</li><li>Hexagonal architecture</li></ul></li><li>Programming paradigms<ul><li>Object-oriented</li><li>Functional</li><li>Declarative vs. procedural</li></ul></li></ul><p>That is by no means an exhaustive list - but are fundamental to becoming a quality developer.</p><p>If you don’t know most of these topics then I would suggest learning a little bit about each one in general. </p><p>Then, pick a few to really dive into.</p><p>Knowing some of these <strong>really well</strong> can help you stand out among your peers. </p><p>But that’s a topic for another day.</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;Being a software developer is &lt;strong&gt;much more&lt;/strong&gt; than simply knowing everything about mastering programming languages.&lt;/p&gt;
&lt;p&gt;You need to know how to deal with people, understand how software is best built from a high-level, best practices and trade-offs between them, etc.&lt;/p&gt;
&lt;p&gt;We’ll look at a question I received from someone who is struggling with the fact that he just graduated from university - but has no idea how to apply everything he’s learned to solve real-world problems.&lt;/p&gt;
    
    </summary>
    
    
      <category term="career" scheme="https://blog.jamesmichaelhickey.com/tags/career/"/>
    
  </entry>
  
  <entry>
    <title>.NET Core Dependency Injection: Everything You Ought To Know</title>
    <link href="https://blog.jamesmichaelhickey.com/NET-Core-Dependency-Injection/"/>
    <id>https://blog.jamesmichaelhickey.com/NET-Core-Dependency-Injection/</id>
    <published>2018-12-06T23:57:02.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>If you go to the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1" target="_blank" rel="noopener">official docs for ASP.NET Core</a> you’ll find that Dependency Injection is under the “fundamentals” area.</p><p>Is that true - is it really <strong>fundamental?</strong></p><a id="more"></a><h1 id="TLDR"><a href="#TLDR" class="headerlink" title="TLDR;"></a>TLDR;</h1><p>Dependency injection is baked into .NET Core. And, it’s there for a reason: it promotes building classes having loose coupling and gives developers tools to build maintainable, modular and testable software.</p><p>It also provides library authors with tools that can help make installation/configuration of their libraries very simple and straightforward.</p><h1 id="Intro"><a href="#Intro" class="headerlink" title="Intro"></a>Intro</h1><p>As you guessed, this article will go over some things I’ve learned about DI in .NET Core, along with my suggestions for what you should know. 😊</p><p>To begin, I want to explore DI for those who may not be too familiar with dependency injection. We’ll start with the basics and move toward some more advanced scenarios.</p><p>If you already know what DI is, and how to use interfaces to mock your classes and test them, etc. then you can move onto the <a href="#Using-Dependency-Injection-In-NET-Core">Using Dependency Injection In .NET Core section</a>.</p><p>Yes, this is going to be a long one. Get ready. 😎</p><h1 id="What-Is-Dependency-Injection"><a href="#What-Is-Dependency-Injection" class="headerlink" title="What Is Dependency Injection?"></a>What Is Dependency Injection?</h1><p>If you aren’t familiar with DI, it pretty much just refers to passing dependencies into your objects as an external arguments.</p><p>This can be done via an object’s constructor or method.</p><pre class=" language-csharp"><code class="language-csharp"><span class="token comment" spellcheck="true">// Argument "dep" is "injected" as a dependency.</span><span class="token keyword">public</span> <span class="token function">MyClass</span><span class="token punctuation">(</span>ExternalDependency dep<span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">this</span><span class="token punctuation">.</span>_dep <span class="token operator">=</span> dep<span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Dependency injection then is, at a fundamental level, just passing dependencies as arguments. That’s it. That’s all.</p><p>Well… if that was <strong>really</strong> all of what DI is - I wouldn’t be writing this. 😜</p><h1 id="Why-Should-We-Pass-Dependencies-As-Arguments"><a href="#Why-Should-We-Pass-Dependencies-As-Arguments" class="headerlink" title="Why Should We Pass Dependencies As Arguments?"></a>Why Should We Pass Dependencies As Arguments?</h1><p>Why would you want to do this? A few reasons:</p><ul><li>Promotes splitting logic into multiple smaller classes and/or structures</li><li>Promotes code testability</li><li>Promotes using abstractions that allow a more modular code structure in general</li></ul><p>Let’s look briefly at the idea that this promotes testability (which in turn affects all the other points mentioned).</p><p>Why do we test code? <strong>To make sure our system behaves properly.</strong> </p><p>This means that <strong>you can trust your code</strong>.</p><p>With no tests, <strong>you can’t really trust your code</strong>.</p><p>I discuss this in more detail in another blog post about <a href="https://www.blog.jamesmichaelhickey.com/refactoring-game-plan-and-tips/" target="_blank" rel="noopener">Refactoring Legacy Monoliths</a> - where I discuss some refactoring techniques around this issue.</p><h1 id="What-Is-Dependency-Injection-Revisited"><a href="#What-Is-Dependency-Injection-Revisited" class="headerlink" title="What Is Dependency Injection (Revisited)"></a>What Is Dependency Injection (Revisited)</h1><p>Of course, DI is more than “just passing in arguments.” Dependency injection is a mechanism where the runtime (let’s say - .NET Core) will automatically pass (inject) required dependencies into your classes.</p><p>Why would we ever need that?</p><p>Look at this simple class:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Car</span><span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">Car</span><span class="token punctuation">(</span>Engine engine<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_engine <span class="token operator">=</span> engine<span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>What if, somewhere else, we needed to do this:</p><pre class=" language-csharp"><code class="language-csharp">Car ferrari <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Car</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">Engine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Great. What if we wanted to test this <code>Car</code> class?</p><p>The problem is <strong>in order to test <code>Car</code> you need <code>Engine</code>.</strong> This is a “hard” dependency, if you will.</p><p>This means that these classes are tightly tied together. In other words, tightly coupled. Those are bad words.</p><p>We want loosely coupled classes. This makes our code more modular, generalized and easier to test (which means <strong>more trust</strong> and <strong>more flexibility</strong>).</p><h1 id="Quick-Look-At-Testing"><a href="#Quick-Look-At-Testing" class="headerlink" title="Quick Look At Testing"></a>Quick Look At Testing</h1><p>Some common techniques when testing are to use “mocks”. A mock is just a stubbed-out class that “pretends” to be a real implementation.</p><p>We can’t mock concrete classes. But, we can mock interfaces!</p><p>Let’s change our <code>Car</code> to rely on an interface instead:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">Car</span><span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">Car</span><span class="token punctuation">(</span>IEngine engine<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_engine <span class="token operator">=</span> engine<span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Cool! Let’s test that:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token comment" spellcheck="true">// Mock code configuration would be here.</span><span class="token comment" spellcheck="true">// "mockEngine" is just a stubbed IEngine.</span>Car ferrari <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Car</span><span class="token punctuation">(</span>mockEngine<span class="token punctuation">)</span><span class="token punctuation">;</span>Assert<span class="token punctuation">.</span><span class="token function">IsTrue</span><span class="token punctuation">(</span>ferrari<span class="token punctuation">.</span><span class="token function">IsFast</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>So now we are testing the <code>Car</code> class <strong>without a hard dependency on <code>Engine</code></strong>. 👍</p><h1 id="A-Quick-Look-At-Modularization"><a href="#A-Quick-Look-At-Modularization" class="headerlink" title="A Quick Look At Modularization"></a>A Quick Look At Modularization</h1><p>I had mentioned that using DI allows your code to be modular. Well, it’s not really DI that does, but the technique above (relying on interfaces).</p><p>Compare these two examples:</p><pre class=" language-csharp"><code class="language-csharp">Car ferrari <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Car</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">FastEngine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>and</p><pre class=" language-csharp"><code class="language-csharp">Car civic <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">Car</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">HondaEngine</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Since we are relying on interfaces, we have way more flexibility as to what kinds of cars we can build!</p><h1 id="Avoiding-Class-Inheritance"><a href="#Avoiding-Class-Inheritance" class="headerlink" title="Avoiding Class Inheritance"></a>Avoiding Class Inheritance</h1><p>Another benefit is that you <strong>don’t need to use class inheritance.</strong> </p><p>This is something I see abused all the time. So much so that I do my best to “never” use class inheritance.</p><p>It’s hard to test, hard to understand and usually leads to building an incorrect model anyways since it’s so hard to change after-the-fact.</p><p>99% of the time there are better ways to build your code using patterns like this - which rely on abstractions rather than tightly coupled classes.</p><p>And yes - class inheritance is <strong>the most</strong> highly coupled relationship you can have in your code! (But that’s another blog post 😉)</p><h1 id="Using-Dependency-Injection-In-NET-Core"><a href="#Using-Dependency-Injection-In-NET-Core" class="headerlink" title="Using Dependency Injection In .NET Core"></a>Using Dependency Injection In .NET Core</h1><p>The example above highlights why we need DI. </p><p>Dependency injection allows us to “bind” a specific type to be used globally in place of, for example, a specific interface. </p><p>At runtime we rely on the DI system to create new instances of these objects for us. All the dependencies are handled automatically.</p><p>In .NET Core, you might do something like this to tell the DI system what classes we want to use when asking for certain interfaces, etc.</p><pre class=" language-csharp"><code class="language-csharp"><span class="token comment" spellcheck="true">// Whenever the type 'Car' is asked for we get a new instance of the 'Car' type.</span>services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>Car<span class="token punctuation">,</span>Car<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// Whenever the type 'IEngine' is asked for we get a new instance of the concrete 'HondaEngine' type.</span>services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>IEngine<span class="token punctuation">,</span> HondaEngine<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p><code>Car</code> relies on <code>IEngine</code>. </p><p>When the DI system tries to “build” (instantiate) a new <code>Car</code> it will first grab a <code>new HondaEngine()</code> and then inject that into the <code>new Car()</code>.</p><p>Whenever we need a <code>Car</code> .NET Core’s DI system will automatically rig that up for us! All the dependencies will cascade.</p><p>So, In an MVC controller we might do this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token function">CarController</span><span class="token punctuation">(</span>Car car<span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">this</span><span class="token punctuation">.</span>_car <span class="token operator">=</span> car<span class="token punctuation">;</span> <span class="token comment" spellcheck="true">// Car will already be instantiated by the DI system using the 'HondaEngine' as the engine.</span><span class="token punctuation">}</span></code></pre><h1 id="A-Real-World-Example"><a href="#A-Real-World-Example" class="headerlink" title="A Real World Example"></a>A Real World Example</h1><p>Alright - the car example was simple. That’s to get the basics down. Let’s look at a more realistic scenario.</p><p>Get ready. 😎</p><p>We have a use case for creating a new user in our app:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CreateUser</span><span class="token punctuation">{</span>        <span class="token comment" spellcheck="true">// Filled out later...</span><span class="token punctuation">}</span></code></pre><p>That use case needs to issue some database queries to persist new users. </p><p>In order to make this testable - and make sure that we can test our code <strong>without requiring the database as a dependency</strong> - we can use the technique already discussed:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">IUserRepository</span><span class="token punctuation">{</span>    <span class="token keyword">public</span> Task<span class="token operator">&lt;</span><span class="token keyword">int</span><span class="token operator">></span> <span class="token function">CreateUserAsync</span><span class="token punctuation">(</span>UserModel user<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>And the concrete implementation that will hit the database:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">UserRepository</span> <span class="token punctuation">:</span> IUserRepository<span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> ApplicationDbContext _dbContext<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">UserRepository</span><span class="token punctuation">(</span>ApplicationDbContext dbContext<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_dbContext <span class="token operator">=</span> dbContext<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task<span class="token operator">&lt;</span><span class="token keyword">int</span><span class="token operator">></span> <span class="token function">CreateUserAsync</span><span class="token punctuation">(</span>UserModel user<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_dbContext<span class="token punctuation">.</span>Users<span class="token punctuation">.</span><span class="token function">Add</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_dbContext<span class="token punctuation">.</span><span class="token function">SaveChangesAsync</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>Using DI, we would have something like this:</p><pre class=" language-csharp"><code class="language-csharp">services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>CreateUser<span class="token punctuation">,</span> CreateUser<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>IUserRepository<span class="token punctuation">,</span> UserRepository<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Whenever we have a class that needs an instance of the <code>IUserRepository</code> the DI system will automatically build a <code>new</code> <code>UserRepository</code> for us. </p><p>The same can be said for <code>CreateUser</code> - a new <code>CreateUser</code> will be given to us when asked (along with all of it’s dependencies already injected).</p><p>Now, in our use case we do this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CreateUser</span><span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> IUserRepository _repo<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">CreateUser</span><span class="token punctuation">(</span>IUserRepository repo<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_repo <span class="token operator">=</span> repo<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task <span class="token function">InvokeAsync</span><span class="token punctuation">(</span>UserModel user<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_repo<span class="token punctuation">.</span><span class="token function">CreateUserAsync</span><span class="token punctuation">(</span>user<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token punctuation">}</span></code></pre><p>In an MVC controller, we can “ask” for the <code>CreateUser</code> use case:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">CreateUserController</span> <span class="token punctuation">:</span> Controller<span class="token punctuation">{</span>    <span class="token keyword">private</span> <span class="token keyword">readonly</span> CreateUser _createUser<span class="token punctuation">;</span>    <span class="token keyword">public</span> <span class="token function">CreateUserController</span><span class="token punctuation">(</span>CreateUser createUser<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>        <span class="token keyword">this</span><span class="token punctuation">.</span>_createUser <span class="token operator">=</span> createUser<span class="token punctuation">;</span>    <span class="token punctuation">[</span>HttpPost<span class="token punctuation">]</span>    <span class="token keyword">public</span> <span class="token keyword">async</span> Task<span class="token operator">&lt;</span>ActionResult<span class="token operator">></span> <span class="token function">Create</span><span class="token punctuation">(</span>UserModel userModel<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">await</span> <span class="token keyword">this</span><span class="token punctuation">.</span>_createUser<span class="token punctuation">.</span><span class="token function">InvokeAsync</span><span class="token punctuation">(</span>userModel<span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token keyword">return</span> <span class="token function">Ok</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span>    <span class="token punctuation">}</span></code></pre><p>The DI system will automatically:</p><ul><li>Try to create a new instance of <code>CreateUser</code>.</li><li>Since <code>CreateUser</code> depends on the <code>IUserRepository</code> interface, the DI system will next look to see if there is a type “bound” to that interface. </li><li>Yes - it’s the concrete <code>UserRepository</code>. </li><li>Create a new <code>UserRepository</code>.</li><li>Pass that into a new <code>CreateUser</code> as the implementation of it’s constructor argument <code>IUserRepository</code>.</li></ul><p>Some benefits that are obvious:</p><ul><li>Your code is much more modular and flexible (as mentioned)</li><li>Your controllers etc. (whatever is using DI) become way simpler and easy to read.</li></ul><h1 id="Real-World-Testing"><a href="#Real-World-Testing" class="headerlink" title="Real World Testing"></a>Real World Testing</h1><p>And the final benefit, again, we can test this <strong>without needing to hit the database</strong>.</p><pre class=" language-csharp"><code class="language-csharp"><span class="token comment" spellcheck="true">// Some mock configuration...</span><span class="token keyword">var</span> createUser <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">CreateUser</span><span class="token punctuation">(</span>mockUserRepositoryThatReturnsMockData<span class="token punctuation">)</span><span class="token punctuation">;</span><span class="token keyword">int</span> createdUserId <span class="token operator">=</span> <span class="token keyword">await</span> createUser<span class="token punctuation">.</span><span class="token function">InvokeAsync</span><span class="token punctuation">(</span>dummyUserModel<span class="token punctuation">)</span><span class="token punctuation">;</span>Assert<span class="token punctuation">.</span><span class="token function">IsTrue</span><span class="token punctuation">(</span>createdUserId <span class="token operator">==</span> expectedCreatedUserId<span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>This makes for:</p><ul><li>Fast testing (no database)</li><li>Isolated testing (only focusing on testing the code in <code>CreateUser</code>)</li></ul><h1 id="What-You-Should-Know-About-Using-NET-Core-Dependency-Injection"><a href="#What-You-Should-Know-About-Using-NET-Core-Dependency-Injection" class="headerlink" title="What You Should Know About Using .NET Core Dependency Injection"></a>What You Should Know About Using .NET Core Dependency Injection</h1><p>Now I want to run through some of the more proper and technical terms that you should know, along with recommended pieces of knowledge around .NET Core’s DI system.</p><h2 id="Service-Provider"><a href="#Service-Provider" class="headerlink" title="Service Provider"></a>Service Provider</h2><p>When we refer to the “DI system” we are really talking about the Service Provider.</p><p>In other frameworks or DI systems this is also called a <em>Service Container</em>.</p><p>This is the object that holds the configuration for all the DI stuff.</p><p>It’s also what will ultimately be “asked” to create new objects for us. And therefore, it’s what figures out what dependencies each service requires at runtime.</p><h2 id="Binding"><a href="#Binding" class="headerlink" title="Binding"></a>Binding</h2><p>When we talk about binding, we just mean that type <code>A</code> is mapped to type <code>B</code>. </p><p>In our example about the <code>Car</code> scenario, we would say that <code>IEngine</code> is bound to <code>HondaEngine</code>. </p><p>When we ask for a dependency of <code>IEngine</code> we are returned an instance of <code>HondaEngine</code>.</p><h2 id="Resolving"><a href="#Resolving" class="headerlink" title="Resolving"></a>Resolving</h2><p>Resolving refers to the process of figuring out what dependencies are required for a particular service.</p><p>Using the example above with the <code>CreateUser</code> use case, when the Service Provider is asked to inject an instance of <code>CreateUser</code> we would say that the provider is “resolving” that dependency.</p><p>Resolving involves figuring out the entire tree of dependencies:</p><ul><li><code>CreateUser</code> requires an instance of <code>IUserRepository</code></li><li>The provider sees that <code>IUserRepository</code> is bound to <code>UserRepository</code></li><li><code>UserRepository</code> requires an instance of <code>ApplicationDbContext</code></li><li>The provider see that <code>ApplicationDbContext</code> is available (and bound to the same type).</li></ul><p>Figuring out that tree of cascading dependencies is what we call “resolving a service.”</p><h2 id="Scopes"><a href="#Scopes" class="headerlink" title="Scopes"></a>Scopes</h2><p>Generally termed scopes, or otherwise called service lifetimes, this refers to whether a service is short or long living.</p><p>For example, a singleton (as the pattern is defined) is a service that will always resolve to the same instance every time.</p><p>Without understanding what scopes are you can run into some really weird errors. 😜</p><p>The .NET Core DI system has 3 different scopes:</p><h3 id="Singleton"><a href="#Singleton" class="headerlink" title="Singleton"></a>Singleton</h3><pre class=" language-csharp"><code class="language-csharp">services<span class="token punctuation">.</span><span class="token generic-method function">AddSingleton<span class="token punctuation">&lt;</span>IAlwaysExist<span class="token punctuation">,</span> IAlwaysExist<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Whenever we resolve <code>IAlwaysExist</code> in an MVC controller constructor, for example, it will always be the exact same instance.</p><p><em>As a side note: This implies concerns around thread-safety, etc. depending on what you are doing.</em></p><h3 id="Scoped"><a href="#Scoped" class="headerlink" title="Scoped"></a>Scoped</h3><pre class=" language-csharp"><code class="language-csharp">services<span class="token punctuation">.</span><span class="token generic-method function">AddScoped<span class="token punctuation">&lt;</span>IAmSharedPerRequests<span class="token punctuation">,</span> IAmSharedPerRequests<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Scoped is the most complicated lifetime. We’ll look at it in more detail later. </p><p>To keep it simple for now, it means that within a particular HttpRequest (in an ASP .NET Core application) the resolved instance will be the same.</p><p>Let’s say we have service <code>A</code> and <code>B</code>. Both are resolved by the same controller:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token function">SomeController</span><span class="token punctuation">(</span>A a<span class="token punctuation">,</span> B b<span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">this</span><span class="token punctuation">.</span>_a <span class="token operator">=</span> a<span class="token punctuation">;</span>    <span class="token keyword">this</span><span class="token punctuation">.</span>_b <span class="token operator">=</span> b<span class="token punctuation">;</span><span class="token punctuation">}</span></code></pre><p>Now imagine <code>A</code> and <code>B</code> both rely on service <code>C</code>. </p><p>If <code>C</code> is a scoped service, and since scoped services resolve to the same instance for the same HTTP request, both <code>A</code> and <code>B</code> will have the exact same instance of <code>C</code> injected.</p><p>However, a different <code>C</code> will be instantiated for all other HTTP requests.</p><h3 id="Transient"><a href="#Transient" class="headerlink" title="Transient"></a>Transient</h3><pre class=" language-csharp"><code class="language-csharp">services<span class="token punctuation">.</span><span class="token generic-method function">AddTransient<span class="token punctuation">&lt;</span>IAmAlwaysADifferentInstance<span class="token punctuation">,</span> IAmAlwaysADifferentInstance<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>Transient services are always an entirely new instance when resolved. </p><p>Given this example:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token function">SomeController</span><span class="token punctuation">(</span>A a<span class="token punctuation">,</span> A anotherA<span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span></code></pre><p>Assuming that type <code>A</code> was configured as a transient service, variables <code>a</code> and <code>anotherA</code> would be different instances of type <code>A</code>.</p><p><em>Note: Given the same example, if <code>A</code> was a scoped service then variables <code>a</code> and <code>anotherA</code> would be the same instance. However, in the next HTTP Request, if <code>A</code> was scoped then <code>a</code> and <code>anotherA</code> in the next request would be different from the instances in the first request.</em></p><p><em>If <code>A</code> was a singleton, then variables <code>a</code> and <code>anotherA</code> in <strong>both</strong> HTTP requests would reference the same single instance.</em></p><h2 id="Scope-Issues"><a href="#Scope-Issues" class="headerlink" title="Scope Issues"></a>Scope Issues</h2><p>There are issues that arise when using differently scoped services who are trying to depend on each other.</p><h3 id="Circular-Dependencies"><a href="#Circular-Dependencies" class="headerlink" title="Circular Dependencies"></a>Circular Dependencies</h3><p>Just don’t do it. It doesn’t make sense 😜</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">A</span><span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">A</span><span class="token punctuation">(</span>B b<span class="token punctuation">)</span> <span class="token punctuation">{</span> <span class="token punctuation">}</span><span class="token punctuation">}</span><span class="token keyword">public</span> <span class="token keyword">class</span> <span class="token class-name">B</span><span class="token punctuation">{</span>    <span class="token keyword">public</span> <span class="token function">B</span><span class="token punctuation">(</span>A a<span class="token punctuation">)</span><span class="token punctuation">{</span> <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><h3 id="Singletons-Transitive-Services"><a href="#Singletons-Transitive-Services" class="headerlink" title="Singletons + Transitive Services"></a>Singletons + Transitive Services</h3><p>A singleton, again, lives “forever”. It’s always the same instance. </p><p>Transitive services, on the other hand, are always a different instance when requested - or resolved.</p><p>So here’s an interesting question: When a singleton depends on a transitive dependency <strong>how long does the transitive dependency live?</strong></p><p>The answer is <strong>forever</strong>. More specifically, <strong>as long as it’s parent lives.</strong></p><p>Since the singleton lives forever so will all of it’s child objects that it references.</p><p>This isn’t necessarily <strong>bad</strong>. But it could introduce weird issues when you don’t understand what this setup implies.</p><h4 id="Thread-Safety"><a href="#Thread-Safety" class="headerlink" title="Thread-Safety"></a>Thread-Safety</h4><p>Perhaps you have a transitive service - let’s call it <code>ListService</code> that isn’t thread-safe. </p><p><code>ListService</code> has a list of stuff and exposes methods to <code>Add</code> and <code>Remove</code> those items.</p><p>Now, you started using <code>ListService</code> inside of a singleton as a dependency.</p><p>That singleton will be re-used <strong>everywhere</strong>. That means, <strong>on every HTTP Request</strong>. Which implies <strong>on many many different threads.</strong></p><p>Since the singleton accesses/uses <code>ListService</code>, and <code>ListService</code> isn’t thread-safe - big problems!</p><p>Be careful.</p><h3 id="Singletons-Scoped-Services"><a href="#Singletons-Scoped-Services" class="headerlink" title="Singletons + Scoped Services"></a>Singletons + Scoped Services</h3><p>Let’s assume now that <code>ListService</code> is a scoped service.</p><p>If you try to inject a scoped service into a singleton what will happen?</p><p><strong>.NET Core will blow up and tell you that you can’t do it!</strong></p><p>Remember that scoped services live for as long as an HTTP request? </p><p>But, remember how I said it’s actually more complicated than that?…</p><h4 id="How-Scoped-Services-Really-Work"><a href="#How-Scoped-Services-Really-Work" class="headerlink" title="How Scoped Services Really Work"></a>How Scoped Services Really Work</h4><p>Under the covers .NET Core’s service provider exposes a method <code>CreateScope</code>.</p><p><em>Note: Alternatively, you can use <code>IServiceScopeFactory</code> and use the same method <code>CreateScope</code>. We’ll look at this later</em> 😉</p><p><code>CreateScope</code> creates a “scope” that implements the <code>IDisposable</code> interface. It would be used like this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">using</span><span class="token punctuation">(</span><span class="token keyword">var</span> scope <span class="token operator">=</span> serviceProvider<span class="token punctuation">.</span><span class="token function">CreateScope</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token comment" spellcheck="true">// Do stuff...</span><span class="token punctuation">}</span></code></pre><p>The service provider also exposes methods for resolving services: <code>GetService</code> and <code>GetRequiredService</code>.</p><p>The difference between them is that <code>GetService</code> returns null when a service isn’t bound to the provider, and <code>GetRequiredService</code> will throw an exception.</p><p>So, a scope might be used like this:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">using</span><span class="token punctuation">(</span><span class="token keyword">var</span> scope <span class="token operator">=</span> serviceProvider<span class="token punctuation">.</span><span class="token function">CreateScope</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">var</span> provider <span class="token operator">=</span> scope<span class="token punctuation">.</span>ServiceProvider<span class="token punctuation">;</span>    <span class="token keyword">var</span> resolvedService <span class="token operator">=</span> provider<span class="token punctuation">.</span><span class="token function">GetRequiredService</span><span class="token punctuation">(</span>someType<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">// Use resolvedService...</span><span class="token punctuation">}</span></code></pre><p>When .NET Core begins an HTTP request under the covers it’ll do something like that. It will resolve the services that your controller may need, for example, so you don’t have to worry about the low-level details.</p><p>In terms of injecting services into ASP controllers - scoped services are basically attached to the life of the HTTP request.</p><p>But, we can create our own services (which would then be a form of the Service Locator pattern - more on that later)!</p><p>So it’s not true that scoped services are <strong>only</strong> attached to an HTTP request. Other types of applications can create their own scopes within whatever lifespan or context they need.</p><h4 id="Multiple-Service-Providers"><a href="#Multiple-Service-Providers" class="headerlink" title="Multiple Service Providers"></a>Multiple Service Providers</h4><p>Notice how each scope has it’s own <code>ServiceProvider</code>? What’s up with that?</p><p>The DI system has <strong>multiple Service Providers.</strong> Woah 🤯</p><p>Singletons are resolved from a root service provider (which exists for the lifetime of your app). The root provider <strong>is not scoped</strong>.</p><p>Anytime you create a scope - you get a new <strong>scoped</strong> service provider! This scoped provider will still be able to resolve singleton services, but by proxy they come from the root provider as all scoped providers have access to their “parent” provider.</p><p>Here’s the rundown of what we just learned:</p><ul><li>Singleton services are always resolvable (from root provider or by proxy)</li><li>Transitive service are always resolvable (from root provider or by proxy)</li><li>Scoped services require a scope and therefore a scoped service provider that’s available</li></ul><p><strong>So what happens when we try to resolve a scoped service from the root provider (a non-scoped provider)?…</strong> </p><p>Boom 🔥</p><h4 id="Back-To-Our-Topic"><a href="#Back-To-Our-Topic" class="headerlink" title="Back To Our Topic"></a>Back To Our Topic</h4><p>All that to say that scoped services <strong>require a scope to exist</strong>.</p><p>Singletons are resolved by the root provider.</p><p>Since the root provider has no scope (it’s a “global” provider in a sense) - it just doesn’t make sense to inject a scoped service into a singleton.</p><h3 id="Scoped-Transitive-Services"><a href="#Scoped-Transitive-Services" class="headerlink" title="Scoped + Transitive Services"></a>Scoped + Transitive Services</h3><p>What about a scoped service who relies on a transitive service?</p><p>In practice it’ll work. But, for the same reasons as using a transitive service inside a singleton, it may not behave as you expect.</p><p>The transitive service that is used by the scoped service will live as long as the scoped service.</p><p>Just be sure that makes sense within your use-case.</p><h2 id="Dependency-Injection-For-Library-Authors"><a href="#Dependency-Injection-For-Library-Authors" class="headerlink" title="Dependency Injection For Library Authors"></a>Dependency Injection For Library Authors</h2><p>As library authors we sometimes want to provide native-like tools. For example, with <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> I wanted to make the library integrate seamlessly with the .NET Core DI system.</p><p>How do we do that?</p><h3 id="IServiceScopeFactory"><a href="#IServiceScopeFactory" class="headerlink" title="IServiceScopeFactory"></a>IServiceScopeFactory</h3><p>As mentioned in passing, .NET Core provides a utility for creating scopes. This is useful for library authors.</p><p>Instead of grabbing an instance of <code>IServiceProvider</code>, library authors probably should use <code>IServiceScopeFactory</code>.</p><p>Why? Well, remember how the root service provider cannot resolve scoped services? What if your library needs to do some “magic” around scoped services? Oops!</p><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a>, for example, needs to resolve certain types from the service provider in certain situations (like instantiating <a href="https://github.com/jamesmh/coravel/blob/master/Docs/Invocables.md" target="_blank" rel="noopener">invocable classes</a>).</p><p>Entity Framework Core contexts are scoped, so doing things such as performing database queries inside your library (on behalf of the user/developer) is something you may want to do.</p><p>This is something that <a href="https://www.pro.coravel.net/" target="_blank" rel="noopener">Coravel Pro</a> does - execute queries from the user’s EF Core context automatically under-the-covers.</p><p>As a side note, issues around capturing services in a closure to be used in a background <code>Task</code> and/or resolving services from a background <code>Task</code> also facilitate the need for resolving services manually (which <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> needs to do).</p><p><a href="https://github.com/davidfowl/AspNetCoreDiagnosticScenarios/blob/master/AspNetCoreGuidance.md#do-not-capture-services-injected-into-the-controllers-on-background-threads" target="_blank" rel="noopener">David Fowler has written briefly about this here if interested.</a></p><h3 id="Service-Locator-Pattern"><a href="#Service-Locator-Pattern" class="headerlink" title="Service Locator Pattern"></a>Service Locator Pattern</h3><p>In general, the service locator pattern is not a good practice. This is when we ask for a specific type from the service provider manually.</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">using</span><span class="token punctuation">(</span><span class="token keyword">var</span> scope <span class="token operator">=</span> serviceProvider<span class="token punctuation">.</span><span class="token function">CreateScope</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span>    <span class="token keyword">var</span> provider <span class="token operator">=</span> scope<span class="token punctuation">.</span>ServiceProvider<span class="token punctuation">;</span>    <span class="token keyword">var</span> resolvedService <span class="token operator">=</span> provider<span class="token punctuation">.</span><span class="token function">GetRequiredService</span><span class="token punctuation">(</span>someType<span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token comment" spellcheck="true">// Use resolvedService...</span><span class="token punctuation">}</span></code></pre><p>However, for cases like mentioned above, it is what we need to do - grab a scope, resolve services and do some “magic”.</p><p>This would be akin to how .NET Core prepares a DI scope and resolves services for your ASP .NET Core controllers.</p><p>It’s not bad because it’s not “user code” but “framework code” - if you will.</p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>We looked at some reasons behind why dependency injection is a useful tool at our disposal.</p><p>It helps to promote:</p><ul><li>Code testability</li><li>Code reuse through composition</li><li>Code readability</li></ul><p>Then we looked at how dependency injection in .NET Core is used, and some of the lower-level aspects of how it works.</p><p>In general, we found <strong>problems arise when services rely on other services who have a shorter lifetime.</strong></p><ul><li>Singleton -&gt; scoped</li><li>Singleton -&gt; transitive</li><li>Scoped -&gt; transitive</li></ul><p>Finally we looked at how .NET Core provides library authors with some useful tools that can help integration with .NET Core’s DI system seamless.</p><p>I hoped you learned something new! As always, leave some your thoughts in the comments 👌</p><hr><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><h2 id="You-Might-Enjoy"><a href="#You-Might-Enjoy" class="headerlink" title="You Might Enjoy"></a>You Might Enjoy</h2><ul><li><a href="https://www.blog.jamesmichaelhickey.com/What-Makes-NET-Core-So-Special-Why-You-Should-Use-NET-Core/" target="_blank" rel="noopener">What Makes .NET Core So Special?</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/" target="_blank" rel="noopener">What I’ve Learned So Far Building Coravel (Open Source .NET Core Tooling)</a></li><li><a href="https://builtwithdot.net/blog/fluent-apis-make-developers-love-using-your-net-libraries" target="_blank" rel="noopener">Fluent APIs Make Developers Love Using Your .NET Libraries</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;If you go to the &lt;a href=&quot;https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;official docs for ASP.NET Core&lt;/a&gt; you’ll find that Dependency Injection is under the “fundamentals” area.&lt;/p&gt;
&lt;p&gt;Is that true - is it really &lt;strong&gt;fundamental?&lt;/strong&gt;&lt;/p&gt;
    
    </summary>
    
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core/"/>
    
      <category term="Dependency Injection" scheme="https://blog.jamesmichaelhickey.com/tags/Dependency-Injection/"/>
    
      <category term=".NET Core Dependency Injection" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core-Dependency-Injection/"/>
    
  </entry>
  
  <entry>
    <title>Scalable Task Scheduling In .NET Core With Coravel</title>
    <link href="https://blog.jamesmichaelhickey.com/Scalable-Task-Scheduling-In-Net-Core-Coravel/"/>
    <id>https://blog.jamesmichaelhickey.com/Scalable-Task-Scheduling-In-Net-Core-Coravel/</id>
    <published>2018-12-05T08:25:33.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>This post is part of the <a href="https://crosscuttingconcerns.com/The-Second-Annual-C-Advent" target="_blank" rel="noopener">2018 C# Advent Calendar</a>.</p><p>In the spirit of the season, we’ll be discussing how Santa Clause has recently been using .NET Core to build his internal Christmas present processing system.</p><a id="more"></a><h1 id="Santa’s-Needs"><a href="#Santa’s-Needs" class="headerlink" title="Santa’s Needs"></a>Santa’s Needs</h1><p>Santa is an intermediate developer but has been learning the ins-and-outs of .NET Core. </p><p>He recently needed to build a system that was robust in terms of security and ease of development.</p><p>He decided that .NET Core was the best choice when considering these criteria.</p><p>Santa didn’t want to re-invent the wheel - but he needed a reliable yet simple way to schedule background tasks, queue work so his web app was responsive (mostly for the elves), etc.</p><h1 id="Coravel"><a href="#Coravel" class="headerlink" title="Coravel"></a>Coravel</h1><p>One day he came across <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> - which is a near-zero config open source library for .NET Core developers. </p><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> focuses on helping developers get their web applications up-and-running fast - without compromising code quality. It makes what are usually very advanced features super easy-to-use and accessible - without needing to install any extra 3rd-party infrastructure:</p><ul><li>Task scheduling</li><li>Queuing</li><li>Caching</li><li>Event broadcasting</li><li>and more</li></ul><p>Because it’s written specifically as a set of tools targeted for .NET Core, it takes advantage of native features - such as full support for the <a href="https://docs.microsoft.com/en-us/aspnet/core/fundamentals/dependency-injection?view=aspnetcore-2.1" target="_blank" rel="noopener">built-in dependency injection services</a> and the <a href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice" target="_blank" rel="noopener">hosted background services</a>.</p><p>For example, you can inject dependencies/services into scheduled tasks, queued tasks, event listeners, etc. with zero fuss!</p><p>Santa has really enjoyed using <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> - especially the time savings gained from not having to configure and install other dependencies for scheduling, queuing, event broadcasting, etc. individually. </p><p>He especially loves that <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> ties into .NET Core’s DI system so seamlessly.</p><h1 id="Drawback"><a href="#Drawback" class="headerlink" title="Drawback"></a>Drawback</h1><p>But - now Santa has to schedule some <strong>really</strong> long running tasks. Tasks that might take hours to run. And these are important tasks.</p><p>Doing this <strong>inside</strong> his ASP .NET Core application is not an option since doing these types of long-running tasks in a web app will cause issues (as you probably know).</p><h1 id="The-Solution"><a href="#The-Solution" class="headerlink" title="The Solution"></a>The Solution</h1><p>Santa decided to check out <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel’s GitHub repo</a> - just in case this has been addressed before. </p><p>It turns out that <a href="https://github.com/jamesmh/coravel/blob/master/Samples/HostBuilderConsole/Program.cs" target="_blank" rel="noopener">there is a sample to address this exact concern!</a> </p><p>I asked Santa if I could share how he decided to implement this. He agreed, but I was only permitted to show a very small sample of his system.</p><h1 id="Scheduling-Tasks-From-NET-Core-Console-Applications"><a href="#Scheduling-Tasks-From-NET-Core-Console-Applications" class="headerlink" title="Scheduling Tasks From .NET Core Console Applications"></a>Scheduling Tasks From .NET Core Console Applications</h1><p>One of the benefits of <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> being specially for .NET Core is that it’s <strong>so simple to configure</strong>. </p><p>Combined with one of .NET Core’s coolest features, <code>HostBuilder</code>, and you can do some really powerful things in just a few lines of code.</p><p>The <code>HostBuilder</code>, by the way, let’s you construct a .NET Core application by adding just the specific pieces you need. Then you can “host” whatever you need (mini-API endpoints, console app running background tasks, or multiple <a href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice" target="_blank" rel="noopener">hosted services</a>) without the full dependencies needed for a typical web project.</p><p>Because Coravel is not a port of a .NET Framework library, but is specially built for .NET Core, Coravel’s features - such as scheduling and queuing - are implemented as a <a href="https://docs.microsoft.com/en-us/dotnet/standard/microservices-architecture/multi-container-microservice-net-applications/background-tasks-with-ihostedservice" target="_blank" rel="noopener">hosted services</a>. <strong>This means <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> is 100% compatible in non-web scenarios.</strong></p><p>Using the sample mentioned above, let’s look at a very basic implementation of using <code>HostBuilder</code> along with Coravel’s scheduling:</p><pre class=" language-csharp"><code class="language-csharp"><span class="token keyword">class</span> <span class="token class-name">Program</span><span class="token punctuation">{</span>    <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">Main</span><span class="token punctuation">(</span><span class="token keyword">string</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span>    <span class="token punctuation">{</span>        <span class="token keyword">var</span> host <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">HostBuilder</span><span class="token punctuation">(</span><span class="token punctuation">)</span>            <span class="token punctuation">.</span><span class="token function">ConfigureAppConfiguration</span><span class="token punctuation">(</span><span class="token punctuation">(</span>hostContext<span class="token punctuation">,</span> configApp<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>            <span class="token punctuation">{</span>                configApp<span class="token punctuation">.</span><span class="token function">AddCommandLine</span><span class="token punctuation">(</span>args<span class="token punctuation">)</span><span class="token punctuation">;</span>            <span class="token punctuation">}</span><span class="token punctuation">)</span>            <span class="token punctuation">.</span><span class="token function">ConfigureServices</span><span class="token punctuation">(</span><span class="token punctuation">(</span>hostContext<span class="token punctuation">,</span> services<span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span>            <span class="token punctuation">{</span>                <span class="token comment" spellcheck="true">// Add Coravel's Scheduling...</span>                services<span class="token punctuation">.</span><span class="token function">AddScheduler</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>            <span class="token punctuation">}</span><span class="token punctuation">)</span>            <span class="token punctuation">.</span><span class="token function">Build</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">// Configure the scheduled tasks....</span>        host<span class="token punctuation">.</span>Services<span class="token punctuation">.</span><span class="token function">UseScheduler</span><span class="token punctuation">(</span>scheduler <span class="token operator">=</span><span class="token operator">></span>            scheduler                <span class="token punctuation">.</span><span class="token function">Schedule</span><span class="token punctuation">(</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token operator">=</span><span class="token operator">></span> Console<span class="token punctuation">.</span><span class="token function">WriteLine</span><span class="token punctuation">(</span><span class="token string">"This was scheduled every minute."</span><span class="token punctuation">)</span><span class="token punctuation">)</span>                <span class="token punctuation">.</span><span class="token function">EveryMinute</span><span class="token punctuation">(</span><span class="token punctuation">)</span>        <span class="token punctuation">)</span><span class="token punctuation">;</span>        <span class="token comment" spellcheck="true">// Run it!</span>        host<span class="token punctuation">.</span><span class="token function">Run</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    <span class="token punctuation">}</span><span class="token punctuation">}</span></code></pre><p>This will be a console app that hooks into Coravel’s scheduler. </p><p>Every minute something will happen.</p><h1 id="Supporting-NET-Core-Dependency-Injection-With-Invocables"><a href="#Supporting-NET-Core-Dependency-Injection-With-Invocables" class="headerlink" title="Supporting .NET Core Dependency Injection With Invocables"></a>Supporting .NET Core Dependency Injection With Invocables</h1><p>Ok - that’s a simple sample. Santa needs something more maintainable and he <strong>really</strong> needs to inject his Entity Framework Core Db context, <code>HttpClientFactory</code>, etc. into his scheduled tasks.</p><p>With <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> you can use <a href="https://github.com/jamesmh/coravel/blob/master/Docs/Invocables.md" target="_blank" rel="noopener">Invocable</a> classes to solve this problem.</p><blockquote><p>Invocables are ubiquitous classes that can be scheduled, queued, etc. with full support for .NET Core dependency injection. </p><p>They represent some “job” in your application:</p><ul><li>Sending automated emails</li><li>Cleaning your database</li><li>Processing messages from an external queue</li><li>Syncing data between an external API and your system</li></ul></blockquote><h1 id="Santa’s-Invocables"><a href="#Santa’s-Invocables" class="headerlink" title="Santa’s Invocables"></a>Santa’s Invocables</h1><p>Santa has an API that he uses to fetch who is nice and naughty (it’s a secret end-point from his legacy system). He then needs to do some CPU intensive processing to validate the data, and then store the results in his database. </p><p>He needs this done once every hour using the invocable classes he’s created. </p><pre class=" language-csharp"><code class="language-csharp">scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>PutNaughtyChildrenFromAPIIntoDb<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">.</span><span class="token function">Hourly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>PutNiceChildrenFromAPIIntoDb<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">.</span><span class="token function">Hourly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    </code></pre><h1 id="Problem-With-Scalability"><a href="#Problem-With-Scalability" class="headerlink" title="Problem With Scalability"></a>Problem With Scalability</h1><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> internally uses <code>Task.WhenAll</code> to make sure async calls within scheduled tasks are processed efficiently. </p><p>However, CPU intensive tasks will “hog” the thread that is currently processing due tasks. This would force other due tasks to wait until the CPU intensive processing is completed.</p><p>This design makes sure that in web application scenarios <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> won’t be hogging multiple threads that could otherwise be (and should be) used to respond to HTTP requests.</p><p>But Santa is specifically using a console application so he doesn’t need to worry about that! </p><p>What should he do?</p><h1 id="Schedule-Workers"><a href="#Schedule-Workers" class="headerlink" title="Schedule Workers"></a>Schedule Workers</h1><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> solves this problem with <a href="https://github.com/jamesmh/coravel/blob/master/Docs/Scheduler.md#schedule-workers" target="_blank" rel="noopener">Schedule Workers</a>.</p><p>By using schedule workers Santa can put each of these tasks onto their own dedicated pipeline/thread:</p><pre class=" language-csharp"><code class="language-csharp">scheduler<span class="token punctuation">.</span><span class="token function">OnWorker</span><span class="token punctuation">(</span><span class="token string">"NaughtyWorker"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>PutNaughtyChildrenFromAPIIntoDb<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">.</span><span class="token function">Hourly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler<span class="token punctuation">.</span><span class="token function">OnWorker</span><span class="token punctuation">(</span><span class="token string">"NiceWorker"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>PutNiceChildrenFromAPIIntoDb<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span>    <span class="token punctuation">.</span><span class="token function">Hourly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>    </code></pre><p>This will now execute each task in parallel so Santa can fetch and process both of these more efficiently. Any intensive CPU work that either task may perform will not cause the other to wait/block.</p><h1 id="Schedule-Task-Groups"><a href="#Schedule-Task-Groups" class="headerlink" title="Schedule Task Groups"></a>Schedule Task Groups</h1><p>In some cases, you may want to put multiple tasks onto one worker and perhaps dedicate one worker for a task that is known to either take a long time or is just CPU intensive.</p><p>For example:</p><pre class=" language-csharp"><code class="language-csharp">scheduler<span class="token punctuation">.</span><span class="token function">OnWorker</span><span class="token punctuation">(</span><span class="token string">"EmailTasks"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>SendNightlyReportsEmailJob<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Daily</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>SendPendingNotifications<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">EveryMinute</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler<span class="token punctuation">.</span><span class="token function">OnWorker</span><span class="token punctuation">(</span><span class="token string">"CPUIntensiveTasks"</span><span class="token punctuation">)</span><span class="token punctuation">;</span>scheduler    <span class="token punctuation">.</span><span class="token generic-method function">Schedule<span class="token punctuation">&lt;</span>RebuildStaticCachedData<span class="token punctuation">></span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">Hourly</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span></code></pre><p>The first two tasks don’t take that long to complete and are not a priority in terms of CPU usage (they are mostly I/O bound).</p><p>The second, however, needs to be able to work without being blocked or blocking other tasks.</p><p>This setup will ensure that <code>RebuildStaticCachedData</code> is always executed in isolation with it’s own dedicated pipeline.</p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>I hope you’ve enjoyed this article and would love to hear from you in the comments! Maybe there’s a better way to do this? Maybe you simply prefer some other way?</p><hr><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h2 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h2><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><h2 id="You-Might-Also-Enjoy"><a href="#You-Might-Also-Enjoy" class="headerlink" title="You Might Also Enjoy"></a>You Might Also Enjoy</h2><ul><li><a href="https://www.blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/" target="_blank" rel="noopener">What I’ve Learned So Far Building Coravel (Open Source .NET Core Tooling)</a></li><li><a href="https://builtwithdot.net/blog/fluent-apis-make-developers-love-using-your-net-libraries" target="_blank" rel="noopener">Fluent APIs Make Developers Love Using Your .NET Libraries</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/What-Makes-NET-Core-So-Special-Why-You-Should-Use-NET-Core/" target="_blank" rel="noopener">What Makes .NET Core So Special?</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;This post is part of the &lt;a href=&quot;https://crosscuttingconcerns.com/The-Second-Annual-C-Advent&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;2018 C# Advent Calendar&lt;/a&gt;.&lt;/p&gt;
&lt;p&gt;In the spirit of the season, we’ll be discussing how Santa Clause has recently been using .NET Core to build his internal Christmas present processing system.&lt;/p&gt;
    
    </summary>
    
      <category term="Task Scheduling" scheme="https://blog.jamesmichaelhickey.com/categories/Task-Scheduling/"/>
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/categories/Task-Scheduling/NET-Core/"/>
    
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/tags/C/"/>
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core/"/>
    
      <category term="Coravel" scheme="https://blog.jamesmichaelhickey.com/tags/Coravel/"/>
    
      <category term="Task Scheduling" scheme="https://blog.jamesmichaelhickey.com/tags/Task-Scheduling/"/>
    
  </entry>
  
  <entry>
    <title>What Is .NET Core? (What Makes It So Special?)</title>
    <link href="https://blog.jamesmichaelhickey.com/What-Makes-NET-Core-So-Special-Why-You-Should-Use-NET-Core/"/>
    <id>https://blog.jamesmichaelhickey.com/What-Makes-NET-Core-So-Special-Why-You-Should-Use-NET-Core/</id>
    <published>2018-10-18T00:43:27.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>With all the buzz around .NET Core I figured that I should tackle some of the fundamental issues that make .NET Core a gamechanger.</p><p>.NET Core <strong>really</strong> is the next generation of .NET development and I believe that it’s time for .NET developers everywhere to migrate!</p><a id="more"></a><h1 id="What-Is-NET-Core"><a href="#What-Is-NET-Core" class="headerlink" title="What Is .NET Core"></a>What Is .NET Core</h1><p>For those new to .NET Core, I’d like to quickly explain what .NET Core is.</p><ul><li><p>Imagine being able to run C# apps (natively) in Linux.</p></li><li><p>Imagine being able to use “npm like” tools that scaffold new projects for you.</p></li><li><p>What if you didn’t need Visual Studio anymore? What if you could build entire apps using VS Code? 🤯</p></li></ul><p>.NET Core is basically the .NET languages (C#, F#, etc.) re-written onto a completely new runtime/sdk.</p><p>This runtime is not Windows specific. That means it runs on Linux, Mac and Windows.</p><p>It offers developers modern tooling that can scaffold projects, build, run, test and deploy using incredibly easy-to-use CLI tools.</p><p>.NET Core isn’t simply a huge framework (like .NET Framework) that you built on top of. It’s included as NuGet packages that you can use to carefully craft only the little tiny pieces that you need - if you do need that level of flexibility.</p><p>Since .NET apps have much less of a footprint, they are perfect for scenarios where you need to build small, high-performing, isolated applications - Micro-services.</p><h1 id="Who-Is-Using-NET-Core-Anyways"><a href="#Who-Is-Using-NET-Core-Anyways" class="headerlink" title="Who Is Using .NET Core Anyways?"></a>Who Is Using .NET Core Anyways?</h1><p>Aren’t all the massive/large scale apps using Nodejs though? Nodejs is typically touted as the highest performing and most scalable platform for building modern web apps. Is that true?</p><p>I want to go through some of the companies and products that are currently using .NET Core in production (taken from <a href="https://www.microsoft.com/net/platform/customers" target="_blank" rel="noopener">these case studies on the official .NET site</a>). We’ll look at why they decided to use .NET Core and what benefits they found were critical to their businesses.</p><h2 id="RayGun-High-Performance"><a href="#RayGun-High-Performance" class="headerlink" title="RayGun: High Performance"></a>RayGun: High Performance</h2><p>Quoting the official site:</p><blockquote><p>Using the same-size server, we were able to go from 1,000 requests per second per node with Node.js to 20,000 requests per second with .NET Core.</p></blockquote><p>That’s pretty amazing! That’s an increase of <strong>2000%</strong> in terms of requests per second. Imagine how much money you could save by moving to a smaller hosting environment because you don’t need so much “juice”?</p><h2 id="Siemens-Healthineers-Linux-Enabled"><a href="#Siemens-Healthineers-Linux-Enabled" class="headerlink" title="Siemens Healthineers: Linux Enabled"></a>Siemens Healthineers: Linux Enabled</h2><blockquote><p> It also gives us strong benefits with regard to operation costs in the cloud, because we can use it to run some workloads on Linux machines.</p></blockquote><p>Not only does .NET Core allow you to run-more-code-on-less-machine, but you can also run an entire .NET Core app within a Linux operating system. Since they are generally free, the cost savings of <strong>not</strong> requiring paid OS licenses can save <strong>a lot</strong> of money.</p><h2 id="GoDaddy-Scalability"><a href="#GoDaddy-Scalability" class="headerlink" title="GoDaddy: Scalability"></a>GoDaddy: Scalability</h2><blockquote><p>Services can be developed more quickly, perform faster in production, and scale better if they’re written using .NET Core</p></blockquote><blockquote><p>.NET Core gives us the freedom to take advantage of new infrastructure technologies that run on Linux such as Kubernetes and Docker.</p></blockquote><p>.NET Core was designed to allow you to create small isolated services and scale them independently if needed. </p><p>You don’t need to buy a new massive server just because one small part of your app is seeing a higher load. Just build a .NET Core app and stick it into a container. </p><p>Now you can infinitely scale your app as needed!</p><h2 id="VQ-Communications-Freedom-and-Flexibility"><a href="#VQ-Communications-Freedom-and-Flexibility" class="headerlink" title="VQ Communications: Freedom and Flexibility"></a>VQ Communications: Freedom and Flexibility</h2><blockquote><p>The fact that .NET Core is cross-platform allows developers more freedom in how they develop the product because, at the end of the day, it’s going to run on .NET Core, and that will be macOS, Linux, or Windows</p></blockquote><p>.NET Core can target Linux, Windows or Mac. This means you can build .NET Core apps using a Mac or Ubuntu - using VS Code or Sublime Text. You have more freedom now to use the tools that work for you.</p><p>Personally, I’ve been using VS Code to build all my .NET Core apps and libraries. I don’t need Windows. I don’t need Visual Studio. And it’s great!</p><h2 id="Age-Of-Ascent-Open-For-Contributions-And-Improvements"><a href="#Age-Of-Ascent-Open-For-Contributions-And-Improvements" class="headerlink" title="Age Of Ascent: Open For Contributions And Improvements"></a>Age Of Ascent: Open For Contributions And Improvements</h2><blockquote><p>ASP.NET is open source, that allows us to contribute back to it if we have any performance issues which Microsoft review and together we make a better product.</p></blockquote><p>Ben Adams is considered one of the most knowledgeable .NET developers in the world. He doesn’t work for Microsoft - he’s the CTO of Illyriad Games.</p><p>Since .NET Core is open source - Ben has been able to be a part of many non-Microsoft employed developers who have made .NET Core more performant, added new features and provided insights into the product.</p><h1 id="What-About-Indie-And-Side-Projects"><a href="#What-About-Indie-And-Side-Projects" class="headerlink" title="What About Indie And Side Projects?"></a>What About Indie And Side Projects?</h1><p>“But I’m not some super sized-organization” - you might say. What about building my side-projects quickly?</p><p>.NET Core gives you some fantastic tools that can accelerate your development:</p><ul><li>Built-in Dependency Injection</li><li>Easy and isolated configuration (no more web.config!)</li><li>Razor Pages (a new type of project that allows you to build web apps quickly)</li><li>Easy database access with Entity Framework Core</li><li>Fantastic CLI tools to scaffold and build your apps with more productivity</li></ul><p>On top of all that, I’ve been building an open source library that can accelerate building .NET Core web apps even faster!</p><p><a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel</a> gives you a near-zero config set of tools such as Task Scheduling, Queuing, Caching and a CLI that lets you scaffold even more so you can be super productive.</p><h1 id="How-To-Get-Started"><a href="#How-To-Get-Started" class="headerlink" title="How To Get Started"></a>How To Get Started</h1><p>Thinking about building your next project using .NET Core? <a href="https://docs.microsoft.com/en-us/aspnet/core/getting-started/?view=aspnetcore-2.1" target="_blank" rel="noopener">Start here.</a></p><p>Do you have a .NET Framework app that you are considering migrating to .NET Core? <a href="https://docs.microsoft.com/en-us/aspnet/core/migration/?view=aspnetcore-2.1" target="_blank" rel="noopener">Start here.</a></p><p>Already know how to use .NET Core but need more tools that will help you build fully featured web apps? <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Start here.</a></p><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="You-Might-Like-These"><a href="#You-Might-Like-These" class="headerlink" title="You Might Like These"></a>You Might Like These</h1><ul><li><a href="https://www.blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/" target="_blank" rel="noopener">What I’ve Learned So Far Building Coravel (Open Source .NET Core Tooling)</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/Async-Await-For-The-Rest-Of-Us/" target="_blank" rel="noopener">Async/Await For The Rest Of Us</a></li></ul><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;With all the buzz around .NET Core I figured that I should tackle some of the fundamental issues that make .NET Core a gamechanger.&lt;/p&gt;
&lt;p&gt;.NET Core &lt;strong&gt;really&lt;/strong&gt; is the next generation of .NET development and I believe that it’s time for .NET developers everywhere to migrate!&lt;/p&gt;
    
    </summary>
    
      <category term=".Net Core" scheme="https://blog.jamesmichaelhickey.com/categories/Net-Core/"/>
    
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core/"/>
    
  </entry>
  
  <entry>
    <title>What I&#39;ve Learned So Far Building Coravel (Open Source .NET Core Tooling) - Part 1</title>
    <link href="https://blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/"/>
    <id>https://blog.jamesmichaelhickey.com/What-I-ve-Learned-So-Far-Building-Coravel-Open-Source-NET-Core-Tooling/</id>
    <published>2018-09-28T14:54:24.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>One night, about 4 months ago, I had a couple hours of free-time. I was really enjoying the benefits of building apps with .NET Core. But I felt it was still missing all the “built-in” features that makes <a href="https://laravel.com/" target="_blank" rel="noopener">Laravel</a> (PHP Framework) such a breeze to work with. </p><p>After all, I just want to build awesome apps and not tinker with the same old boilerplate stuff. </p><p><strong>What if I just want to schedule <em>my code</em> to run once a week?</strong> I don’t want to configure Windows Task Scheduler. Or Cron. I just want to tell my code to schedule itself. Shouldn’t that be easy to do (like with Laravel)?</p><a id="more"></a><h1 id="Beginning-Of-The-Story"><a href="#Beginning-Of-The-Story" class="headerlink" title="Beginning Of The Story"></a>Beginning Of The Story</h1><p>So I set out to learn some .NET Core while building an easy to use scheduler - similar to Laravel’s. Just to challenge myself and see if I could do it. Eventually, “version 1” was completed.</p><p>I don’t have much free time, so I need to make sure what I do is important. So I decided to tweet what I had on Twitter to <strong>maybe</strong> get some feedback. Who knows… </p><p>To my surprise, <a href="https://twitter.com/davidfowl" target="_blank" rel="noopener">David Fowler</a> (.NET Core Architect) responded and the tweet gained <strong>way more</strong> interactions than I ever thought it would!</p><p><blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">What if you could do this in your .Net Core apps? <a href="https://t.co/dj7JgbVELC" target="_blank" rel="noopener">https://t.co/dj7JgbVELC</a><a href="https://twitter.com/hashtag/dotnet?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#dotnet</a> <a href="https://twitter.com/hashtag/coravel?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#coravel</a> <a href="https://twitter.com/hashtag/dotnetcore?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#dotnetcore</a> <a href="https://t.co/KNHZwJbrg0" target="_blank" rel="noopener">pic.twitter.com/KNHZwJbrg0</a></p>&mdash; James Hickey (@jamesmh_dev) <a href="https://twitter.com/jamesmh_dev/status/1010238650825756672?ref_src=twsrc%5Etfw" target="_blank" rel="noopener">June 22, 2018</a></blockquote></p><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><p>That was on a Friday. In just <strong>two days</strong> the <a href="https://github.com/jamesmh/coravel" target="_blank" rel="noopener">Coravel repo</a> became the top #4 trending C# repo on all of GitHub! Wow! I was (and still am) super humbled and surprised!</p><p><img src="/img/coravel-4th-github.png" alt="Coravel trending on GitHub"></p><h1 id="Building-More-Features"><a href="#Building-More-Features" class="headerlink" title="Building More Features"></a>Building More Features</h1><p>Obviously, people thought this was a useful tool. So I decided to keep going and build other features that I personally would like available:</p><ul><li>Easy to use queuing</li><li>A terse way to cache stuff</li><li>Mailer that is easy to configure, has an expressive syntax and comes with out-of-the-box responsive e-mail templates</li><li>CLI to generate files, etc.</li></ul><p>When I had the time, I did my best to build them. Today, there are even more features than I had anticipated.</p><p>Originally, the scheduler was just a fun challenge. But now people were <strong>actually using it</strong>. So I had to re-write it to be more flexible, more unit tests, thread safety, etc.</p><h1 id="What-Did-I-Learn"><a href="#What-Did-I-Learn" class="headerlink" title="What Did I Learn?"></a>What Did I Learn?</h1><p>Throughout this journey, I’ve learned <strong>tons</strong> - and am still learning each day.</p><p>I wanted to start documenting some of these things - and give tips to those wanting to build their own .NET based open source projects.</p><h2 id="1-NuGet-Gotcha’s"><a href="#1-NuGet-Gotcha’s" class="headerlink" title="1. NuGet Gotcha’s"></a>1. NuGet Gotcha’s</h2><p>I had no experience building NuGet packages. I’ve never done it before.</p><p>When I had originally built the Mailer feature, it was a separate .NET project that was referenced by the “main” Coravel project. My thinking was that NuGet packages just swallowed any referenced projects and included them.</p><p><strong>Wrong.</strong></p><p>Nuget packages don’t do that. And, it sounds like they never will. </p><p><strong>What do you do?</strong> There are two solutions to my knowledge:</p><ul><li>Include them into your <strong>one</strong> package</li><li>Package other projects as <strong>separate NuGet</strong> packages and reference them</li></ul><p>The second option does force you to focus on building small modular packages.</p><p>But one of the driving philosophies behind Coravel is that it should be as easy and possible to get up-and-running. Multiple packages, in my eyes, was straying from this.</p><p>I chose to go with option 1. I didn’t want to have to maintain more than one package (and all the extra maintenance that comes with it).</p><h2 id="2-Listen-To-The-Community"><a href="#2-Listen-To-The-Community" class="headerlink" title="2. Listen To The Community"></a>2. Listen To The Community</h2><p>But what happens when you make the wrong choice?</p><p>I had comments from people around the idea of not wanting to include the Mailer’s dependencies (MailKit, etc,) when just wanting to use, for example, the scheduler. Fair enough. </p><p>So I ran I poll to see what others thought:</p><p><blockquote class="twitter-tweet" data-lang="en"><p lang="en" dir="ltr">Question for peeps: <br><br>Right now Coravel includes MailKit as a dependency for the Mailer. Should the Mailer be a separate nuget so that using the Scheduler doesn&#39;t include MailKit? Should all the features be split?<a href="https://twitter.com/hashtag/AspNetCore?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#AspNetCore</a> <a href="https://twitter.com/hashtag/ASPNET?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#ASPNET</a> <a href="https://twitter.com/hashtag/Dotnet?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#Dotnet</a> <a href="https://twitter.com/hashtag/dotnetcore?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#dotnetcore</a> <a href="https://twitter.com/hashtag/coravel?src=hash&amp;ref_src=twsrc%5Etfw" target="_blank" rel="noopener">#coravel</a></p>&mdash; James Hickey (@jamesmh_dev) <a href="https://twitter.com/jamesmh_dev/status/1035487034679455744?ref_src=twsrc%5Etfw" target="_blank" rel="noopener">August 31, 2018</a></blockquote></p><script async src="https://platform.twitter.com/widgets.js" charset="utf-8"></script><p>Since this project is for others to use - it’s important to know how people generally are wanting to use it.</p><p>But, I’m not fond of having to maintain multiple packages. The technical complexities this would introduce (splitting all the features) is not wanted right now either. </p><p>So, I decided to go with splitting the Mailer into its own NuGet package. </p><h2 id="3-It’s-OK-To-Go-Back-And-Fix-Things"><a href="#3-It’s-OK-To-Go-Back-And-Fix-Things" class="headerlink" title="3. It’s OK To Go Back And Fix Things"></a>3. It’s OK To Go Back And Fix Things</h2><p>So, I had made the wrong choice in bundling the Mailer into the main Coravel package.</p><p>Is that a sin? Nope. Did I beat myself up because of it? Nope.</p><p>As your project grows you <strong>discover how people are using your project and adapt</strong>. <strong>Actively listen</strong> to how people want to use your project.</p><p>For example, I’ve had people mention they don’t like the fact that Coravel is targeting .NET Core and <strong>not</strong> .NET Standard. </p><p>Originally, Coravel was designed <strong>only for</strong> .NET Core apps. One of the main principles was that Coravel needed to just “hook” into the native .NET Core tooling so that it was seamless and super easy to configure. Especially making things hook into the service provider, <code>IHostedService</code> interface, etc.</p><p>However, slimming of some dependencies (due to some issues posted by others on GitHub) <strong>caused me to learn more</strong> about how .NET Core works. Due to those changes, switching to .NET Standard might actually make sense now. So I’m looking at investigating this as we speak.</p><p>And that’s OK. I may have gone the “wrong” route originally. But <strong>I’m still learning</strong>. </p><blockquote><p>It’s OK to learn from your mistakes. That’s how we gain experience. Go back and make it “right”.</p></blockquote><h2 id="4-Building-A-Project-Takes-Time-Be-In-It-For-The-Long-Haul"><a href="#4-Building-A-Project-Takes-Time-Be-In-It-For-The-Long-Haul" class="headerlink" title="4. Building A Project Takes Time - Be In It For The Long-Haul"></a>4. Building A Project Takes Time - Be In It For The Long-Haul</h2><p>It’s been 4 months since I started Coravel. Have I been coding every night for 4 hours non-stop? Nope.</p><p>I’ve got 7 kids. We homeschool. I’m married. I’ve got a full-time job. I’ve got a life. </p><p>Do I have much free time? Nope.</p><p>The little bit of free time that I do get has to be allocated to a handful of “important” projects, such as this blog. </p><p>If I spend time working on this blog then it’s time that I won’t be able to work on other things - like Coravel.</p><p>It’s a juggling act for me. Probably for you too.</p><p>Having a long-term vision is what I need to ensure that I don’t get overwhelmed when I don’t get around to doing X for a few weeks.</p><p>And it’s what you’ll need if you want to build a lasting, useful and robust open source project. </p><h2 id="5-Pull-Requests-Take-Time"><a href="#5-Pull-Requests-Take-Time" class="headerlink" title="5. Pull Requests Take Time"></a>5. Pull Requests Take Time</h2><p>Talking about time-suckers…</p><p>Pull-requests take <strong>a lot</strong> of time. <strong>Way more than I had ever expected</strong>. </p><p>I’m super excited that people are interested in contributing to something that I’ve built. </p><p>But open source doesn’t mean that anyone can change projects to be what they want. I have a vision and philosophy behind everything I create in Coravel. Others can’t read my mind.</p><p>It’s my job then to make sure all contributions adhere to that vision. This means (for me) addressing what may seem like super insignificant details - one-word changes to documentation, variable naming, etc.</p><p>But, to me, all the small details matter. It’s what makes Coravel unique. It’s what makes it easy to use.</p><p>So don’t feel bad when you aren’t just accepting pull-requests right-and-left. <strong>It’s still your project</strong>. </p><h1 id="Until-Next-Time"><a href="#Until-Next-Time" class="headerlink" title="Until Next Time"></a>Until Next Time</h1><p>I hope you enjoyed the story behind Coravel so far and some things I’ve learned along the way. </p><p>I’d like to write another post soon that highlights the technical things I’ve learned - and get into some code!</p><h1 id="Other-Parts-In-This-Series"><a href="#Other-Parts-In-This-Series" class="headerlink" title="Other Parts In This Series"></a>Other Parts In This Series</h1><ul><li><a href="https://builtwithdot.net/blog/fluent-apis-make-developers-love-using-your-net-libraries" target="_blank" rel="noopener">Part 2: Fluent APIs Make Developers Love Using Your .NET Libraries</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/NET-Core-Dependency-Injection/" target="_blank" rel="noopener">Part 3: .NET Core Dependency Injection: Everything You Ought To Know</a></li></ul><hr><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;One night, about 4 months ago, I had a couple hours of free-time. I was really enjoying the benefits of building apps with .NET Core. But I felt it was still missing all the “built-in” features that makes &lt;a href=&quot;https://laravel.com/&quot; target=&quot;_blank&quot; rel=&quot;noopener&quot;&gt;Laravel&lt;/a&gt; (PHP Framework) such a breeze to work with. &lt;/p&gt;
&lt;p&gt;After all, I just want to build awesome apps and not tinker with the same old boilerplate stuff. &lt;/p&gt;
&lt;p&gt;&lt;strong&gt;What if I just want to schedule &lt;em&gt;my code&lt;/em&gt; to run once a week?&lt;/strong&gt; I don’t want to configure Windows Task Scheduler. Or Cron. I just want to tell my code to schedule itself. Shouldn’t that be easy to do (like with Laravel)?&lt;/p&gt;
    
    </summary>
    
    
      <category term=".NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core/"/>
    
      <category term="Coravel" scheme="https://blog.jamesmichaelhickey.com/tags/Coravel/"/>
    
      <category term="ASP .NET Core" scheme="https://blog.jamesmichaelhickey.com/tags/ASP-NET-Core/"/>
    
      <category term=".NET Core Sass" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core-Sass/"/>
    
      <category term="Open Source Development" scheme="https://blog.jamesmichaelhickey.com/tags/Open-Source-Development/"/>
    
      <category term=".NET Core Indie Developer" scheme="https://blog.jamesmichaelhickey.com/tags/NET-Core-Indie-Developer/"/>
    
  </entry>
  
  <entry>
    <title>Async/Await For The Rest Of Us</title>
    <link href="https://blog.jamesmichaelhickey.com/Async-Await-For-The-Rest-Of-Us/"/>
    <id>https://blog.jamesmichaelhickey.com/Async-Await-For-The-Rest-Of-Us/</id>
    <published>2018-08-28T02:26:21.000Z</published>
    <updated>2022-09-07T01:11:18.496Z</updated>
    
    <content type="html"><![CDATA[<p>What’s the deal with <code>async</code> and <code>await</code> in C#? Why should a .NET developer in 2019 <strong>need</strong> to know what it is and how to use it?</p><a id="more"></a><p>Perhaps you’ve used <code>async/await</code> but find yourself having to go back and figure it out again?</p><p>I’ve had to figure out the hard way that, for example, using <code>ConfigureAwait(false).GetResult()</code> doesn’t magically make your async method “work” synchronously.</p><p>But this isn’t an in-depth look at the internals of <code>async/await</code> and how to get fancy with <code>async/await</code>.</p><p>This is <em>“Async/await for the rest of us”</em>. Who are <em>the rest of us</em>?</p><p>We:</p><ul><li>Might have never used <code>async/await</code></li><li>Are not Microsoft gurus</li><li>Are not C# gurus</li><li>Admittedly forget how to use <code>async/await</code> properly at times.</li><li>Might have to go back to Google and figure out why a method can return a <code>Task</code> but not use the <code>async</code> keyword.</li><li>Might wonder why a method that’s <strong>not</strong> marked as <code>async</code> can be awaited by it’s caller</li></ul><p>This - I hope - is an article for “the rest of us” that’s to the point and practical.</p><p><em>P.S. If you do want to dig into this topic more the best starting point is <a href="https://blog.stephencleary.com/2012/02/async-and-await.html" target="_blank" rel="noopener">I’d suggest starting with this article.</a></em></p><h1 id="Why-Async"><a href="#Why-Async" class="headerlink" title="Why Async?"></a>Why Async?</h1><p>What’s the benefit of using <code>async/await</code>?</p><h2 id="For-Web-Developers"><a href="#For-Web-Developers" class="headerlink" title="For Web Developers"></a>For Web Developers</h2><p>If you build web apps using .NET technologies - the answer is simple: <strong>Scalability</strong>.</p><p>When you make I/O calls - database queries, file reading, reading from HTTP requests, etc. - the thread that is handling the current HTTP request is <strong>just waiting</strong>.</p><p>That’s it. <strong>It’s just waiting for a result to come back from the operating system.</strong></p><p>Performing a database query, for example, ultimately asks the operating system to connect to the database, send a message and get a message in return. But that is the OS making these requests - <strong>not your app.</strong></p><blockquote><p>Using <code>async/await</code> allows your .NET web apps to be able to handle <strong>more HTTP requests while waiting for IO to complete.</strong></p></blockquote><h2 id="For-Desktop-App-Developers"><a href="#For-Desktop-App-Developers" class="headerlink" title="For Desktop/App Developers"></a>For Desktop/App Developers</h2><p>But desktop apps don’t handle HTTP requests…</p><p>Well, desktop apps <strong>do</strong> handle user input (keyboard, mouse, etc.), animations, etc. And there’s only <strong>one UI thread</strong> to do that.</p><h3 id="User-Input-Is-User-Input"><a href="#User-Input-Is-User-Input" class="headerlink" title="User Input Is User Input"></a>User Input Is User Input</h3><p>If we consider that HTTP requests in a web app are <em>just user input</em>, and desktop (or app) keyboard and mouse events are <em>just user input</em> - then it’s actually worse for desktop/app developers! They only get <strong>one thread</strong> to handle user input!</p><p>The I/O issues and fixes still apply.</p><p>However, the issue of CPU intensive tasks is another concern. In a nutshell, these types of tasks should not be done on the UI thread.</p><p>The types of tasks would include:</p><ul><li>Processing a large number of items in a loop</li><li>Computing aggregations for reporting</li></ul><p>If your app does this (on the main/UI thread), then there’s nothing to handle user input and UI stuff like animations, etc.</p><p>This leads to freezing and laggy apps.</p><p>The solution is to offload CPU intensive tasks to a background task/thread. This starts to get into queuing up new threads/tasks, how to use <code>ConfigureAwait(false)</code> to keep asynchronous branches of your code on a non-UI context, etc. All things beyond the scope of our article.</p><h1 id="The-Async-Keyword"><a href="#The-Async-Keyword" class="headerlink" title="The Async Keyword"></a>The Async Keyword</h1><p>Let’s start looking at the <code>async/await</code> keywords and how they are to be used.</p><p>There’s confusion over the async keyword. Why? Because it looks like it <strong>makes</strong> your method asynchronous. But, it doesn’t.</p><p>That’s confusing. The <code>async</code> keyword <strong>doesn’t make my method asynchronous</strong>? Yep.</p><h2 id="What-Does-it-Do-Then"><a href="#What-Does-it-Do-Then" class="headerlink" title="What Does it Do Then?"></a>What Does it Do Then?</h2><p>All the <code>async</code> keyword does is <strong>enable the await keyword</strong>. That’s it. That’s all. It does nothing else.</p><p>So, just think of the <code>async</code> keyword as the <code>enableAwait</code> keyword.</p><h1 id="The-Await-Keyword"><a href="#The-Await-Keyword" class="headerlink" title="The Await Keyword"></a>The Await Keyword</h1><p>The <code>await</code> keyword is where the magic happens. It basically says (to the reader of the code):</p><blockquote><p>I (the thread) will make sure if something asynchronous happens under here, that I’ll go do something else (like handle HTTP requests). Some thread in the future will come back here once the asynchronous stuff is done.</p></blockquote><p>Generally, the most common usage of <code>await</code> is when you are doing I/O - like getting results from a database query or getting contents from a file.</p><p>When you <code>await</code> a method that does I/O, it’s <strong>not your app</strong> that does the I/O - it’s ultimately the operating system. So your thread is just sitting there…waiting…</p><p><code>await</code> will tell the current thread to just go away and do something useful. Let the operating system and the .NET framework get another thread later - whenever it needs one.</p><p>Consider this as a visual guide:</p><pre class=" language-c#"><code class="language-c#">var result1 = await SomeAsyncIO1(); // OS is doing I/O while thread will go do something else.// A thread gets the results.var result2 = await SomeAsyncIO2(result1); // Thread goes to do something else.// One comes back...await SomeAsyncIO3(result2); // Goes away again...// Comes back to finish the method.</code></pre><p>You might ask yourself at this point:</p><blockquote><p>If the <code>async</code> keyword doesn’t make a method asynchronous then what does?</p></blockquote><h2 id="What-Makes-A-Method-Asynchronous-Then"><a href="#What-Makes-A-Method-Asynchronous-Then" class="headerlink" title="What Makes A Method Asynchronous Then?"></a>What Makes A Method Asynchronous Then?</h2><p>Well - it’s not the <code>async</code> keyword as we learned. Go figure.</p><p>Any method that returns an “awaitable” - <code>Task</code> or <code>Task&lt;T&gt;</code> can be awaited using the <code>await</code> keyword.</p><p>There are actually other awaitables types. And, an “awaitable” method doesn’t strictly have to be an asynchronous method. But ignore that - this is meant to be for “the rest of us.”</p><p>For the purpose of this article, we’ll assume that an “asynchronous method” is a method that returns <code>Task</code> or <code>Task&lt;T&gt;</code>.</p><h3 id="When-Does-This-Happen"><a href="#When-Does-This-Happen" class="headerlink" title="When Does This Happen?"></a>When Does This Happen?</h3><p>When will we ever need to return a <code>Task</code> from a method? It’s usually when doing I/O. Most I/O libraries or built-in .NET APIs will have an “Async” version of a method.</p><p>For example, the <code>SqlConnection</code> class has an <code>Open</code> method that will begin the connection. But, it also has an <code>OpenAsync</code> method. It also has an <code>ExecuteNonQueryAsync</code> method.</p><pre class=" language-c#"><code class="language-c#">public async Task<int> IssueSqlCommandAsync() {    using(var con = new SqlConnection(_connectionString))    {        // Some code to create an sql command "sqlCommand" would be here...        await con.OpenAsync();        return await sqlCommand.ExecuteNonQueryAsync();    }}</code></pre><p>What makes the <code>OpenAsync</code> and <code>ExecuteNonQueryAsync</code> methods asynchronous is <strong>not</strong> the <code>async</code> keyword, but it is that they <strong>return a <code>Task</code> or <code>Task&lt;T&gt;</code></strong>.</p><h1 id="Async-All-The-Way-Down"><a href="#Async-All-The-Way-Down" class="headerlink" title="Async All The Way Down"></a>Async All The Way Down</h1><p>It is possible to do something like this (notice the lack of <code>async</code> and <code>await</code>):</p><pre class=" language-c#"><code class="language-c#">public Task<int> GetSomeData() {    return DoSomethingAsync();}</code></pre><p>And then <code>await</code> that method:</p><pre class=" language-c#"><code class="language-c#">// Inside some other method....await GetSomeData();</code></pre><p><code>GetSomeData</code> doesn’t await the call to <code>DoSomethingAsync</code> - it just returns the <code>Task</code>. Remember that <code>await</code> doesn’t care if a method is using the <code>async</code> keyword - <strong>it just requires that the method return a <code>Task</code></strong>.</p><p>It is possible to do this - create a method that calls an asynchronous method but doesn’t await.</p><h2 id="It’s-A-Best-Practice"><a href="#It’s-A-Best-Practice" class="headerlink" title="It’s A Best Practice"></a>It’s A Best Practice</h2><p>However, this is considered a bad practice. Why?</p><p>Since this article is supposed to be to the point and practical:</p><p><strong>Using async/await “all the way down” simply captures exceptions in asynchronous methods better.</strong></p><p>If you mark every method that returns a <code>Task</code> with the <code>async</code> keyword - which in turn enables the <code>await</code> keyword - it handles exceptions better and makes them understandable when looking at the exception’s message and stack trace.</p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>To summarize briefly:</p><ul><li><p>The <code>async</code> keyword doesn’t make methods asynchronous - it simply enables the <code>await</code> keyword.</p></li><li><p>If a method returns a <code>Task</code> or <code>Task&lt;T&gt;</code> then it can be used by the <code>await</code> keyword to manage the asynchronous details of our code.</p></li><li><p>Doing I/O always results in blocking threads. This means your web apps can’t process as many HTTP requests in parallel and freezing and laggy apps.</p></li><li><p>Using <code>async/await</code> helps us create code that will allow our threads to stop blocking and do useful work while performing I/O.</p></li><li><p>This leads to web apps that can handle more requests per second and apps that are more responsive for their users.</p></li></ul><p>I hope this is an understandable introduction to <code>async/await</code>. It’s not an easy topic - and as always - gaining experience by using this feature will, over time, help us to understand what’s going on.</p><p>There’s so much more to be said and so many more concepts surrounding <code>async/await</code>. Some include:</p><ul><li>What is a <code>SynchronizationContext</code>? When should I be aware of this?</li><li>What about .NET Core vs .NET Framework - is there a difference I should be aware of?</li><li>Why can I mark a method as <code>async void</code>? What does this do? Should I do this?</li><li>How do I offload CPU intensive work to a background thread/task?</li><li>Is it possible to do work on a background thread and return to the UI thread at the very end?</li><li>How do I call a method marked with the <code>async</code> keyword from synchronous code? What happens when I do this?</li></ul><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;What’s the deal with &lt;code&gt;async&lt;/code&gt; and &lt;code&gt;await&lt;/code&gt; in C#? Why should a .NET developer in 2019 &lt;strong&gt;need&lt;/strong&gt; to know what it is and how to use it?&lt;/p&gt;
    
    </summary>
    
      <category term="Async/Await" scheme="https://blog.jamesmichaelhickey.com/categories/Async-Await/"/>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/categories/Async-Await/C/"/>
    
    
      <category term="async" scheme="https://blog.jamesmichaelhickey.com/tags/async/"/>
    
      <category term="async/await" scheme="https://blog.jamesmichaelhickey.com/tags/async-await/"/>
    
      <category term="await" scheme="https://blog.jamesmichaelhickey.com/tags/await/"/>
    
      <category term="csharp" scheme="https://blog.jamesmichaelhickey.com/tags/csharp/"/>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/tags/C/"/>
    
      <category term="csharp async" scheme="https://blog.jamesmichaelhickey.com/tags/csharp-async/"/>
    
      <category term="C# async" scheme="https://blog.jamesmichaelhickey.com/tags/C-async/"/>
    
  </entry>
  
  <entry>
    <title>Keeping Your ADO Sql Connections Safe</title>
    <link href="https://blog.jamesmichaelhickey.com/keeping-ado-sql-connections-safe/"/>
    <id>https://blog.jamesmichaelhickey.com/keeping-ado-sql-connections-safe/</id>
    <published>2018-08-15T22:00:27.000Z</published>
    <updated>2022-09-07T01:11:18.500Z</updated>
    
    <content type="html"><![CDATA[<p>What happens when you don’t close your .NET <code>SqlConnection</code>s? Bad stuff. Bad stuff that will inevitably bring your IIS website crumbling down to ashes. Well… something like that. We all know that we should take extra care to always <strong>close</strong> our DB connections. Right?</p><p>But what happens when developers try to get fancy with their DB connections and focus more on being able to re-use open DB connections rather than being safe? Well, the consequences were bestowed upon me a few weeks ago.</p><p>Let me explain (briefly) what happened, what <em>could</em> happen to you, and a way to fix it - while maintaining the flexibility of re-using open DB connections and being able to safely use DB transactions from your C# code (using ADO).</p><a id="more"></a><h1 id="When-Leaky-Connections-Strike"><a href="#When-Leaky-Connections-Strike" class="headerlink" title="When Leaky Connections Strike"></a>When Leaky Connections Strike</h1><p>In the codebase I work with for my day job, there are utilities for performing SQL queries (well… calling stored procs) in C#. When I first saw this code (many months ago) I immediately thought that it was not a good thing (and told the team my thoughts).</p><p>Why? Because mishandling DB connections lead to very bad things. Better to be safe than sorry. But, it wasn’t considered an issue - it never had caused any issues yet. It was working well so far. So, it wasn’t worth fussing over - other than making my concerns public.</p><p>The pattern in question is something like this:</p><ol><li>A method that accepts a <code>SqlConnection</code> as a parameter.</li><li>Checks if the <code>SqlConnection</code> is already opened. If it is, don’t close it since the caller wants to keep it open to issue further queries.</li><li>If the <code>SqlConnection</code> is closed, open it, then run the query, then close it.</li></ol><p>The code might look like this:</p><pre><code>if (cmd.Connection.State != ConnectionState.Open){    cmd.Connection.Open();}// Do your stuff...if (origConnectionState == ConnectionState.Closed){    cmd.Connection.Close();}</code></pre><p>And yes, there is no try block.</p><h1 id="When-It-All-Comes-Crumbling-Down"><a href="#When-It-All-Comes-Crumbling-Down" class="headerlink" title="When It All Comes Crumbling Down"></a>When It All Comes Crumbling Down</h1><p>A few weeks ago, we had major issues where our site kept locking up for everyone. Long story short - the code was calling a stored procedure that didn’t exist, the DB call threw an error, and the calling code (just by chance!) silently caught the error and kept on chugging away.</p><p>Since the code was attempting to be fancy with the connections - when an error was thrown it by-passed the code that was supposed to close the connection. Normally, exceptions like this would be caught during development (and fixed).</p><p>But what happens when things aren’t thoroughly tested? And the caller is silently catching the error? Boom!</p><p>Users saw no error. Until all those un-closed connections piled up.</p><p>This took a full day to figure out where the issue was coming from since the exception was silently caught! Eventually, looking at IIS logs and the event viewer gave us some clues. I literally found and fixed the issue during my shift’s last ten minutes. Phew! What a scramble!</p><h1 id="Why-Was-This-Done"><a href="#Why-Was-This-Done" class="headerlink" title="Why Was This Done?"></a>Why Was This Done?</h1><p>Why would anyone do this? Well, the reasoning is that the caller of this method might want to issue multiple queries. Instead of having to open and close multiple <code>SqlConnection</code>s, we can have more performance by keeping one opened and closing it ourselves after all our queries are completed. Avoiding the extra re-connections to the database would be avoided.</p><p>In reality, there was not even <em>one</em> instance where a caller was re-using an open <code>SqlConnection</code> in the entire codebase. :(</p><h1 id="But-NET-Handles-ADO-Connections-For-You"><a href="#But-NET-Handles-ADO-Connections-For-You" class="headerlink" title="But .NET Handles ADO Connections For You!"></a>But .NET Handles ADO Connections For You!</h1><p>Is it true that this <em>would</em> boost performance though? Not really. By default, .NET ADO connections are <a href="https://docs.microsoft.com/en-us/dotnet/framework/data/adonet/sql-server-connection-pooling" target="_blank" rel="noopener">pooled</a>. This means that calling <code>Close()</code> on your DB connection doesn’t <em>really</em> close it (physically).</p><p>.NET handles this under the covers and keeps a pool of active connections. Any performance benefit gained is most likely just the mere cost of instantiating a new c# object in memory and the cost of finding a connection in the pool. The <strong>actual hit</strong> of connecting to the database is most likely not gained.</p><blockquote><p>Rule of thumb: Test real-world scenarios if performance is an issue. Then, test your optimizations under those same scenarios and compare.</p></blockquote><h1 id="Who’s-Responsibility-Is-It"><a href="#Who’s-Responsibility-Is-It" class="headerlink" title="Who’s Responsibility Is It?"></a>Who’s Responsibility Is It?</h1><p>There’s another issue here. Who is responsible for managing the “low-level” database access? In the code above - it’s:</p><ol><li>The low-level database utilities</li><li>And anyone who wants to use them!</li></ol><p>So, essentially, you could have an MVC controller who is creating a <code>SqlConnection</code>, passing it into the utility to perform a query, then closing the connection back inside the controller action.</p><p>But that never happens, right? Well, sometimes we inherit code that does do this. :(</p><blockquote><p>This is like going to a mechanic’s shop, asking them to fix your car, but giving them <strong>your cheap tools to use to fix the vehicle</strong>.</p></blockquote><p>The same is true with the code above. Lower-level database objects should always own that domain/responsibility. Someone else shouldn’t be telling them how to manage their database connections.</p><h1 id="What-To-Do-What-To-Do"><a href="#What-To-Do-What-To-Do" class="headerlink" title="What To Do. What To Do."></a>What To Do. What To Do.</h1><p>How could we <em>safely</em> re-use open <code>SqlConnection</code>s if we wanted to?</p><p>In this same code base, I introduced using <a href="https://github.com/StackExchange/Dapper" target="_blank" rel="noopener">Dapper</a> to replace database access moving forward. Dapper turned out to be more than 5 times faster than the hand-built mini-object mapper that was in place anyways. That’s another story for another day.</p><p>In conjunction with these changes, I had created a few methods that allowed us to use <code>SqlConnection</code>s safely - but retaining the flexibility of connection reuse and the ability to use transactions.</p><p>In <a href="https://www.blog.jamesmichaelhickey.com/csharp-functional-programming-a-simple-use-case/" target="_blank" rel="noopener">a past post</a> I explained how you can use higher-order functions to encapsulate repetitive code while allowing the “meat” of your code to be passed in. What do I mean?</p><p>Take, for example, a <code>Query</code>class that has the method <code>UsingConnectionAsync</code> which might be used like this:</p><pre><code>await _query.UsingConnectionAsync&lt;int&gt;(    async con =&gt;    {        var result1 = await con.ExecuteAsync(sql1, parameters1); // ExecuteAsync comes from Dapper        var result2 = await con.ExecuteAsync(sql2, parameters2);        return PutTheResultsTogether(result1, result2);    });</code></pre><p>Such a method accepts a function that will be given a <code>SqlConnection</code>. The function can use that <code>SqlConnection</code> however it wants. Once done, the higher-order method <code>UsingConnectionAsync</code> will manage to close the connection “magically” (in a manner of speaking).</p><p>We can wrap all our database related code inside of a “scope”, as it were, and just do what we want. It’s safe and yet flexible.</p><p>You could make another method <code>UsingTransactionAsync</code> that would manage to open a <code>SqlConnection</code>, start a transaction, and rollback on errors while committing successful usages.</p><p><a href="#gist">See the section below</a> for a gist containing one way to implement these methods.</p><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>Hopefully, this real-world crisis will encourage you to think about how your <code>SqlConnection</code> objects are being managed. Especially in older “legacy” applications (ya, we all have to deal with them), you might see these kinds of attempts at optimizing database connections.</p><p>Just remember:</p><ul><li>Be safe and keep low-level responsibilities in one place. DB connection management and query logic are not the same things.</li><li>Even if the code is obviously not causing immediate issues - if it looks stinky, it might be stinky. Better safe than sorry.</li><li>Higher-order functions are a great way to encapsulate responsibilities of one domain/object while allowing the callers to still be flexible in how they can use those managed resources.</li></ul><h1 id="Extras-Gist"><a href="#Extras-Gist" class="headerlink" title=" Extras: Gist"></a><a name="gist"></a> Extras: Gist</h1><script src="https://gist.github.com/jamesmh/9e1382a567e0891670c2d55b47ec3ba7.js"></script><h2 id="New-Site"><a href="#New-Site" class="headerlink" title="New Site!"></a>New Site!</h2><p>I’ll be writing new content over at my <a href="https://www.jamesmichaelhickey.com" target="_blank" rel="noopener">new site/blog</a>. Check it out!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;What happens when you don’t close your .NET &lt;code&gt;SqlConnection&lt;/code&gt;s? Bad stuff. Bad stuff that will inevitably bring your IIS website crumbling down to ashes. Well… something like that. We all know that we should take extra care to always &lt;strong&gt;close&lt;/strong&gt; our DB connections. Right?&lt;/p&gt;
&lt;p&gt;But what happens when developers try to get fancy with their DB connections and focus more on being able to re-use open DB connections rather than being safe? Well, the consequences were bestowed upon me a few weeks ago.&lt;/p&gt;
&lt;p&gt;Let me explain (briefly) what happened, what &lt;em&gt;could&lt;/em&gt; happen to you, and a way to fix it - while maintaining the flexibility of re-using open DB connections and being able to safely use DB transactions from your C# code (using ADO).&lt;/p&gt;
    
    </summary>
    
      <category term="ADO" scheme="https://blog.jamesmichaelhickey.com/categories/ADO/"/>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/categories/ADO/C/"/>
    
      <category term="Functional Programming" scheme="https://blog.jamesmichaelhickey.com/categories/ADO/C/Functional-Programming/"/>
    
      <category term="Refactoring" scheme="https://blog.jamesmichaelhickey.com/categories/ADO/C/Functional-Programming/Refactoring/"/>
    
    
      <category term="ado" scheme="https://blog.jamesmichaelhickey.com/tags/ado/"/>
    
      <category term="ado connection" scheme="https://blog.jamesmichaelhickey.com/tags/ado-connection/"/>
    
      <category term="database connection" scheme="https://blog.jamesmichaelhickey.com/tags/database-connection/"/>
    
      <category term="sqlconnection" scheme="https://blog.jamesmichaelhickey.com/tags/sqlconnection/"/>
    
  </entry>
  
  <entry>
    <title>C# Pattern Matching: Are The Official Docs Lying?</title>
    <link href="https://blog.jamesmichaelhickey.com/pattern-matching-official-docs-lying/"/>
    <id>https://blog.jamesmichaelhickey.com/pattern-matching-official-docs-lying/</id>
    <published>2018-06-11T16:32:45.000Z</published>
    <updated>2022-09-07T01:11:18.500Z</updated>
    
    <content type="html"><![CDATA[<p>During my day job, I had a case where I needed to use some pattern matching to do some type checking. If you don’t know, pattern matching in C# allows you to test the type of an object and perform some additional “magic” at the same time. While having the chance to play around with this feature some questions arose from my usage.</p><a id="more"></a><p>I want to bring you through some steps in typical pattern matching usage, and we’ll ask some fun questions and test this feature to see how far we can bring it!</p><h1 id="Usage-1-If-Statement"><a href="#Usage-1-If-Statement" class="headerlink" title="Usage 1: If Statement"></a>Usage 1: If Statement</h1><p>The common usage is by issuing type checking within an <code>if</code> statement.</p><pre><code>object value = SomeFactory();if(value is long asLong){    // asLong is type &lt;long&gt;}else if(value is int asInt){    // asInt is type &lt;int&gt;}else if(value is string str){    // str is type &lt;string&gt;}</code></pre><p>Fair enough. Let’s move onto the next common usage of pattern matching.</p><h1 id="Usage-2-Switch-Statement"><a href="#Usage-2-Switch-Statement" class="headerlink" title="Usage 2: Switch Statement"></a>Usage 2: Switch Statement</h1><pre><code>object value = SomeFactory();switch (value){    case long asLong:        // asLong is type &lt;long&gt;        break;    case int asInt:        // asInt is type &lt;int&gt;        break;    case string str:        // str is type &lt;string&gt;        break;}</code></pre><p>Looks good. Very convenient and useful.</p><p>But, this is where my brain has some questions. The syntax <code>[var] is [type] [newVar]</code> is interesting. It is not really a statement. It’s an expression. But… it’s also a statement. Why?</p><p>It’s an expression because it evaluated to a <code>boolean</code>. But, it also makes an assignment to a new variable…</p><h1 id="Getting-Fancy…"><a href="#Getting-Fancy…" class="headerlink" title="Getting Fancy…"></a>Getting Fancy…</h1><pre><code>object value = SomeFactory();bool isLong = value is long asLong;bool isInt = value is int asInt;bool isString = value is string str;// ... etc.</code></pre><p>This works. Each of these <code>boolean</code> values is set properly. In the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/pattern-matching#the-is-type-pattern-expression" target="_blank" rel="noopener">official docs</a>, the <code>is</code> operation is called the <code>is</code> <strong>expression</strong>. Fair enough.</p><p>This means we might be able to do this?</p><pre><code>object value = SomeFactory();bool isLong = value is long asLong;bool isInt = value is int asInt;bool isString = value is string str;// Doesn&#39;t compile. &quot;asLong&quot; etc. are all in scope, but are &quot;unassigned&quot; (so Visual Studio tells me)return isLong ? asLong    : isInt ? asInt    : isString ? str    : new object();</code></pre><p>Nope.</p><p>So the assignment to <code>asLong</code>, <code>asInt</code> and <code>str</code> seem to be scoped to the outer level - but the variables are just never set. That’s what Visual Studio says. But, the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#a-nametype--type-pattern-a" target="_blank" rel="noopener">official C# docs</a> say:</p><blockquote><p>If exp is true and <code>is</code> is used with an if statement, <code>varname</code> is assigned and has local scope within the if statement only.</p></blockquote><p>Alright. What if we did this?</p><pre><code>object value = SomeFactory();return value is long asLong ? asLong    : value is int asInt ? asInt    : value is string str ? str    : new object();</code></pre><p>That works and is a succinct way of expressing what we wanted to do.</p><h1 id="Getting-Really-Fancy"><a href="#Getting-Really-Fancy" class="headerlink" title="Getting Really Fancy"></a>Getting Really Fancy</h1><p>Did you notice though - what Visual Studio says and what the docs say is actually not perfectly in harmony? Visual Studio says that the variable (for example) <code>asLong</code> is in scope - it just hasn’t been assigned. The docs say that when doing pattern matching in an <code>if</code> statement the variable is only in scope <strong>within the <code>if</code> statement only</strong>.</p><p>Let’s play around with this.</p><pre><code>if (value is long asLong)    value = asLong;else if (value is int asInt)    value = asInt;else if (value is string str)    value = str;asLong = 5; // This compiles! asLong is in scope!asInt = 5; // Fails! asInt is not in scope at all!str = &quot;&quot;; // Fails! str is not in scope at all!</code></pre><p>Weird. <code>asLong</code> is actually in the function / outer scope. But not the other variables. Must be the way the compiler chooses to modify the code.</p><h1 id="Going-The-Extra-Mile"><a href="#Going-The-Extra-Mile" class="headerlink" title="Going The Extra Mile!"></a>Going The Extra Mile!</h1><p>Ok… let’s get super weird. Remember how in one of the code examples above we talked about the fact that the <code>is</code> operation is an expression?</p><pre><code>bool isLong = value is long asLong;bool isInt = value is int asInt;bool isString = value is string str;asLong = 5;asInt = 5;str = &quot;&quot;;</code></pre><p>Well, what do ya know! That works. Weird. Why?</p><p>Apparently, using the <code>is</code> expression in a <strong>pure</strong> <code>if</code> statement will declare the variable <strong>above</strong> the <code>if</code> statement. So what really ends up in your code after compiling is something like this:</p><pre><code>if(value is long asLong){}else if(value is int asInt){}// Really becomes something like this by the compiler.long asLong;if(value is long){    asLong = (long) value;}else if(value is int){    int asInt = (int) value;}// NOT this (like the docs say).if(value is long){    long asLong = (long) value;}else if(value is int){    int asInt = (int) value;}</code></pre><p>Neat.</p><p>In one of the code samples above - where we are assigning the result of the <code>is</code> expression to a boolean - the compiler must be treating each expression the same way it treats a pure <code>if</code> statement. Each variable is pushed up. Like this:</p><pre><code>bool isLong = value is long asLong;bool isInt = value is int asInt;bool isString = value is string str;// Must become...long asLong;bool isLong = value is long;int asInt;bool isInt = value is int;string str;bool isString = value is string;</code></pre><h1 id="Are-The-Docs-Wrong"><a href="#Are-The-Docs-Wrong" class="headerlink" title="Are The Docs Wrong?"></a>Are The Docs Wrong?</h1><p>Again, the <a href="https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/is#a-nametype--type-pattern-a" target="_blank" rel="noopener">official C# docs</a> say (with bold added by me):</p><blockquote><p>If exp is true and <code>is</code> is used with an if statement, <code>varname</code> is assigned and has local scope within the if statement <strong>only</strong>.</p></blockquote><p>If we removed the last word of that statement, then it would be true. The variable doesn’t have local scope <code>only</code> within the if statement. But as it is, it’s technically false.</p><p>So - by being very technical and nit-picky - the docs are not totally 100% bang-on.</p><h1 id="Conclusion-Looking-Ahead-To-C-8"><a href="#Conclusion-Looking-Ahead-To-C-8" class="headerlink" title="Conclusion + Looking Ahead To C# 8"></a>Conclusion + Looking Ahead To C# 8</h1><p>Does it matter? Not really. But, it’s fun to play around with this stuff.</p><p>Using the ternary operator in conjunction with the <code>is</code> pattern matching is handy and very compact. But in C# version 8 we are expecting something that takes this to a whole new level!</p><p>Switch expressions are the “next level” and will look something like this:</p><pre><code>object value = SomeFactory();value switch{    long asLong =&gt; // Do something with it!,    int asInt =&gt; // Do something else!,    string str =&gt; // Do another thing!};</code></pre><p>Since this new usage of <code>switch</code> is an expression, you can return the result of that block of code. This should be great for things like the strategy pattern, factory patterns, etc.</p><h1 id="Appendix-Using-IL-Spy"><a href="#Appendix-Using-IL-Spy" class="headerlink" title="Appendix: Using IL Spy"></a>Appendix: Using IL Spy</h1><p>In trying to push this feature as far as I could, I wrote some really weird code to figure out how the compiled code really works.</p><pre><code>object value = 5;if(value is int asInt){}else if(value is long asLong){    asInt = 101;}else{    asInt = 102;}Console.Write(asInt);</code></pre><p>Yes, that compiles. The Console writes <code>5</code>!</p><p>Changing the first line to <code>object value = 5L;</code> outputs <code>101</code>.</p><p>Changing it to <code>object value = &#39;g&#39;;</code> outputs <code>102</code>.</p><p>This confirms our conclusions from the article above.</p><p>But, by using IL Spy, we can see the <strong>real code</strong>. This is what is really outputted:</p><pre><code>object value = 5;int asInt;object obj;if ((obj = value) is int){    asInt = (int)obj;}else if ((obj = value) is long){    long num = (long)obj;    asInt = 101;}else{    asInt = 102;}Console.Write((object)asInt);</code></pre><p>Nice. If you follow closely (ya, it’s hard to follow - I know…), this is exactly what my entire article was concluding.</p><p>What about this?</p><pre><code>object value = 5;bool isLong = value is long asLong;bool isInt = value is int asInt;Console.WriteLine(isLong == isInt);</code></pre><p>It becomes:</p><pre><code>object obj = 5;int num;object obj2;if ((obj2 = obj) is long){    long num3 = (long)obj2;    num = 1;}else{    num = 0;}bool isLong = (byte)num != 0;obj2 = obj;int num2;if (obj is int){    int num4 = (int)obj2;    num2 = 1;}else{    num2 = 0;}bool isInt = (byte)num2 != 0;Console.WriteLine(isLong == isInt);</code></pre><p>What? That’s a mouthful. But, we can see that our conclusions about what <strong>it seemed like the compiler is doing</strong> are true.</p><p>Fun!</p><p>Hopefully, you learned something new! Let me know what you think!</p><p><em>P.S. Here are some other articles you might enjoy!</em></p><ul><li><a href="https://www.blog.jamesmichaelhickey.com/linq-6x-faster-using-functional-optimization/" target="_blank" rel="noopener">How I Made LINQ 6X Faster Using A Functional Optimization!</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-4-refactoring-tools/" target="_blank" rel="noopener">Refactoring Legacy Monoliths – Part 4: Refactoring Tools</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-game-plan-and-tips/" target="_blank" rel="noopener">Refactoring Legacy Monoliths Part 3: Refactoring Game Plan And Tips</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/strategy-pattern-implementations/" target="_blank" rel="noopener">Deck The Halls With Strategy Pattern Implementations In C#: Basic To Advanced</a></li></ul><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;During my day job, I had a case where I needed to use some pattern matching to do some type checking. If you don’t know, pattern matching in C# allows you to test the type of an object and perform some additional “magic” at the same time. While having the chance to play around with this feature some questions arose from my usage.&lt;/p&gt;
    
    </summary>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/categories/C/"/>
    
    
      <category term="c#" scheme="https://blog.jamesmichaelhickey.com/tags/c/"/>
    
      <category term="pattern matching" scheme="https://blog.jamesmichaelhickey.com/tags/pattern-matching/"/>
    
      <category term="type checking" scheme="https://blog.jamesmichaelhickey.com/tags/type-checking/"/>
    
  </entry>
  
  <entry>
    <title>Refactoring Legacy Monoliths – Part 4: Refactoring Tools</title>
    <link href="https://blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-4-refactoring-tools/"/>
    <id>https://blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-4-refactoring-tools/</id>
    <published>2018-05-29T16:47:59.000Z</published>
    <updated>2022-09-07T01:11:18.500Z</updated>
    
    <content type="html"><![CDATA[<p>As a software developer it’s important to know what tools are available to you. Tedious and repetitive tasks or large “one-off” time-consuming tasks can often be automated by third-party tooling. And yes - sometimes it’s even worth purchasing some of these tools with your own money. Specifically, when refactoring, we should have some knowledge of what refactoring tools are available to us.</p><p>Continuing my “Refactoring Legacy Monoliths” series - I want to go over a few tools that I’ve found super helpful and worth investing in.</p><p>To make this blog post more useful than a list of products, I’ll go through some high-level steps that represent a way to tackle a refactoring project.</p><a id="more"></a><h1 id="Step-1-Identification-Of-Problem-Areas"><a href="#Step-1-Identification-Of-Problem-Areas" class="headerlink" title="Step 1: Identification Of Problem Areas"></a>Step 1: Identification Of Problem Areas</h1><p>Getting an overview of where pain-points are in your code-base has to be done. Why? Well, how do you know <strong>for sure</strong> that some code <strong>ought</strong> to be refactored? Because you <em>feel like it</em>? Because of <em>ugly code</em>?</p><p>Unless you measure your code-base in the same way that you would measure - let’s say - the performance of a real application, you don’t <strong>really</strong> know where issues really are. You might have <em>educated guesses</em> about what needs to change. But not objectively quantifiable conclusions.</p><p>The best tool I’ve found to get this kind of objective view of your code-base is <a href="https://www.ndepend.com/" target="_blank" rel="noopener">NDepend</a>.</p><p>NDepend integrates right into Visual Studio and basically just adds it’s own menu etc. It can be run via an external .exe if you want to.</p><p>NDepend has so many features it’s almost overwhelming (which is a good thing). I’ll mention a couple features that I’ve found the most helpful in getting a high-level overview of our code-base.</p><h2 id="NDepend-Feature-Code-Treemap-or-“Heat-Map”"><a href="#NDepend-Feature-Code-Treemap-or-“Heat-Map”" class="headerlink" title="NDepend Feature: Code Treemap (or “Heat Map”)"></a>NDepend Feature: Code Treemap (or “Heat Map”)</h2><p>This feature is called a <a href="https://www.ndepend.com/features/code-complexity#Diagrams" target="_blank" rel="noopener">Treemap diagram</a> but reminds me of a Heat Map for your code. It colours specific areas of the diagram (modules in your code) according to their code quality (red is bad…). It reminds me of hard disk usage diagrams that show you what applications in your system are using lots of space, etc.</p><p>This is a super quick and reliable way to see where your investigation might want to start. Large red areas are immediate candidates for further investigation. And, most likely, represent some critical part of your app. Again, I said <em>most likely</em>.</p><p>In my professional experience, the large red areas almost always correspond to where most “bugs” in the software are eventually found.</p><p>If you are a consultant who deals with code-bases in any form, but more specifically in offering code-refactoring or code-analysis services, then I would say this feature is maybe worth the entire cost of the tool. It’s just so easy to get started - especially with huge code-bases.</p><h2 id="NDepend-Feature-Dashboard"><a href="#NDepend-Feature-Dashboard" class="headerlink" title="NDepend Feature: Dashboard"></a>NDepend Feature: Dashboard</h2><p>Just like any great piece of software, NDepend has an awesome dashboard.</p><p><img src="https://www.ndepend.com/Doc/VS_CQL/Dashboard.png" alt="NDepend dashboard"></p><p>From here you can drill into “issues” which gives you a list, ordered by severity, of specific issues in your code-base. Taking note of the most common wide-spread issues give you an idea of the overall technical concerns you might have about the code-base.</p><p>Right away, in your face, is a “grade” of how much technical debt the overall code-base has accumulated. These metrics are customizable too, in the event you have certain measurements you feel are not needed to analyze.</p><p>This is a time-saver and gives you super-powers for gaining insight into how a code-base was built and what specific issues need to be dealt with. If you are new to a project, you can - within 15 minutes - have the ability to say to those experienced in that project:</p><blockquote><p>“Hey [team-mate], I’ve had a quick look at the code to get a high-level overview. Let me take a guess and say that [module name] has probably been causing issues for you? Lots of bugs? Most of the team doesn’t like to work in that area?”</p></blockquote><p>This can be a way of having others trust you quicker than they would have otherwise.</p><h2 id="Roslyn-Analysers-In-C"><a href="#Roslyn-Analysers-In-C" class="headerlink" title="Roslyn Analysers In C"></a>Roslyn Analysers In C</h2><p>Roslyn analyzers are native C# code analyzers that you can use in Visual Studio. Visual Studio 2017 has the ability to run a code analysis on your entire solution and also has a feature that will calculate code metrics - similar to NDepend.</p><p>This can be an easy way to analyze your code-base if you are already using Visual Studio. The cool thing is that you can install different Roslyn analyzers into Visual Studio to enhance your intellisense, real-time suggestions, build time error checking, etc.</p><p>Running these metrics/analyzers will show up in your code (as a squiggly) and in the error list in Visual Studio. You can export the code metrics to an excel file, which is nice.</p><p>These features aren’t comparable to the power of NDepend, but I think these represent an area that Visual Studio has been lacking in. I’m excited to see if Microsoft will add some advanced reporting on the analyzers like charts, dashboards, etc.</p><h1 id="Step-2-Gain-Momentum-By-Tackling-Safer-Areas-First"><a href="#Step-2-Gain-Momentum-By-Tackling-Safer-Areas-First" class="headerlink" title="Step 2: Gain Momentum By Tackling Safer Areas First"></a>Step 2: Gain Momentum By Tackling Safer Areas First</h1><p>Once you know where the problem areas are, I would suggest tackling the smaller red areas (from the Treemap). These represent areas that don’t have an overwhelming amount of code, yet do need to be refactored. These areas are probably known as “small” bug producers.</p><p>Think of the system you are working with as a <strong>“bug producing onion”</strong>.</p><blockquote><p>In the center is the largest, most horrible, horrendous piece of the system known to frighten even the mightiest at heart. As we move closer to the outside of the onion we encounter error-prone but less intimidating and less crucial pieces of the system.</p></blockquote><p>Let’s start by unravelling the onion from the outside.</p><p>This approach is less risky, allows you to build up confidence and domain knowledge (if working in a system you’re not so familiar with).</p><p>But <strong>how</strong> do you begin tackling these areas?</p><h2 id="NDepend"><a href="#NDepend" class="headerlink" title="NDepend"></a>NDepend</h2><p>Using NDepend’s dashboard, you can see a list of specific code quality issues. Drilling into each issue will give you tips on how to fix those specific issues. I encourage you to explore this feature yourself :)</p><h2 id="ReSharper"><a href="#ReSharper" class="headerlink" title="ReSharper"></a>ReSharper</h2><p>Moving onto another tool though, <a href="https://www.jetbrains.com/resharper/" target="_blank" rel="noopener">JetBrain’s ReSharper</a> is fantastic. Just like NDepend, ReSharper has tons of features. It integrates into Visual Studio seamlessly. It is known to be resource intensive on larger project/solutions, but for the sake of refactoring code, it’s invaluable.</p><h3 id="ReSharper-Feature-Move-Types-into-Matching-Files"><a href="#ReSharper-Feature-Move-Types-into-Matching-Files" class="headerlink" title="ReSharper Feature: Move Types into Matching Files"></a>ReSharper Feature: Move Types into Matching Files</h3><p>This was an issue I had specifically on a project I was refactoring. There was one file which had <strong>hundreds</strong> of different types (classes, interfaces, etc.) that were in <strong>one</strong> file named “WIP.cs”. That’s short for “Work In Progress”. And yes, this was in production code. Some types were actively used. Some weren’t. And, some had version numbers appended to them - like “Class2” and “Class3”. Fun.</p><p>So, instead of going through each of the types one-by-one and extracting them into their own files, ReSharper has a command that you can run on this file that will just magically do that for you. Just that saved me days of work - not to mention my sanity.</p><h3 id="ReSharper-Feature-Adjust-Solution-Namespaces"><a href="#ReSharper-Feature-Adjust-Solution-Namespaces" class="headerlink" title="ReSharper Feature: Adjust (Solution) Namespaces"></a>ReSharper Feature: Adjust (Solution) Namespaces</h3><p>I now had a few hundred extra files to deal with - all in the same folder. Next, I needed to structure the files as best as I could with a proper file/folder structure. This was manual work - but once all the files are in their proper place we still need to adjust all the namespaces for each type!</p><p>ReSharper has that covered. Just run the “Adjust Namespaces” command on a specific project, file or the entire solution and the folder structure for each file will be automatically applied to the namespace of the file. Again, that saved me <em>at least</em> a few days of work.</p><p>This feature shines when doing high-level re-organization refactoring (i.e. file structure and folder structure changes).</p><p>From this real-life example, I was able to perform what otherwise would have taken weeks of work and get it done in a few days. Win!</p><h1 id="Appendix-Performance-And-Web-Metrics"><a href="#Appendix-Performance-And-Web-Metrics" class="headerlink" title="Appendix: Performance And Web Metrics"></a>Appendix: Performance And Web Metrics</h1><p>After you refactor your code and have some unit tests in place (yes, you really should…), I always like to profile run-time performance of the code that was changed. This next tool is one I <strong>always</strong> have running <strong>all the time</strong>. As a web developer (primarily) this tool is non-negotiable.</p><h2 id="Stackify-Prefix"><a href="#Stackify-Prefix" class="headerlink" title="Stackify Prefix"></a>Stackify Prefix</h2><p><a href="https://stackify.com/prefix/" target="_blank" rel="noopener">Prefix</a> is a <strong>free</strong> real-time web profiler. Basically, you install it on your machine and then hit a local URL that Prefix is assigned to. Voila!</p><p>It will automatically show you every HTTP request that your machine is handling with <strong>tons</strong> of details about each request. It’s not a generic performance profiler - Prefix will show you <strong>specific details</strong> about each request. Features I’ve come to love are:</p><ul><li><p>It will show you hidden exceptions you never knew were happening (and are slowing your app down)</p></li><li><p>All database calls are displayed with the actual code that was executed, how long the query took and even how long just downloading the data from the SQL server took (helpful with large data sets!)</p></li><li><p>A code “hot-path” shows you which methods in your code are taking up the most time to execute (with the actual metrics displayed)</p></li></ul><h1 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h1><p>To recap, NDepend, ReSharper, and Stackify’s Prefix are all fantastic tools that boost your refactoring capabilities and ability to comprehend code from a high-level. They also give us tooling that will assist in the nitty-gritty details of improving our code.</p><p>Visual Studio code analysis tools offer an area of great potential. Roslyn analyzers, in particular, are an area where I see future potential integration into charts, dashboarding, etc. within Visual Studio to be a useful addition.</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div><h1 id="Here-are-some-other-posts-you-may-enjoy"><a href="#Here-are-some-other-posts-you-may-enjoy" class="headerlink" title="Here are some other posts you may enjoy:"></a>Here are some other posts you may enjoy:</h1><ul><li><a href="https://www.blog.jamesmichaelhickey.com/linq-6x-faster-using-functional-optimization/" target="_blank" rel="noopener">How I Made LINQ 6X Faster Using A Functional Optimization!</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-game-plan-and-tips/" target="_blank" rel="noopener">Refactoring Legacy Monoliths Part 3: Refactoring Game Plan And Tips</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-2-convincing-management/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 2: Cost-Benefit Analysis Of Refactoring</a></li><li><a href="https://www.blog.jamesmichaelhickey.com/strategy-pattern-implementations/" target="_blank" rel="noopener">Deck The Halls With Strategy Pattern Implementations In C#: Basic To Advanced</a></li></ul>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;As a software developer it’s important to know what tools are available to you. Tedious and repetitive tasks or large “one-off” time-consuming tasks can often be automated by third-party tooling. And yes - sometimes it’s even worth purchasing some of these tools with your own money. Specifically, when refactoring, we should have some knowledge of what refactoring tools are available to us.&lt;/p&gt;
&lt;p&gt;Continuing my “Refactoring Legacy Monoliths” series - I want to go over a few tools that I’ve found super helpful and worth investing in.&lt;/p&gt;
&lt;p&gt;To make this blog post more useful than a list of products, I’ll go through some high-level steps that represent a way to tackle a refactoring project.&lt;/p&gt;
    
    </summary>
    
      <category term="Refactoring" scheme="https://blog.jamesmichaelhickey.com/categories/Refactoring/"/>
    
      <category term="Software Architecture And Design" scheme="https://blog.jamesmichaelhickey.com/categories/Refactoring/Software-Architecture-And-Design/"/>
    
    
      <category term="software design" scheme="https://blog.jamesmichaelhickey.com/tags/software-design/"/>
    
      <category term="refactoring" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring/"/>
    
      <category term="c#" scheme="https://blog.jamesmichaelhickey.com/tags/c/"/>
    
      <category term="legacy software" scheme="https://blog.jamesmichaelhickey.com/tags/legacy-software/"/>
    
      <category term="maintainability" scheme="https://blog.jamesmichaelhickey.com/tags/maintainability/"/>
    
      <category term="tools" scheme="https://blog.jamesmichaelhickey.com/tags/tools/"/>
    
  </entry>
  
  <entry>
    <title>Refactoring Legacy Monoliths - Part 3: Game Plan And Refactoring Tips</title>
    <link href="https://blog.jamesmichaelhickey.com/refactoring-game-plan-and-tips/"/>
    <id>https://blog.jamesmichaelhickey.com/refactoring-game-plan-and-tips/</id>
    <published>2018-03-07T16:25:04.000Z</published>
    <updated>2022-09-07T01:11:18.500Z</updated>
    
    <content type="html"><![CDATA[<p>So your engineering team is convinced that you need to make some drastic changes. The direction of future development needs to improve. Things can’t stay as they are. Management is also convinced that the product needs to move in a new direction. What’s next? </p><p>Before doing any actual changes or refactoring to your product, planning a refactor is your next step. In other words, you need a game plan. I’ll also discuss some refactoring tips for you to get started!</p><a id="more"></a><h1 id="A-Word-From-Our-Sponsors…"><a href="#A-Word-From-Our-Sponsors…" class="headerlink" title="A Word From Our Sponsors…"></a>A Word From Our Sponsors…</h1><p>P.s. This is part 3 of my “Refactoring Legacy Monoliths” series:</p><p><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-first-steps/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 1: First Steps</a><br><a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-2-convincing-management/" target="_blank" rel="noopener">Refactoring Legacy Monoliths - Part 2: Cost-Benefit Analysis Of Refactoring</a></p><h1 id="Does-Refactoring-Mean-a-Rewrite"><a href="#Does-Refactoring-Mean-a-Rewrite" class="headerlink" title="Does Refactoring Mean a Rewrite?"></a>Does Refactoring Mean a Rewrite?</h1><p>One comment I’ve seen come up on Reddit about this series (quite a bit…) is the accusation that I’m suggesting you ought to rewrite your entire codebase. I’ve never said that. Nor have I ever implied that you should. Really, you probably shouldn’t.</p><h1 id="Trust"><a href="#Trust" class="headerlink" title="Trust"></a>Trust</h1><p>As a refresher, in his book Working Effectively With Legacy Code, Michael states:</p><blockquote><p>To me, legacy code is simply code without tests.</p></blockquote><p>Why does Michael care so much about testing your code from the inside? (i.e. not by having people test your <strong>website</strong> over and over - which is really expensive btw). There’s a simple question that can answer this:</p><blockquote><p>If you were to change a core feature of your product in a non-trivial way, would you feel confident about making that change? Would you trust the system to still act exactly as it did?</p></blockquote><p>If you don’t have any testing, then how can you be confident? How can you <strong>trust</strong> your system?</p><p>Having tests in place is like doing acrobatics in the air with a safety net vs. not having a safety net. <strong>Ouch!</strong></p><h1 id="What-Are-Your-Goals"><a href="#What-Are-Your-Goals" class="headerlink" title="What Are Your Goals?"></a>What Are Your Goals?</h1><p>Your first goal should be to start implementing unit tests on your code. This is foundational work. You need to be able to change your code and have confidence that it still works.</p><p>Again:</p><blockquote><p>Your first goal should be to implement code-based testing. You cannot refactor your system with confidence unless you have a safety net.</p></blockquote><p>After this, your goals may vary. If you have completed <a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-first-steps/" target="_blank" rel="noopener">Step 1</a> and <a href="https://www.blog.jamesmichaelhickey.com/refactoring-legacy-monoliths-part-2-convincing-management/" target="_blank" rel="noopener">Step 2</a> then you should have a solid list of what needs to change.</p><p>What I would suggest at this point is having a formal discussion (with a formal outcome/document) that answers the following question:</p><blockquote><p>What do we want our system to look like in 1 year? In 2 years?</p></blockquote><p>Maybe we should be using a new technology stack like ASP .NET Core? Maybe our current code architecture does not allow us to re-use our business rules in other platforms (web vs. mobile API vs. desktop app)? This would imply that we need to consolidate our business logic and rules. (P.s. None of these cases require a re-write)</p><h1 id="Dealing-With-Dependencies"><a href="#Dealing-With-Dependencies" class="headerlink" title="Dealing With Dependencies"></a>Dealing With Dependencies</h1><p>The number one obstacle that (most likely) prevents you from creating isolated unit tests and isolating your business rules and entities are <strong>dependencies</strong>.</p><p>Once you start, you find that you start telling yourself:</p><blockquote><p>Well, in order to test [thing 1] I now need to have an instance of [thing 2]. But, [thing 2] needs an instance of [thing 3].</p></blockquote><p>“Thing 1” might be an entity you want to test - let’s say, a <code>Report</code> entity (which models some tabular data).</p><p>Now, imagine that “Thing 2” is another class - <code>LinkGenerator</code> (which generates links for the report).</p><p><code>LinkGenerator</code> needs access to “Thing 3”, which is, the <code>HttpSession</code>.</p><p>If you want to unit test the <code>Report</code> entity, you need:</p><ul><li>an instance of <code>LinkGenerator</code> which needs…</li><li>an instance of <code>HttpSession</code></li></ul><p><strong>Uh Oh.</strong> How can you unit test when you need <code>HttpSession</code>? Unit tests don’t run off a web server! (Well, they shouldn’t…)</p><p>Sorry to say (you already know…), it’s going to take some work. You need to <strong>break the chain of dependencies.</strong></p><p>Fortunately for us, that’s one of the primary goals of refactoring. Others have already done the hard lifting for us.</p><h1 id="Dependency-Breaking-And-Refactoring-Tips"><a href="#Dependency-Breaking-And-Refactoring-Tips" class="headerlink" title="Dependency Breaking And Refactoring Tips"></a>Dependency Breaking And Refactoring Tips</h1><p>Let’s look at a couple dependency breaking refactoring tips.</p><h3 id="1-Turn-Globals-Into-Interfaces-Then-Inject-Them"><a href="#1-Turn-Globals-Into-Interfaces-Then-Inject-Them" class="headerlink" title="1. Turn Globals Into Interfaces. Then Inject Them."></a>1. Turn Globals Into Interfaces. Then Inject Them.</h3><p>The title says it all. Sticking with our little example, imagine the <code>LinkGenerator</code> has the following method (pseudo-ish code).</p><pre class=" language-c#"><code class="language-c#">public string GenerateLink(){     // ... some kind of processing     var someValue = HttpSession["SomeKey"];     // ... more processing     var someOtherValue = HttpSession["SomeOtherKey"];     return link;}</code></pre><p>We can’t test this method because it references the <code>HttpSession</code> object that only exists in a web application. We don’t want our models or business entities to know about the web (this is in line with our goal of isolating business entities from the presentation of our data).</p><p>By injecting an interface instead, we can remove the dependency on the actual <code>HttpSession</code>.</p><pre class=" language-c#"><code class="language-c#">public string GenerateLink(IHttpSessionAccessor session){     // ... some kind of processing     var someValue = session.GetValue("SomeKey");     // ... more processing     var someOtherValue = session.GetValue("SomeOtherKey");     return link;}</code></pre><p>I’m sure you can imagine what the interface definition would look like. The concrete class might look something like this:</p><pre class=" language-c#"><code class="language-c#">public class HttpSessionAccessor : IHttpSessionAccessor{    private readonly HttpSession _session;    public HttpSessionAccessor(HttpSession session)    {        this._session = session;    }    // You could be fancy and use generics?    public object GetValue(string key)    {        return this._session[key];    }}</code></pre><p>Now, we can do something like this in our testing code:</p><pre class=" language-c#"><code class="language-c#">IHttpSessionAccessor session = new Mock<IHttpSessionAccessor>();// Implement the mock// Or just assign "session" with a dummy implementation of IHttpSessionAccessor.LinkGenerator generator = new LinkGenerator();string link = generator.GenerateLink(session);// Assert ...</code></pre><p>Now we can build tests around the <code>LinkGenerator</code> and have confidence that:</p><ul><li>It actually works the way we expect it to work</li><li>Any breaking changes will be caught (and fixed).</li></ul><h3 id="2-Adapt-Parameter"><a href="#2-Adapt-Parameter" class="headerlink" title="2. Adapt Parameter"></a>2. Adapt Parameter</h3><p>Imagine our code above was originally this:</p><pre class=" language-c#"><code class="language-c#">public string GenerateLink(HttpSession session){     // ... some kind of processing     var someValue = session["SomeKey"];     // ... more processing     var someOtherValue = session["SomeOtherKey"];     return link;}</code></pre><p>What’s wrong? We have the same issue as above. We <strong>still</strong> need an instance of <code>HttpSession</code>. Which means… we need a web server to be running. Bad.</p><p>To solve this, just do the same thing as #1. Turn the parameter into an interface and access the interface instead of the actual implementation (HttpSession).</p><h3 id="3-Extract-Method"><a href="#3-Extract-Method" class="headerlink" title="3. Extract Method"></a>3. Extract Method</h3><p>You are probably familiar with this technique. If you have a section of code that is doing multiple chunks or has multiple responsibilities, then you need to break them up. Take a chunk of code that does one thing, and create a new method out of it. Avoid references to global state (like <code>HttpSession</code>) so that you can unit test your new methods.</p><p>Good indicators of where to break up your code are:</p><ul><li>Comments saying “Do this”, then “Do this next thing” inside the same code block are usually each a candidate for extraction.</li><li>C# regions are a <strong>really good</strong> indicator that you need to split this code up!</li></ul><h3 id="Conclusion"><a href="#Conclusion" class="headerlink" title="Conclusion"></a>Conclusion</h3><p>The primary areas you need to focus on are:</p><ul><li>Building a game plan describing <strong>where you want your system to be in 1 year</strong></li><li>Making your software <strong>trustable</strong></li><li>Being able to have <strong>confidence</strong> after changes are made to the code</li></ul><p>Dependencies will need to be broken. But this ultimately leads you to a place where:</p><ul><li>Your code is testable</li><li>Your overall design is (overall) better</li><li>You can trust the system/software after changes</li></ul><p>Thanks for reading :) Let me know what you think in the comments. Have you ever had to go through this process personally? Let me know!</p><h1 id="Keep-In-Touch"><a href="#Keep-In-Touch" class="headerlink" title="Keep In Touch"></a>Keep In Touch</h1><p>Don’t forget to connect with me on <a href="https://twitter.com/jamesmh_dev" target="_blank" rel="noopener">twitter</a> or <a href="https://www.linkedin.com/in/jamesmhickey/" target="_blank" rel="noopener">LinkedIn</a>!</p><div style="padding:0   20px; border-radius:6px; background-color: #efefef; margin-bottom:50px; margin-top:20px"><br>    <h1 class="margin-bottom:0"> Navigating Your Software Development Career<br></h1><br>An e-mail newsletter where I’ll answer subscriber questions and offer advice around topics like:<br><br>✔ What are the general stages of a software developer?<br>✔ How do I know which stage I’m at? How do I get to the next stage?<br>✔ What is a tech leader and how do I become one?<br><br><br><div class="text-center"><br>    <a href="http://eepurl.com/gdIV5X" target="_blank" rel="noopener"><br>        <button class="btn btn-sign-up" style="margin-top:0;margin-bottom:0">Join The Community!</button><br>    </a><br></div><br></div>]]></content>
    
    <summary type="html">
    
      &lt;p&gt;So your engineering team is convinced that you need to make some drastic changes. The direction of future development needs to improve. Things can’t stay as they are. Management is also convinced that the product needs to move in a new direction. What’s next? &lt;/p&gt;
&lt;p&gt;Before doing any actual changes or refactoring to your product, planning a refactor is your next step. In other words, you need a game plan. I’ll also discuss some refactoring tips for you to get started!&lt;/p&gt;
    
    </summary>
    
      <category term="C#" scheme="https://blog.jamesmichaelhickey.com/categories/C/"/>
    
      <category term="Object Oriented Programming" scheme="https://blog.jamesmichaelhickey.com/categories/C/Object-Oriented-Programming/"/>
    
      <category term="Refactoring" scheme="https://blog.jamesmichaelhickey.com/categories/C/Object-Oriented-Programming/Refactoring/"/>
    
      <category term="Software Architecture And Design" scheme="https://blog.jamesmichaelhickey.com/categories/C/Object-Oriented-Programming/Refactoring/Software-Architecture-And-Design/"/>
    
    
      <category term="refactoring" scheme="https://blog.jamesmichaelhickey.com/tags/refactoring/"/>
    
      <category term="legacy code" scheme="https://blog.jamesmichaelhickey.com/tags/legacy-code/"/>
    
      <category term="legacy software" scheme="https://blog.jamesmichaelhickey.com/tags/legacy-software/"/>
    
      <category term="monolith" scheme="https://blog.jamesmichaelhickey.com/tags/monolith/"/>
    
  </entry>
  
</feed>
