<?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[Bastien Foucher]]></title><description><![CDATA[Bastien Foucher]]></description><link>https://www.bastienfoucher.net</link><image><url>https://cdn.hashnode.com/res/hashnode/image/upload/v1683814142427/urcwQVf_1.png</url><title>Bastien Foucher</title><link>https://www.bastienfoucher.net</link></image><generator>RSS for Node</generator><lastBuildDate>Tue, 07 Apr 2026 20:47:52 GMT</lastBuildDate><atom:link href="https://www.bastienfoucher.net/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing APIs requirements: the best of API goal canvas and DDD Event Storming]]></title><description><![CDATA[Today I would like to talk from an elevated perspective about a topic I enjoy: APIs. Because when well-designed, they help us produce highly sustainable software. But this is not an easy task...
The API goal canvas
The API goal canvas is an API model...]]></description><link>https://www.bastienfoucher.net/writing-apis-requirements-the-best-of-api-goal-canvas-and-ddd-event-storming</link><guid isPermaLink="true">https://www.bastienfoucher.net/writing-apis-requirements-the-best-of-api-goal-canvas-and-ddd-event-storming</guid><category><![CDATA[DDD]]></category><category><![CDATA[APIs]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Thu, 25 May 2023 12:55:37 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1685017628753/0e13b0ad-9f84-41dc-92c9-6cc83ae1c756.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>Today I would like to talk from an elevated perspective about a topic I enjoy: APIs. Because when well-designed, they help us produce highly sustainable software. But this is not an easy task...</p>
<h1 id="heading-the-api-goal-canvas">The API goal canvas</h1>
<p>The API goal canvas is an API modeling tool suggested by <a target="_blank" href="https://apihandyman.io">Arnaud Lauret</a> in his excellent book <a target="_blank" href="https://www.manning.com/books/the-design-of-web-apis">"Designing Web API" at Manning</a>. It is very simple and efficient: it involves filling in a table that lists the APIs to be executed for a user to reach his goal (eg: "Place an order").</p>
<p>To create an API goal canvas, you can provide the following information:</p>
<ul>
<li><p>The "what": what does the user want to do?</p>
</li>
<li><p>The "who": who has access to the resource?</p>
</li>
<li><p>The "how": what are the necessary API steps to achieve the user's goal?</p>
</li>
<li><p>API inputs and outputs.</p>
</li>
<li><p>The goal of the API.</p>
</li>
</ul>
<p>Other columns can be added as needed:</p>
<ul>
<li><p>The category: purchase, administration, ...</p>
</li>
<li><p>The scope to manage permissions, for example buy:create, admin:manage_products...</p>
</li>
<li><p>The endpoint path.</p>
</li>
<li><p>...</p>
</li>
</ul>
<p>Here is what it could looks like for an online store:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681740111554/c7dac1de-7e60-4bc4-9dca-867b1acff140.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-the-problem">The problem</h1>
<p>The API goal canvas is a very simple and efficient tool, domain experts can quickly adopt it. However, it has some drawbacks:</p>
<ul>
<li><p><strong>The level of detail is important</strong>. This can be problematic in large domains: how to forget as few APIs as possible?</p>
</li>
<li><p>In a microservices architecture, systems need to communicate. <strong>But when? What messages to send to other systems?</strong></p>
</li>
</ul>
<p>To answer these questions, <a target="_blank" href="https://en.wikipedia.org/wiki/Event_storming">DDD's Event Storming</a> is of great help.</p>
<h1 id="heading-event-storming-to-the-rescue">Event storming to the rescue</h1>
<h2 id="heading-principle">Principle</h2>
<p>Event storming is a method for discovering and modeling a business domain. It is a question of being interested in first place in the events which occur in this domain. This makes the work efficient: events are facts that happened and they are non-debatable.</p>
<p><strong>The principle is as follows:</strong></p>
<ol>
<li><p>Get post-its (it can be a lot!).</p>
</li>
<li><p>Invite the different profiles of your team: developers, business experts, testers...</p>
</li>
<li><p>Ask everyone to write on a post-it an event that happened in the domain. For example: "An order has been paid.". The participants must be at ease: there is no harm in imagining an event that does not exist in reality. The audience is here to learn from each other.</p>
</li>
<li><p>Organize and sort the events in chronological order.</p>
</li>
<li><p>For each event, ask participants which command (which process) is at its origin. Other information can be added on other color post-its such as <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-5-entities-and-aggregates">aggregates</a>.</p>
</li>
</ol>
<p>Here is what it could look like for our online store:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681738783936/4b66bcc0-01e8-4870-873b-3345570c5135.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-domain-events-as-api-goal-canvas-milestones">Domain Events as API goal canvas milestones</h2>
<p>We can use domain events in the API goal canvas as the milestones of our API journey. This allows a classic problem-solving approach: thoughts must begin by identifying the objectives to be achieved.</p>
<h2 id="heading-step-1-focus-on-the-essentials">Step 1: focus on the essentials</h2>
<p>In the previous example, the "Validate cart" API is missing in our first canvas because we dove too much into the details.</p>
<p>So we need to focus on the essentials first:</p>
<ul>
<li><p>Let's remove the input and output columns. These are implementation details.</p>
</li>
<li><p>Add the events and their associated command.</p>
</li>
<li><p>Add all the actions that lead to the event.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681740047357/42b14f37-2399-439e-94b4-62b1a3a0a9ab.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-step-2-complete-the-api-canvas">Step 2: complete the API canvas</h2>
<p>Now it's about identifying all APIs and their implementation details (input, outputs, scopes, ...) that lead to a consistent API journey. Pay attention to the input and output data to ensure that it will be possible to chain API calls.</p>
<p>Below is an example of a completed API goal canvas:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681740562115/f142914d-a513-4bde-bb1f-227652f7276f.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-domain-events-are-of-great-interest">Domain events are of great interest</h1>
<p>Domain events serve as milestones during the APIs requirement analysis. They also play a vital role in microservices architectures:</p>
<ol>
<li><p>They make it possible to establish clear audit trails.</p>
</li>
<li><p>They allow microservices to communicate asynchronously</p>
</li>
<li><p>They allow caches to update. I will talk about that in further articles.</p>
</li>
</ol>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1681740761473/54c12563-3c74-4b98-b36e-b76fd33c1de5.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-in-summary">In summary</h1>
<p>To effectively identify the APIs to be implemented within a business domain and make them useful in your system, adopt an "Event first" (or "Message first") approach:</p>
<ol>
<li><p>Organize a DDD Event storming.</p>
</li>
<li><p>Use the results of this work to create the milestones of your API goal canvas.</p>
</li>
<li><p>Complete your API goal canvas by identifying the APIs needed to reach these milestones.</p>
</li>
<li><p>Finally, add all implementation details you need (input, output, scopes, goal, ...) for your APIs into your goal canvas.</p>
</li>
</ol>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>Messier 78. This well-known reflection nebula is found in the Orion constellation, just above Horsehead nebula. It asks very clear skies to be photographed.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/nebulae-natural-colors/m78">View it in large size on my website</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Faster integration tests with ASP.Net Core Test Server?]]></title><description><![CDATA[Introduction
I have been working recently on integration tests, an important topic for building sustainable software. I then discovered ASP.Net Core's TestServer to perform fast integration testing. But is it really faster than a classic ASP.Net Core...]]></description><link>https://www.bastienfoucher.net/faster-integration-tests-with-aspnet-core-test-server</link><guid isPermaLink="true">https://www.bastienfoucher.net/faster-integration-tests-with-aspnet-core-test-server</guid><category><![CDATA[C#]]></category><category><![CDATA[asp.net core]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Tue, 18 Apr 2023 16:02:28 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1681809164523/e0c2d5c2-29bb-4676-b928-2ad5e0e8f6f9.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>I have been working recently on integration tests, an important topic for building sustainable software. I then discovered <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/api/microsoft.aspnetcore.testhost.testserver?view=aspnetcore-7.0">ASP.Net Core's TestServer</a> to perform fast integration testing. But is it really faster than a classic ASP.Net Core server? Let's see that.</p>
<h1 id="heading-the-test-project">The test project</h1>
<p>The project we are going to work on is a simple online sales website. It contains some microservices, all written using a <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-2-functional-architecture">functional architecture</a>. We will focus on the Shopping Cart microservice. It contains an endpoint to add a product to a cart: we will use it to perform some benchmarking.</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">HttpPost</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ActionResult&gt; <span class="hljs-title">AddProductToCart</span>(<span class="hljs-params">[FromBody] AddProductToCartDto addProductToCartDto</span>)</span>
{
    <span class="hljs-comment">/*...*/</span>
}
</code></pre>
<h1 id="heading-aspnet-core-testserver">ASP.Net Core TestServer</h1>
<p>ASP.Net Core TestServer is a web server you can find in <a target="_blank" href="https://www.nuget.org/packages/Microsoft.AspNetCore.TestHost">ASPNetCore.TestHost</a> package. It makes the handling of HTTP requests fast because they don't go through a normal network stack.</p>
<h1 id="heading-benchmarkdotnet">BenchmarkDotNet</h1>
<p>We will use <a target="_blank" href="https://github.com/dotnet/BenchmarkDotNet">BenchmarkDotNet</a> to compare the performance between the two approaches. It is a small and extremely well-made library to carry out performance measurements. The purpose of this article is not to show how it works, for that you need to refer to its documentation.</p>
<h1 id="heading-the-benchmark-classes">The benchmark classes</h1>
<h2 id="heading-serverbasecs">ServerBase.cs</h2>
<p>To make a fair comparison, the context must be the same between the two servers. So we will pool as much code as possible between the two approaches, i.e.:</p>
<ul>
<li><p>Creation of an in-memory SQLite database.</p>
</li>
<li><p>Initialization of the test data.</p>
</li>
<li><p>Initialization of DI services.</p>
</li>
<li><p>Initialization of the web server.</p>
</li>
</ul>
<p>These initializations are done in the constructor of an abstract <code>ServerBase.cs</code> class:</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">ServerBase</span>
{
    <span class="hljs-keyword">protected</span> WebApplicationBuilder WebAppBuilder { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">protected</span> WebApplication WebApp { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">protected</span> CallistoDbContext DbContext { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">protected</span> SqliteConnection Connection { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">protected</span> HttpClient? Sut { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> _baseUrl;

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-title">ServerBase</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> baseUrl</span>)</span>
    {
        WebAppBuilder = WebApplication.CreateBuilder();
        WebAppBuilder.Services.AddControllers().PartManager.ApplicationParts.Add(<span class="hljs-keyword">new</span> AssemblyPart(<span class="hljs-keyword">typeof</span>(CartController).Assembly)); <span class="hljs-comment">// Necessary to add controllers from other projects</span>

        Connection = <span class="hljs-keyword">new</span> SqliteConnection(<span class="hljs-string">"DataSource=file::memory:"</span>); <span class="hljs-comment">// We will use an in-memory Database</span>
        Connection.Open();

        <span class="hljs-comment">// Database Initialization</span>
        <span class="hljs-keyword">var</span> options = <span class="hljs-keyword">new</span> DbContextOptionsBuilder&lt;CallistoDbContext&gt;().UseSqlite(Connection);
        DbContext = <span class="hljs-keyword">new</span> CallistoDbContext(options.Options);
        DbContext.Database.Migrate();
        DbContext.Product.Add(<span class="hljs-keyword">new</span> ProductModel(<span class="hljs-string">"2EJX-6HCC"</span>, <span class="hljs-string">"PS5"</span>, <span class="hljs-string">"Playstation 5"</span>, <span class="hljs-number">500</span>, DateTime.UtcNow));
        DbContext.SaveChanges();

        <span class="hljs-comment">// Services configuration</span>
        WebAppBuilder.Services.AddSingleton&lt;CallistoDbContext&gt;(_ =&gt; DbContext);
        WebAppBuilder.Services.AddTransient&lt;ICartRepository, CartRepository&gt;();
        WebAppBuilder.Services.AddTransient&lt;IProductRepository, ProductRepository&gt;();

        WebAppBuilder.WebHost.UseUrls(baseUrl);
        _baseUrl = baseUrl;
    }
}
</code></pre>
<p>Finally, we will add a test method to call the endpoint for adding a product to a cart. The first call adds a product to a new cart (because no <code>CartId</code> is given), then we add 10 times the same product in this cart:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RunTest</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">var</span> addProductToCart = <span class="hljs-keyword">new</span>
    {
        CartId = <span class="hljs-string">""</span>,
        ProductId = <span class="hljs-string">"2EJX-6HCC"</span>,
        Quantity = <span class="hljs-number">1</span>
    };

    <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> Sut!.PostUtf8Async(<span class="hljs-string">$"<span class="hljs-subst">{_baseUrl}</span>/carts"</span>, addProductToCart);
    <span class="hljs-keyword">var</span> cartId = (<span class="hljs-keyword">await</span> response!.Content.ReadFromJsonAsync&lt;List&lt;Read.Entities.Cart&gt;&gt;())!.ElementAt(<span class="hljs-number">0</span>).CartId;


    <span class="hljs-comment">// Adding 10 times the same product in the cart</span>
    <span class="hljs-keyword">for</span> (<span class="hljs-keyword">int</span> i = <span class="hljs-number">0</span>; i &lt; <span class="hljs-number">10</span>; i++)
    {
        addProductToCart = <span class="hljs-keyword">new</span>
        {
            CartId = cartId,
            ProductId = <span class="hljs-string">"2EJX-6HCC"</span>,
            Quantity = <span class="hljs-number">1</span>
        };
        <span class="hljs-keyword">await</span> Sut.PostUtf8Async(<span class="hljs-string">$"<span class="hljs-subst">{_baseUrl}</span>/carts"</span>, addProductToCart);
    }
}
</code></pre>
<h2 id="heading-classicservercs">ClassicServer.cs</h2>
<p>This class contains initializations specific to the test with the classic server. It inherits from <code>ServerBase.cs</code>:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Builder;
<span class="hljs-keyword">using</span> Microsoft.Extensions.DependencyInjection;
<span class="hljs-keyword">using</span> Microsoft.Extensions.Hosting;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Callisto.Sales.Benchmark</span>
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ClassicServer</span> : <span class="hljs-title">ServerBase</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ClassicServer</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> baseUrl</span>) : <span class="hljs-title">base</span>(<span class="hljs-params">baseUrl</span>)</span>
        {
            WebAppBuilder.Services.AddHttpClient();
            <span class="hljs-keyword">var</span> serviceProvider = WebAppBuilder.Services.BuildServiceProvider();
            Sut = serviceProvider.GetService&lt;HttpClient&gt;()!;

            WebApp = WebAppBuilder.Build();
            WebApp.MapControllers();
            WebApp.Start();
        }
    }
}
</code></pre>
<h2 id="heading-testservercs">TestServer.cs</h2>
<p>This class contains initializations specific to testing with the ASP.Net Core TestServer; it also inherits from the ServerBase.cs class:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> Microsoft.AspNetCore.Builder;
<span class="hljs-keyword">using</span> Microsoft.AspNetCore.TestHost;
<span class="hljs-keyword">using</span> Microsoft.Extensions.Hosting;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Callisto.Sales.Benchmark</span> 
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TestServer</span> : <span class="hljs-title">ServerBase</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">TestServer</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> baseUrl</span>) : <span class="hljs-title">base</span>(<span class="hljs-params">baseUrl</span>)</span>
        {
            WebAppBuilder.WebHost.UseTestServer(); <span class="hljs-comment">// Using TestServer</span>

            WebApp = WebAppBuilder.Build();
            WebApp.MapControllers();
            WebApp.Start();

            Sut = WebApp.GetTestClient(); <span class="hljs-comment">// Getting an HttpClient directly from the app.</span>
        }
    }
}
</code></pre>
<h1 id="heading-the-benchmark-class">The benchmark class</h1>
<p>The benchmark class is as follows:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> BenchmarkDotNet.Attributes;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Callisto.Sales.Benchmark</span>
{
    [<span class="hljs-meta">SimpleJob(launchCount: 5, warmupCount: 2, iterationCount: 10)</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">ClassicServerVSTestServerBenchmark</span>
    {
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> ClassicServer _classicServer;
        <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> TestServer _testServer;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ClassicServerVSTestServerBenchmark</span>(<span class="hljs-params"></span>)</span>
        {
            _classicServer = <span class="hljs-keyword">new</span> ClassicServer(<span class="hljs-string">"http://localhost:5000"</span>);
            _testServer = <span class="hljs-keyword">new</span> TestServer(<span class="hljs-string">"http://localhost:5001"</span>);
        }

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Classic_Server_Benchmark</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">await</span> _classicServer.RunTest();
        }

        [<span class="hljs-meta">Benchmark</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Test_Server_Benchmark</span>(<span class="hljs-params"></span>)</span>
        {
            <span class="hljs-keyword">await</span> _testServer.RunTest();
        }
    }
}
</code></pre>
<p>And finally, to run the benchmark, we create a simple console project:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">using</span> BenchmarkDotNet.Configs;
<span class="hljs-keyword">using</span> BenchmarkDotNet.Running;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">Callisto.Sales.Benchmark</span>
{
    <span class="hljs-keyword">internal</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            BenchmarkRunner.Run&lt;ClassicServerVSTestServerBenchmark&gt;();
        }
    }
}
</code></pre>
<h1 id="heading-first-results">First results</h1>
<p>Now, let's run the benchmark:</p>
<pre><code class="lang-powershell">dotnet run <span class="hljs-literal">-c</span> Release
</code></pre>
<p>After a few minutes, I get these results:</p>
<pre><code class="lang-powershell">|                      Method |         Mean |        Error |       StdDev |
|---------------------------- |-------------:|-------------:|-------------:|
|    Classic_Server_Benchmark | <span class="hljs-number">455</span>,<span class="hljs-number">511.2</span> us | <span class="hljs-number">24</span>,<span class="hljs-number">192.14</span> us | <span class="hljs-number">48</span>,<span class="hljs-number">314.32</span> us |
|       Test_Server_Benchmark | <span class="hljs-number">454</span>,<span class="hljs-number">201.1</span> us |  <span class="hljs-number">7</span>,<span class="hljs-number">812.13</span> us | <span class="hljs-number">15</span>,<span class="hljs-number">780.88</span> us |
</code></pre>
<p>Intermediate conclusion: the gain with the test server is not obvious (~1.5 ms/test). I was a bit disappointed... So I wondered what the result would be without database interaction, only focusing on the network part. Let's see that.</p>
<h1 id="heading-a-benchmark-without-database-interaction">A benchmark without database interaction</h1>
<p>In the Shopping Cart microservice, I added a stub endpoint that does strictly nothing.</p>
<p>Then, in <code>ServerBase.cs</code>, I added a test for this endpoint :</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">RunTestWithoutDatabaseInteraction</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">await</span> Sut.GetAsync(<span class="hljs-string">$"<span class="hljs-subst">{_baseUrl}</span>/carts/stub"</span>);
}
</code></pre>
<p>I then added the following two new benchmarks in <code>ClassicServerVSTestServerBenchmark.cs</code> :</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">Benchmark</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Classic_Server_Without_Database_Interaction_Benchmark</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">await</span> _classicServer.RunTestWithoutDatabaseInteraction();
}

[<span class="hljs-meta">Benchmark</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task <span class="hljs-title">Test_Server_Without_Database_Interaction_Benchmark</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">await</span> _testServer.RunTestWithoutDatabaseInteraction();
}
</code></pre>
<p>Here are the results :</p>
<pre><code class="lang-powershell">|                                                Method |         Mean |        Error |       StdDev |
|------------------------------------------------------ |-------------:|-------------:|-------------:|
| Classic_Server_Without_Database_Interaction_Benchmark |   <span class="hljs-number">2</span>,<span class="hljs-number">137.9</span> us |     <span class="hljs-number">32.98</span> us |     <span class="hljs-number">61.94</span> us |
|    Test_Server_Without_Database_Interaction_Benchmark |     <span class="hljs-number">177.6</span> us |      <span class="hljs-number">6.99</span> us |     <span class="hljs-number">13.48</span> us |
</code></pre>
<p>This time, the gain brought by the TestServer is clear: the calls to an endpoint are 12x faster! We gain ~2 ms per endpoint call, which is consistent with the results from the previous benchmark.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>ASP.Net Core's TestServer only saves time on network calls by a few milliseconds. Perhaps the gains could be significant on a broad base of integration tests.</p>
<p>In any case, your database will remain the bottleneck for integration testing.</p>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>The Source of the Universe. In the desert of Atacama in Chile, the Milky Way seems to spring from a small and perfectly calm water hole...</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/milky-way/voieLacteeSourceUnivers">View it in large size on my website</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 6: the application layer]]></title><description><![CDATA[Introduction
Last article of the series: the application layer. We will talk about its role, how to write it in a functional style with just a few lines of code but also how to deal with asynchronism. For that, we will use all the concepts we have le...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-6-the-application-layer</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-6-the-application-layer</guid><category><![CDATA[C#]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Sat, 01 Apr 2023 17:26:18 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680787830168/3a1edb74-80c9-41b6-9c32-5b50d7c34fdf.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Last article of the series: the application layer. We will talk about its role, how to write it in a functional style with just a few lines of code but also how to deal with asynchronism. For that, we will use all the concepts we have learned so far. Let's dive in and let's create sustainable software.</p>
<h1 id="heading-a-refresher-on-the-functional-architecture">A refresher on the functional architecture</h1>
<p>Functional architecture is a rigorous clean or onion architecture. Its domain and application layers are written by applying the principles of functional programming: immutability, function composition, etc.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680369363383/c8e3127c-688f-43ea-8860-48eb5320bc7a.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-a-functional-application-layer">A functional application layer</h1>
<p><a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-2-functional-architecture">Remember</a>, the application layer is an orchestrator between the infrastructure layer and the domain layer: the domain layer make the decisions and the infrastructure layer executes the necessary side effects (saving to a database, posting a message in a bus, ....) thanks to the application layer.</p>
<p>Let's take an example: adding a product to a catalog. The application layer will be responsible to perform the following steps:</p>
<ol>
<li><p>Transform a <code>ProductDto</code> into a domain <code>Product</code>.</p>
</li>
<li><p>Check if the product reference already exists.</p>
</li>
<li><p>Save the product to the database.</p>
</li>
</ol>
<p>We want these steps to be written in a functional style by creating a pipeline<strong>.</strong> We will use for that techniques we've learned so far: containers, <code>Bind()</code> and <code>Map()</code> functions.</p>
<h1 id="heading-creating-the-pipeline">Creating the pipeline</h1>
<h2 id="heading-creating-the-addproduct-function">Creating the AddProduct() function</h2>
<p>Let's create this function. We will complete it all along this article. It will look like this :</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> OperationResultDto&lt;ProductDto&gt; <span class="hljs-title">AddProduct</span>(<span class="hljs-params">
    AddProductDto addProductDto</span>)</span>
{
}
</code></pre>
<p>I have defined an <code>OperationResult&lt;T&gt;</code>: it will contain a value if no error happened during the operation, else it will contain an error.</p>
<h2 id="heading-railway-oriented-programming">Railway-oriented programming</h2>
<p>A word about railway-oriented programming first. As soon as something wrong happens in the flow, then it is switched towards an error path: the execution flow of the pipeline is interrupted and the error messages are returned.</p>
<p>In our pipeline, the execution flow will be automatically routed to the error path whenever an entity is in an invalid state, thanks to <code>Map()</code> and <code>Bind()</code> functions defined on the entities.</p>
<p>Here is a little drawing to help you understand. This programming style is extremely well explained by Scott Wlaschin <a target="_blank" href="https://fsharpforfunandprofit.com/rop/">here</a>.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1680368879253/269a1774-d70a-41b7-9678-a3a2996003e1.png" alt class="image--center mx-auto" /></p>
<h2 id="heading-identifying-the-signatures-of-the-pipeline-functions">Identifying the signatures of the pipeline functions</h2>
<p>First step to write our pipeline: identifying the signatures of the functions that we will use for each step.</p>
<p>To easily create our pipeline, we will use an <code>Entity&lt;Product&gt;</code> as we've learned in the previous articles.</p>
<p>Its steps will be as follows:</p>
<ol>
<li><p>We need to transform a <code>ProductDto</code> into a domain <code>Product</code>. The signature of this function will be <code>ProductDto -&gt; Entity&lt;Product&gt;</code>.</p>
</li>
<li><p>Next, we need to check if the product reference already exists. For that, we will create a function that takes a domain <code>Product</code> and a count of identical references as parameters. It will return an <code>Entity&lt;Product&gt;</code> in a valid state if no other references have been found in the database, else it will be in an invalid state. So the function's signature will be <code>Product -&gt; int -&gt; Entity&lt;Product&gt;</code>.</p>
</li>
<li><p>Next, we need to save the product. The saving will be done by a repository. It will take a domain <code>Product</code> as a parameter and will return the saved domain product as a response. The signature of such a function is <code>Product -&gt; Product</code>.</p>
</li>
</ol>
<p>Nevertheless, we have a problem to create our pipeline because the function's outputs are all different, thus preventing us to chain them using a fluent style. That is where <code>Bind()</code> and <code>Map()</code> functions will come into play.</p>
<h2 id="heading-first-step-converting-a-productdto-to-entityandltproductandgt">First step: converting a ProductDto to Entity&lt;Product&gt;</h2>
<p>This first step is an easy one. We need transform a <code>ProductDto</code> into an <code>Entity&lt;Product&gt;</code>.</p>
<p>To do that, we simply define an extension method on the <code>ProductDto</code> class. I already have defined <code>Reference</code>, <code>Name</code> and <code>Price</code> Value Objects as explained in the <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-4-value-objects">4th article</a> of this series. I then create the Product Entity using the guidelines of the <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-5-entities-and-aggregates">previous article</a> of this series.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">AddProductDtoExtensions</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Product&gt; <span class="hljs-title">ToProductEntity</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> AddProductDto addProductDto</span>)</span>
    {
        <span class="hljs-keyword">return</span> Product.CreateEmpty()
                        .WithReference(addProductDto.Reference)
                        .WithName(addProductDto.Name)
                        .WithPrice(addProductDto.Price);
    }
}
</code></pre>
<p>If a value of the <code>ProductDto</code> is not or incorrectly filled in, then the value objects will return an error when they are instantiated: they act as control gates and a big advantage of that is that we don't need to provide any model validation in the Dtos thus avoiding code duplication between the domain layer and the infrastructure layer. The entity will then be created in an invalid state and all subsequent steps in the flow will be skipped.</p>
<p>Now let's complete <code>AddProduct()</code> function and let's call our new extension method to convert our <code>AddProductDto</code> into an <code>Entity&lt;Product&gt;</code>:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> OperationResultDto&lt;ProductDto&gt; <span class="hljs-title">AddProduct</span>(<span class="hljs-params">
    AddProductDto addProductDto</span>)</span>
{
    <span class="hljs-keyword">var</span> p = addProductDto.ToProductEntity();

    <span class="hljs-keyword">return</span> p.Match(
        Valid: (v) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(v.ToProductDto()),
        Invalid: (e) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(e)
    );
}
</code></pre>
<h2 id="heading-second-step-verifying-if-the-product-reference-exists">Second step: verifying if the product reference exists</h2>
<p>Let's create our verification function. It is a decision-making function, so you need to put in the domain layer. It returns an invalid <code>Entity&lt;Product&gt;</code> if the reference already exists:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Product&gt; <span class="hljs-title">VerifyProductReference</span>(<span class="hljs-params">Product product, <span class="hljs-keyword">int</span> existingReferencesCount</span>)</span>
{
    <span class="hljs-keyword">if</span> (existingReferencesCount &gt; <span class="hljs-number">0</span>)
        <span class="hljs-keyword">return</span> Entity&lt;Product&gt;.Invalid(<span class="hljs-keyword">new</span> Error(<span class="hljs-keyword">string</span>.Format(Messages.TheProductReferenceAlreadyExists, product.Reference.Value)));
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> Entity&lt;Product&gt;.Valid(product);
}
</code></pre>
<p>In Grenat.Functional.DDD library, I added some implicit conversions to simplify writing. The following code is equivalent and shorter:</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Product&gt; <span class="hljs-title">VerifyProductReference</span>(<span class="hljs-params">Product product, <span class="hljs-keyword">int</span> existingReferencesCount</span>)</span>
{
    <span class="hljs-keyword">if</span> (existingReferencesCount &gt; <span class="hljs-number">0</span>)
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-keyword">string</span>.Format(Messages.TheProductReferenceAlreadyExists, product.Reference.Value)); <span class="hljs-comment">// No need do call Entity&lt;Product&gt;.Invalid()</span>
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> product;
}
</code></pre>
<p>But how does this function chain to the result of the previous step? The previous function outputs an <code>Entity&lt;Product&gt;</code>, and we need a <code>Product</code>. Well, we will use the <code>Bind()</code> function. <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world">Remember</a>, <code>Bind()</code> takes a function and it applies it to the wrapped value of the <code>Entity&lt;T&gt;</code> container.</p>
<p>Using <code>Bind()</code>, we can add simply add this new step to our <code>AddProduct()</code> function:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> OperationResultDto&lt;ProductDto&gt; <span class="hljs-title">AddProduct</span>(<span class="hljs-params">
    AddProductDto addProductDto,
    Func&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">int</span>&gt; CountProductReferences</span>)</span>
{
    <span class="hljs-keyword">var</span> p = addProductDto.ToProductEntity()
            .Bind(VerifyProductReference, CountProductReferences(addProductDto.Reference));

    <span class="hljs-keyword">return</span> p.Match(
        Valid: (v) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(v.ToProductDto()),
        Invalid: (e) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(e)
    );
}
</code></pre>
<h2 id="heading-third-step-saving-the-product">Third step: saving the product</h2>
<p>I did not want to introduce an <code>Entity&lt;Product&gt;</code> container in the repository for that. It would have been useless to deal with an entity's state in the repository. The decision to save the product was already made by the domain layer, so the repository just have to execute. It does not need to verify the decision.</p>
<p>So the save function signature will be <code>Product -&gt; Product</code>. Here again how to chain it to the function of the previous step? We need a <code>Product</code> whereas the previous step outputs an <code>Entity&lt;Product&gt;</code>. What's more, we need to get back an <code>Entity&lt;Product&gt;</code> to stay in the <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world">elevated world</a>.</p>
<p>In that situation, <code>Map()</code> becomes handy. It is the same as <code>Bind()</code>, i.e. it takes a function and its parameters and it applies it to the wrapped value of the <code>Entity&lt;T&gt;</code> container.</p>
<p>But <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world#heading-what-about-map">instead</a>, it lifts the function's output to the elevated world: <code>Entity&lt;Product&gt;</code>, allowing us to stick to the elevated world.</p>
<p>So let's update the <code>AddProduct()</code> function by adding this last step. I will not give the details of the <code>SaveProduct()</code> function, it is a classical repository function.</p>
<pre><code class="lang-csharp"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> OperationResultDto&lt;ProductDto&gt; <span class="hljs-title">AddProduct</span>(<span class="hljs-params">
    AddProductDto addProductDto,
    Func&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">int</span>&gt; CountProductReferences
    Func&lt;Product, Product&gt; SaveProduct</span>)</span>
{
    <span class="hljs-keyword">var</span> p = addProductDto.ToProductEntity()
            .Bind(Domain.Services.VerifyProductReference, CountProductReferences(addProductDto.Reference))
            .Map(SaveProduct);

    <span class="hljs-keyword">return</span> p.Match(
        Valid: (v) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(v.ToProductDto()),
        Invalid: (e) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(e)
    );
}
</code></pre>
<p>Look how simple and clear is this code. Thanks to functional concepts, it deals with <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-5-entities-and-aggregates#heading-error-harvesting">error harvesting</a> and error management without having to write any conditional logic. If another step needs to be added to the flow, well... just insert it into the pipeline using <code>Map()</code>, <code>Bind()</code> and <code>Entity&lt;Product&gt;</code>. Forget about errors, say goodbye to many bugs :)</p>
<h1 id="heading-dealing-with-asynchrony">Dealing with asynchrony</h1>
<p>All functions working with infrastructure resources must be asynchronous. Therefore, they must work with <code>Tasks</code>. But in C#, the syntax for representing functions returning Tasks is quite cumbersome… <code>Func&lt;Task&lt;T&gt;&gt;, Func&lt;T, Task&lt;R&gt;&gt;</code> …</p>
<p>To make our life easier, I added an <code>AsyncFunc</code> delegate to simplify this writing in <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">Grenat.Functional.DDD</a>:</p>
<ul>
<li><p><code>Func&lt;Task&lt;T&gt;&gt;</code> is equivalent to <code>AsyncFunc&lt;T&gt;</code>.</p>
</li>
<li><p><code>Func&lt;T, Task&lt;R&gt;&gt;</code> is equivalent to <code>AsyncFunc&lt;T, R&gt;</code>.</p>
</li>
<li><p>Etc., etc…</p>
</li>
</ul>
<p>I also added asynchronous versions of <code>Map()</code> and <code>Bind()</code> : <code>MapAsync()</code> and <code>BindAsync()</code>. So, an asynchronous version of <code>AddProduct()</code> will be as follows:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;OperationResultDto&lt;ProductDto&gt;&gt; AddProduct(
    AddProductDto addProductDto,
    AsyncFunc&lt;<span class="hljs-keyword">string</span>, <span class="hljs-keyword">int</span>&gt; CountProductReferences,
    AsyncFunc&lt;Product, Product&gt; SaveProduct)
{
    <span class="hljs-keyword">var</span> p = <span class="hljs-keyword">await</span> addProductDto.ToProductEntity()
                    .BindAsync(VerifyProductReference, CountProductReferences(addProductDto.Reference))
                    .MapAsync(SaveProduct);

    <span class="hljs-keyword">return</span> p.Match(
        Valid: (v) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(v.ToProductDto()),
        Invalid: (e) =&gt; <span class="hljs-keyword">new</span> OperationResultDto&lt;ProductDto&gt;(e)
    );
}
</code></pre>
<h1 id="heading-improving-performance-with-lazy-evaluation">Improving performance with lazy evaluation</h1>
<p>We have a performance problem with the previous code. It comes from this line of code:</p>
<pre><code class="lang-csharp">.BindAsync(VerifyProductReference, CountProductReferences(addProductDto.Reference))
</code></pre>
<p>Here, the function <code>CountProductReferences()</code> is called even if <code>Entity&lt;Product&gt;</code> is in an invalid state because it is given as a parameter.</p>
<p>To correct this problem, you should give a function as a parameter. An overload of <code>BindAsync()</code> exists for that in my library: it will call the given function only if <code>Entity&lt;T&gt;</code> is valid. This behavior is called lazy evaluation.</p>
<p>The correct statement is as follows:</p>
<pre><code class="lang-csharp">.BindAsync(VerifyProductReference, () =&gt; CountProductReferences(addProductDto.Reference))
</code></pre>
<h1 id="heading-calling-addproduct-from-an-aspnet-core-controller">Calling AddProduct from an ASP.Net Core controller</h1>
<p>Finally, the code to call the application layers' <code>AddProduct()</code> function from an ASP.Net Core controller could look like this:</p>
<pre><code class="lang-csharp">[<span class="hljs-meta">HttpPost</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">async</span> Task&lt;ActionResult&gt; <span class="hljs-title">AddProduct</span>(<span class="hljs-params">AddProductDto addProductDto</span>)</span>
{
    <span class="hljs-keyword">var</span> response = <span class="hljs-keyword">await</span> CatalogOperations.AddProduct(
                                addProductDto,
_productRepository.CountExistingProductReferences,
                                _productRepository.AddProduct);
    <span class="hljs-keyword">if</span> (response.Success)
        <span class="hljs-keyword">return</span> Ok(response.Data);
    <span class="hljs-keyword">else</span>
        <span class="hljs-keyword">return</span> UnprocessableEntity(response.Errors);
}
</code></pre>
<p>As you can see, I pass <strong>functions</strong> as parameters instead of passing <strong>interfaces</strong> to <code>AddProduct()</code>. This functional approach makes the application much easier to test.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>Use functional techniques to write a very thin application layer: railway-oriented programming, containers (<code>Entity&lt;T&gt;</code>, <code>ValueObject&lt;T&gt;</code>, ...) and their underlying operations: <code>Map()</code>, <code>Bind()</code>.</p>
</li>
<li><p>Use my library <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">Grenat.Functional.DDD</a> to help you with that.</p>
</li>
<li><p>Don't forget to use asynchrony for better performance when handling out-of-process resources (databases, message bus, ....).</p>
</li>
<li><p>Think of lazy evaluation for better performance: when calling a function that needs to handle time-consuming resources, give a function reference as a parameter and don't call it in case of an error.</p>
</li>
</ul>
<h1 id="heading-final-words-about-the-series">Final words about the series</h1>
<p>This was the last article of this series. I hope you enjoyed it and that you learned new techniques for your daily C# DDD work. Feel free to contact me if you have any questions! :)</p>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>IC 4628, the Prawn nebula. This pretty nebula is found in the Scorpius constellation. It is visible with good conditions only in the southern hemisphere. Total exposure time is about 9 hours.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/nebulae-hubble-palette/ic4628Crevette">See it in large size in my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 5: entities and aggregates]]></title><description><![CDATA[Introduction
Now that you know a lot about the functional representation of value objects, it is time to switch to entities and aggregates.
Entities in a few words
Unlike value objects, entities are data structures that have an identity. Let's take a...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-5-entities-and-aggregates</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-5-entities-and-aggregates</guid><category><![CDATA[DDD]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Tue, 07 Mar 2023 11:59:57 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680786752028/3f17cd87-43f0-44c8-b987-a3e2042a1755.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Now that you know a lot about the functional representation of value objects, it is time to switch to entities and aggregates.</p>
<h1 id="heading-entities-in-a-few-words">Entities in a few words</h1>
<p>Unlike value objects, entities are data structures that have an identity. Let's take an example: a shopping cart. It must be traced in the purchase flows, so it must be assigned an identity.</p>
<p>Let’s start from this very first definition, we will improve it throughout this article:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } <span class="hljs-comment">// An entity have an identifier</span>
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-comment">// Incoming : Cart Items</span>
}
</code></pre>
<h1 id="heading-the-composition-of-an-entity">The composition of an entity</h1>
<p>An entity should consist of:</p>
<ul>
<li><p>Value objects (or list of value objects).</p>
</li>
<li><p>And/or entities (or list of entities).</p>
</li>
</ul>
<p>Let's see why.</p>
<h2 id="heading-a-word-on-primitive-obsession-first">A word on primitive obsession first</h2>
<p>In the current cart implementation, we used two integers for the identifier and the total amount. Using primitives is a bad idea because it leads to the writing of defensive code, that is, code that does not believe in itself. This is called "Primitive obsession".</p>
<p>For example, suppose we need to calculate the total cart price with tax. What's more, the business asks us to implement two validations:</p>
<ul>
<li><p>Tax amount cannot be negative.</p>
</li>
<li><p>The total amount of an order cannot exceed 10000.</p>
</li>
</ul>
<p>It may be tempting to write this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span> 
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-comment">// Incoming : Cart Items</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetTotalAmountWithTax</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> taxAmount</span>)</span> 
    {
        <span class="hljs-keyword">if</span> (taxAmount &lt; <span class="hljs-number">0</span>) 
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BusinessException(<span class="hljs-string">"The tax amount cannot be negative."</span>);

        <span class="hljs-keyword">var</span> totalAmountWithTax = TotalAmountWithoutTax * taxAmount;        
        <span class="hljs-keyword">if</span> (totalAmountWithTax &gt; <span class="hljs-number">10000</span>) 
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BusinessException(<span class="hljs-string">"The total amount cannot be more than 10000."</span>);

        TotalAmountWithTax = totalAmountWithTax;
    }
}
</code></pre>
<p>The problem is that this code is very defensive: several validations are carried out before executing the code. Now imagine these rules may have to be implemented in other places in the code: there is a high risk of code duplication.</p>
<h2 id="heading-an-entity-should-consist-of-value-objects">An entity should consist of value objects...</h2>
<p>Now we have seen value objects are so important, we will systematically use value objects in our entities instead of using primitives. They will our elementary blocks of code. We will define two of them: <code>Amount</code> and <code>Identifier</code>.</p>
<p>Here is the <code>Amount</code> Value Object. It is very important to define them as <code>record</code> so they remain immutable.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Amount</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> MAX_AMOUNT = <span class="hljs-number">10000</span>;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> MIN_AMOUNT = <span class="hljs-number">0</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> Value;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Amount</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> amount</span>)</span> 
    {
        <span class="hljs-keyword">if</span> (amount &lt; MIN_AMOUNT) 
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BusinessException(<span class="hljs-string">"An amount cannot be negative."</span>);
        <span class="hljs-keyword">if</span> (amount &gt; MAX_AMOUNT)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> BusinessException(<span class="hljs-string">$"An amount cannot be more than <span class="hljs-subst">{MAX_AMOUNT}</span>."</span>);

        Value = amount;
    }
}
</code></pre>
<p>Our cart class is slimmed down and now looks like this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span> 
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-comment">// Incoming : Cart Items, Client</span>

    <span class="hljs-function"><span class="hljs-keyword">public</span> Amount <span class="hljs-title">GetTotalAmountWithTax</span>(<span class="hljs-params">Amount taxAmount</span>)</span> 
    {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Amount(TotalAmountWithoutTax.Value * taxAmount.Value);        
    }
}
</code></pre>
<p>With Value Objects, you no longer need elementary checks or even to think about it. I recommend that you apply a strict rule: do not use any primitive in the entities. It is restrictive at first, but after that, it will ease your mind.</p>
<p>The only downside of Value Objects is the lack of context in the error messages. For example, you will get a standard error "An amount cannot be negative." But I think that's OK because we usually know the context when the error occurs. If you really need to contextualize the error message, you can assign a code to the error, then catch that code and change the error message where you need to.</p>
<h2 id="heading-and-they-should-consist-of-other-entities">... and they should consist of other entities</h2>
<p>An entity should consist of other entities or a collection of entities. In that case, it becomes an aggregate and it must be saved as a whole in the database.</p>
<p>For example, our cart becomes an aggregate when we introduce the items:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span> 
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> ImmutableList&lt;Item&gt; items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } 
    <span class="hljs-keyword">public</span> Amount TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetTotalAmountWithTax</span>(<span class="hljs-params">Amount taxAmount</span>)</span> { <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p>In an aggregate, one entity must be designated as the aggregate root: it is responsible for the consistency of all the data in the aggregate. For example, the operation of updating a child entity is the responsibility of the aggregate root.</p>
<p>In our example, the aggregate root is the cart entity and it will embed the modification of an item. Thus, the total amount of the basket will be updated and will remain consistent with the current items in the basket.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span> 
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> List&lt;Item&gt; items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; } 
    <span class="hljs-keyword">public</span> Amount TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">SetTotalAmountWithTax</span>(<span class="hljs-params">Amount taxAmount</span>)</span> { <span class="hljs-comment">/* ... */</span> }

    <span class="hljs-comment">// Updating the quantity of an item is the responsability of the cart class</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">UpdateItem</span>(<span class="hljs-params">Item item</span>)</span>{ <span class="hljs-comment">/* ... */</span> }
}
</code></pre>
<p>Note that it is very important to favor simple identifiers instead of entities to limit the size of the aggregates. Do not try to model the reality: use only the data you need to persist the aggregate and maintain its consistency.</p>
<p>For more information about DDD, aggregates, entities and value objects in .Net, I strongly recommend the lecture on "<a target="_blank" href="https://www.wiley.com/en-us/Patterns,+Principles,+and+Practices+of+Domain+Driven+Design-p-9781118714706">Patterns, principles and practices of DDD</a>" where the concepts are extremely well explained.</p>
<h1 id="heading-a-functional-entity">A functional entity</h1>
<h2 id="heading-a-read-only-data-structure">A read-only data structure</h2>
<p>As we have seen previously, data structures are immutable in functional programming. The easiest change to make is transforming the class into a record like the value objects, and transforming the Lists into immutable lists.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Cart</span> 
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> ImmutableList&lt;Item&gt; Items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
}
</code></pre>
<h2 id="heading-behaviors">Behaviors</h2>
<p>In functional programming, data is immutable and there is no state. Thus, behaviors become static extension methods of the immutable data structure and they return a new instance of it:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CartExtensions</span> 
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Cart <span class="hljs-title">SetTotalAmountWithTax</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Cart cart, Amount taxAmount</span>)</span> 
    {
        <span class="hljs-keyword">return</span> cart with { TotalAmountWithTax = <span class="hljs-keyword">new</span> Amount(cart.TotalAmountWithoutTax.Value * taxAmount.Value) } ;
    }
}
</code></pre>
<h2 id="heading-an-entityandlttandgt-container">An Entity&lt;T&gt; container</h2>
<p>As we have seen in previous articles, containers are a great help for chaining function calls. This will serve us a lot in the Application layer we will study it in the next article.</p>
<p>An <code>Entity&lt;T&gt;</code> container has been defined in my little library <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">Grenat.Functional.DDD</a>. Like <code>ValueObject&lt;T&gt;</code> it has two states: one valid and one invalid. <code>Bind</code> and <code>Match</code> operations have also been defined. <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-4-value-objects#heading-value-objects-in-a-few-words">See the previous article</a> of this series for more details.</p>
<h1 id="heading-the-challenges-of-immutability-and-container-composition">The challenges of immutability and container composition</h1>
<p>Dealing with immutability and containerized entities is not an easy task. We will face several problems. Let's see why and how to tackle them.</p>
<h2 id="heading-the-problem-of-container-composition">The problem of container composition</h2>
<p>If you read <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-4-value-objects">my previous article</a>, Value Objects will be created and containerized in a <code>ValueObject&lt;T&gt;</code> container thanks to their static constructor. And they will be themselves containerized in a parent <code>Entity&lt;T&gt;</code> container. And we face the problem of a container containing other containers, i.e. an <code>Entity&lt;T&gt;</code> containing some <code>ValueObject&lt;T&gt;</code> or some <code>Entity&lt;T&gt;</code>. This is not convenient.</p>
<p>We don't want to write this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Cart</span>
{
    <span class="hljs-keyword">public</span> ValueObject&lt;Identifier&gt; Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> ImmutableList&lt;Entity&lt;Item&gt;&gt; Items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> ValueObject&lt;Amount&gt; TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> ValueObject&lt;Amount&gt; TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }

    <span class="hljs-comment">/*...*/</span>
}
</code></pre>
<p>We want to write this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Cart</span>
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> ImmutableList&lt;Item&gt; Items { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithoutTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Amount TotalAmountWithTax { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }

    <span class="hljs-comment">/*...*/</span>
}
</code></pre>
<p>What's more, whenever we need to change an entity's property, we have to recreate a new instance of it to stick with immutability principles.</p>
<p>To solve these problems, Grenat.Functional.DDD contains some setters:</p>
<ul>
<li><p><code>SetValueObject</code></p>
</li>
<li><p><code>SetEntity</code></p>
</li>
<li><p><code>SetEntityList</code></p>
</li>
<li><p><code>SetEntityDictionary</code></p>
</li>
<li><p><code>SetEntityOption</code></p>
</li>
<li><p><code>SetValueObjectOption</code></p>
</li>
</ul>
<p>Behind the scenes, these setters :</p>
<ol>
<li><p>Unwrap the inner value of the <code>Entity&lt;T&gt;</code> to modify. Then :</p>
</li>
<li><p>Unwrap the inner value of the container (an <code>Entity&lt;V&gt;</code>, a <code>ValueObject&lt;V&gt;</code>, an <code>Option&lt;V&gt;</code>, ...) that is passed as a parameter,</p>
</li>
<li><p>They modify the targeted property of <code>Entity&lt;T&gt;</code> thanks the setter function,</p>
</li>
<li><p>And they wrap the result in an new instance of <code>Entity&lt;T&gt;</code>.</p>
</li>
</ol>
<p>If one of the <code>Entity</code> or <code>ValueObject</code> parameter is invalid, then the resulting <code>Entity&lt;T&gt;</code> will become invalid too.</p>
<p>Finally, <code>Error</code>s are harvested into this resulting entity.</p>
<p>Let's study them.</p>
<h3 id="heading-setvalueobject">SetValueObject</h3>
<p>Here is the function's signature :</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">Entity</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">SetValueObject</span>&lt;<span class="hljs-title">T</span>, <span class="hljs-title">V</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> Entity&lt;T&gt; entity, ValueObject&lt;V&gt; valueObject, Func&lt;T, V, T&gt; setter</span>)</span> { <span class="hljs-comment">/*...*/</span> }
</code></pre>
<p>It takes as arguments:</p>
<ul>
<li><p>The entity.</p>
</li>
<li><p>The value object to set into the entity.</p>
</li>
<li><p>A setter function.</p>
</li>
</ul>
<p>You can use it this way:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Cart&gt; <span class="hljs-title">SetTotalAmount</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Entity&lt;Cart&gt; cart, ValueObject&lt;Amount&gt; totalAmount</span>)</span>
{
     <span class="hljs-keyword">return</span> cart.SetValueObject(totalAmount, <span class="hljs-keyword">static</span> (cart, totalAmount) =&gt; cart with { TotalAmount = totalAmount });
}
</code></pre>
<h3 id="heading-setentity">SetEntity</h3>
<p><code>SetEntity</code> is the same as <code>SetValueObject</code> but instead of accepting a <code>ValueObject&lt;T&gt;</code> as a parameter, it accepts an <code>Entity&lt;T&gt;</code>. Here is its signature:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">Entity</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">SetEntity</span>&lt;<span class="hljs-title">T</span>, <span class="hljs-title">E</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> Entity&lt;T&gt; parentEntity, Entity&lt;E&gt; entity, Func&lt;T, E, T&gt; setter</span>)</span> { <span class="hljs-comment">/* ... */</span> }
</code></pre>
<h3 id="heading-setvalueobjectlist-setentitylist-setentitydictionary-setentityoption">SetValueObjectList, SetEntityList, SetEntityDictionary, SetEntityOption...</h3>
<p>As their name suggests, these setters do the same than the previous ones, but for immutable lists, immutable dictionaries and optionable entities and value objects.</p>
<h3 id="heading-error-harvesting">Error harvesting</h3>
<p>All setters perform error harvesting. That is to say, if you try to set an invalid value object or an invalid entity, their errors are harvested and added to the ones already existing on the parent entity. It is very interesting for APIs: if the user types bad data, then all the errors will be returned.</p>
<p>Let's have a look at an example, and let's define two value objects <code>Identifier</code> and <code>Amount</code>, written following the guidelines of the <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-4-value-objects">previous article</a>:</p>
<p>Here is an <code>Identifier</code> value object:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Identifier</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> DEFAULT_VALUE = <span class="hljs-string">""</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> Value = <span class="hljs-string">""</span>;
      
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Identifier</span>(<span class="hljs-params"></span>)</span> { Value = DEFAULT_VALUE; }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Identifier</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> identifier</span>)</span>
    {
        Value = identifier;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ValueObject&lt;Identifier&gt; <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> identifier</span>)</span>
    {
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">string</span>.IsNullOrEmpty(identifier))
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-string">"An identifier cannot be null or empty."</span>);

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Identifier(identifier);
    }
}
</code></pre>
<p>And here is an <code>Amount</code> value object:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Amount</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> MAX_AMOUNT = <span class="hljs-number">2500</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> DEFAULT_VALUE = <span class="hljs-number">0</span>;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">string</span> DEFAULT_CURRENCY = <span class="hljs-string">"EUR"</span>;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> Value;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> Currency = DEFAULT_CURRENCY;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Amount</span>(<span class="hljs-params"></span>)</span> { Value = DEFAULT_VALUE; }

    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Amount</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> <span class="hljs-keyword">value</span>, <span class="hljs-keyword">string</span> currency = DEFAULT_CURRENCY</span>)</span>
    {
        Value = <span class="hljs-keyword">value</span>;
        Currency = currency;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ValueObject&lt;Amount&gt; <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> amount</span>)</span>
    {
        <span class="hljs-keyword">if</span> (amount &lt; <span class="hljs-number">0</span>)
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-string">"An amount cannot be negative."</span>);
        <span class="hljs-keyword">if</span> (amount &gt; MAX_AMOUNT)
            <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(String.Format(<span class="hljs-string">$"An amount cannot be more than <span class="hljs-subst">{MAX_AMOUNT}</span>"</span>));

        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Amount(amount);
    }
}
</code></pre>
<p>Now let's create a cart by setting invalid data and let's see the errors harvesting in action. <code>Cart.Create()</code> is a static constructor returning an empty <code>Entity&lt;Cart&gt;</code>:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> cart = Cart.Create()
            .SetValueObject(Identifier.Create(<span class="hljs-literal">null</span>), <span class="hljs-keyword">static</span> (cart, identifier) =&gt; cart with { Id = identifier })
            .SetValueObject(Amount.Create(<span class="hljs-number">-1</span>), <span class="hljs-keyword">static</span> (cart, totalAmountWithoutTax) =&gt; cart with { TotalAmountWithoutTax = totalAmountWithoutTax })
            .SetValueObject(Amount.Create(<span class="hljs-number">3000</span>), <span class="hljs-keyword">static</span> (cart, totalAmountWithTax) =&gt; cart with { TotalAmountWithTax = totalAmountWithTax });

Console.WriteLine(cart.Errors);
<span class="hljs-comment">// Output :</span>
<span class="hljs-comment">// An identifier cannot be null or empty.</span>
<span class="hljs-comment">// An amount cannot be negative.</span>
<span class="hljs-comment">// An amount cannot be more than 2500.</span>
</code></pre>
<p>But, I agree with you, this code is a bit cryptic and not very "ubiquitous language"... Can we do better? Of course we can! Let's have a look.</p>
<h3 id="heading-creating-ubiquitous-language-setters">Creating "ubiquitous language" setters</h3>
<p>For better readability, you can create some setters using extension methods. They will call <code>SetValueObject</code>, <code>SetEntity</code>, <code>SetEntityList</code>, <code>SetEntityDictionary</code> functions under the hood. But be careful, Setters can be an anti-pattern that leads to data inconsistency, so use them wisely.</p>
<p>Here is an example:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CartSetters</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Cart&gt; <span class="hljs-title">SetId</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Entity&lt;Cart&gt; cart, <span class="hljs-keyword">string</span> id</span>)</span> 
    {
        <span class="hljs-keyword">return</span> cart.SetValueObject(Identifier.Create(id), <span class="hljs-keyword">static</span> (cart, identifier) =&gt; cart with { Id = identifier });
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Cart&gt; <span class="hljs-title">SetTotalAmountWithoutTax</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Entity&lt;Cart&gt; cart, <span class="hljs-keyword">int</span> totalAmount</span>)</span> 
    {
        <span class="hljs-keyword">return</span> cart.SetValueObject(Amount.Create(totalAmount), <span class="hljs-keyword">static</span> (cart, totalAmount) =&gt; cart with { TotalAmountWithoutTax = totalAmount });
    }

<span class="hljs-comment">/* ... */</span>
}
</code></pre>
<h2 id="heading-the-problem-of-constructors">The problem of constructors</h2>
<p>An entity with 6 fields requires a constructor with 6 parameters which is a lot... Moreover, some parameters could not be known depending on the call context. This would require creating several constructors or creating optional parameters.</p>
<p>To avoid multiplying the constructors, we will take inspiration from the builder pattern. Here is what I want to write to create a cart item:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> cartItem = <span class="hljs-keyword">new</span> CartItemBuilder()
    .WithId(<span class="hljs-string">"45xxsDg1="</span>)
    .WithProductId(<span class="hljs-string">"ne252TJqAWk3"</span>)
    .WithAmount(<span class="hljs-number">25</span>)
    .Build();
</code></pre>
<p>How to do that? First, let's create the CartItem Entity :</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Item</span> 
{
    <span class="hljs-keyword">public</span> Identifier Id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Identifier ProductId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
    <span class="hljs-keyword">public</span> Amount Amount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
      
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Item</span>(<span class="hljs-params"></span>)</span>
    {
        Id = <span class="hljs-keyword">new</span> Identifier();
        ProductId = <span class="hljs-keyword">new</span> Identifier();
        Amount = <span class="hljs-keyword">new</span> Amount();
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Entity&lt;Item&gt; <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> id, <span class="hljs-keyword">string</span> productId, <span class="hljs-keyword">int</span> amount</span>)</span>
    {
        <span class="hljs-comment">/* Add some verifications here if needed by returning an Error 
         * which will be automatically converted in an invalid Entity.
         * Eg: return new Error("Error !!")
         */</span>

        <span class="hljs-keyword">return</span> Entity&lt;Item&gt;.Valid(<span class="hljs-keyword">new</span> Item())
            .SetId(id)
            .SetProductId(productId)
            .SetAmount(amount);
    }
}
</code></pre>
<p>And let's create the builder:</p>
<pre><code class="lang-csharp"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">ItemBuilder</span>
{
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _id { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">string</span> _productId { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> _amount { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">set</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> ItemBuilder <span class="hljs-title">WithId</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> id</span>)</span> { _id = id; <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> ItemBuilder <span class="hljs-title">WithProductId</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> productId</span>)</span> { _productId = productId; <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>; }
    <span class="hljs-function"><span class="hljs-keyword">public</span> ItemBuilder <span class="hljs-title">WithAmount</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> amount</span>)</span> { _amount = amount; <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>; }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Entity&lt;Item&gt; <span class="hljs-title">Build</span>(<span class="hljs-params"></span>)</span> =&gt; Item.Create(_id, _productId, _amount);
}
</code></pre>
<p>Et voilà! :) We now have a fully functional, immutable and containerized entity. It is the best approach I found so far, if you have new ideas to improve this, please let me know!</p>
<p>Next, we will talk about the application layer: containerization and binding will reveal their full power for chaining functions and error management, without writing tons of conditional logic.</p>
<p>You can find the complete source code of this article on my <a target="_blank" href="https://github.com/BastienFoucher/Articles.Examples/blob/master/Functional.DDD.C%23.Part5.linq">Github</a>.</p>
<h2 id="heading-some-code-generation">Some code generation</h2>
<p>Writing all these setters and builders can be cumbersome work. So I wrote some Roslyn generators for that, have a look if you are interested: <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD.Generators">Grenat.Functional.DDD.Generators</a>.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>An entity should be composed of entities, a list of entities or value objects, but never primitives.</p>
</li>
<li><p>In a functional approach :</p>
<ul>
<li><p>Use C# records to create immutable entities.</p>
</li>
<li><p>All behaviors take the form of extension methods that return a copy of the new entity.</p>
</li>
</ul>
</li>
<li><p>Use my library <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">Grenat.Functional.DDD</a> to help you with container composition and immutability.</p>
</li>
</ul>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>This pretty little nebula located in the Cygnus constellation seems to make its way in the middle of a field of stars… The total exposure time is about 15 hours.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/nebulae-natural-colors/ic5146Cocon">See it in large size in my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 4: Value Objects]]></title><description><![CDATA[Introduction
Now is the time to tackle DDD... and let's start with Value Objects. We will study them using a classic object approach and then we will switch to a more functional approach.
Value objects in a few words
Value objects are the building bl...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-4-value-objects</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-4-value-objects</guid><category><![CDATA[C#]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Wed, 15 Feb 2023 12:01:42 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680788001174/932466de-dc0d-47d7-b89a-da1562a13260.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>Now is the time to tackle DDD... and let's start with Value Objects. We will study them using a classic object approach and then we will switch to a more functional approach.</p>
<h1 id="heading-value-objects-in-a-few-words">Value objects in a few words</h1>
<p>Value objects are the building blocks of any development made using DDD thinking. Value objects model things that don't have an identity: an amount of money, a quantity, an address, or a price... And since they have no identity, the equality of two Values Objects is achieved by comparing all the values they contain.</p>
<p>Another very important characteristic of Value objects is their immutability. They are not "variables", they are, as their name suggests, values. So to modify a Value Object, you need to create a new one.</p>
<h1 id="heading-an-object-approach">An object approach</h1>
<p>Let's take an example to illustrate this article. Here is a <code>Quantity</code> Value Object made using an object approach. It contains two fields: <code>Value</code> and <code>Unit</code>.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Quantity</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> Value;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> Unit;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Quantity</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> Quantity, <span class="hljs-keyword">string</span> unit</span>)</span>
    {
        Value = Quantity;
        Unit = unit;
    }
}
</code></pre>
<p>As you can see, the Quantity Value Object is immutable because of its read-only attributes. So to modify one of its properties, you need to create a new one.</p>
<p>Let's enrich this object by adding a business rule. Let's say a quantity can never be more than 100. So we add a rule in the constructor, ensuring that no <code>Quantity</code> object will ever exist in our application with a value superior to 100. What's very interesting is that Value Objects Value Object helps us make illegal states unrepresentable in our application.</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Quantity</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> quantity, <span class="hljs-keyword">string</span> unit</span>)</span>
{
    <span class="hljs-keyword">if</span> (quantity &gt; MAX_QUANTITY)
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ValueObjectException(<span class="hljs-string">$"A quantity cannot be more than <span class="hljs-subst">{MAX_QUANTITY}</span>."</span>);

    Value = quantity;
    Unit = unit;
}
</code></pre>
<p>We need now to implement the equality comparison. Remember, in case of Value Objects, we need to compare their members one by one. To do this, we will use the <code>ValueObject</code> base class as shown on <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/architecture/microservices/microservice-ddd-cqrs-patterns/implement-value-objects">Microsoft's website</a>.</p>
<p>For the purposes of this article, we'll also add a function to increment the value. The final code of our quantity Value Object looks like this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Quantity</span> : <span class="hljs-title">ValueObject</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> Value;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> Unit;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> MAX_QUANTITY = <span class="hljs-number">100</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Quantity</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> quantity, <span class="hljs-keyword">string</span> unit</span>)</span>
    {
        <span class="hljs-keyword">if</span> (quantity &gt; MAX_QUANTITY)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"A quantity cannot be more than <span class="hljs-subst">{MAX_QUANTITY}</span>."</span>);

        Value = quantity;
        Unit = unit;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Quantity <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> increment</span>)</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Quantity(Value + increment, Unit);
    }

    <span class="hljs-function"><span class="hljs-keyword">protected</span> <span class="hljs-keyword">override</span> IEnumerable&lt;<span class="hljs-keyword">object</span>&gt; <span class="hljs-title">GetEqualityComponents</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">yield</span> <span class="hljs-keyword">return</span> Value;
        <span class="hljs-keyword">yield</span> <span class="hljs-keyword">return</span> Unit;
    }
}
</code></pre>
<p>Now it is time to move to a more functional approach.</p>
<h1 id="heading-a-functional-value-object">A functional Value Object</h1>
<p>The functional approach requires us to make some modifications in our <code>Quantity</code> Value Object:</p>
<ul>
<li><p>Inheritance being absent from functional concepts, we will remove the inheritance from the ValueObject class.</p>
</li>
<li><p>Functional programming separating data and functions: we will move the <code>Add</code> method into an extension method.</p>
</li>
<li><p>In functional programming, functions need to be <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-1-the-benefits-of-functional-thinking">honest</a>. So we will remove the <code>Exception</code> thrown in the constructor and we will use another mechanism.</p>
</li>
<li><p>And finally, we will define a container to facilitate function chaining.</p>
</li>
</ul>
<h2 id="heading-removing-inheritance-and-using-records">Removing inheritance and using records</h2>
<p>In functional programming, there is normally no inheritance (keep a pragmatic attitude about this statement and use inheritance if necessary): we can remove the one using the <code>ValueObject</code> class. We will instead use <code>records</code> that provide equality comparison out of the box.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Quantity</span>
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">int</span> Value;
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">string</span> Unit;

    <span class="hljs-keyword">public</span> <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> MAX_QUANTITY = <span class="hljs-number">100</span>;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Quantity</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> quantity, <span class="hljs-keyword">string</span> unit</span>)</span>
    {
        <span class="hljs-keyword">if</span> (quantity &gt; MAX_QUANTITY)
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> Exception(<span class="hljs-string">$"A quantity cannot be more than <span class="hljs-subst">{MAX_QUANTITY}</span>."</span>);

        Value = quantity;
        Unit = unit;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Quantity <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> increment</span>)</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Quantity(Value + increment, Unit);
    }
}
</code></pre>
<p>In the previous code, I let the attributes <code>Quantity</code> and <code>Value</code> <code>readonly</code>. If I turned them in <code>{get; init;}</code> properties like this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Value { <span class="hljs-keyword">get</span>; <span class="hljs-keyword">init</span>; }
</code></pre>
<p>Then a developer could use the <code>with</code> copy constructor like the following example, thus violating the rule (the invariant) stating than a <code>Quantity</code> cannot be more than 100 because in such a case, the normal positional constructor is not called:</p>
<pre><code class="lang-C#">q = q with { Value = <span class="hljs-number">110</span> }
</code></pre>
<p>So you have to be really really careful when using <code>{get; init;}</code> properties.</p>
<h2 id="heading-behaviors">Behaviors</h2>
<p>Now let's have a look to the <code>Add()</code> function. In functional programming, we don't have objects so behavior does not exist, because, in object programming, a behaviour implies modifying the state of an object. And remember, in functional programming, everything is immutable.</p>
<p>So we need to move the <code>Add()</code> function from the record to a static extension class:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QuantityExtensions</span> {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Quantity <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Quantity quantity, <span class="hljs-keyword">int</span> increment</span>)</span> {
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Quantity(quantity.Value + increment, quantity.Unit);
    }
}
</code></pre>
<p>Some may think of <a target="_blank" href="https://martinfowler.com/bliki/AnemicDomainModel.html">Martin Fowler's Anemic Data Model</a> reading this: for me, it is not a problem as long as the methods are named using domain knowledge and as long as the codebase remains well structured.</p>
<h2 id="heading-a-valueobject-container">A ValueObject container</h2>
<p>To chain function as studied in <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world">the previous part of this series</a>, we need a container. Let's have a look.</p>
<h3 id="heading-get-the-code">Get the code</h3>
<p>To follow this article, you will need the <code>ValueObject&lt;T&gt;</code> container in my Grenat.Functional.DDD <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">project repository</a>.</p>
<h3 id="heading-a-valueobject-with-two-states-one-valid-one-invalid">A ValueObject with two states: one valid, one invalid</h3>
<p>A classic programming approach leads to the use of exceptions. However, exceptions should only be used to handle exceptional cases. What's more, they are forbidden in functional programming (see <a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-1-the-benefits-of-functional-thinking">honest functions</a> in the first article of this series).</p>
<p>So <code>ValueObject&lt;T&gt;</code> is a two states container:</p>
<ul>
<li><p>A valid state: the inner value of <code>ValueObject&lt;T&gt;</code> is accessible.</p>
</li>
<li><p>An invalid state: the inner value of <code>ValueObject&lt;T&gt;</code> is unaccessible and only the error causing this invalid state is available.</p>
</li>
</ul>
<h2 id="heading-a-static-constructor-for-quantity">A static constructor for Quantity</h2>
<p>To ensure every one will use the <code>ValueObject&lt;T&gt;</code> container, we will replace the public constructor by a static one that returns a <code>ValueObject&lt;Quantity&gt;</code>:</p>
<pre><code class="lang-C#"><span class="hljs-comment">// Make standard constructor private</span>
<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Quantity</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> quantity</span>)</span>
{
    Value = quantity;
    Unit = unit;
}

<span class="hljs-comment">// Use instead a public constructor</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ValueObject&lt;Quantity&gt; <span class="hljs-title">Create</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> quantity</span>)</span>
{
    <span class="hljs-keyword">if</span> (quantity &gt; MAX_QUANTITY)
    {
        <span class="hljs-comment">// The Error class is embeded in Grenat.Functionnal.DDD.</span>
        <span class="hljs-comment">// An implicit conversion is also defined in the library to convert an Error to an invalid ValueObject&lt;T&gt;.</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Error(<span class="hljs-string">$"Quantity cannot be more than <span class="hljs-subst">{MAX_QUANTITY}</span>"</span>);
    }
    <span class="hljs-keyword">else</span> 
    {
        <span class="hljs-comment">// An implicit conversion has been defined to convert a T to a valid ValueObject&lt;T&gt;.</span>
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Quantity(quantity);
    }
}
</code></pre>
<p>We also need to change the <code>Add()</code> extension method accordingly:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">QuantityExtensions</span> {
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ValueObject&lt;Quantity&gt; <span class="hljs-title">Add</span>(<span class="hljs-params"><span class="hljs-keyword">this</span> Quantity quantity, <span class="hljs-keyword">int</span> increment</span>)</span> {
        <span class="hljs-keyword">return</span> Quantity.Create(quantity.Value + increment, quantity.Unit);
    }
}
</code></pre>
<h2 id="heading-getting-the-inner-value-of-valueobjectandlttandgt">Getting the inner value of ValueObject&lt;T&gt;</h2>
<p><a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world">Remember the previous article</a>, getting the inner value of a container means that you need to go back to the normal world using a <code>Match</code>. Because a <code>ValueObject&lt;T&gt;</code> has two states, one valid and one invalid, we will use <code>Match()</code> to retrieve the inner value by providing it two functions:</p>
<ul>
<li><p>One for the valid state. The inner value of the <code>ValueObject&lt;T&gt;</code> will be injected into it.</p>
</li>
<li><p>One for the invalid state. An <code>IEnumerable&lt;T&gt;</code> containing the errors will be injected into it.</p>
</li>
</ul>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> quantity = Quantity.Create(<span class="hljs-number">10</span>, <span class="hljs-string">"Liters"</span>);
<span class="hljs-keyword">var</span> <span class="hljs-keyword">value</span> = quantity.Match(
                Valid: v =&gt; v.Value,
                Invalid: e =&gt; <span class="hljs-number">0</span>);
Console.WriteLine(<span class="hljs-keyword">value</span>); <span class="hljs-comment">//10</span>
</code></pre>
<h2 id="heading-chaining-functions-with-bind">Chaining functions with Bind()</h2>
<p>Now let's move to binding. If necessary, I recommend you have a refresher about <code>Bind</code> reading the previous Article of this series: "<a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-3-the-elevated-world">The elevated world</a>".</p>
<p>I have defined a <code>Bind()</code> function for <code>ValueObject&lt;T&gt;</code> in Grenat.Functional.DDD. Using it allows us chain calls to other functions like this:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> result = Quantity.Create(<span class="hljs-number">10</span>, <span class="hljs-string">"Liters"</span>)
            .Bind((q) =&gt; q.Add(<span class="hljs-number">10</span>))
            .Bind((q) =&gt; q.Add(<span class="hljs-number">30</span>))
            .Match(Valid: v =&gt; <span class="hljs-keyword">new</span> { <span class="hljs-keyword">value</span> = v.Value, errors = Enumerable.Empty&lt;Error&gt;()},
                    Invalid: e =&gt; <span class="hljs-keyword">new</span> { <span class="hljs-keyword">value</span> = <span class="hljs-number">0</span>, errors = e});

Console.WriteLine(result.<span class="hljs-keyword">value</span>); <span class="hljs-comment">//50</span>
</code></pre>
<h2 id="heading-a-superpower-of-bind-easily-handling-errors">A superpower of Bind(): easily handling errors</h2>
<p>Bind makes function chaining much easier. It also gets rid of all the plumbing needed for handling <code>Error</code> cases, because in case of an error in the execution pipeline, <code>Bind()</code> automatically switches the normal execution path to the error execution path. This will prevent you from writing tons of conditional logic.</p>
<p>Let's take an example using a functional approach:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> resultInError = Quantity.Create(<span class="hljs-number">10</span>, <span class="hljs-string">"Liters"</span>)
                        .Bind((q) =&gt; q.Add(<span class="hljs-number">10</span>))
                        .Bind((q) =&gt; q.Add(<span class="hljs-number">100</span>))
                        .Bind((q) =&gt; q.Add(<span class="hljs-number">10</span>))
                        .Match(Valid: v =&gt; <span class="hljs-keyword">new</span> { Value = v.Value, Errors = Enumerable.Empty&lt;Error&gt;()},
                                Invalid: e =&gt; <span class="hljs-keyword">new</span> { Value = <span class="hljs-number">0</span>, Errors = e});

Console.WriteLine(resultInError.Errors); <span class="hljs-comment">//Error { Message = A quantity cannot be more than 100 }</span>
</code></pre>
<p>Now let's try to rewrite an equivalent using imperative approaches.</p>
<p>Attempt 1: a pure imperative way, without using a <code>ValueObject&lt;T&gt;</code> container:</p>
<pre><code class="lang-C#">Quantity q;
<span class="hljs-keyword">try</span> 
{
    q = <span class="hljs-keyword">new</span> Quantity(<span class="hljs-number">10</span>, <span class="hljs-string">"Liters"</span>);
    q = q.Add(<span class="hljs-number">10</span>);
    q = q.Add(<span class="hljs-number">100</span>);
    q = q.Add(<span class="hljs-number">10</span>);
}
<span class="hljs-keyword">catch</span> (Exception e) 
{
    Console.WriteLine(e);
    q = <span class="hljs-keyword">new</span> Quantity(<span class="hljs-number">0</span>,<span class="hljs-string">""</span>); <span class="hljs-comment">//wrote this to avoid the following code that needs quantity to crash</span>
}
</code></pre>
<p>Attempt 2: handling a <code>ValueObject&lt;T&gt;</code> container in an imperative way:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> quantity = Quantity.Create(<span class="hljs-number">10</span>, <span class="hljs-string">"Liters"</span>);

<span class="hljs-keyword">if</span> (quantity.IsValid)
{
    quantity = quantity.Value.Add(<span class="hljs-number">10</span>);
    <span class="hljs-keyword">if</span> (quantity.IsValid) 
    {
        quantity = quantity.Value.Add(<span class="hljs-number">100</span>);
        <span class="hljs-keyword">if</span> (quantity.IsValid)
        {
            quantity = quantity.Value.Add(<span class="hljs-number">10</span>);
        }
        <span class="hljs-keyword">else</span> 
        {
            Console.WriteLine(quantity.Errors);
        }
    }
    <span class="hljs-keyword">else</span>
    {
        Console.WriteLine(quantity.Errors);
    }
}
<span class="hljs-keyword">else</span> 
{
    Console.WriteLine(quantity.Errors);
}
</code></pre>
<p>So, which approach do you prefer? I think the purely functional approach using <code>Bind</code> is simply the best and the clearest. What's more, we've been using far fewer lines of code.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>Value Objects are the building blocks of any application made using DDD thinking.</p>
</li>
<li><p>To create a functional approach of Value Objects:</p>
<ul>
<li><p>We removed inheritance and we used records.</p>
</li>
<li><p>The functional Value Object no longer throws an exception.</p>
</li>
<li><p>Behaviors are moved to static extension methods.</p>
</li>
<li><p>Constructors return a Value Object wrapped in a <code>ValueObject&lt;T&gt;</code> container. This will make it easier to chain functions and make it easier to write conditional logic with <code>Bind</code>.</p>
</li>
<li><p>If <code>ValueObject&lt;T&gt;</code> is invalid, then the encapsulated value is inaccessible thus forcing the programmer to handle the error case.</p>
</li>
</ul>
</li>
</ul>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>An aurora near Kiruna in Swedish Lapland. The solar wind particles, very energetic, reached the lower layers of the atmosphere: the bottom part of the aurora was rosy (due to a combination of red - ionized nitrogen - and blue - nitrogen -). This color was perfectly visible to the naked eye.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/northern-lights/auroreTaiga">See it in large size in my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 3: the elevated world]]></title><description><![CDATA[Introduction
In the two previous articles, we talk about the fundamentals of functional programming and functional architecture. But before moving to functional DDD, we need to talk about another fundamental of functional programming: the elevated wo...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-3-the-elevated-world</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-3-the-elevated-world</guid><category><![CDATA[C#]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Tue, 07 Feb 2023 16:33:16 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680788323263/a447459b-0d53-4bb3-a6f6-5184a0807887.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In the two previous articles, we talk about the fundamentals of functional programming and functional architecture. But before moving to functional DDD, we need to talk about another fundamental of functional programming: the elevated world.</p>
<h1 id="heading-what-is-the-elevated-world">What is the elevated world?</h1>
<p>In functional programming, the elevated world is a world in which objects are wrapped in a container <code>Elevated&lt;T&gt;</code> or, more concisely, <code>E&lt;T&gt;</code>. You unknowingly use the elevated world when you deal with asynchronous programming: <code>Task&lt;T&gt;</code>.</p>
<p>So we can write:</p>
<ul>
<li><p><code>int -&gt; E&lt;int&gt;</code></p>
</li>
<li><p><code>string -&gt; E&lt;string&gt;</code></p>
</li>
</ul>
<p>And so on.</p>
<h1 id="heading-what-is-it-for">What is it for?</h1>
<p>The elevated world has a lot of interests. The main one is that it makes it easier to chain functions.</p>
<p>Chaining functions bring out what software does: a succession of operations that transforms data into other data. Halas, too often, we first think about implementation details instead of thinking about a flow: structures, classes, interfaces, inheritance, algorithms, data tables and so many other details in which we drown.</p>
<p>Let's see how the elevated world helps us with functions chaining with a LINQ example. The following code gets the average of the 5 best scores. Look how comprehensive the program is using function chaining:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> scores = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">int</span>&gt; { <span class="hljs-number">12</span>, <span class="hljs-number">18</span>, <span class="hljs-number">17</span>, <span class="hljs-number">14</span>, <span class="hljs-number">13</span>, <span class="hljs-number">20</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">14</span> };

<span class="hljs-keyword">var</span> averageOf5BestScores = scores.OrderByDescending(x =&gt; x)
                                    .Take(<span class="hljs-number">5</span>)
                                    .Average();

Console.WriteLine(averageOf5BestScores); <span class="hljs-comment">//16.6</span>
</code></pre>
<p>This chaining works because each function returns a value in the elevated world of enumerable integers: <code>IEnumerable&lt;int&gt;</code>.</p>
<h1 id="heading-writing-functions-that-chain-well">Writing functions that chain well</h1>
<p>Writing a function that chains well requires 4 criteria:</p>
<ul>
<li><p>It must be pure. If it produces side effects, it will be complicated to chain other functions;</p>
</li>
<li><p>It must take an input parameter in the elevated world, for example, <code>IEnumerable&lt;T&gt;</code>;</p>
</li>
<li><p>It must be defined as an extension method of the input value (<code>this IEnumerable&lt;T&gt;</code>);</p>
</li>
<li><p>And it must return a result in an elevated world (<code>IEnumerable&lt;T&gt;</code>).</p>
</li>
</ul>
<p>Let's take an example using the previous example:</p>
<ul>
<li><p>I define a method <code>TakeTopValuesOrderedByDescending()</code> that extends <code>IEnumerable&lt;T&gt;</code>. It has no side effects.</p>
</li>
<li><p>It returns an <code>IEnumerable&lt;T&gt;</code> to chain calls of other functions.</p>
</li>
</ul>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">IEnumerableExtensions</span>
{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">IEnumerable</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">TakeTopValuesOrderedByDescending</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> IEnumerable&lt;T&gt; values, <span class="hljs-keyword">int</span> top</span>)</span> 
    {
        <span class="hljs-keyword">return</span> values
                .OrderByDescending(m =&gt; m)
                .Take(top);
    }
}
</code></pre>
<p>Now I can rewrite the very first example by replacing the calls to <code>OrderByDescending()</code> and <code>Take()</code> with <code>TakeTopValuesSortedByDescending()</code>:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> scores = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">int</span>&gt; { <span class="hljs-number">12</span>, <span class="hljs-number">18</span>, <span class="hljs-number">17</span>, <span class="hljs-number">14</span>, <span class="hljs-number">13</span>, <span class="hljs-number">20</span>, <span class="hljs-number">8</span>, <span class="hljs-number">9</span>, <span class="hljs-number">14</span> };

<span class="hljs-keyword">var</span> averageOf5BestScores = scores
                            .TakeTopValuesOrderedByDescending(<span class="hljs-number">5</span>)
                            .Average();

Console.WriteLine(averageOf5BestScores); <span class="hljs-comment">//16.6</span>
</code></pre>
<h1 id="heading-working-with-the-normal-and-the-elevated-world">Working with the normal and the elevated world</h1>
<p>During your work, you will have to jump from the normal world to the elevated world and vice-versa.</p>
<p>This is done by 3 types of operations:</p>
<ul>
<li><p>An operation called <code>Return</code> in functional programming, which raises a value from the normal world to the elevated world;</p>
</li>
<li><p>An operation called <code>Match</code> to move back from the elevated world to the normal world and get the embedded value;</p>
</li>
<li><p>An operation to chain function calls in the elevated world: <code>Bind</code>, <code>Map</code> or <code>Apply</code>.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675785508336/4f033b7a-530d-4b54-a30d-dc5aa08962dd.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-writing-our-elevated-world-optionandlttandgt">Writing our elevated world: Option&lt;T&gt;</h1>
<p>Let's take an example and let's write our first elevated world: <code>Option&lt;T&gt;</code>. It is a very useful and very well-known pattern <a target="_blank" href="https://learn.microsoft.com/en-us/dotnet/fsharp/language-reference/options">embedded in F#</a> to model the absence of data (instead of using null which is a terrible idea).</p>
<h2 id="heading-a-first-definition">A first definition</h2>
<p><code>Option&lt;T&gt;</code> has two possible values: Some and None. Here is its first definition:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">record</span> <span class="hljs-title">Option</span>&lt;<span class="hljs-title">T</span>&gt;
{
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">readonly</span> <span class="hljs-keyword">bool</span> IsSome;

    <span class="hljs-keyword">private</span> <span class="hljs-keyword">readonly</span> T? _value;

    <span class="hljs-comment">//a private constructor to force the use of static constructors (see below)</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">Option</span>(<span class="hljs-params">T v, <span class="hljs-keyword">bool</span> isSome</span>)</span> =&gt; (_value, IsSome) = (v, isSome);
}
</code></pre>
<p>Next, we need to write the 3 basic operations described before: elevating to <code>Option&lt;T&gt;</code>, returning from <code>Option&lt;T&gt;</code> and getting its inner value, and a chaining-functions helper <code>Bind()</code> or <code>Map()</code>.</p>
<h2 id="heading-operation-1-elevating-a-value-to-optionandlttandgt">Operation 1: elevating a value to Option&lt;T&gt;</h2>
<p>To elevate a value <code>t</code> to <code>Option&lt;T&gt;</code>, we will write two functions: <code>Some(T t)</code> and <code>None()</code>.</p>
<p>First, we add two static constructors:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> Option&lt;T&gt; <span class="hljs-title">CreateSome</span>(<span class="hljs-params">T v</span>)</span> =&gt; <span class="hljs-keyword">new</span>(v, <span class="hljs-literal">true</span>);
<span class="hljs-function"><span class="hljs-keyword">internal</span> <span class="hljs-keyword">static</span> Option&lt;T&gt; <span class="hljs-title">CreateNone</span>(<span class="hljs-params"></span>)</span> =&gt; <span class="hljs-keyword">new</span>(<span class="hljs-keyword">default</span>!, <span class="hljs-literal">false</span>);
</code></pre>
<p>But they are not practical to use (<code>Option.CreateSome(value)</code>), that is why I keep them <code>internal</code>. I want to write <code>Some(value)</code>. So let's do a small helper static class:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Option</span>
{  
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">Option</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">Some</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">T <span class="hljs-keyword">value</span></span>)</span> =&gt; Option&lt;T&gt;.CreateSome(<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-title">Option</span>&lt;<span class="hljs-title">T</span>&gt; <span class="hljs-title">None</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params"></span>)</span> =&gt; Option&lt;T&gt;.CreateNone();
}
</code></pre>
<p>Now we have two "Return" functions to elevate a value to <code>Option&lt;T&gt;</code>. Here is how to use them:</p>
<pre><code class="lang-C#"><span class="hljs-comment">//define some value</span>
Option&lt;<span class="hljs-keyword">string</span>&gt; someString = Some(<span class="hljs-string">"foo"</span>);
<span class="hljs-comment">//define the absence of value, instead of using null</span>
Option&lt;<span class="hljs-keyword">string</span>&gt; none = None&lt;<span class="hljs-keyword">string</span>&gt;();
</code></pre>
<h2 id="heading-operation-2-returning-to-the-normal-world">Operation 2: returning to the normal world</h2>
<p>Next, we need to move back to the normal world and read the inner value of <code>Option&lt;T&gt;</code>. We will use a <code>Match</code> function. It unwraps the inner value of <code>Option&lt;T&gt;</code> and fires 2 functions that are set as parameters: one if the value is defined and the other one if it is not.</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> R <span class="hljs-title">Match</span>&lt;<span class="hljs-title">R</span>&gt;(<span class="hljs-params">Func&lt;R&gt; None, Func&lt;T, R&gt; Some</span>)</span> =&gt; IsSome ? Some(_value!) : None();
</code></pre>
<p>Here is how to use it. <strong>Important:</strong> the returned value of provided functions for <code>Some</code> and <code>None</code> cases must be of the same type (string in this example).</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">string</span> <span class="hljs-title">GetOptionValue</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">Option&lt;T&gt; <span class="hljs-keyword">value</span></span>)</span>
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">value</span>.Match(
            None: () =&gt; <span class="hljs-string">"Empty"</span>,
            Some: (<span class="hljs-keyword">value</span>) =&gt; <span class="hljs-string">$"<span class="hljs-subst">{<span class="hljs-keyword">value</span>}</span>"</span>);
}
</code></pre>
<h2 id="heading-operation-3-chaining-functions-in-the-elevated-world">Operation 3: chaining functions in the elevated world</h2>
<p>We need a generic mechanism to chain operations in the elevated world. In the world of <code>Option&lt;T&gt;</code>, chaining operations must be done only if the inner value of <code>Option&lt;T&gt;</code> is defined. This will be the purpose of the <code>Bind()</code> function.</p>
<p>It takes 2 parameters :</p>
<ul>
<li><p>A value in the elevated world (<code>Option&lt;T&gt;</code> in our example);</p>
</li>
<li><p>And a function that operates in the normal world <code>T</code> and returns another value in the world of <code>Option</code>. The returned value wrapped in <code>Option&lt;&gt;</code> can be of another type (<code>R</code> for "result type"): the signature of this function is therefore <code>T =&gt; Option&lt;R&gt;</code>.</p>
</li>
</ul>
<p>So here is the definition of <code>Bind()</code> for <code>Option&lt;T&gt;</code>:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-title">Option</span>&lt;<span class="hljs-title">R</span>&gt; <span class="hljs-title">Bind</span>&lt;<span class="hljs-title">T</span>, <span class="hljs-title">R</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> Option&lt;T&gt; option, Func&lt;T, Option&lt;R&gt;&gt; func</span>)</span>
{
    <span class="hljs-keyword">return</span> option.Match(
                Some: v =&gt; func(v),
                None: () =&gt; None&lt;R&gt;());
}
</code></pre>
<p>What we see is that <code>Bind</code> applies <code>func</code> on the inner value of <code>option</code> only if it exists. Else, the result will be <code>None&lt;R&gt;</code>.</p>
<p>Let's give it a try :</p>
<pre><code class="lang-C#">[<span class="hljs-meta">TestMethod</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">When_binding_a_AddOne_function_on_some_zero_value_then_the_result_is_one</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">var</span> addOne = (<span class="hljs-keyword">int</span> i) =&gt; Some(i + <span class="hljs-number">1</span>);
    <span class="hljs-keyword">var</span> sut = Some(<span class="hljs-number">0</span>);

    <span class="hljs-keyword">var</span> result = sut.Bind(addOne)
                    .Match(
                            Some: v =&gt; v,
                            None: () =&gt; <span class="hljs-number">0</span>);

    Assert.AreEqual(<span class="hljs-number">1</span>, result);
}
</code></pre>
<p>Now let's test the chaining:</p>
<pre><code class="lang-C#">[<span class="hljs-meta">TestMethod</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">When_binding_three_AddOne_functions_on_some_zero_value_then_the_result_is_three</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">var</span> addOne = (<span class="hljs-keyword">int</span> i) =&gt; Some(i + <span class="hljs-number">1</span>);
    <span class="hljs-keyword">var</span> sut = Some(<span class="hljs-number">0</span>);

    <span class="hljs-keyword">var</span> result = sut.Bind(addOne)
                    .Bind(addOne)
                    .Bind(addOne)
                    .Match(
                            Some: v =&gt; v,
                            None: () =&gt; <span class="hljs-number">0</span>);

    Assert.AreEqual(<span class="hljs-number">3</span>, result);
}
</code></pre>
<p>But what if one of the chained functions returns a <code>None</code> because something wrong happened? Well, the final result of the chain will be a <code>None</code> because <code>Bind</code> applies the parameterized function only if the value of <code>Option&lt;T&gt;</code> is <code>Some</code>.</p>
<pre><code class="lang-C#">[<span class="hljs-meta">TestMethod</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">When_binding_a_function_that_returns_none_then_the_result_is_none</span>(<span class="hljs-params"></span>)</span>
{
    <span class="hljs-keyword">var</span> addOne = (<span class="hljs-keyword">int</span> i) =&gt; Some(i + <span class="hljs-number">1</span>);
    <span class="hljs-keyword">var</span> funcNone = (<span class="hljs-keyword">int</span> i) =&gt; None&lt;<span class="hljs-keyword">int</span>&gt;();
    <span class="hljs-keyword">var</span> sut = Some(<span class="hljs-number">0</span>);

    <span class="hljs-keyword">var</span> result = sut.Bind(addOne)
                    .Bind(funcNone)
                    .Bind(addOne);

    Assert.IsFalse(result.IsSome);
}
</code></pre>
<p>What is great is that <code>Bind</code> uses a "railway" management of problems: if one function in the chain returns a <code>None</code>, then the final result will be <code>None</code>. This mechanism is extremely well explained by Scott Wlaschin <a target="_blank" href="https://fsharpforfunandprofit.com/posts/recipe-part2/">here</a>. Managing errors in the domain become then very easy because you don't have to write any conditional logic. We will use it a lot in the application layer of our functional architecture.</p>
<h2 id="heading-what-about-map"><strong>What about Map()?</strong></h2>
<p><code>Map()</code> is the same than <code>Bind()</code> instead that it takes as a parameter a function that returns a value in the normal world. As a result, it needs to lift it the elevated world.</p>
<p>Map() for Option&lt;T&gt; looks like this:</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-title">Option</span>&lt;<span class="hljs-title">R</span>&gt; <span class="hljs-title">Map</span>&lt;<span class="hljs-title">T</span>, <span class="hljs-title">R</span>&gt;(<span class="hljs-params"><span class="hljs-keyword">this</span> Option&lt;T&gt; option, Func&lt;T, R&gt; func</span>)</span>
{
    <span class="hljs-keyword">return</span> option.Match(
             Some: v =&gt; Some(func(v)), <span class="hljs-comment">// Lifting func's result in the elevated world</span>
             None: () =&gt; None&lt;R&gt;());
}
</code></pre>
<h1 id="heading-stick-to-the-elevated-world-as-long-as-you-can">Stick to the elevated world as long as you can</h1>
<p>Given the power of the <code>Bind</code> and <code>Map</code> to chain functions and their efficient way of handling errors, I highly recommend sticking to the elevated world for as long as you can.</p>
<h1 id="heading-get-the-code">Get the code</h1>
<p>You can get <code>Option&lt;T&gt;</code> and its unit tests in my Grenat.Functional.DDD library <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">here</a>.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>The elevated world makes it easier to write functions that can be chained together.</p>
</li>
<li><p>3 types of operations allow you to work between the elevated world and the real world:</p>
<ul>
<li><p>A <code>Return</code> operation (<code>Some</code> and <code>None</code> in this example) to raise a value from the normal world to the elevated world.</p>
</li>
<li><p>A <code>Match</code> operation to return to the normal world.</p>
</li>
<li><p>Operations to chain functions in the elevated world: <code>Bind</code>, <code>Map</code>, <code>Apply</code>.</p>
</li>
</ul>
</li>
<li><p><code>Bind</code> and <code>Map</code> are great to manage errors without having to write conditional logic.</p>
</li>
<li><p>Stay in the elevated world as long as you can to benefit from the power of <code>Bind</code> and <code>Map</code>.</p>
</li>
</ul>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>Light pillars on the city of Kiruna in Swedish Lapland. This phenomenon of the polar regions is caused by the reflection of the intense light sources of the cities in the millions of ambient air crystals.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/phenomena/piliersLumiere">See it in large size on my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 2: functional architecture]]></title><description><![CDATA[Introduction
In part 1 of this series, we understood why an application core should be designed using functional thinking. To achieve this, we need to encapsulate the performing of side effects in external layers: communicating with a message bus, ca...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-2-functional-architecture</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-2-functional-architecture</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[C#]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Mon, 30 Jan 2023 17:36:14 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680788362362/f6d72bf8-c54a-47cc-a800-81436ca7ae98.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-introduction">Introduction</h1>
<p>In part 1 of this series, we understood why an application core should be designed using functional thinking. To achieve this, we need to encapsulate the performing of side effects in external layers: communicating with a message bus, calling APIs… This architecture is called functional architecture. Its goal is to maximize the amount of code written in the functional style.</p>
<p>Let's talk about it and let's start with a schema, I will explain it in the rest of this article:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675097293300/f2d75b33-945c-4670-8a48-4fe4ac06b5df.png" alt="Functional architecture" class="image--center mx-auto" /></p>
<h1 id="heading-the-functional-core">The functional core</h1>
<p>The functional core contains all the business logic: price calculation, discount calculation, input validation... Its role to make decisions and give instructions to the external layers to perform side effects. In the DDD world, all this work is done by aggregates, entities, value objects and services.</p>
<p>Your application heritage resides here, it has to cross the ages and survive any technological change. So:</p>
<ul>
<li><p>Take great care of it by minimizing its technical dependencies and guaranteeing bulletproof reliability,</p>
</li>
<li><p>Maximize the amount of code that resides in this functional core. You will gain very good reliability and easily achievable automated tests.</p>
</li>
</ul>
<h1 id="heading-input-and-output-gates">Input and output gates</h1>
<p>Communication between the functional core and the outside world (API, bus, database, etc.) must be done by using input and output gates. Their roles will be as follows:</p>
<ul>
<li><p>Validating the input data before it enters your functional core,</p>
</li>
<li><p>Transforming the data that goes out to the outside world to hide implementation details. This is also necessary for security reasons so that confidential data does not leak out.</p>
</li>
</ul>
<h1 id="heading-the-outside-world">The outside world</h1>
<p>The role of outer layers is to generate side effects: querying a database, sending an email, a message on an application bus... It also contains all the technological dependencies.</p>
<p>Because it produces side effects, uses technological libraries and interacts with other systems or users, this outside world is dangerous. That is why:</p>
<ul>
<li><p>It is important to isolate it in its layer,</p>
</li>
<li><p>It is important to verify its data before any communication with the functional core thanks to the gates.</p>
</li>
</ul>
<p>Finally, the outer layers must contain no or very little logic: they should be as dumb as possible and must act upon requests of the functional core.</p>
<h1 id="heading-a-parallel-with-clean-architecture">A parallel with clean architecture</h1>
<p>Functional architecture and clean architecture (or onion architecture or hexagonal architecture, the principles are the same) are very close:</p>
<ul>
<li><p>The application and domain layers of clean architecture (left image below) correspond to the functional core,</p>
</li>
<li><p>The infrastructure layer of clean architecture corresponds to the outside world of functional architecture.</p>
</li>
</ul>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1675108743755/b47cbd3d-bcd6-4ba9-8a69-ae0623da69ef.png" alt class="image--center mx-auto" /></p>
<p>Finally, functional architecture is a rigorous clean architecture. Its domain and application layers are written by applying the principles of functional programming: immutability, function composition, etc.</p>
<h1 id="heading-choose-your-architecture-wisely">Choose your architecture wisely</h1>
<p>Adopting the functional architecture can be overkill for some very simple needs because it requires additional work to manage immutability (see previous article),</p>
<p>Be pragmatic and do not over-engineer your applications. The functional architecture is very well suited for core business areas, complex functionalities or functionalities requiring a high level of reliability.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>The functional architecture consists of two layers: the functional core and the external world.</p>
</li>
<li><p>The functional core layer makes the decisions, the outside world layer applies them.</p>
</li>
<li><p>The functional core can be divided into an application layer and a domain layer like clean architecture.</p>
</li>
<li><p>Functional architecture can be seen as a rigorous version of clean architecture.</p>
</li>
<li><p>Choose your architecture pragmatically and do not overdesign your software (YAGNI!).</p>
</li>
</ul>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>In 2015, at the very maximum of the Geminid meteor shower. A celestial fireworks happened above the Fuencaliente lighthouse on the Palma island in Canary Islands, on a red airglow background.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/milky-way/geminidesFuencaliente">See it in large size on my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[Functional DDD with C# Part 1: the benefits of functional thinking]]></title><description><![CDATA[Series introduction
DDD (Domain Driven Design) and functional programming have become increasingly popular to master the complexity of our modern applications.
But how DDD tactical object patterns (entities, aggregates, value objects) apply in functi...]]></description><link>https://www.bastienfoucher.net/functional-ddd-with-c-part-1-the-benefits-of-functional-thinking</link><guid isPermaLink="true">https://www.bastienfoucher.net/functional-ddd-with-c-part-1-the-benefits-of-functional-thinking</guid><category><![CDATA[DDD]]></category><category><![CDATA[C#]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Sun, 29 Jan 2023 13:50:17 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1680788400113/b0565906-914c-4ded-9cf8-7130f216e78d.jpeg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<h1 id="heading-series-introduction">Series introduction</h1>
<p>DDD (Domain Driven Design) and functional programming have become increasingly popular to master the complexity of our modern applications.</p>
<p>But how DDD tactical object patterns (entities, aggregates, value objects) apply in functional programming? And how to do it in C# which is an object language? Lots of questions I searched for and found answers to.</p>
<p>I will explain my functional DDD C# journey throughout this series. I wrote a small library for that: <a target="_blank" href="https://github.com/BastienFoucher/Grenat.Functional.DDD">Grenat.Functional.DDD</a>. I hope you will learn new useful techniques for your daily work to write less and more sustainable code.</p>
<p>Let's dive in!</p>
<h1 id="heading-why-you-should-adopt-functional-thinking">Why you should adopt functional thinking</h1>
<h2 id="heading-functional-programming-is-not-complicated">Functional programming is not complicated</h2>
<p>A few words first about functional programming. Of course, it is a very large topic. But if we focus on its more important concepts, it is not so complicated. It is just an all-rounder programming style based on functions and on the avoidance of side effects.</p>
<p>Every developer knows what a function is and every developer knows what a side effect is. So everyone can use it. Functional programming is just a rigorous procedural programming style. It is another way to think about our programs, which is why I like to talk about "functional thinking".</p>
<h2 id="heading-functional-thinking-is-applicable-in-any-language">Functional thinking is applicable in any language</h2>
<p>What I find interesting is that the fundamental principles of functional thinking are simple and can be used in many languages. In an object language like C# or Java, it is even possible to find a subtle balance between object and functional thinking.</p>
<h2 id="heading-say-goodbye-to-unwanted-side-effects">Say goodbye to unwanted side effects</h2>
<p>Let's go back to side effects. For a refresher, a function does a side effect if it modifies a state outside of its local state. It can be something like sending an email or persisting data in a database. A side effect can also be more localized, like modifying an object attribute or a function parameter.</p>
<p>Here is a simple side effect that can happen everywhere, especially in large teams and large codebases: the reference parameter is modified by accident.</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> names = <span class="hljs-keyword">new</span> List&lt;<span class="hljs-keyword">string</span>&gt;() {<span class="hljs-string">"Emmanuel"</span>, <span class="hljs-string">"Justin"</span>, <span class="hljs-string">"Joe"</span>};

<span class="hljs-function"><span class="hljs-keyword">void</span> <span class="hljs-title">DoASideEffectByAccident</span>(<span class="hljs-params">List&lt;<span class="hljs-keyword">string</span>&gt; names</span>)</span> 
{
    <span class="hljs-comment">// do something...</span>
    names.Add(<span class="hljs-string">"Donald"</span>);
    <span class="hljs-comment">// do something...</span>
}

DoASideEffectByAccident(names);

Console.WriteLine(names); <span class="hljs-comment">// Output : Emmanuel, Justin, Joe, Donald</span>
</code></pre>
<p>We will see in the rest of the article how functional thinking will help to avoid this problem.</p>
<p>However, a program has no interest if it does not perform a side effect. So what is functional thinking for? Well, we will use functional thinking fundamentals at the core of our programs while other layers will be in charge of performing side effects.</p>
<h1 id="heading-the-fundamentals-of-functional-thinking">The fundamentals of functional thinking</h1>
<h2 id="heading-pure-functions">Pure functions</h2>
<p>A pure function is a function that produces the same result when called multiple times with the same parameter.</p>
<p>This function is not pure because when called several times it will produce a different result:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">NewRandom</span>(<span class="hljs-params"></span>)</span> {
    <span class="hljs-keyword">var</span> r = <span class="hljs-keyword">new</span> Random();
    <span class="hljs-keyword">return</span> r.Next();
}
</code></pre>
<p>The following function is also unpure because it calls the database: there is no guarantee that at its next call you will get the same result.</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> Task&lt;Price&gt; <span class="hljs-title">GetProductPrice</span>(<span class="hljs-params">DbContext context, <span class="hljs-keyword">int</span> id</span>)</span>
{
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">await</span> context.Product.AsNoTracking()
                        .Where(p =&gt; p.ProductId == id)
                        .Select(p =&gt; Price.Create(p.Price))
                        .FirstOrDefaultAsync();
}
</code></pre>
<p>And finally, this other <code>RemoveItem()</code> function is also unpure because if modifies one of the <code>Cart</code>'s attribute. Also, if it is called multiple times, the result will be different because her behavior depends on a shared state (the <code>Items</code> and <code>CartTotal</code> attributes):</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">Cart</span>
{
    <span class="hljs-keyword">public</span> List&lt;CartItem&gt; Items { <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">int</span> CartTotal { <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-keyword">int</span> <span class="hljs-title">RemoveItem</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> cartItemId, <span class="hljs-keyword">int</span> units</span>)</span> 
    {
        Items.RemoveAll(i =&gt; i.ItemId == cartItemId);
        <span class="hljs-keyword">return</span> Items.Sum(i =&gt; i.Price);
    }
}
</code></pre>
<p>The behavior of a pure function depends exclusively on its input parameter and therefore:</p>
<ul>
<li><p>It doesn't produce side effects,</p>
</li>
<li><p>It is easily testable,</p>
</li>
<li><p>It is parallelizable.</p>
</li>
</ul>
<h2 id="heading-immutability">Immutability</h2>
<p>Immutability is one of the most important principles of functional programming. It requires a <strong>"copy on write"</strong> discipline, i.e. you have to make a copy of the object before modifying its data.</p>
<h3 id="heading-avoiding-side-effects">Avoiding side effects</h3>
<p>The biggest advantage of immutability is that it avoids creating accidental side effects. When a developer modifies an existing code, he no longer has to identify all its potential side effects. Combined with pure functions, immutability allows the developer to focus only on the code that he needs to modify. It saves time, energy and avoids accidents.</p>
<p>A simple action is to use immutable collections using a C# immutable list:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> immutableNames = ImmutableList.Create(<span class="hljs-string">"Emmanuel"</span>, <span class="hljs-string">"Justin"</span>, <span class="hljs-string">"Joe"</span>);

<span class="hljs-function"><span class="hljs-keyword">int</span> <span class="hljs-title">DoSomethingWithoutSideEffect</span>(<span class="hljs-params">ImmutableList&lt;<span class="hljs-keyword">string</span>&gt; names</span>)</span> {
    <span class="hljs-comment">// With Immutable Lists, a copy of the modified object is returned when calling the Add function, thus avoiding a side effect.</span>
    <span class="hljs-keyword">var</span> newNames = names.Add(<span class="hljs-string">"Donald"</span>);

    <span class="hljs-comment">// Do something...</span>
    <span class="hljs-keyword">return</span> result;
}

DoSomethingWithoutSideEffect(immutableNames);

Console.WriteLine(immutableNames); <span class="hljs-comment">//Output : Emmanuel, Justin, Joe</span>
</code></pre>
<h3 id="heading-more-predictable-code-in-multi-threaded-environments">More predictable code in multi-threaded environments</h3>
<p>Immutable code is automatically thread-safe because we can only read the values. And concurrent reads by multiple threads pose no problems.</p>
<h2 id="heading-honest-functions">Honest functions</h2>
<p>An honest function (or a total function) is a function that for any value of a starting set matches a value in the destination set.</p>
<p>This function is not honest (it is <a target="_blank" href="https://en.wikipedia.org/wiki/Partial_function">partial</a>) because it has no matching result in the integer destination set for a negative parameter:</p>
<pre><code class="lang-C#"><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">AddOne</span>(<span class="hljs-params"><span class="hljs-keyword">int</span> number</span>)</span>
{
    <span class="hljs-keyword">if</span> (number &lt;<span class="hljs-number">0</span>) 
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> ArgumentException(<span class="hljs-string">$"<span class="hljs-subst">{number}</span> cannot be negative."</span>);
    <span class="hljs-keyword">else</span> 
        <span class="hljs-keyword">return</span> number++;
}
</code></pre>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1674997926707/d489911e-b482-43e4-b4fd-bac1db758d5e.png" alt class="image--center mx-auto" /></p>
<p>Honest functions are less restrictive than pure functions: a function that performs a side effect like an input/output but which in any case returns a value of the declared type in its signature is honest.</p>
<p>However, writing honest functions requires a mindset change: you must forget exceptions and favor tangible results in case of an error. Exceptions should only occur in exceptional cases as its name suggests. In C#, the <a target="_blank" href="https://github.com/altmann/FluentResults">Fluent Results</a> library is perfectly suited for writing honest functions: it avoids throwing exceptions.</p>
<h1 id="heading-some-other-benefits-of-functional-thinking">Some other benefits of functional thinking</h1>
<h2 id="heading-make-unit-testing-easier">Make unit testing easier</h2>
<p>By creating a maximum of pure and honest functions, we make the writing of automated tests easier: it is enough to compare the function output with what is expected.</p>
<p>On the other hand, if your code base contains procedures that produce side effects, creating automated tests becomes more difficult since:</p>
<ul>
<li><p>You have to test the side effect,</p>
</li>
<li><p>You may have to mock the class to test an outcoming interaction (with a database for example).</p>
</li>
</ul>
<p>Of course, testing side effects would still be necessary because each application produces side effects. But you have to minimize them to the maximum.</p>
<h2 id="heading-less-code-in-critical-parts-of-the-codebase">Less code in critical parts of the codebase</h2>
<p>In functional programming, we use declarative programming: we write what the program should do. Imperative programming remains however necessary because almost all processors work this way: they are designed to execute sequences of elementary instructions.</p>
<p>For example, SQL is a declarative language. Take the following query:</p>
<pre><code class="lang-SQL"><span class="hljs-keyword">Select</span> <span class="hljs-keyword">Sum</span>(amount) Order_total <span class="hljs-keyword">from</span> <span class="hljs-keyword">Order</span> 
<span class="hljs-keyword">Inner</span> <span class="hljs-keyword">join</span> OrderLine <span class="hljs-keyword">on</span> OrderLine.Id = Order.Id
<span class="hljs-keyword">Where</span> Order.Id = @OrderId
</code></pre>
<p>I did not write all the necessary loops because the declarative statement was translated into a set of imperative statements by the compiler: the execution plan. A similar example could be made with .Net Linq to Objects query: the compiler generates all the imperative code for us.</p>
<p>Here is another example: adding a product in the orchestrating layer of the application (<a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-6-the-application-layer">see part 6 of this series</a>). This code deals with all of the error cases without writing any conditional "glue":</p>
<pre><code class="lang-C#"><span class="hljs-keyword">var</span> p = <span class="hljs-keyword">await</span> Product.Create(addProductDto.Reference, addProductDto.Name, addProductDto.Price, addProductDto.FamilyId)
        .BindAsync(VerifyProductReference, () =&gt; CountProductReferences(addProductDto.Reference))
        .BindAsync(VerifyFamilyId, () =&gt; CountFamilyIds(addProductDto.FamilyId))
        .MapAsync(SaveProduct);
</code></pre>
<p>In these examples, we wrote very little code which drives to produce fewer bugs. Nevertheless, do not believe that you'll write less code everywhere in your codebase with functional thinking. Some parts of your application will indeed require to write more code, especially to deal with immutability.</p>
<p>What's important is that functional thinking allows you to write less code in the critical parts of your codebase: the domain and application layers (<a target="_blank" href="https://grenat.hashnode.dev/functional-ddd-with-c-part-2-functional-architecture">see next post</a>).</p>
<h2 id="heading-less-interfaces-boilerplate-code">Less interfaces boilerplate code</h2>
<p>In the object paradigm, developers tend to create too much interfaces. Sometimes to abstract things that will finally have only one implementation. But sometimes we really need to write interfaces to abstract an out-of-process resource like a database. The good news is that we can get rid of most of them using functional thinking: just inject functions.</p>
<p>Let's compare the object and functional approaches to write a repository. Both are perfectly suitable depending on your needs.</p>
<p>Let's begin with the classical object approach:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">interface</span> <span class="hljs-title">ICatalogRepository</span> 
{
    <span class="hljs-keyword">public</span> Task&lt;List&lt;Product&gt;&gt; GetProducts();

    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">SaveProduct</span>(<span class="hljs-params">Product product</span>)</span>;

    <span class="hljs-comment">/*...*/</span>
}
</code></pre>
<p>Now we need to implement this interface:</p>
<pre><code class="lang-C#"><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">CatalogRepository</span> : <span class="hljs-title">ICatalogRepository</span>
{ 
    <span class="hljs-keyword">public</span> Task&lt;List&lt;Product&gt;&gt; GetProducts() 
    {
        <span class="hljs-comment">/*...*/</span>
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> Task <span class="hljs-title">SaveProduct</span>(<span class="hljs-params">Product product</span>)</span>
    {
       <span class="hljs-comment">/*...*/</span>
    }
}
</code></pre>
<p>Eventually, you will have some extra work with your dependency injection tool:</p>
<pre><code class="lang-C#">Services.AddScoped&lt;ICatalogRepository, CatalogRepository&gt;();
</code></pre>
<p>Then, pass an <code>ICatalogRepository</code> as a parameter in a <code>Save</code> method:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-keyword">async</span> <span class="hljs-title">Save</span>(<span class="hljs-params">ICatalogRepository catalogRepository, Product product</span>)</span> 
{
    <span class="hljs-comment">/*Do some verifications before saving product in database...*/</span>
    <span class="hljs-keyword">await</span> catalogRepository.SaveProduct(product);
}
</code></pre>
<p>Now, let's switch to a more functional approach. You can write a static function that performs the save in the database :</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> Task <span class="hljs-title">SaveProduct</span>(<span class="hljs-params">DbContext context, Product product</span>)</span>
{
   <span class="hljs-comment">/*...*/</span>
}
</code></pre>
<p>Then, inject it in a <code>Save</code> method:</p>
<pre><code class="lang-C#"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">async</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Save</span>(<span class="hljs-params">Func&lt;DbContext, Product, Task&gt; SaveProduct, DbContext context, Product product</span>)</span> {
     <span class="hljs-comment">/*Do some verifications before saving product in database...*/</span>
    <span class="hljs-keyword">await</span> SaveProduct(context, product);
}
</code></pre>
<p>As you can see, the functional approach can save you some work: less boilerplate interface code, no dependency injection mechanism to deal with and easier testing with on-the-fly declared lambda functions. Think about it before writing interfaces.</p>
<h1 id="heading-some-drawbacks">Some drawbacks</h1>
<h2 id="heading-watch-out-for-external-libraries">Watch out for external libraries</h2>
<p>Some libraries may not be compatible with the fundamentals of functional thinking such as immutability. <strong>This is particularly the case of EF Core</strong> which needs write Therefore, avoid calling external libraries in your functional core as much as possible.</p>
<h2 id="heading-some-additional-work-to-deal-with-immutability">Some additional work to deal with immutability</h2>
<p>Since dealing with immutability implies making copies of data structures to modify them, more work has to be done on the constructors:</p>
<ul>
<li><p>Default constructors must be banned,</p>
</li>
<li><p>Depending on the call context, you may need to create several constructors to take into account the optional parameters,</p>
</li>
<li><p>It is necessary to check all the invariants in constructors to ensure the created data structure is valid.</p>
</li>
</ul>
<p>Immutability also involves more work in client code: creating a new object to modify it involves more code than directly updating it. This will be especially true for more complex data structures like DDD aggregates.</p>
<p>Immutability also means being constantly vigilant. For an object to be truly immutable, all of its attributes must be immutable. Particular care should be taken with reference types: collections, objects, etc. If one of a class's attributes is mutable then that class is not immutable.</p>
<h2 id="heading-performance-that-may-be-a-little-worse">Performance that may be a little worse</h2>
<p>Creating a new instance of an object to modify it creates a performance hit, especially <a target="_blank" href="https://learn.microsoft.com/en-us/archive/msdn-magazine/2017/march/net-framework-immutable-collections">on immutable collections in C#</a>. But these problems will only appear if you manipulate large amounts of data or perform complex calculations. In this case, it will be necessary to create optimized code by putting aside immutability.</p>
<h1 id="heading-summary">Summary</h1>
<ul>
<li><p>Functional thinking is simple and can be seen as a rigorous procedural programming style. It's a new way to think about our programs.</p>
</li>
<li><p>Functional thinking is applicable in any language. If it is an object language, it is possible to benefit from both paradigms.</p>
</li>
<li><p>Functional thinking brings a synergy of benefits to master our complex modern applications.</p>
</li>
<li><p>Be careful with external libraries that could be incompatible with the functional thinking fundamentals.</p>
</li>
<li><p>Some functional thinking fundamentals like immutability may require you to write more code, so use it wisely: in your core business areas, on features that require high reliability or in complex features.</p>
</li>
</ul>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>Messier 94, the Croc-eye galaxy, is located in the Canes Venatici constellation, about 16 million light-years from us. Its heart is extremely brilliant: it is a starburst galaxy. It means it exhibits an exceptional new star formation rate compared to other galaxies.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/galaxies/m94">See it in large size on my portfolio</a>.</p>
]]></content:encoded></item><item><title><![CDATA[What is sustainable software?]]></title><description><![CDATA[This is my first post on this blog. The idea of making one has been in my head for quite a while, so I give it a try.
As an introduction, I must quickly talk about my experience. I live in France, and I have two jobs. The first one is CTO and the sec...]]></description><link>https://www.bastienfoucher.net/what-is-sustainable-software</link><guid isPermaLink="true">https://www.bastienfoucher.net/what-is-sustainable-software</guid><category><![CDATA[sustainability]]></category><dc:creator><![CDATA[Bastien Foucher]]></dc:creator><pubDate>Tue, 20 Dec 2022 13:08:41 GMT</pubDate><enclosure url="https://cdn.hashnode.com/res/hashnode/image/upload/v1671374933531/jgzviap-V.jpg" length="0" type="image/jpeg"/><content:encoded><![CDATA[<p>This is my first post on this blog. The idea of making one has been in my head for quite a while, so I give it a try.</p>
<p>As an introduction, I must quickly talk about my experience. I live in France, and I have two jobs. The first one is CTO and the second one is about my passion: astrophotography.</p>
<p>My work as CTO is quite common. The other, astrophotographer, is not. It is about taking pictures of stars for entire nights: I had to travel the world in search of the most beautiful starry skies. Unfortunately, I have seen the damage that our modern societies inflict on the environment during my adventures. And digital is a big part of that.</p>
<p>I will not change things. But my experience allows me to activate a lever: to ensure that the software we develop is of high quality and that it lasts a long time.</p>
<h1 id="heading-what-is-sustainability">What is sustainability?</h1>
<p>Sustainability is <a target="_blank" href="https://en.wikipedia.org/wiki/Sustainability">officially</a> defined by three pillars of decreasing importance:</p>
<ol>
<li><p>Environment.</p>
</li>
<li><p>Society.</p>
</li>
<li><p>Economy.</p>
<p> <img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671546003025/uR582scFb.png" alt class="image--center mx-auto" /></p>
</li>
</ol>
<h1 id="heading-there-is-no-official-definition-of-sustainable-software">There is no official definition of sustainable software</h1>
<p>There is no official definition of sustainable software because it is a complicated topic. And I think those that are found on the Internet focus too much on <a target="_blank" href="https://principles.green/">performance and energy consumption</a>.</p>
<p>In reality, energy consumption is one impact factor amongst others. <a target="_blank" href="https://marmelab.com/blog/2022/01/27/greenframe-lemonde-reduction-impact-carbone.html">A special case</a> on one of the most visited website in France <a target="_blank" href="https://www.lemonde.fr">Le Monde.fr</a> shows that after several optimizations, only approximately 70 trees are saved per year. It is very good, but we have to admit that software optimization is not a truly efficient lever.</p>
<p>Other factors will harm the environment to a greater extent. One of the biggest is that some modern software only run on recent devices. The old ones will then become obsolete and will go to the trash. Windows 11 is a perfect example.</p>
<p>The other pillars (people, profit) are also forgotten in sustainable software definitions. For example, security and GDPR are related to the social pillar and I did not spot references to them. Yet it is a very important concern of modern computing because our data is shared and centralized in the cloud.</p>
<p>That is why I thought about my own definition of sustainable software.</p>
<h1 id="heading-implementing-sustainability-pillars">Implementing sustainability pillars</h1>
<p>So, as developers, how can we implement the three pillars of sustainability to create sustainable software? As discussed before, performance and energy consumption are not the only problems. I think we should keep these three principles in mind:</p>
<ol>
<li><p>Usefulness (environment, society and economy pillars).</p>
</li>
<li><p>Security (society and economy pillars).</p>
</li>
<li><p>Extensibility (economy pillar).</p>
</li>
</ol>
<p>We can create nested a view of sustainable software principles based on the sustainability pillars:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671546156589/KDDE_xxLj.png" alt class="image--center mx-auto" /></p>
<p>Let's examine these principles in detail now.</p>
<h2 id="heading-usefulness">Usefulness</h2>
<p>Useful software is the most important principle because it embeds answers to all the pillars of sustainability. Useful software is efficient, ergonomic and compatible with a maximum of networks and hardware, from the oldest to the most recent. This makes our digital equipment last which is the most powerful lever to reduce the impact of digital on the environment. For example, <a target="_blank" href="https://www2.deloitte.com/uk/en/insights/industry/technology/technology-media-and-telecom-predictions/2022/environmental-impact-smartphones.html">83% of the total smartphone CO2 emissions will come from manufacture</a>, shipping, and first-year use. The more software is useful and lasts, the less people buy new digital devices, the better it is for the planet.</p>
<p>Useful software can however degrade over time, it is necessary to remain vigilant. Two phenomena need to be monitored:</p>
<ul>
<li><p>The "<a target="_blank" href="https://en.wikipedia.org/wiki/Feature_creep">Feature Creep</a>" phenomenon: software is enriched with features that affect its usefulness.</p>
</li>
<li><p>The functional debt phenomenon: it is becoming more and more difficult to bring new features to the software while ensuring its current quality.</p>
</li>
</ul>
<p>Useless software is an evil in our industry. A study by consulting firm Standish Group "<a target="_blank" href="https://www.standishgroup.com%2Fsample_research_files%2FModernization.pdf&amp;usg=AOvVaw09_sZrjA9SDC-5ioarY4EF">Modernization</a>" claims that only 20% of software features are used. This value should be handled with care, but it shows the trend.</p>
<h2 id="heading-security">Security</h2>
<p>Security is a very important principle to answer the social pillar, especially today because a lot of our data is stored and shared in the cloud. To implement security in our software, we must think of the CIA cybersecurity triad:</p>
<ul>
<li><p><strong>Confidentiality</strong>: it concerns secret data that no one wishes to be made public. Our banking information for example.</p>
</li>
<li><p><strong>Integrity</strong>: only authorized processes should modify our data. A software bug or a vulnerability that leads our data to be changed is a security issue.</p>
</li>
<li><p><strong>Availability</strong>: our data must be available quickly. If our medical data is unavailable due to poor software performance during emergency care, we are in serious trouble.</p>
</li>
</ul>
<p>The security principle is also an answer to the economic pillar: security issues can lead to massive money losses. The famous Equifax data breach cost <a target="_blank" href="https://www.bankinfosecurity.com/equifaxs-data-breach-costs-hit-14-billion-a-12473">1.4 billion dollars</a> to the company.</p>
<h2 id="heading-extensibility">Extensibility</h2>
<p>Extensibility principle is an answer to the economy pillar: poorly extensible software may be phased out because of its rising maintenance costs. Productivity also decreases due to increasing <a target="_blank" href="https://en.wikipedia.org/wiki/Technical_debt">technical debt</a>, which leads to economic losses for companies.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1671545680575/Tl-3TwEgf.png" alt class="image--center mx-auto" /></p>
<h1 id="heading-summary">Summary</h1>
<p>Sustainable software integrates principles of usefulness, security and extensibility into each decision made all along its lifetime.</p>
<p>This is my vision of software sustainability. Some may not agree, but it is the one that, as a developer, best suits me at the moment. Throughout this blog, I will illustrate my posts using examples made with Microsoft environments (Azure, .Net).</p>
<h1 id="heading-about-the-cover-image">About the cover image</h1>
<p>IC 1848 is a pretty nebula located in the Cassiopeia constellation. It has the shape of a heart. The total exposure time is about 30 hours.</p>
<p><a target="_blank" href="https://www.bastienfoucher.com/en/galleries/nebulae-hubble-palette/ic1848Ame">See it in large size in my portfolio.</a></p>
]]></content:encoded></item></channel></rss>