<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0"><channel><title><![CDATA[Untitled Publication]]></title><description><![CDATA[Untitled Publication]]></description><link>https://blog.samferree.dev</link><generator>RSS for Node</generator><lastBuildDate>Mon, 13 Apr 2026 05:31:18 GMT</lastBuildDate><atom:link href="https://blog.samferree.dev/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Testability of Large Objects]]></title><description><![CDATA[Okay I lied
“Testability of functions which need to accept large objects as a parameter but only use a fraction of the properties of the object” just do not roll off the tongue.
We’re going to take a look at some strategies for increasing the testabi...]]></description><link>https://blog.samferree.dev/testability-of-large-objects</link><guid isPermaLink="true">https://blog.samferree.dev/testability-of-large-objects</guid><category><![CDATA[C#]]></category><category><![CDATA[Testing]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Sun, 25 Jan 2026 08:04:40 GMT</pubDate><content:encoded><![CDATA[<h2 id="heading-okay-i-lied">Okay I lied</h2>
<p>“Testability of functions which need to accept large objects as a parameter but only use a fraction of the properties of the object” just do <em>not</em> roll off the tongue.</p>
<p>We’re going to take a look at some strategies for increasing the testability of your code. Particularly when the function you’re testing requires you to mock large input objects. This blog will not discuss strategies for <em>impure</em> functions that require large, mocked services, as Mark Seemann has already <a target="_blank" href="https://blog.ploeh.dk/2020/03/02/impureim-sandwich/">described how to structure an impure function to extract the testable pure parts of it</a>.</p>
<h2 id="heading-just-pass-the-parameters-you-need">Just pass the parameters you need</h2>
<pre><code class="lang-csharp"><span class="hljs-comment">// Instead of:</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">SomeFunction</span>(<span class="hljs-params">SomeLargeObject obj</span>)</span>
{
  <span class="hljs-keyword">return</span> obj.SomeProp + obj.SomeOtherProp
}

<span class="hljs-comment">// Try:</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">int</span> <span class="hljs-title">SomeFunction</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> someProp, <span class="hljs-keyword">int</span> SomeOtherProp</span>)</span>
{
  <span class="hljs-keyword">return</span> somePromp + someOtherProp
}
</code></pre>
<p>If <code>SomeLargeObject</code> has several required properties and complicated rules to enforce invariants, then testing <code>SomeFunction</code> becomes much easier if we just pass in the information it needs.</p>
<p>Sometimes the number of parameters gets quick long. We can pass in an object which has only these properties, but copying all the fields from the old object to the new object creates some verbose code, and it’s particularly dangerous if the function has multiple call sites.</p>
<p>Ideally, in our domain code we’d like to pass in our whole domain object for simplicity, but in our test code pass in just the properties the function actually needs to return a result.</p>
<p>The solution is something I’m calling a facet, as in “<strong>a particular aspect or feature of something”</strong>. First, we make an object that will serve as our parameter to our function, containing only the properties it needs. Then, using the features of C# we create an implicit converter from our domain object to our facet. This is what will allow us to pass in either the facet, or the domain model.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Account</span>
{
 <span class="hljs-comment">// Incredibly large domain model omitted for sanity</span>
}

<span class="hljs-comment">// This object contains the information needed</span>
<span class="hljs-comment">// to calculate loyalty, the age of the account</span>
<span class="hljs-comment">// and total amount spent</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">AccountLoyaltyInformation</span>(<span class="hljs-params">
  DateTime CreationDate,
  <span class="hljs-keyword">decimal</span> TotalSpent</span>)</span>;
{   
  <span class="hljs-comment">// create an implicit conversion from our domain model</span>
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">implicit</span> <span class="hljs-keyword">operator</span> <span class="hljs-title">AccountLoyaltyInformation</span>(<span class="hljs-params">Account account</span>)</span>
    =&gt; <span class="hljs-keyword">new</span> AccountLoyaltyInformation(account.CreationDate, account.TotalSpent);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">CalculateLoyalty</span>(<span class="hljs-params">AccountLoyaltyInformation loyaltyInfo</span>)</span>
{
  <span class="hljs-comment">// Implementation omitted</span>
}

<span class="hljs-comment">// Use the parameter object directly to simplify testing</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">TestLoyaltyCalculations</span>(<span class="hljs-params">Date someDate, <span class="hljs-keyword">decimal</span> someTotalSpent, <span class="hljs-keyword">int</span> expectedLoyaltyRating</span>)</span>
{
  <span class="hljs-keyword">int</span> actualLoyaltyRating = CalculateLoyalty(<span class="hljs-keyword">new</span>(someDate, someTotalSpent));
  actualLoyaltyRating.ShouldBe(expectedLoyaltyRating);
}

<span class="hljs-comment">// pass in the domain object directly in the application code</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">int</span>&gt; <span class="hljs-title">GetCustomerLoyalty</span>(<span class="hljs-params">Guid customerId</span>)</span>
{
  Account account = <span class="hljs-keyword">await</span> _db.LoadCustomerAccount(customerId);
  <span class="hljs-keyword">return</span> CalculateLoyalty(account); <span class="hljs-comment">// implicitly converts to 'AccountLoyaltyInformation'</span>
}
</code></pre>
<h2 id="heading-why-not-an-object-property">Why not an object property?</h2>
<p>At first it might seem like the obvious better solution is to simply make some <code>LoyaltyInformation</code> object a property on the Account object, and we can get rid of all this nonsense around implicit conversions.</p>
<p>But often, Account is a large object with a rich history of why it’s properties are subdivided the way they are, and some new feature may just have to deal with the fact that <code>CreationDate</code> is on <code>Account.AuditInformation</code> and <code>TotalSpent</code> is on <code>Account.PurchaseHistory</code>.</p>
]]></content:encoded></item><item><title><![CDATA[I Meant To Write Something Else, But I Can't Stop Playing with Pico.css]]></title><description><![CDATA[I have plenty of articles in my //TODO list, but I found something that really brings the dopamine for a serial side project starter that isn't as good at css as he'd like to be.
I was taking a look at Tailwind
After all the discussion, and having my...]]></description><link>https://blog.samferree.dev/i-meant-to-write-something-else-but-i-cant-stop-playing-with-picocss</link><guid isPermaLink="true">https://blog.samferree.dev/i-meant-to-write-something-else-but-i-cant-stop-playing-with-picocss</guid><category><![CDATA[PicoCss]]></category><category><![CDATA[C#]]></category><category><![CDATA[Blazor]]></category><category><![CDATA[Web Development]]></category><category><![CDATA[CSS]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 12 Jul 2024 19:23:06 GMT</pubDate><content:encoded><![CDATA[<p>I have plenty of articles in my //TODO list, but I found something that really brings the dopamine for a serial side project starter that isn't as good at css as he'd like to be.</p>
<h3 id="heading-i-was-taking-a-look-at-tailwind">I was taking a look at Tailwind</h3>
<p>After all the discussion, and having my eye on it for quite some time, I decided to finally take a look at Tailwind CSS, and while watching a video to get a high level view of it, the creator said something that started a free fall into my latest obsession. "I usually reserve Tailwind for larger projects and use Pico for small projects and prototypes"</p>
<p>Now I had something else to look up, and boy am I glad I did. You see, I <em>love</em> semantic html. I pine for the days when navbars were made with <code>&lt;nav&gt;</code>. When we knew that just because something had an <code>onclick</code> event, it didn't mean you should use it as a <code>&lt;button&gt;</code>. The days when, if you had tabular data, you put that in a <code>&lt;table&gt;</code>!</p>
<p>So you can imagine my delight when I found Pico CSS, a small, mostly classless stylesheet that used semantic html to build simple, but very pleasant web UI's. I couldn't stop myself from pulling up VS Code, and tooling up a quick greeting page for a sample Blackjack app.</p>
<p>No joke, the following took me &lt; 5 minutes:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720803732163/a16a9457-599b-4529-bc30-b6d16e6978c1.png" alt /></p>
<p>In about a half hour, I'd tooled out most of the actual game UI:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720803737539/337832da-d336-4712-8a45-007318113fbe.png" alt /></p>
<p>With a little work and my own custom CSS, I probably could have gotten unicode card characters to work with a better font and larger size, but out of the box, they didn't render well with Pico.</p>
<h3 id="heading-okay-so-now-what">Okay, So Now What</h3>
<p>None of this means anything if we can't actually play BlackJack, let's try and add this to a Blazor app. A simple blackjack app has no persistence, so as standalone WASM app will work fine for our purposes.</p>
<p>My first approach was to continue using Pico as I had been, simply linking the cdn. When I did a few things felt... off.</p>
<p>Firstly, the padding between my bank/betting <code>&lt;header&gt;</code> and my <code>&lt;main&gt;</code> playmat looks all wrong, and there was this strange white border around the "Bank $975" <code>&lt;h1&gt;</code>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720803744624/1fdedacf-8222-4821-b0c5-ed0cb80ce214.png" alt /></p>
<p>The weird outline kept going away as soon as I clicked anywhere on the page, so I decided to tackle the padding first.</p>
<h3 id="heading-semantic-layout-and-root-elements">Semantic Layout and Root Elements</h3>
<p>Pico is built around semantic html, and by default it applies styles to <code>&lt;header&gt;</code>, <code>&lt;main&gt;</code>, and <code>&lt;footer&gt;</code> tags that are <em>immediate children</em> of <code>&lt;body&gt;</code>. This works great for static html, this does not work great for Blazor WASM. Blazor needs a root element, and by default it's a <code>&lt;div id="app"&gt;</code> at the top of <code>&lt;body&gt;</code>, which means when my content was moved to the <code>Home</code> component, <code>&lt;header&gt;</code> and <code>&lt;main&gt;</code> where immediate children to a <code>&lt;div&gt;</code>, so the styling wasn't correct.</p>
<p>Pico has a fix for this.</p>
<p>When you import Pico CSS with Sass, you can specify your root element, what we need in Blazor is something like this:</p>
<pre><code class="lang-scss"><span class="hljs-keyword">@use</span> <span class="hljs-string">"pico"</span> with (
    <span class="hljs-variable">$semantic-root-element</span>: <span class="hljs-string">"#app"</span>,
    <span class="hljs-variable">$enable-semantic-container</span>: true,
);
</code></pre>
<p>Just one problem. I'm not using Pico with Sass.</p>
<h3 id="heading-sassy-blazor">Sassy Blazor</h3>
<p>I didn't want to hack together a solution. I am after all trying to lay the groundwork for a system which will help me reliably get up and running with my next side project. So I set out to find out how adding Sass to Blazor works. I found <a target="_blank" href="https://adrianhall.github.io/asp.net/2022/08/26/adding-sass-to-blazor/">this</a> article written by Adrian Hall, and it was just what I was looking for. Using this as a guide, I added the WebCompiler extension for Visual Studio, and compiled a sass file into <code>app.min.css</code>, which I have since renamed <code>customPico.min.css</code></p>
<p>Once that was done, I needed to get the Pico <code>.scss</code> source files, and they provided instructions on how to do this with npm or yarn.</p>
<pre><code class="lang-bash">npm install @picocss/pico
</code></pre>
<p>Just one problem. I don't want to use npm or yarn.</p>
<p>First, I simply went to the Pico CSS github repo, and downloaded the latest release, and stuffed the <code>.scss</code> files into my project. Worked well enough, but not exactly maintainable.</p>
<h3 id="heading-libman-to-the-rescue">LibMan to the Rescue</h3>
<p>While clicking around my project, I noticed something very curious I've never noticed before.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720803753177/5d012f93-5c6d-4803-a7cf-44e51802c004.png" alt /></p>
<p>Recent versions of Visual Studio ship with a client side library manager, all I had to do was point it at the <code>unpkg</code> source, do a quick search for <code>@picocss</code> and I even got to select only the <code>.scss</code> files I needed instead of the whole package.</p>
<p>Sure the resulting folder structure was <code>picocss/pico/scss</code> but I can live with that all things considered.</p>
<h3 id="heading-adding-the-finishing-touches">Adding the finishing touches</h3>
<p>Once I had that setup, I ended up with a very short <code>customPico.scss</code> file</p>
<pre><code class="lang-scss"><span class="hljs-keyword">@use</span> <span class="hljs-string">"picocss/pico/scss/pico"</span> with (
    <span class="hljs-variable">$semantic-root-element</span>: <span class="hljs-string">"#app"</span>,
    <span class="hljs-variable">$enable-semantic-container</span>: true,
    <span class="hljs-variable">$theme-color</span>: <span class="hljs-string">"cyan"</span>
);
</code></pre>
<p>Then, I linked it to the <code>index.html</code> file of my <code>wwwroot</code> folder</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"customPico.min.css"</span> /&gt;</span>
</code></pre>
<p>That just left that weird white border, and that turned out to be a one line fix after consulting the oracles on r/Blazor, simply removing this from my <code>App.razor</code> file did the trick</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">FocusOnNavigate</span> <span class="hljs-attr">RouteData</span>=<span class="hljs-string">"@routeData"</span> <span class="hljs-attr">Selector</span>=<span class="hljs-string">"h1"</span> /&gt;</span>
</code></pre>
<p>And now my Blazor app matched my static html</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1720803758877/dba296a5-080c-45b8-a8ca-b7e495c388a6.png" alt /></p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>I plan on building out the rest of this BlackJack app using Blazor and Pico CSS, but in getting set up I learned some valuable lessons for using this wonderful classless (read: less classes) css framework with Blazor.</p>
]]></content:encoded></item><item><title><![CDATA[Avoiding Result Pitfalls]]></title><description><![CDATA[Sadly, C# does not ship with a Result<T> as part of the BCL. Even sadder, our friends lucky enough to work in F# have a really good one, so the .NET IL is clearly capable of it.
This hasn't prevented many an ambitious programmer from attempting to wr...]]></description><link>https://blog.samferree.dev/avoiding-result-pitfalls</link><guid isPermaLink="true">https://blog.samferree.dev/avoiding-result-pitfalls</guid><category><![CDATA[C#]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[error handling]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 28 Jun 2024 14:30:43 GMT</pubDate><content:encoded><![CDATA[<p>Sadly, C# does not ship with a <code>Result&lt;T&gt;</code> as part of the BCL. Even sadder, our friends lucky enough to work in F# have a really good one, so the .NET IL is clearly capable of it.</p>
<p>This hasn't prevented many an ambitious programmer from attempting to write their own <code>Result&lt;T&gt;</code> type, and why wouldn't you? Exceptions are unexpected, and expensive. A type that communicates to the programmer that failure is a possibility and that they should be prepared to handle it will only ensure good coding practices, right? Sadly, this isn't always the case.</p>
<p>Many codebases end up littered with <code>Result&lt;T&gt;</code> types <em>and</em> throw many exceptions. The object causes friction and is most often ignored. This leaves developers with a bad taste in their mouth about the <code>Result&lt;T&gt;</code> type. Some of this is avoidable, and some of this, sadly represents a shortcoming in the C# language itself.</p>
<p>By understanding where developers go wrong, and where they language falls short, we can create a more robust <code>Result&lt;T&gt;</code> type that stands a much better chance of justifying the additional complexity.</p>
<h2 id="heading-where-c-falls-short-no-safe-unwrap">Where C# Falls Short: No Safe Unwrap</h2>
<p>Some languages, like Rust, provide an elegant way to unwrap <code>Result&lt;T&gt;</code> types. In the case of Rust, the <code>?</code> operator will unwrap a <code>Result&lt;T&gt;</code> and return the value. If the <code>Result&lt;T&gt;</code> represents an error, the function immediately early returns the error. Thus, any function that uses the <code>?</code> operator in Rust, must itself return a <code>Result&lt;T&gt;</code> type.</p>
<pre><code class="lang-rust"><span class="hljs-function"><span class="hljs-keyword">fn</span> <span class="hljs-title">read_file_contents</span></span>(filename: &amp;<span class="hljs-built_in">str</span>) -&gt; <span class="hljs-built_in">Result</span>&lt;<span class="hljs-built_in">String</span>, io::Error&gt;
{
    <span class="hljs-comment">// Open the file, using `?` to propagate errors</span>
    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> file = File::open(filename)?;

    <span class="hljs-keyword">let</span> <span class="hljs-keyword">mut</span> contents = <span class="hljs-built_in">String</span>::new();
    <span class="hljs-comment">// Read the file contents into a string, using `?` to propagate errors</span>
    file.read_to_string(&amp;<span class="hljs-keyword">mut</span> contents)?;
    <span class="hljs-literal">Ok</span>(contents) 
}
</code></pre>
<p>This will feel very familiar to C# developers who have a similar unwrap mechanic for <code>Task&lt;T&gt;</code>: async/await. the <code>await</code> keyword unwraps a task, and any function which uses <code>await</code> must be marked <code>async</code> and itself, return a task.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;<span class="hljs-keyword">string</span>[]&gt; ReadFileContents(<span class="hljs-keyword">string</span> path)
{
    <span class="hljs-comment">// read all lines using `await` to unwrap an asynchronus function</span>
    <span class="hljs-keyword">var</span> lines = <span class="hljs-keyword">await</span> File.ReadAllLinesAsync(path);
    <span class="hljs-keyword">return</span> lines;
}
</code></pre>
<p>Because a <code>Result&lt;T&gt;</code> type is not part of the BCL, there's no reason (or good way really) to add a similar operator to unwrap a <code>Result&lt;T&gt;</code> in C# and propagate any errors. Sadly, the following is not valid C#</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> Result&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">GetUsername</span>(<span class="hljs-params">Guid userId</span>)</span>
{
    <span class="hljs-comment">// use `?` to propogate errors</span>
    <span class="hljs-keyword">var</span> user = _db.Find&lt;User&gt;(userId)?
    <span class="hljs-keyword">return</span> user.Name;
}
</code></pre>
<h2 id="heading-where-developers-go-wrong-the-unsafe-unwrap">Where Developers Go Wrong: The Unsafe Unwrap</h2>
<p>In an effort to make their <code>Result&lt;T&gt;</code> types easier to use, many developers will add an unsafe unwrap. Usually this takes the form a property called <code>Value</code> which simply throws if the <code>Result&lt;T&gt;</code> represents a failure. The following examples for the rest of this article are using C# 12 with nullable enabled, and all warnings treated as errors.</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// A simple Result&lt;T&gt; with an unsafe unwrap called `Value`</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> T? _value;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Exception? _exception;
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Result</span>(<span class="hljs-params">T? <span class="hljs-keyword">value</span>, Exception? exception</span>)</span>
    =&gt; (_value, _exception) = (<span class="hljs-keyword">value</span>, exception);

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Success</span>(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-keyword">value</span>, exception: <span class="hljs-literal">null</span>);
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Failure</span>(<span class="hljs-params">Exception ex</span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-keyword">value</span>: <span class="hljs-literal">null</span>, ex);

    <span class="hljs-comment">// The unsafe unwrap</span>
    <span class="hljs-keyword">public</span> T Value =&gt; _value ?? <span class="hljs-keyword">throw</span> ex;
}
</code></pre>
<p>If the option to simply "get the value out" of a <code>Result&lt;T&gt;</code> is there, developers will take it. They will take it and the code will work, until one day it doesn't. The entire reason for switching to a <code>Result&lt;T&gt;</code> type is lost. You're carefully wrapping return values in a type that prepares for failure, only for the calling code to assume success anyway.</p>
<h2 id="heading-what-can-we-do">What can we do?</h2>
<p>Understanding the language shortfalls, and the pitfalls of an unsafe unwrap, is it possible to make a <code>Result&lt;T&gt;</code> worth using in C#? That answer to that will always be subjective, but I believe we can do better than the example above.</p>
<h3 id="heading-matchswitch-functions">Match/Switch Functions</h3>
<p>How do you best get the value out of a <code>Result&lt;T&gt;</code>? One way is to flip the question, or "How do you best inject behavior <em>into</em> a <code>Result&lt;T&gt;</code>" By providing Match/Switch functions we can require that calling code provide a path forward in both the case of a success or a failure. Here is an implementation of this, and an example of its usage</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Error</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Message</span>)</span>;

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> T? _value;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Error? _error;

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Result</span>(<span class="hljs-params">T? <span class="hljs-keyword">value</span>, Error error</span>)</span>
    =&gt; (_value, _error) = (<span class="hljs-keyword">value</span>, error);

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Success</span>(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-keyword">value</span>, <span class="hljs-literal">null</span>);
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Failure</span>(<span class="hljs-params">Error error</span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-literal">null</span>, error);

    <span class="hljs-function"><span class="hljs-keyword">public</span> TOut <span class="hljs-title">Switch</span>&lt;<span class="hljs-title">TOut</span>&gt;(<span class="hljs-params">
      Func&lt;T, TOut&gt; success,
      Func&lt;Error, TOut&gt; error</span>)</span>
    =&gt; _value <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span>
        ? success(_value)
        : error(_error!);
}

<span class="hljs-comment">// Usage</span>
Result&lt;User&gt; userResult = GetUser(userId);
<span class="hljs-keyword">string</span> userName = userResult.Switch(
    success: user =&gt; user.Name,
    error: err =&gt; <span class="hljs-string">$"Unable to find user: <span class="hljs-subst">{err.Message}</span>"</span>);

<span class="hljs-keyword">return</span> userName;
</code></pre>
<p>This doesn't have an unsafe unwrap, but it can be a little awkward in an imperative codebase, which describes quite a bit of C# code. To address this, we can rely on subclasses and pattern matching</p>
<h2 id="heading-subtypes-and-pattern-matching">Subtypes and Pattern Matching</h2>
<p>C# pattern matching provides a powerful and straight forward way to ask about the runtime type of an object and capture a typed reference to that object. This makes it easy for use to check for a successful <code>Result&lt;T&gt;</code> with a simple <code>if</code> statement and use the successful value in a compile checked way.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Error</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Message</span>)</span>;
<span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Success</span>(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span> =&gt; <span class="hljs-keyword">new</span> Success(<span class="hljs-keyword">value</span>);
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">Failure</span>(<span class="hljs-params">Error error</span>)</span> =&gt; <span class="hljs-keyword">new</span> Failure(error);
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Success</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> T Value { <span class="hljs-keyword">get</span>; }
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">Success</span>(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span> =&gt; Value = <span class="hljs-keyword">value</span>;
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Failure</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> Error Error { <span class="hljs-keyword">get</span>; }
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">Failure</span>(<span class="hljs-params">Error error</span>)</span> =&gt; Error = error;
}

<span class="hljs-comment">// Usage</span>
Result&lt;User&gt; userResult = GetUser(userId);
<span class="hljs-keyword">if</span> (userResult <span class="hljs-keyword">is</span> Success&lt;User&gt; success)
{
    <span class="hljs-keyword">return</span> success.Value.Name;
}
</code></pre>
<p>Unfortunately, there isn't a great way to tell the compiler that if a <code>Result&lt;T&gt;</code> instance isn't a <code>Success&lt;T&gt;</code> type, then it <em>must</em> be a <code>Failure&lt;T&gt;</code> type. The lack of discriminated unions is why we're in this pickle to begin with. Still however, we can press on and refine this type further</p>
<h3 id="heading-implicit-operators">Implicit operators</h3>
<p>We can clean up our static factory methods with implicit conversions, this if a function's return type is <code>Result&lt;T&gt;</code> we can simply return a <code>T</code> or an <code>Error</code></p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">implicit</span> <span class="hljs-keyword">operator</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span>
    =&gt; <span class="hljs-keyword">new</span> Success(<span class="hljs-keyword">value</span>);

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">implicit</span> <span class="hljs-keyword">operator</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">Error error</span>)</span>
    =&gt; <span class="hljs-keyword">new</span> Failure(error);
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;<span class="hljs-keyword">decimal</span>&gt; <span class="hljs-title">Divide</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> numerator, <span class="hljs-keyword">decimal</span> denominator</span>)</span>
{
    <span class="hljs-keyword">if</span> (denominator == <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-string">"Cannot divide by zero"</span>);
    <span class="hljs-keyword">return</span> numerator / denominator;
}
</code></pre>
<h3 id="heading-adding-a-safe-unwrap">Adding a Safe Unwrap</h3>
<p>Next let's try and add a safe unwrap (or at least to most elegant one that C# will let us) We want failure to be the <code>true</code> condition so we can early return the error. We'll use the nullable branch analysis to indicate to the client code when out parameters are or are not null.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-comment">// Omitted</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">UnwrapFailed</span>(<span class="hljs-params">
        [NotNullWhen(<span class="hljs-literal">true</span></span>)]
        <span class="hljs-keyword">out</span> Error? error,
        [<span class="hljs-title">NotNullWhen</span>(<span class="hljs-params"><span class="hljs-literal">false</span></span>)]
        <span class="hljs-keyword">out</span> T? <span class="hljs-keyword">value</span>)</span>;
}


<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Success</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">UnwrapFailed</span>(<span class="hljs-params">
        [NotNullWhen(<span class="hljs-literal">true</span></span>)]
        <span class="hljs-keyword">out</span> Error? error,
        [<span class="hljs-title">NotNullWhen</span>(<span class="hljs-params"><span class="hljs-literal">false</span></span>)]
        <span class="hljs-keyword">out</span> T? <span class="hljs-keyword">value</span>)</span>
    {
        error = <span class="hljs-literal">null</span>;
        <span class="hljs-keyword">value</span> = Value;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
    }
}
<span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Failure</span>&lt;<span class="hljs-title">T</span>&gt; : <span class="hljs-title">Result</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">override</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">UnwrapFailed</span>(<span class="hljs-params">
        [NotNullWhen(<span class="hljs-literal">true</span></span>)]
        <span class="hljs-keyword">out</span> Error? error,
        [<span class="hljs-title">NotNullWhen</span>(<span class="hljs-params"><span class="hljs-literal">false</span></span>)]
        <span class="hljs-keyword">out</span> T? <span class="hljs-keyword">value</span>)</span>
    {
        error = Error;
        <span class="hljs-keyword">value</span> = <span class="hljs-literal">null</span>;
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
}

<span class="hljs-comment">// Usage</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> Result&lt;<span class="hljs-keyword">string</span>&gt; <span class="hljs-title">AssembleGreeting</span>(<span class="hljs-params">Guid greetingId, Guid nameId</span>)</span>
{
    Result&lt;<span class="hljs-keyword">string</span>&gt; greetingResult = LoadGreeting(greetingId);
    Result&lt;<span class="hljs-keyword">string</span>&gt; nameResult = LoadName(nameId);

    <span class="hljs-keyword">if</span> (greetingResult.UnwrapFailed(<span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> error, <span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> greeting))
        <span class="hljs-keyword">return</span> error; <span class="hljs-comment">// error is not null here</span>
    <span class="hljs-keyword">if</span> (nameReuslt.UnwrapFailed(<span class="hljs-keyword">out</span> error, <span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> name))
        <span class="hljs-keyword">return</span> error <span class="hljs-comment">// error is not null here</span>

    <span class="hljs-comment">// neither greeting or name are null here</span>
    <span class="hljs-keyword">return</span> <span class="hljs-string">$"<span class="hljs-subst">{greeting}</span>, <span class="hljs-subst">{name}</span>!"</span>;
}
</code></pre>
<h3 id="heading-conclusion">Conclusion</h3>
<p>C# is a high ceremony language, and there are limits to how succinctly we can express certain concepts and structures that come naturally to other languages like Rust or F#, but with this in mind we can still craft a result that achieves its goal: forcing the calling code to deal with any potential errors at compile time.</p>
<p>Here are some fun exercises when crafting your own result types:</p>
<ul>
<li><p>Add a map/select function</p>
</li>
<li><p>Extend the map/select function to automatically flatten (<code>Result&lt;Result&lt;T&gt;&gt;</code> becomes <code>Result&lt;T&gt;</code>)</p>
</li>
<li><p>Add a way for a <code>Result&lt;Task&lt;T&gt;&gt;</code> to be <code>awaited</code> returning <code>Result&lt;T&gt;</code></p>
</li>
<li><p>Add an equality operator which respects referential transparency</p>
<ul>
<li><p>Two <code>Result&lt;int&gt;</code> objects which both contain the same number should be equal</p>
</li>
<li><p>A <code>Result&lt;int&gt;</code> which is a <code>Success&lt;int&gt;</code> that holds <code>5</code> should be equal to an <code>int</code> which holds <code>5</code></p>
</li>
</ul>
</li>
</ul>
]]></content:encoded></item><item><title><![CDATA[Basics In Blazor - Modal]]></title><description><![CDATA[This post is part of a series called Basics in Blazor, where I explore returning to the simplicity of web UI, preferring semantic HTML and CSS to bloated, complicated, and/or restrictive component libraries. These posts focus on using Blazor to work ...]]></description><link>https://blog.samferree.dev/basics-in-blazor-modal</link><guid isPermaLink="true">https://blog.samferree.dev/basics-in-blazor-modal</guid><category><![CDATA[Blazor]]></category><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[modal]]></category><category><![CDATA[HTML5]]></category><category><![CDATA[Web Development]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 21 Jun 2024 15:46:00 GMT</pubDate><content:encoded><![CDATA[<p>This post is part of a series called Basics in Blazor, where I explore returning to the simplicity of web UI, preferring semantic HTML and CSS to bloated, complicated, and/or restrictive component libraries. These posts focus on using Blazor to work <em>with</em> native web UI, not fight an uphill battle <em>against it</em>.</p>
<p>To that end, this post aims to show an example of a lightweight, yet powerful Blazor modal, built on top of the html <code>&lt;dialog&gt;</code> element.</p>
<h2 id="heading-the-dialog-element">The Dialog Element</h2>
<p>HTML has out of the box, native <code>dialog</code> element and modal support with just a bit of JavaScript (and our implementation will only use a small amount of this). Let's take a look at the dialog element:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dialog</span> <span class="hljs-attr">open</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is an open dialog<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dialog</span>&gt;</span>
</code></pre>
<p>This creates a dialog that is always open. From here it's trivial to use a conditional to show or hide this in Blazor:</p>
<pre><code class="lang-xml">@if (ShouldShowDialog)
{
    <span class="hljs-tag">&lt;<span class="hljs-name">dialog</span> <span class="hljs-attr">open</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>Hello World!<span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>This is an open dialog
    <span class="hljs-tag">&lt;/<span class="hljs-name">dialog</span>&gt;</span>
}
</code></pre>
<p>This works, and it's a very "Blazor" way to go about this, but it isn't a modal. It's a dialog, a pop up even, but it doesn't disable the rest of the view, or have other behaviors we typically associate with modals. This modal functionality of the <code>dialog</code> element is available via JavaScript:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> dialogRef = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'dialog'</span>);
dialogRef.showModal();
dialogRef.close();
</code></pre>
<p>If we want this behavior in Blazor, we'll have to utilize the built in JavaScript Interop. The <code>IJSRuntime</code> interface lets us call a JavaScript function asynchronously, so let's add a couple utility methods to do that in a file we will call modal.js</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">showModal</span>(<span class="hljs-params">modal</span>) </span>{ modal.showModal(); }
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">closeModal</span>(<span class="hljs-params">modal</span>) </span>{ modal.close(); }
</code></pre>
<p>That's it! Once we've served this up with the rest of our source files, we can craft the following Blazor component, <code>Modal</code>. First the template:</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dialog</span> @<span class="hljs-attr">ref</span>=<span class="hljs-string">DialogRef</span>&gt;</span>
    @ChildContent
<span class="hljs-tag">&lt;/<span class="hljs-name">dialog</span>&gt;</span>
</code></pre>
<p>I did say this control was going to be very lightweight. We only add 2 things to the <code>dialog</code> element. First we capture a reference to this element called <code>DialogRef</code> and second, we render any child content that was passed to us, in the <code>dialog</code> element. Let's take a look at the code behind file.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Modal</span>
{
    [<span class="hljs-meta">Inject</span>]
    <span class="hljs-keyword">public</span> required IJSRuntime JS { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }

    ElementReference DialogRef;

    [<span class="hljs-meta">Parameter</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsOpen { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> _isOpen;

    [<span class="hljs-meta">Parameter</span>]
    <span class="hljs-keyword">public</span> required RenderFragment ChildContent { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> Task <span class="hljs-title">OnParametersSetAsync</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">await</span> ToggleModal();
        <span class="hljs-keyword">await</span> <span class="hljs-keyword">base</span>.SetParametersAsync(parameters);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">ToggleModal</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">if</span> (_isOpen == IsOpen) <span class="hljs-keyword">return</span>;

        <span class="hljs-keyword">string</span> jsCommand = IsOpen ? <span class="hljs-string">"showModal"</span> : <span class="hljs-string">"closeModal"</span>;
        <span class="hljs-keyword">await</span> JS.InvokeVoidAsync(jsCommand, DialogRef);
        _isOpen = IsOpen;
    }
}
</code></pre>
<p>First, we inject a reference to the <code>IJSRuntime</code> so we can call our JavaScript functions from earlier. Then we provide a field to store the reference to our <code>dialog</code> element. We take in two parameters, <code>IsOpen</code> and <code>ChildContent</code>. <code>ChildContent</code> will contain whatever inner elements were defined when this component was used, <code>IsOpen</code> is the binding we've given the client to determine whether the modal should show or hide.</p>
<p>You may notice the <code>_isOpen</code> backing field doesn't <em>really</em> back the auto-property. Component parameters are recommended to be auto properties, but we need to track the <em>actual</em> state of the modal, not just what our client is requesting the state to be. Because the input parameter is an auto-prop, we can't react to the value changing in the setter, so we override the <code>OnParametersSetAsync()</code> method to call our own <code>ToggleModal()</code>.</p>
<p>It's important to note that just because <code>OnParametersSetAsync()</code> is called, it doesn't necessarily mean any of the values have changed, so we check for this case and early return if we don't have anything to do. In the case that the value of <code>IsOpen</code> did change, we execute the correct JavaScript function, passing in our dialog reference as a parameter, and then update our actual state, <code>_isOpen</code> to match the client requested state.</p>
<h2 id="heading-seriously-thats-it">Seriously, That's it.</h2>
<p>And just like that, we're ready to put this component in action. Let's drop this component on a page and see how it's used</p>
<pre><code class="lang-xml">@page "/"

<span class="hljs-tag">&lt;<span class="hljs-name">PageTitle</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">PageTitle</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>This is a page<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">onclick</span>=<span class="hljs-string">"ShowModal"</span>&gt;</span>Show Modal<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">Modal</span> <span class="hljs-attr">IsOpen</span>=<span class="hljs-string">ShouldShowModal</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>This is a modal<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">onclick</span>=<span class="hljs-string">"CloseModal"</span>&gt;</span>Close Modal<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">Modal</span>&gt;</span>
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Home</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> ShouldShowModal { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-literal">false</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ShowModal</span>(<span class="hljs-params"></span>)</span>
    {
        ShouldShowModal = <span class="hljs-literal">true</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CloseModal</span>(<span class="hljs-params"></span>)</span>
    {
        ShouldShowModal = <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<p>We throw a button on the page to show the modal, and then define some content <em>for</em> the modal which includes a button to close the modal. We toggle this by toggling the value of <code>ShouldShowModal</code> and the <code>Modal</code> component takes care of the rest.</p>
<p>While we have provided a functional modal, I think it's important to note what we <em>haven't done</em>. We haven't pulled in some bloated and/or restrictive 3rd party component library, we haven't added layers of elements and divs between the parent component and the modal content, and we haven't limited the users control over the modal style, and contents. This latter feature really made this design shine when I tried to take the next step of functionality the HTML <code>dialog</code> element offers: form return values</p>
<h3 id="heading-getting-data-out">Getting Data Out</h3>
<p>If we take a look at the documentation example for the <code>dialog</code> element from MDN, obtaining and returning the value of form data is a complex process when compared to the <code>showModal()</code> and <code>close()</code> functions we used previously.</p>
<pre><code class="lang-xml"><span class="hljs-tag">&lt;<span class="hljs-name">dialog</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"favDialog"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">form</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">label</span>&gt;</span>
        Favorite animal:
        <span class="hljs-tag">&lt;<span class="hljs-name">select</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"default"</span>&gt;</span>Choose…<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span>&gt;</span>Brine shrimp<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span>&gt;</span>Red panda<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">option</span>&gt;</span>Spider monkey<span class="hljs-tag">&lt;/<span class="hljs-name">option</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">select</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"cancel"</span> <span class="hljs-attr">formmethod</span>=<span class="hljs-string">"dialog"</span>&gt;</span>Cancel<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"confirmBtn"</span> <span class="hljs-attr">value</span>=<span class="hljs-string">"default"</span>&gt;</span>Confirm<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">dialog</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"showDialog"</span>&gt;</span>Show the dialog<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">output</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">output</span>&gt;</span>
</code></pre>
<h3 id="heading-8jkog">🤢</h3>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> showButton = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"showDialog"</span>);
<span class="hljs-keyword">const</span> favDialog = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"favDialog"</span>);
<span class="hljs-keyword">const</span> outputBox = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"output"</span>);
<span class="hljs-keyword">const</span> selectEl = favDialog.querySelector(<span class="hljs-string">"select"</span>);
<span class="hljs-keyword">const</span> confirmBtn = favDialog.querySelector(<span class="hljs-string">"#confirmBtn"</span>);

<span class="hljs-comment">// "Show the dialog" button opens the &lt;dialog&gt; modally</span>
showButton.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">() =&gt;</span> {
  favDialog.showModal();
});

<span class="hljs-comment">// "Cancel" button closes the dialog without submitting because of [formmethod="dialog"], triggering a close event.</span>
favDialog.addEventListener(<span class="hljs-string">"close"</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  outputBox.value =
    favDialog.returnValue === <span class="hljs-string">"default"</span>
      ? <span class="hljs-string">"No return value."</span>
      : <span class="hljs-string">`ReturnValue: <span class="hljs-subst">${favDialog.returnValue}</span>.`</span>; <span class="hljs-comment">// Have to check for "default" rather than empty string</span>
});

<span class="hljs-comment">// Prevent the "confirm" button from the default behavior of submitting the form, and close the dialog with the `close()` method, which triggers the "close" event.</span>
confirmBtn.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
  event.preventDefault(); <span class="hljs-comment">// We don't want to submit this fake form</span>
  favDialog.close(selectEl.value); <span class="hljs-comment">// Have to send the select box value here.</span>
});
</code></pre>
<h3 id="heading-8jkrg">🤮</h3>
<p>So, I set about doing what I thought I should do; encapsulating all of this and making it easier for a Blazor developer to use. And after a few hours of struggling, it dawned on me: <em>I already had</em></p>
<p>The same trick I used to pass a button (whose click handler I had bound to a local function) into the modal would work for, in theory, any content. Let's modify our home page example one more time and test my hunch.</p>
<pre><code class="lang-xml">@page "/"

<span class="hljs-tag">&lt;<span class="hljs-name">PageTitle</span>&gt;</span>Home<span class="hljs-tag">&lt;/<span class="hljs-name">PageTitle</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>This is a page<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">onclick</span>=<span class="hljs-string">"ShowModal"</span>&gt;</span>Show Modal<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">Modal</span> <span class="hljs-attr">IsOpen</span>=<span class="hljs-string">ShouldShowModal</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h3</span>&gt;</span>This is a modal<span class="hljs-tag">&lt;/<span class="hljs-name">h3</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Add an input element and bind it's value to a property called 'Input' --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span> @<span class="hljs-attr">bind-value</span>=<span class="hljs-string">Input</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span> @<span class="hljs-attr">onclick</span>=<span class="hljs-string">"CloseModal"</span>&gt;</span>Close Modal<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">Modal</span>&gt;</span>
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">partial</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Home</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> ShouldShowModal { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-literal">false</span>;
    <span class="hljs-comment">// Add a string property called Input</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Input { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } = <span class="hljs-keyword">string</span>.Empty;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">ShowModal</span>(<span class="hljs-params"></span>)</span>
    {
        ShouldShowModal = <span class="hljs-literal">true</span>;
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">CloseModal</span>(<span class="hljs-params"></span>)</span>
    {
        Console.WriteLine(<span class="hljs-string">$"Input: <span class="hljs-subst">{Input}</span>"</span>);
        ShouldShowModal = <span class="hljs-literal">false</span>;
    }
}
</code></pre>
<p>I tested this and was pleasantly surprised when, in the end, it did turn out to be that simple. The <code>input</code> element binds to our <code>Input</code> even as part of the modal, so the value is already updated when we click close. No need to mess around with form actions, submit values, confusing callbacks or preventing default actions. An entire form, bound to a property of the parent component, can be put into the <code>Modal</code> content.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Whenever I encounter some difficulty, the solution is often "It's easier than I'm making it", and web development is no exception to this rule. In our example here, we've created a modal control that is flexible and powerful enough to be shared throughout your entire application, but small enough to fit in your head.</p>
]]></content:encoded></item><item><title><![CDATA[A Simple and Safe Stack]]></title><description><![CDATA[As a developers, sometimes our end user is going to be other developers. When this happens, it's prudent for us to use all the tools available to us to protect our users from encountering an error when calling our code. Ideally, the user should not e...]]></description><link>https://blog.samferree.dev/a-simple-and-safe-stack</link><guid isPermaLink="true">https://blog.samferree.dev/a-simple-and-safe-stack</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[Programming Blogs]]></category><category><![CDATA[stack]]></category><category><![CDATA[Object Oriented Programming]]></category><category><![CDATA[oop]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 14 Jun 2024 17:41:38 GMT</pubDate><content:encoded><![CDATA[<p>As a developers, sometimes our end user is going to be other developers. When this happens, it's prudent for us to use all the tools available to us to protect our users from encountering an error when calling our code. Ideally, the user should not experience an exception. What follows is an example of this idea taken to it's full potential, an easy to use, and 100% exception free Stack.</p>
<p>What do I mean by exception free? Not only will the object never throw an exception, but it will not allow you to try and remove an item from top of it when none exists. This is due to not only it's design, but also that the stack is itself, an extremly simple data type (we will see in a later post how much harder this is with the Stack's opposite, a Queue)</p>
<h2 id="heading-the-status-quo">The Status Quo</h2>
<p>First, let's look at the promises made by the <code>System.Collections.Generic.Stack&lt;T&gt;</code>, specifically the <code>Pop()</code> method</p>
<hr />
<h4 id="heading-returns">Returns</h4>
<p>T</p>
<p>The object removed from the top of the <code>Stack&lt;T&gt;</code></p>
<h4 id="heading-exceptions">Exceptions</h4>
<p>InvalidOperationException The <code>Stack&lt;T&gt;</code> is empty.</p>
<hr />
<p>This object places the burden on the client code to check whether or not the stack has items in it, in order to ensure that they do not experience an exception. Of course, no stack can <code>Pop()</code> an item which does not exist, but is it possible to do better than a runtime exception? We could return <code>null</code>, but can we do better yet still? As it so happens, we can.</p>
<h2 id="heading-the-method-does-not-exist">The method does not exist</h2>
<p>If the stack is empty, the method (<code>Pop()</code>) does not exist. Let's see how we can achieve this with an abstract base class, and two inherited sub classes</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">Data</span>&gt; { }

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EmptyStack</span>&lt;<span class="hljs-title">Data</span>&gt; : <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">Data</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">EmptyStack</span>(<span class="hljs-params"></span>)</span> { }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">NonEmptyStack</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> Top Data { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Stack _rest;

    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">NonEmptyStack</span>(<span class="hljs-params">Data top, Stack rest</span>)</span>
    {
        Top = top;
        _rest = rest;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Stack <span class="hljs-title">Pop</span>(<span class="hljs-params"></span>)</span> =&gt; _rest;
}
</code></pre>
<p>First, let's note that this <code>Stack</code> is <em>immutable</em>. Which is to say that when you <code>Pop()</code> you are not removing the top item <em>from this stack</em>, but rather <em>getting back a stack that has all the items except for the top of this one</em>.</p>
<p>This is how we achieve an exception free <code>Top</code> and <code>Pop()</code>, we hide the method behind a type which is guaranteed to have at least one item, and therefore can return the <code>Top</code>, and execute a <code>Pop()</code> without exception.</p>
<p>We only need to add a little bit more code to complete this <code>Stack</code>, namely the <code>Push()</code> method, since currently there is no way of getting data into the <code>Stack</code>. Let's do that now.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">Data</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">readonly</span> <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">Data</span>&gt; Empty</span> = <span class="hljs-keyword">new</span> EmptyStack&lt;Data&gt;();
    <span class="hljs-function"><span class="hljs-keyword">public</span> Stack&lt;Data&gt; <span class="hljs-title">Push</span>(<span class="hljs-params">Data data</span>)</span> =&gt; <span class="hljs-keyword">new</span> NonEmptyStack(data, rest: <span class="hljs-keyword">this</span>);
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">EmptyStack</span>&lt;<span class="hljs-title">Data</span>&gt; : <span class="hljs-title">Stack</span>&lt;<span class="hljs-title">Data</span>&gt;
{
    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">EmptyStack</span>(<span class="hljs-params"></span>)</span> { }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">NonEmptyStack</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> Top Data { <span class="hljs-keyword">get</span>; }
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> Stack _rest;

    <span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-title">NonEmptyStack</span>(<span class="hljs-params">Data top, Stack rest</span>)</span>
    {
        Top = top;
        _rest = rest;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Stack <span class="hljs-title">Pop</span>(<span class="hljs-params"></span>)</span> =&gt; _rest;
}
</code></pre>
<p>As before our <code>Push()</code> method respects the fact that our stack is immutable. It returns a new <code>Stack</code>, which has all the items before, except with the new data as the <code>Top</code> of the <code>Stack</code></p>
<h2 id="heading-putting-it-to-work">Putting it to work</h2>
<p>Let's use this stack to execute a simple string reverse. We try to pattern match the abstract <code>Stack</code> to the concrete <code>NonEmptyStack</code> and as long as we can successfully do so, we add the <code>Top</code> character to the reversed string. We then execute a <code>Pop()</code> and assign the returned <code>Stack</code> to our stack variable so as to move toward the <code>EmptyStack</code>, which will break the loop.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">string</span> hello = <span class="hljs-string">"Hello World"</span>;
Stack&lt;<span class="hljs-keyword">char</span>&gt; stack = Stack&lt;<span class="hljs-keyword">char</span>&gt;.Empty;
<span class="hljs-keyword">string</span> olleh = <span class="hljs-keyword">string</span>.Empty;

<span class="hljs-keyword">foreach</span>(<span class="hljs-keyword">char</span> c <span class="hljs-keyword">in</span> hello)
{
    stack = stack.Push(c);
}

<span class="hljs-keyword">while</span>(stack <span class="hljs-keyword">is</span> NonEmptyStack&lt;<span class="hljs-keyword">char</span>&gt; nonEmpty)
{
    olleh += nonEmpty.Top;
    stack = nonEmpty.Pop();
}
Console.WriteLine(olleh)
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>By taking advantage of immutability, a small amount of inheritance, and pattern matching, we've designed a type that will catch any attempt to read an empty stack not in Prod, QA or even in automated tests, but at the time of compilation.</p>
]]></content:encoded></item><item><title><![CDATA[IEnumerable, It's Not a Collection.]]></title><description><![CDATA[IEnumerable<T> has become one of the most popular ways not only to manipulate collections, but to pass them around as a read only structure. The power of LINQ and the safety of read-only immutable structures make it an excellent choice when modeling ...]]></description><link>https://blog.samferree.dev/ienumerable-not-a-collection</link><guid isPermaLink="true">https://blog.samferree.dev/ienumerable-not-a-collection</guid><category><![CDATA[C#]]></category><category><![CDATA[linq]]></category><category><![CDATA[dotnet]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 07 Jun 2024 14:25:00 GMT</pubDate><content:encoded><![CDATA[<p><code>IEnumerable&lt;T&gt;</code> has become one of the most popular ways not only to manipulate collections, but to pass them around as a read only structure. The power of LINQ and the safety of read-only immutable structures make it an excellent choice when modeling your domain.</p>
<p>But with great power, comes great responsibility, and <code>IEnumerable&lt;T&gt;</code> has it's fair share of quirks to trip up unsuspecting developers.</p>
<h3 id="heading-its-an-enumerable-not-a-collection">It's an Enumerable, not a Collection</h3>
<p>While we often use <code>IEnumerable&lt;T&gt;</code> as a way to pass around collections, especially if we aren't picky about the underlying data structure. Maybe it's an <code>T[]</code>, maybe it's a <code>List&lt;T&gt;</code>. We don't know and we (allegedly) don't care.</p>
<p>But there are lots of objects that implement the <code>IEnumerable&lt;T&gt;</code> interface and they aren't collections, and thus don't behave how we might expect them to. Often times developers will be unaware that these concrete types are in their codebases, assuming that whatever <code>IEnumerable</code> object they are passing around represents an actual collection. Even if you've always specified a list or array, something as simple as using LINQ can open the door to some of these other types.</p>
<p>These types can get us in to trouble by assuming more than the <code>IEnumerable&lt;T&gt;</code> interface promises.</p>
<h3 id="heading-some-enumerables-are-lazy">Some Enumerables are lazy</h3>
<p>Consider the following code:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Batter</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> Name { <span class="hljs-keyword">get</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsAtBat { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> IsOnDeck { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">private</span> <span class="hljs-keyword">set</span>; }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Batter</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> name</span>)</span>
  {
    Name = name;
    IsOnDeck = <span class="hljs-literal">false</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">MarkAsOnDeck</span>(<span class="hljs-params"></span>)</span>
  {
    IsOnDeck = <span class="hljs-literal">true</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">MarkAsAtBat</span>(<span class="hljs-params"></span>)</span>
  {
    IsOnDeck = <span class="hljs-literal">false</span>;
    IsAtBat = <span class="hljs-literal">true</span>;
  }
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BattingOrder</span>
{
  <span class="hljs-keyword">public</span> IEnumerable&lt;Batter&gt; BattingOrder { <span class="hljs-keyword">get</span>; }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BattingOrder</span>(<span class="hljs-params">IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; battingOrderNames</span>)</span>
  {
    BattingOrder = CreateBatters(battingOrderNames);
    BattingOrder.First().MarkAsAtBat();
    BattingOrder.Skip(<span class="hljs-number">1</span>).First().MarkAsOnDeck();
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;Batter&gt; <span class="hljs-title">CreateBatters</span>(<span class="hljs-params">IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; battingOrderNames</span>)</span>
    =&gt; battingOrderNames.Select(name =&gt; <span class="hljs-keyword">new</span> Batter(name));

  <span class="hljs-function"><span class="hljs-keyword">public</span> Batter <span class="hljs-title">GetCurrentBatter</span>(<span class="hljs-params"></span>)</span>
    =&gt; BattingOrder.First(batter =&gt; batter.IsAtBat);
}
</code></pre>
<p>This code contains a bug, but not in any of the domain logic that's expressed.</p>
<p>The first <code>Batter</code> in the batting order <em>should be</em> at bat. The second <code>Batter</code> in the batting order <em>should be</em> on deck.</p>
<p>But when <code>GetCurrentBatter()</code> is called, the function fails. It can't find a batter that is currently at bat.</p>
<p>How can that be? We created the <code>IEnumerable&lt;Batter&gt;</code> instance, took the first one and marked it as at bat, and took the second one and marked it as on deck.</p>
<p>The key is right here</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> IEnumerable&lt;Batter&gt; <span class="hljs-title">CreateBatters</span>(<span class="hljs-params">IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; battingOrderNames</span>)</span>
    =&gt; battingOrderNames.Select(name =&gt; <span class="hljs-keyword">new</span> Batter(name));
</code></pre>
<p>In this method we use the <code>Select()</code> method to convert an enumerable of <code>string</code>, to an enumerable of <code>Batter</code>, and that's just it. We have an enumerable of batters <em>which makes no guarantees about being a collection</em>. In this specific case, the returned enumerable is <em>lazy</em>. Meaning every time we iterate through it (or call some specific LINQ methods on it) we're going to re-execute the mapping, which means we're constantly getting new references to <code>Batter</code> objects.</p>
<p>When we call this method here</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BattingOrder</span>(<span class="hljs-params">IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; battingOrderNames</span>)</span>
  {
    BattingOrder = CreateBatters(battingOrderNames);
    BattingOrder.First().MarkAsAtBat();
    BattingOrder.Skip(<span class="hljs-number">1</span>).First().MarkAsOnDeck();
  }
</code></pre>
<p>We're creating a lazy enumerable, then enumerating it twice. We're grabbing the first enumeration, then the second time, we're creating a new enumerable that skips the first enumeration, and then enumerating it to grab the second one, but remember each time we enumerate the <code>BattingOrder</code> enumerable, we create new instances of <code>Batter</code> objects. Meaning the "first" <code>Batter</code> we skip over in the last line, isn't the same <code>Batter</code> instance we marked as at bat on the previous line.</p>
<p>So finally when we call this method</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> Batter <span class="hljs-title">GetCurrentBatter</span>(<span class="hljs-params"></span>)</span>
    =&gt; BattingOrder.First(batter =&gt; batter.IsAtBat);
</code></pre>
<p>We're enumerating the enumerable again, creating a whole new set of <code>Batter</code> instances, none of which have been marked as at bat. This seemingly straight forward and readable code, contains a very hard to spot bug, that causes it to always fail.</p>
<h3 id="heading-what-to-do-instead">What to do instead</h3>
<p>What's the solution to avoiding these kinds of errors? If we know we're going to mutate an object (such as marking a <code>Batter</code> as at bat), then we must necessarily have a constant reference to the object being mutated. To ensure that any enumerable we obtain will preserve these references, it's a good idea to copy the enumerable into a private collection, which we know will preserve instances. In our case, we need just a single method call to fix our error.</p>
<pre><code class="lang-csharp">  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BattingOrder</span>(<span class="hljs-params">IEnumerable&lt;<span class="hljs-keyword">string</span>&gt; battingOrderNames</span>)</span>
  {
                                                    <span class="hljs-comment">//Copy enumerable into a list</span>
                                                    <span class="hljs-comment">//to preserve references</span>
    BattingOrder = CreateBatters(battingOrderNames).ToList();
    BattingOrder.First().MarkAsAtBat();
    BattingOrder.Skip(<span class="hljs-number">1</span>).First().MarkAsOnDeck(); 
  }
</code></pre>
<p>With this change, even though the <code>BattingOrder</code> variable is still types as an <code>IEnumerable&lt;Batter&gt;</code> we know that the object itself is an instance of <code>List&lt;Batter&gt;</code> which means we can be confident that calling <code>.First()</code> will always return the same object instance, that is, the first item in the list.</p>
<p>If you get passed an <code>IEnumerable&lt;T&gt;</code> as a parameter, it's almost always a good idea to call <code>.ToList()</code> or <code>.ToArray()</code> on it before assigning to variable, property or field. Not only does this ensure our reference isn't mutated by someone else, we also know that any mutations we might perform will persist.</p>
]]></content:encoded></item><item><title><![CDATA[When to invert your if checks]]></title><description><![CDATA[It's not uncommon to see code like this:
if (someCondition is true)
{
  // Do a thing
  // Do more things
  // do a final thing
  return result;
}
else
{
  return new Failure();
}

Now most people will be quick to spot that we don't need the else, si...]]></description><link>https://blog.samferree.dev/when-to-invert-your-if-checks</link><guid isPermaLink="true">https://blog.samferree.dev/when-to-invert-your-if-checks</guid><category><![CDATA[C#]]></category><category><![CDATA[Programming Tips]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Fri, 31 May 2024 17:33:47 GMT</pubDate><content:encoded><![CDATA[<p>It's not uncommon to see code like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (someCondition <span class="hljs-keyword">is</span> <span class="hljs-literal">true</span>)
{
  <span class="hljs-comment">// Do a thing</span>
  <span class="hljs-comment">// Do more things</span>
  <span class="hljs-comment">// do a final thing</span>
  <span class="hljs-keyword">return</span> result;
}
<span class="hljs-keyword">else</span>
{
  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Failure();
}
</code></pre>
<p>Now most people will be quick to spot that we don't need the else, since the IF block returns and we can save a few lines since the if block does an early return</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (someCondition <span class="hljs-keyword">is</span> <span class="hljs-literal">true</span>)
{
  <span class="hljs-comment">// Do a thing</span>
  <span class="hljs-comment">// Do more things</span>
  <span class="hljs-comment">// do a final thing</span>
  <span class="hljs-keyword">return</span> result;
}
<span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Failure()
</code></pre>
<p>But if we invert our condition we can early return from the else block which is considerable shorter than the if block</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (someCondition <span class="hljs-keyword">is</span> <span class="hljs-literal">false</span>) <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Failure();

<span class="hljs-comment">// Do a thing</span>
<span class="hljs-comment">// Do more things</span>
<span class="hljs-comment">// do a final thing</span>
<span class="hljs-keyword">return</span> result;
</code></pre>
<p>This can be done anytime the blocks result in a method return, and the else block is shorter than the if block. Consider the following function to calculate if a year is a leap year. (A leap year is a year which is divisible by 4, but not 100 unless it's also divisible by 400)</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> <span class="hljs-keyword">is</span> <span class="hljs-title">LeapYear</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> year</span>)</span>
{
  <span class="hljs-keyword">if</span> (year % <span class="hljs-number">4</span> == <span class="hljs-number">0</span>)
  {
    <span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> == <span class="hljs-number">0</span>)
    {
      <span class="hljs-keyword">if</span> (year % <span class="hljs-number">400</span> == <span class="hljs-number">0</span>)
      {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
      }
      <span class="hljs-keyword">else</span>
      {
        <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
      }
    }
    <span class="hljs-keyword">else</span>
    {
      <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
    }
  }
  <span class="hljs-keyword">else</span>
  {
    <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
  }
}
</code></pre>
<p>This is the fully written out leap year algorithm with if and else for every condition. Notice that the else blocks all immediately return, and the first two if blocks have more code (the subsequent if blocks). We can apply our inversion rule to clean this up.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (year % <span class="hljs-number">4</span> != <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
<span class="hljs-keyword">if</span> (year % <span class="hljs-number">100</span> != <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
<span class="hljs-keyword">if</span> (year % <span class="hljs-number">400</span> != <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;
<span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
</code></pre>
<p>If we replace the boolean expressions with some named extension methods and literals with constants, this code becomes very clear</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (year.IsNotDivisibleBy(<span class="hljs-number">4</span>)) <span class="hljs-keyword">return</span> NOT_LEAP_YEAR;
<span class="hljs-keyword">if</span> (year.IsNotDivisibleBy(<span class="hljs-number">100</span>)) <span class="hljs-keyword">return</span> LEAP_YEAR;
<span class="hljs-keyword">if</span> (year.IsNotDivisibleBy(<span class="hljs-number">400</span>)) <span class="hljs-keyword">return</span> NOT_LEAP_YEAR;
<span class="hljs-keyword">return</span> LEAP_YEAR;
</code></pre>
]]></content:encoded></item><item><title><![CDATA[The Trouble with .Single()]]></title><description><![CDATA[\in this article I will use list to refer to any enumerable collection not just List<T>*
The O.G. Singleton
In computing it can often be beneficial to work with lists. They are null-safe by default as an empty list is always valid. From time to time ...]]></description><link>https://blog.samferree.dev/the-trouble-with-single</link><guid isPermaLink="true">https://blog.samferree.dev/the-trouble-with-single</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Tue, 02 Jan 2024 06:49:24 GMT</pubDate><content:encoded><![CDATA[<p><em>\</em>in this article I will use list to refer to any enumerable collection not just List&lt;T&gt;*</p>
<h2 id="heading-the-og-singleton">The O.G. Singleton</h2>
<p>In computing it can often be beneficial to work with lists. They are null-safe by default as an empty list is always valid. From time to time we will expect that a list we are working with will contains one <em>and only one</em> value. The correct mathematical term for this is <code>Singleton</code>, a term which may be confusing now given the rise in popularity of IoC containers and service lifetimes, but take this as another reminder that <em>context always matters</em>.</p>
<p>Out of the box, LINQ gives us two methods for accessing the single item in a singleton: <code>.Single()</code> and <code>.SingleOrDefault()</code>. This has made me very angry and should be widely regarded as a bad move.</p>
<h2 id="heading-single">Single()</h2>
<p>IFF the list contains a single item (or a single item matching a given predicate) <code>Single()</code> will return that item. Else, this method will throw an exception. Which is great for halting program execution, but not so great for error handling. We have methods of proving that a list contains only one item to us and other developers, but not great ways of proving it to the compiler.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">if</span> (items.Count() != <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span>;

<span class="hljs-comment">// A little while later</span>
<span class="hljs-keyword">return</span> items.Single();
</code></pre>
<p>In the example above we know we've checked and that single will not throw, but the compiler is unaware of this assumption, and so, if the check ever gets removed, there's nothing letting the developer know that this assumption is not longer true. It's possible to solve this with a type</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Singleton</span>&lt;<span class="hljs-title">T</span>&gt;
{
  <span class="hljs-keyword">public</span> T Item { <span class="hljs-keyword">get</span>; }
  <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Singleton</span>(<span class="hljs-params">T item</span>)</span> =&gt; Item = item;
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">TryParse</span>(<span class="hljs-params">
    IEnumerable&lt;T&gt; list,
    [NotNullWhen(<span class="hljs-literal">true</span></span>)]
    Singleton&lt;T&gt;? singleton)</span>
  {
    singleton = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">if</span> (list.Count() != <span class="hljs-number">1</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

    singleton = <span class="hljs-keyword">new</span>(list.Single());
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre>
<p>Yes, yes, I know I've used <code>Single()</code> in the type I've said would let us stop using <code>Single()</code> but the enforcement of this constraint is the raison d'etre of this type and so I think it's pretty clear to later developers that remove the check here is a breaking change. This is a perfectly workable solution for older .NET code, but we can (and will) do better later on.</p>
<h2 id="heading-singleordefault">SingleOrDefault()</h2>
<p>A popular alternative, which does not throw is <code>SingleOrDefault()</code> which will always return a value. If the list is a singleton, it will return the single item, if not it will return the <code>default</code> (null for reference types). Combined with <code>nullable</code> enabled, and treating warnings as errors, the compiler will force a null check for you, but that isn't always the case.</p>
<h2 id="heading-enter-c-11">Enter C# 11</h2>
<p>List patterns were introduced in C# 11, and they have come to the rescue here. We now have a compiler safe way to enforce either A) that a list is a singleton, or B) that the developer has handled all alternatives.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">var</span> singleItem = list <span class="hljs-keyword">switch</span>
{
  [<span class="hljs-meta"></span>] =&gt; HandleEmptyList(),
  [<span class="hljs-meta">var item</span>] =&gt; item,
  [<span class="hljs-meta">var first, var second, ..</span>] =&gt; HandleListWithMultipleItems(),
};
</code></pre>
<p>The compiler is now completely aware of the assumption we are making. Therefore if any of the cases are removed, it will give us an error. Well, a warning that you <em>really should</em> be considering an error.</p>
<p>We can adopt this to a variety of error handling methods, below are examples for <code>Try</code>, error handling delegates, and <code>Result</code> types.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">TrySingle</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">
  <span class="hljs-keyword">this</span> IEnumerable&lt;T&gt; list,
  [NotNullWhen(<span class="hljs-literal">true</span></span>)]
  <span class="hljs-keyword">out</span> T? item)</span>
{
  item = list <span class="hljs-keyword">switch</span>
  {
    [<span class="hljs-meta"></span>] =&gt; <span class="hljs-literal">null</span>,
    [<span class="hljs-meta">T singleValue</span>] =&gt; singleValue,
    [<span class="hljs-meta">T first, T second, ..</span>] =&gt; <span class="hljs-literal">null</span>
  };
  <span class="hljs-keyword">return</span> item <span class="hljs-keyword">is</span> not <span class="hljs-literal">null</span>;
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> T? Single(
  <span class="hljs-keyword">this</span> IEnumerable&lt;T&gt; list,
  Action&lt;<span class="hljs-keyword">string</span>&gt; error)
{
  <span class="hljs-keyword">private</span> T? fail(<span class="hljs-keyword">string</span> errorMsg)
  {
    error(errorMsg);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }

  <span class="hljs-keyword">return</span> list <span class="hljs-keyword">switch</span>
  {
    [<span class="hljs-meta"></span>] =&gt; fail(<span class="hljs-string">"The list is empty"</span>),
    [<span class="hljs-meta">T singleItem</span>] =&gt; singleItem,
    [<span class="hljs-meta">T fist, T second, ..</span>] =&gt; fail(<span class="hljs-string">"The list contains multiple entries"</span>)
  };
}
</code></pre>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;T&gt; <span class="hljs-title">ParseSingle</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> IEnumerable&lt;T&gt; list</span>)</span>
=&gt; list <span class="hljs-keyword">switch</span>
{
  [<span class="hljs-meta"></span>] =&gt; <span class="hljs-keyword">new</span> Error(<span class="hljs-string">"The list is empty"</span>),
  [<span class="hljs-meta">T singleItem</span>] =&gt; singleItem,
  [<span class="hljs-meta">T first, T second, ..</span>] =&gt; <span class="hljs-keyword">new</span> Error(<span class="hljs-string">"The list contains multiple entries"</span>)
};
</code></pre>
<p>Note that while each of these methods don't present a significant value from the outside over something like <code>SingleOrDefault()</code>, they still have a compiler checked assumption and are thus more resistant to being broken accidentally by later developers.</p>
<p>In your domain code, it's likely much more appropriate to write the <code>switch</code> expression out in it's entirety as your domain likely has rules and processes for handling this failed assumption, and if it does not, go check with your customer to find out if it should.</p>
]]></content:encoded></item><item><title><![CDATA[Constructors vs Initializers vs Factories]]></title><description><![CDATA[In C# it can be quite useful to obtain an instance of an object. What is important to us as designers of types, are the different ways we can permit others to do this.
Constructors
First we have the constructor. It's worth noting that whatever method...]]></description><link>https://blog.samferree.dev/constructors-vs-initializers-vs-factories</link><guid isPermaLink="true">https://blog.samferree.dev/constructors-vs-initializers-vs-factories</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[error handling]]></category><category><![CDATA[#Domain-Driven-Design]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Thu, 14 Dec 2023 09:46:08 GMT</pubDate><content:encoded><![CDATA[<p>In C# it can be quite useful to obtain an instance of an object. What is important to us as designers of types, are the different ways we can permit others to do this.</p>
<h2 id="heading-constructors">Constructors</h2>
<p>First we have the constructor. It's worth noting that whatever method you expose to your clients, somewhere, somehow a constructor is being called. A constructor allows us to communicate and enforce at compile time which information is required via the parameter list. Unfortunately the constructor gives us only a single method of enforcing constraints which is throwing an exception when they are violated.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; }
  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Dimensions</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> length, <span class="hljs-keyword">decimal</span> height</span>)</span>
  {
    <span class="hljs-keyword">if</span> (Length &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Must have a positive length."</span>)
    <span class="hljs-keyword">if</span> (Height &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Must have a positive height."</span>)
    Length = length;
    Height = height;
  }
}
</code></pre>
<p>This is great for aborting program execution immediately, but not a great way to handle errors. Note here as well that if a client sends us a non-positive length AND height, only the first exception will be hit. Making this method unsuitable for revealing <em>all</em> initialization errors.</p>
<h2 id="heading-initializers">Initializers</h2>
<p>Object initializers were added as a form of <em>syntactic sugar</em> to the language and were very simple early on. Here is an example of the initial offering in C# 3</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}

<span class="hljs-comment">// Pre C# 3</span>
Dimensions d = <span class="hljs-keyword">new</span> Dimensions();
d.Length = <span class="hljs-number">2</span>m;
d.Width = <span class="hljs-number">1</span>m;

<span class="hljs-comment">// Since C# 3</span>
Dimensions d = <span class="hljs-keyword">new</span> Dimensions()
{
  Length = <span class="hljs-number">2</span>m;
  Width = <span class="hljs-number">1</span>m;
}
</code></pre>
<p>Originally, object initializers weren't able to initialize read only properties. Your object's properties would need a public setter. This feature was later added in C# 9.0 with the <code>init</code> keyword</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Since C# 9</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
}

Dimensions d = <span class="hljs-keyword">new</span> Dimensions()
{
  Length = <span class="hljs-number">2</span>m,
  Width = <span class="hljs-number">1</span>m
}

d.Length = <span class="hljs-number">3</span>m; <span class="hljs-comment">// compile error</span>
</code></pre>
<p>If you use a manual backing field instead of an auto property, the <code>init</code> keyword permits a code block allowing us to enforce constraints here. Unfortunately we are limited to throwing an exception, just as we were using a constructor.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">decimal</span> _length;
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length
  {
    <span class="hljs-keyword">get</span> =&gt; _length;
    <span class="hljs-keyword">init</span>
    {
      <span class="hljs-keyword">if</span> (<span class="hljs-keyword">value</span> &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">"Must have positive length."</span>)
      _length = <span class="hljs-keyword">value</span>;
    }
  }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
}

Dimensions d = <span class="hljs-keyword">new</span> Dimensions()
{
  Length = <span class="hljs-number">0</span>m <span class="hljs-comment">// runtime exception</span>
}
</code></pre>
<p>In the previous example. The initializer didn't include a value for the width property. This would compile just fine, and it wasn't until C# 11 that we finally had a way to require properties as part of object initializers with the <code>required</code> keyword</p>
<pre><code class="lang-csharp"><span class="hljs-comment">// Since C# 11</span>
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> required <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
  <span class="hljs-keyword">public</span> required <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }

  Dimensions d = <span class="hljs-keyword">new</span> Dimensions()
  {
    Length = <span class="hljs-number">2</span>m
  } <span class="hljs-comment">// compile error</span>
}
</code></pre>
<p>Despite all these new language features, object initializers still retain the same issue as constructors and offer, near as I can tell, no tangible benefits. With the <code>required</code> keyword, and <code>init</code> block, object initializers and constructors seem to amount to an aesthetic difference. This is not the case with our last method of instantiation, which has been in the language from the very beginning.</p>
<h2 id="heading-factories">Factories</h2>
<p>Sorry to disappoint the Enterprise™ Developers, I do not mean the <a target="_blank" href="https://en.wikipedia.org/wiki/Abstract_factory_pattern">GoF Abstract Factory</a> pattern. I am referring to a static function which has access to a private constructor for a type. Here is the trivial (useless) example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; }

  <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Dimensions</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> length, <span class="hljs-keyword">decimal</span> width</span>)</span>
  {
    Length = length;
    Width = width;
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Dimensions <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> length, <span class="hljs-keyword">decimal</span> width</span>)</span>
  {
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Dimensions(length, width);
  }
}
</code></pre>
<p>In this case, we've no advantage over a simple constructor or initializer, but our static method can choose it's return type. This enables much more robust error handling for constraint violations. Beyond simply returning null, here is an idiomatic TryParse implementation which allows Roslyn's branch analysis to know when you've got an instance of Dimensions and not null.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Dimensions</span>
{
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Length { <span class="hljs-keyword">get</span>; }
  <span class="hljs-keyword">public</span> <span class="hljs-keyword">decimal</span> Width { <span class="hljs-keyword">get</span>; }

  <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Dimensions</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> length, <span class="hljs-keyword">decimal</span> width</span>)</span>
  {
    Length = length;
    Width = width;
  }

  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">TryParse</span>(<span class="hljs-params">
    <span class="hljs-keyword">decimal</span> Length
    <span class="hljs-keyword">decimal</span> Width
    [NotNullWhen(<span class="hljs-literal">true</span></span>)]
    <span class="hljs-keyword">out</span> Dimensions? dimensions)</span>
  {
    dimensions = <span class="hljs-literal">null</span>;
    <span class="hljs-keyword">if</span> (Length &lt;= <span class="hljs-number">0</span> || Width &lt;= <span class="hljs-number">0</span>) <span class="hljs-keyword">return</span> <span class="hljs-literal">false</span>;

    dimensions = <span class="hljs-keyword">new</span> Dimensions(length, width);
    <span class="hljs-keyword">return</span> <span class="hljs-literal">true</span>;
  }
}
</code></pre>
<p>Because these factories are just functions, they can implement whatever method of error handling you prefer. Here's an example with a passed in error handler.</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Dimensions? Create(
  <span class="hljs-keyword">decimal</span> length,
  <span class="hljs-keyword">decimal</span> width,
  Action&lt;<span class="hljs-keyword">string</span>&gt; error)
{
  <span class="hljs-keyword">bool</span> hasErrors = <span class="hljs-literal">false</span>;

  <span class="hljs-keyword">if</span> (length &lt;= <span class="hljs-number">0</span>)
  {
    error(<span class="hljs-string">"Must have positive length."</span>);
    hasErrors = <span class="hljs-literal">true</span>;
  }

  <span class="hljs-keyword">if</span> (width &lt;= <span class="hljs-number">0</span>)
  {
    error(<span class="hljs-string">"Must have positive width."</span>);
    hasErrors = <span class="hljs-literal">true</span>;
  }

  <span class="hljs-keyword">if</span> (hasErrors) <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;

  <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Dimensions(length, width);
}
</code></pre>
<p>Here's an example using a result type.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Result&lt;Dimensions&gt; <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">decimal</span> length, <span class="hljs-keyword">decimal</span> width</span>)</span>
{
  List&lt;<span class="hljs-keyword">string</span>&gt; errors = <span class="hljs-keyword">new</span>();

  <span class="hljs-keyword">if</span> (length &lt;= <span class="hljs-number">0</span>) errors.Add(<span class="hljs-string">"Must have positive length."</span>);

  <span class="hljs-keyword">if</span> (width &lt;= <span class="hljs-number">0</span>) errors.Add(<span class="hljs-string">"Must have positive width."</span>);

  <span class="hljs-keyword">return</span> errors <span class="hljs-keyword">switch</span>
  {
    [<span class="hljs-meta"></span>] =&gt; <span class="hljs-keyword">new</span> Dimensions(length, width),
    [<span class="hljs-meta">message</span>] =&gt; <span class="hljs-keyword">new</span> Error(message),
    _ =&gt; <span class="hljs-keyword">new</span> AggregateError(errors)
  };
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>As we can see the static factory functions provide us much more control around around error handling, and for this reason I tend to use static factory functions if I have any constraints at all.</p>
]]></content:encoded></item><item><title><![CDATA[No Sacred Cows: I, Interface]]></title><description><![CDATA[The Argument
Why should we prefix the names of interfaces with I in C#? Here is the full answer given from Microsoft's documentation on C# coding standards. To save you the click, I'll post it here.

When naming an interface, use pascal casing in add...]]></description><link>https://blog.samferree.dev/no-sacred-cows-i-interface</link><guid isPermaLink="true">https://blog.samferree.dev/no-sacred-cows-i-interface</guid><category><![CDATA[C#]]></category><category><![CDATA[dotnet]]></category><category><![CDATA[coding]]></category><category><![CDATA[coding conventions]]></category><dc:creator><![CDATA[Sam Ferree]]></dc:creator><pubDate>Wed, 16 Feb 2022 21:22:03 GMT</pubDate><content:encoded><![CDATA[<hr />
<h2 id="heading-the-argument">The Argument</h2>
<p>Why should we prefix the names of interfaces with I in C#? Here is the full answer given from <a target="_blank" href="https://docs.microsoft.com/en-us/dotnet/csharp/fundamentals/coding-style/coding-conventions">Microsoft's documentation on C# coding standards</a>. To save you the click, I'll post it here.</p>
<blockquote>
<p>When naming an <code>interface</code>, use pascal casing in addition to prefixing the name with an <code>I</code>. This clearly indicates to consumers that it's an <code>interface</code>.</p>
</blockquote>
<p>So we need to prefix the name of the type with I so that consumers of the type know that it's an interface. Seems simple and straightforward, but already this rule fails the consistency test. I could not find any suggestions that we preface class names with C and structs with S and records with R in order to indicate these things to consumers.</p>
<p>So the question then is, Why do consumers need to know they are using an interface, and why do consumers not need to know they are using a struct, class, or record?</p>
<h2 id="heading-do-consumers-need-to-know-they-are-using-an-interface">Do Consumers need to know they are using an interface?</h2>
<p>As far as I can tell you will encounter an interface in one of exactly three places:</p>
<ol>
<li><p>You are defining the interface</p>
</li>
<li><p>You are implementing the interface</p>
</li>
<li><p>You are working with a variable that is of an interface type</p>
</li>
</ol>
<p>Let's examine, in each of these three scenarios, how helpful it is to know that you are working with an interface, and how valuable that information is.</p>
<h3 id="heading-defining-an-interface">Defining an interface</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">Entity</span>
{
  <span class="hljs-keyword">string</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
}
</code></pre>
<p>Is it clear when defining this type, that it's an interface? Hopefully the word <code>interface</code> preceding the type name is sufficient to communicate that information to us.</p>
<h3 id="heading-implementing-an-interface">Implementing an interface</h3>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Book</span> : <span class="hljs-title">Entity</span>
{
}
</code></pre>
<p>Is it clear when implementing the Entity type that it is an interface? Not Just by looking at it. In fact, we won't notice anything at all until we've run the compiler. Once we've run the compiler we will be informed that we've failed to correctly implement the interface.</p>
<p>But how soon after we type this code is a compilation or language service run? In many IDEs very shortly. The editors that I'm familiar with will not only alert me that I need to do something, they will provide a macro or tool tip to do it quickly (ctrl+. in visual studio).</p>
<p>In fact, whether or not Entity is an interface, or an abstract base class my process is the same. Wait for the red squiggles to appear and then using the auto-complete features to stub out the abstract members I need to implement.</p>
<p>So in this way, In the case that your editor settings don't provide color indicators for the information, You don't actually need to know whether or not you've implemented an interface or extended an abstract base class. The compiler knows there are things you have to add to your type definition.</p>
<p>"But Wait!" you say, "What about multiple inheritance?"</p>
<p>Ah yes, well any given type in C# can have any number of interfaces, but only one base type. Without the I how will we know which one is the base type and which one is the interface?</p>
<p>The answer is again, the compiler. If you're using a modern editor you will likely know very quickly if you've extended multiple base classes, whether by color coding, or language features running error checking as you type. In this case, I don't need an I in front of my interface name any more than I need an A in front of abstract class names.</p>
<h3 id="heading-working-with-a-variable-of-an-interface-type">Working with a variable of an interface type</h3>
<p>What if you get a variable back from a function, and the type is Entity and you aren't sure whether that type is an interface or a concrete type?</p>
<p><em>Even if</em> you are not using an editor that can quickly communicate that information, I would argue that it makes no difference. You don't care if that type is an interface. You care what that type tells you about what methods are on it, and what methods it can be passed into as a parameter. That information is not only quickly available to you in most modern editors, but it's also impossible to determine any of it by whether or not there is an I at the beginning of it's name.</p>
<h2 id="heading-following-the-convention">Following the convention</h2>
<p>Okay, so maybe it's actually not that helpful, but is there any value in following the convention? There very well could be, but that's not the whole question. The question is: "at what cost?"</p>
<p>If <a target="_blank" href="https://www.google.com/search?q=two+hard+things+in+computer+science">Naming things is hard</a>, Why make it harder? We either end up adding I's to everything or you have long descriptive names using I to describe what an object can do, i.e. <code>ISaveBooks</code></p>
<p>Sometimes it's common to use the I to distinguish <em>The</em> interface from <em>The</em> implementation. These types often come in pairs: <code>IBookRepository</code>, <code>BookRepository</code>. The idea here being that we can code against the interface, not the concrete type. There are many good reasons to do this, and nearly all of them go away if our interface has only one implementation. In such a case, the ceremony is all noise and no signal. The interface defines what the type can do, but the name of the implementation doesn't communicate anything to us. What would be useful to see is a descriptive name of how, such as <code>SqlBookRepository</code>, or <code>InMemoryBookRepository</code>. In this, far more clear, example we no longer need to preface our interface with I. The interface is <code>BookRepository</code> and we have two implementations, one that reads and writes books from a SQL database, and one that keeps them in memory. For this problem, I much more likely to do something like this:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">BookWriter</span>
{
  <span class="hljs-function">Task <span class="hljs-title">Save</span>(<span class="hljs-params">Book book</span>)
}

<span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> BookReader</span>
{
  <span class="hljs-function">Task&lt;Book&gt; <span class="hljs-title">Load</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> bookId</span>)
}

<span class="hljs-keyword">public</span> class SqlBookRepository : BookWriter, BookReader</span> { ... }
<span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">InMemoryBookRepository</span> : <span class="hljs-title">BookWriter</span>, <span class="hljs-title">BookReader</span> { ... }
</code></pre>
<p>Aside from the clarity, I no longer need to force a service which only reads books to be bound to the functionality around saving them. If I have any other functionality I might want to insert using decorators, like publishing an event every time a book is created or updated, I can do so without needing to write an empty pass through on the read part of the repository.</p>
<p>For me, I've not found any argument to prefix my interface names with I any more compelling than the idea that I should prefix my class names with C. It's an old convention, a relic of Hungarian notation, something which even other parts of the recommended C# coding conventions have gone away from.</p>
]]></content:encoded></item></channel></rss>