<?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[Kuba's space]]></title><description><![CDATA[Kuba's space]]></description><link>https://blog.ciechowski.net</link><generator>RSS for Node</generator><lastBuildDate>Wed, 15 Apr 2026 01:26:17 GMT</lastBuildDate><atom:link href="https://blog.ciechowski.net/rss.xml" rel="self" type="application/rss+xml"/><language><![CDATA[en]]></language><ttl>60</ttl><item><title><![CDATA[Writing business oriented tests]]></title><description><![CDATA[It took me years to figure out what was wrong with writing tests against the implementation.I knew the theory. Focus on the business-specific behavior and write tests before an actual code.But it was hard. I never understood how I could write tests b...]]></description><link>https://blog.ciechowski.net/writing-business-oriented-tests</link><guid isPermaLink="true">https://blog.ciechowski.net/writing-business-oriented-tests</guid><category><![CDATA[Testing]]></category><category><![CDATA[DDD]]></category><category><![CDATA[product]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Wed, 14 Sep 2022 08:07:20 GMT</pubDate><content:encoded><![CDATA[<p>It took me years to figure out what was wrong with writing tests against the implementation.<br />I knew the theory. Focus on the business-specific behavior and write tests before an actual code.<br />But it was hard. I never understood how I could write tests before code. Are an existing solution not needed for the tests to make sense?  </p>
<p>Spoiler, it's not. If you think about the system as a product that has to deliver value, thinking about test scenarios ahead of the solution is more manageable.  </p>
<p>Imagine the following scenario where we accept a file through an API and want to parse it and read data.<br />From here, we can take two paths.   </p>
<ol>
<li>First one, just do it! Take an expected file, validate it using some method we wrote and then read the data because now we know that file is correct.</li>
<li>The second one, think before doing. 
Ok, we have to read a file. What file can we expect? Is the format fixed? What are we going to do in case of errors? How often will we receive such a file? The list goes on.</li>
</ol>
<h3 id="heading-the-lazy-way">The lazy way</h3>
<p>Using the first approach, we end up with the following test scenarios:</p>
<ul>
<li>When uploading a file, it should store the document</li>
<li>When uploading a file, it contains duplicates; it should store only distinct documents</li>
<li>When uploading a file with only not parsable rows; it should not be stored</li>
<li>When uploading a file and it is not CSV text content type, API should return a bad request</li>
</ul>
<p>It doesn't sound like a description of business behavior. Furthermore, there are many technical details here, like API and parsable rows. It requires a decent knowledge of the inner workings of the code to understand what's going on.</p>
<h3 id="heading-the-product-way">The product way</h3>
<p>Let's take the second path and start by describing expected behavior.</p>
<p>We know that we will receive a file. The file has to be in a specific format, CSV, in our case. It will contain errors, but we can't foresee all kinds of mistakes. When the file is ok, we store it in the database. Who can send us a file?</p>
<p>Now, we can state the problem in the form of test scenarios:</p>
<ul>
<li>Receiving a file with errors in the content should create a summary of mistakes. Going further, how do we handle different kinds of problems?</li>
<li>Discard the empty file.</li>
<li>The correct file should be stored in a database.</li>
<li>An unauthorized user sends a file.</li>
</ul>
<p>I found these scenarios more related to the real problem we are trying to solve. I don't need any knowledge about the details of the implementation. I  want to know if we modeled the process correctly.<br />Additionally, using such scenarios, we can find gaps in our understanding.</p>
<h3 id="heading-it-takes-time">It takes time</h3>
<p>Taking a more product-oriented approach is a skill that took me years to develop. It helped me in other areas and made me a better software developer. </p>
<p>Remember, part of the system you are working on is a more significant piece of the business process. Focus more on the business, and you will gain a lot.</p>
]]></content:encoded></item><item><title><![CDATA[Modeling exceptions]]></title><description><![CDATA[Modeling exceptions is hard. On the surface, it seems easy. Everyone knows what an exception is, right? But when you think deeper about it, there are a lot of traps that you can fall into. 
Throwing an exception is a goto
Exceptions are hidden goto s...]]></description><link>https://blog.ciechowski.net/modeling-exceptions</link><guid isPermaLink="true">https://blog.ciechowski.net/modeling-exceptions</guid><category><![CDATA[C#]]></category><category><![CDATA[Developer]]></category><category><![CDATA[Experience ]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Fri, 31 Dec 2021 12:00:05 GMT</pubDate><content:encoded><![CDATA[<p>Modeling exceptions is hard. On the surface, it seems easy. Everyone knows what an exception is, right? But when you think deeper about it, there are a lot of traps that you can fall into. </p>
<h2 id="heading-throwing-an-exception-is-a-goto">Throwing an exception is a goto</h2>
<p>Exceptions are hidden goto statements. That's one of the most significant troubles with them.<br />Whenever you notice a method that throws an exception and catches it in another place, stop for a moment. Such early returns make it hard to resonate about program control flow and make code difficult to refactor.</p>
<h2 id="heading-dont-use-exceptions-for-validation">Don't use exceptions for validation</h2>
<p>Very often, we use exceptions for validation.<br />Someone called your method with an empty string? Throw an exception!<br />Start date is older than the end date? Throw an exception!<br />Height is a negative number? Throw an exception!    </p>
<p>This doesn't mean that exceptions can't be used for validation.
For example, they are excellent when verifying input to the web API.  </p>
<p>But when working with business logic, take a look at different techniques:  </p>
<ul>
<li><a target="_blank" href="https://lexi-lambda.github.io/blog/2019/11/05/parse-don-t-validate/">Type Driven Programming</a></li>
<li><a target="_blank" href="https://fsharpforfunandprofit.com/posts/elevated-world-3/#example-validation-using-applicative-style-and-monadic-style">Result</a> types widely used in functional programming.</li>
</ul>
<h2 id="heading-when-to-throw">When to throw</h2>
<p>Having all that behind us, how do I know that specific situation should be modeled as an exception?<br />These questions can be helpful to ask:</p>
<ul>
<li>Do you know what to do when the case that seems like an exception occurs?</li>
<li>Is this exception a part of your domain?  </li>
</ul>
<p>If the answer to the first question is positive, just log the issue and move on.<br />The second question is more subtle and requires a bit of thinking.
 <a target="_blank" href="https://fsharpforfunandprofit.com/posts/designing-with-types-making-illegal-states-unrepresentable/">Scott Wlaschin has an excellent post on this issue</a>  </p>
<h2 id="heading-throw-in-an-elegant-way">Throw in an elegant way</h2>
<p>Finally, if you throw an exception, make the reason obvious.<br />Name it correctly using language from your domain. Default exceptions are rarely a good idea.<br />And remember that exceptions are written for other developers. Therefore, there is nothing wrong with keeping it technical.</p>
]]></content:encoded></item><item><title><![CDATA[Surround template for string interpolation in Jetbrains Rider]]></title><description><![CDATA[I dig string interpolation in C#. It is concise and easy to use. 
And even though JetBrains Rider is known for making developers super productive with all kinds of templates and shortcuts, there was one thing I've missed - the ability to surround a v...]]></description><link>https://blog.ciechowski.net/surround-template-for-string-interpolation-in-jetbrains-rider</link><guid isPermaLink="true">https://blog.ciechowski.net/surround-template-for-string-interpolation-in-jetbrains-rider</guid><category><![CDATA[C#]]></category><category><![CDATA[templates]]></category><category><![CDATA[Productivity]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Fri, 12 Nov 2021 13:22:24 GMT</pubDate><content:encoded><![CDATA[<p>I dig string interpolation in C#. It is concise and easy to use. 
And even though JetBrains Rider is known for making developers super productive with all kinds of templates and shortcuts, there was one thing I've missed - the ability to surround a variable with string interpolation.</p>
<h2 id="live-templates">Live templates</h2>
<p>Why not create such a template by yourself?<br />My problem was that I wanted to pass a stream name to the function but add some prefix to the stream beforehand.<br />My code looked like this:</p>
<pre><code><span class="hljs-selector-tag">eventStore</span><span class="hljs-selector-class">.SaveEvents</span>(streamName, events, eventMaxAge)
</code></pre><p>After the change, it should look like this:</p>
<pre><code><span class="hljs-selector-tag">eventStore</span><span class="hljs-selector-class">.SaveEvents</span>($<span class="hljs-string">"rev-{streamName}"</span>, events, eventMaxAge)
</code></pre><p>I've found string interpolation a perfect solution for this issue. But after doing it time and time again, I've got tired of doing it manually. 
I wanted an easy way to surround stream name with string interpolation. </p>
<h2 id="using-surround-template">Using surround template</h2>
<p>Then I've recalled that Rider has an option to surround a variable with brackets, for example.<br />Let's create such a template for string interpolation!<br />Try this sequence: double press shift, type live template, press enter, and voila!<br />From this place, you can create a new template. 
The one I've created looks like this:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636722757930/N8__2TslK.png" alt="image.png" /></p>
<p>How to use it?
Mark a variable you want to surround and press the shortcut set up for the "Surround with" command. In my case, it's ctrl+alt+j, but I've found my keyboard shortcuts relatively uncommon.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636723286303/tusFYaCgT.png" alt="image.png" /></p>
<p>After applying it using enter or pressing one, it will wrap the variable in a string interpolation like so:</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1636723311812/1DfhR2AUo.png" alt="image.png" /></p>
<p>And that's what I need!</p>
<p>Templates are great for automating tedious typing. Who doesn't like IntelliSense tailored to their needs?</p>
]]></content:encoded></item><item><title><![CDATA[Http call using F# and HttpClient]]></title><description><![CDATA[It took me a few tries to finally call an HTTP endpoint using F#.I've ended up with this code:
let result =
    async {
        let client = new HttpClient()
        let url = "https://api.frankfurter.app/latest?amount=10.99&from=USD&to=PLN"

       ...]]></description><link>https://blog.ciechowski.net/http-call-using-f-and-httpclient</link><guid isPermaLink="true">https://blog.ciechowski.net/http-call-using-f-and-httpclient</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[async]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sun, 24 Oct 2021 13:11:51 GMT</pubDate><content:encoded><![CDATA[<p>It took me a few tries to finally call an HTTP endpoint using F#.<br />I've ended up with this code:</p>
<pre><code><span class="hljs-keyword">let</span> result =
    <span class="hljs-keyword">async</span> {
        <span class="hljs-keyword">let</span> client = <span class="hljs-keyword">new</span> HttpClient()
        <span class="hljs-keyword">let</span> url = <span class="hljs-string">"https://api.frankfurter.app/latest?amount=10.99&amp;from=USD&amp;to=PLN"</span>

        <span class="hljs-keyword">let</span>! result =
            client.GetFromJsonAsync&lt;ApiResponse&gt;(url)
            |&gt; Async.AwaitTask

        printfn <span class="hljs-string">$"10.99 in USD is <span class="hljs-subst">{result.Rates.PLN}</span> in PLN"</span>
    }

result |&gt; Async.RunSynchronously
</code></pre><p>For my taste, it is very similar to the C# code.<br />The most significant difference lies in the async block.
It doesn't run until you do it explicitly!<br />In the C#, when you create a task, you have no control over when it starts. I've described one of such scenarios <a target="_blank">here</a>.</p>
<p>Only after calling <em>Async.RunSynchronously</em> the actual workflow runs. It reminds a bit of <em>await</em> instruction in C#, but the inner working is different.</p>
<p>The complete code is available on <a target="_blank" href="https://gist.github.com/jciechowski/0397ef73f889d7a652eb060bd51880d4">gist</a>.</p>
<p>I like this functional approach with cold workflows. It seems more intuitive to me. One downside I can see is that it may require more code. But I don't have enough experience with F# to be sure.</p>
]]></content:encoded></item><item><title><![CDATA[Partial application using delegates in C#]]></title><description><![CDATA[I'm a big proponent of using delegates instead of interfaces as described here.
Recently I've found out that it works wonderfully with the partial application!
Partial application is a concept widely used in functional programming. It's a function th...]]></description><link>https://blog.ciechowski.net/partial-application-using-delegates-in-c</link><guid isPermaLink="true">https://blog.ciechowski.net/partial-application-using-delegates-in-c</guid><category><![CDATA[C#]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sat, 25 Sep 2021 12:21:56 GMT</pubDate><content:encoded><![CDATA[<p>I'm a big proponent of using delegates instead of interfaces as described <a target="_blank" href="https://blog.ciechowski.net/interface-with-one-implementation-give-delegate-a-try">here</a>.
Recently I've found out that it works wonderfully with the partial application!</p>
<p>Partial application is a concept widely used in functional programming. It's a function that has parameters already baked into it.<br />Don't worry if this sounds strange. I hope the example will clear up everything.</p>
<p>When using a DI container, it's common to pass a dependency to our class only to pass it down to some other service. It leads to coupling and no clear separation of responsibilities.<br />What if we could pass a function that has all the dependencies already baked into it? That's precisely how partial application works!</p>
<p>First, create a delegate. It's an abstraction we will pass around. </p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">delegate</span> <span class="hljs-keyword">string</span> <span class="hljs-title">ReadById</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> id</span>)</span>;
</code></pre><p>Next, we create an implementation.</p>
<pre><code><span class="hljs-built_in">static</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DatabaseReader</span> </span>{
    <span class="hljs-built_in">static</span> <span class="hljs-keyword">string</span> ReadById(Database db, <span class="hljs-keyword">string</span> id) =&gt; db.Read(id);
}
</code></pre><p>Registration is the most tricky part.</p>
<pre><code>builder.Services.AddSingleton&lt;Database&gt;();
builder.Services.AddSingleton&lt;ReadById&gt;(<span class="hljs-function"><span class="hljs-params">x</span> =&gt;</span> 
  <span class="hljs-function"><span class="hljs-params">id</span> =&gt;</span> DatabaseReader.ReadById(x.GetRequiredService&lt;Database&gt;(), id));
</code></pre><p>Let's stop for a moment and dissect this construct.
First, we register a database using the usual approach.
Subsequently, we register the <code>ReadById</code> delegate using a partial application. 
We can use it like so:</p>
<pre><code><span class="hljs-keyword">class</span> <span class="hljs-title">ServiceUsingDelegate</span> {
    <span class="hljs-keyword">readonly</span> ReadById _reader;

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">ServiceUsingDelegate</span>(<span class="hljs-params">ReadById reader</span>)</span> =&gt; _reader = reader;

   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">DoingWork</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> id</span>)</span> =&gt; _reader(id);
}
</code></pre><p>Anytime we call the delegate, under the hood container will inject the database into it. We don't have to care about its dependencies at all!
How cool is that?</p>
<p>It allows our service to be solely focused on its task. We don't have to pass any extra params like a logger or mapper into it. We only use the specific function.</p>
<p>I've found such code in one of our projects recently and instantly fell in love with it.</p>
<p>What do you think about it?</p>
]]></content:encoded></item><item><title><![CDATA[Starting with SAFE Stack]]></title><description><![CDATA[Recently I've finally dug a bit deeper into the SAFE stack.One of the most exciting resources to start with full-stack F# applications was SAFE Dojo.
It doesn't require a lot of preparation. Just install .Net Core SDK version 5 or higher, and you are...]]></description><link>https://blog.ciechowski.net/starting-with-safe-stack</link><guid isPermaLink="true">https://blog.ciechowski.net/starting-with-safe-stack</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[full stack]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Wed, 25 Aug 2021 14:04:37 GMT</pubDate><content:encoded><![CDATA[<p>Recently I've finally dug a bit deeper into the SAFE stack.<br />One of the most exciting resources to start with full-stack F# applications was <a target="_blank" href="https://github.com/CompositionalIT/SAFE-Dojo">SAFE Dojo</a>.</p>
<p>It doesn't require a lot of preparation. Just install .Net Core SDK version 5 or higher, and you are ready to go!</p>
<p>You can find my solution on <a target="_blank" href="https://github.com/jciechowski/SAFE-Dojo/commit/0a6024237200c6816d9c1ccbaea22ec37b01e48f">github</a>.
But before reading it, I encourage you to try it by yourself.
It's enjoyable!</p>
<p>Stay tuned for more posts about applications written using the SAFE stack.</p>
]]></content:encoded></item><item><title><![CDATA[Await tasks with multiple result types]]></title><description><![CDATA[Regularly I want to await a few tasks and get their result. Surprisingly, there is no obvious way to do that. Task.WhenAll can be helpful, as we see later, but it doesn't solve the problem.My common scenario looks like this:
var dbTasks = getDataFrom...]]></description><link>https://blog.ciechowski.net/await-tasks-with-multiple-result-types</link><guid isPermaLink="true">https://blog.ciechowski.net/await-tasks-with-multiple-result-types</guid><category><![CDATA[C#]]></category><category><![CDATA[async]]></category><category><![CDATA[await]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sun, 25 Jul 2021 13:42:29 GMT</pubDate><content:encoded><![CDATA[<p>Regularly I want to await a few tasks and get their result. Surprisingly, there is no obvious way to do that. <em>Task.WhenAll</em> can be helpful, as we see later, but it doesn't solve the problem.<br />My common scenario looks like this:</p>
<pre><code><span class="hljs-keyword">var</span> dbTasks = getDataFromDbTasks();
<span class="hljs-keyword">var</span> otherServiceTasks = GetDataFromServiceTasks();

<span class="hljs-keyword">var</span> dbData = <span class="hljs-keyword">await</span> dbTasks;
<span class="hljs-keyword">var</span> otherServiceData = <span class="hljs-keyword">await</span> otherServiceTasks;
</code></pre><p>I found this approach very verbose. I prefer to await all the tasks at the same time.
That's why we have an extension method in our codebase specifically for this purpose:</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">class</span> <span class="hljs-title">TaskAwaiter</span> {
    <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-title">Task</span>&lt;<span class="hljs-title">ValueTuple</span>&lt;<span class="hljs-title">T1</span>, <span class="hljs-title">T2</span>&gt;&gt; <span class="hljs-title">AwaitAll</span>&lt;<span class="hljs-title">T1</span>, <span class="hljs-title">T2</span>&gt;(<span class="hljs-params">
        Task&lt;T1&gt; x,
        Task&lt;T2&gt; y</span>)</span> 
            =&gt; (<span class="hljs-keyword">await</span> x, <span class="hljs-keyword">await</span> y);
}
</code></pre><p>Such AwaitAll method simplifies the above code to this:</p>
<pre><code><span class="hljs-keyword">var</span> dbTask = getDataFromDbTask();
<span class="hljs-keyword">var</span> otherServiceTask = GetDataFromServiceTask();
<span class="hljs-keyword">var</span> (dbData, otherServiceData) = 
    <span class="hljs-keyword">await</span> TaskAwaiter.AwaitAll(dbTask , otherServiceTask);
</code></pre><p>That's precisely what I wanted! So far, so good.</p>
<p>But there is one caveat. What if I have a lot of tasks to await? I don't want to add another extension with more and more parameters.</p>
<p>Here <em>Task.WhenAll()</em> method becomes handy. It creates a single task that completes when all the other supplied tasks have been completed.  </p>
<p>Usage looks like follows:</p>
<pre><code><span class="hljs-keyword">var</span> dbTask = getDataFromDbTask();
<span class="hljs-keyword">var</span> singleTaskFromCollectionOfTasks = Task.WhenAll(CollectionOfTasks());

<span class="hljs-keyword">var</span> (dbData, singleTaskData) = 
    <span class="hljs-keyword">await</span> TaskAwaiter.AwaitAll(dbTasks, singleTaskFromCollectionOfTasks);
</code></pre><p>Armed with these two methods, I can quickly write meaningful and readable code.</p>
]]></content:encoded></item><item><title><![CDATA[Feature flags in GitLab]]></title><description><![CDATA[GitLab has built-in support for feature flags. Since I've become a big supporter of this approach, I was happy to see this. 
GitLab uses Unleash as a feature toggle service. It has a free, open-sourced client for many platforms and can be found on Nu...]]></description><link>https://blog.ciechowski.net/feature-flags-in-gitlab</link><guid isPermaLink="true">https://blog.ciechowski.net/feature-flags-in-gitlab</guid><category><![CDATA[GitLab]]></category><category><![CDATA[continuous deployment]]></category><category><![CDATA[continuous delivery]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Mon, 21 Jun 2021 11:12:31 GMT</pubDate><content:encoded><![CDATA[<p>GitLab has built-in support for feature flags. Since I've become a big supporter of this approach, I was happy to see this. </p>
<p>GitLab uses <a target="_blank" href="https://github.com/Unleash/unleash-client-dotnet">Unleash</a> as a feature toggle service. It has a free, open-sourced client for many platforms and can be found on NuGet. However, it is worth noticing that its .Net implementation requires Newtonsoft dependency. So let's try to make use of it in a .Net Core API.</p>
<p>First, we need to configure it. You can find settings in the Operations -&gt; Feature Flags sidebar menu. And then press the <em>configure</em> button.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624271118869/VGt318xkB.png" alt="feature-flags-configure.png" />
We are interested in the API URL and Instance ID settings from the dialog that pops up.
Now it's time to create a new feature flag called <em>feature-is-here</em> setup for all users and all environments to keep it simple.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1624271134906/mi44sO_SQ.png" alt="new-feature.png" /></p>
<p>It's worth examining the documentation because there are valuable strategies around the <a target="_blank" href="https://docs.gitlab.com/ee/operations/feature_flags.html#feature-flag-strategies">flags configuration</a>.</p>
<p>Armed with these variables, we are ready to write some code.</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">FeatureFlagsReader</span> {
    <span class="hljs-keyword">readonly</span> DefaultUnleash _defaultUnleash;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">FeatureFlagsReader</span>(<span class="hljs-params"></span>)</span> =&gt;
        _defaultUnleash = <span class="hljs-keyword">new</span> DefaultUnleash(<span class="hljs-keyword">new</span>()
        {
              AppName = <span class="hljs-string">"whathever-app-it-is"</span>,
            InstanceTag = <span class="hljs-string">"{Instance ID}"</span>,
            UnleashApi = <span class="hljs-keyword">new</span>(<span class="hljs-string">"{API URL}"</span>)
        });

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">ReadFor</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> flagName</span>)</span> =&gt; 
         _defaultUnleash.IsEnabled(flagName);
}
</code></pre><p>It makes sense to have only one instance of the feature flag client during the whole application lifetime. Therefore I register it as a singleton in default .Net Core DI container.</p>
<pre><code>services.AddSingleton<span class="hljs-tag">&lt;<span class="hljs-name">FeatureFlagsReader</span>&gt;</span>();
</code></pre><p>Now we can inject it into our controller and use it as we see fit:</p>
<pre><code>    [<span class="hljs-meta">ApiController</span>]
    <span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">BeautifulController</span> : <span class="hljs-title">ControllerBase</span> {
        <span class="hljs-keyword">readonly</span> FeatureFlagsReader _featureFlagsReader;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">BeautifulController</span>(<span class="hljs-params">FeatureFlagsReader featureFlagsReader</span>)</span> =&gt;
            _featureFlagsReader = featureFlagsReader;

        [<span class="hljs-meta">HttpGet(<span class="hljs-meta-string">"/featureFlag"</span>)</span>]
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> <span class="hljs-title">GetFeatureFlags</span>(<span class="hljs-params"></span>)</span> =&gt; 
            _featureFlagsReader.ReadFor(<span class="hljs-string">"feature-is-here"</span>).ToString();
    }
</code></pre><p>The whole code is available on my <a target="_blank" href="https://github.com/jciechowski/gitlab-feature-flags">GitHub</a>.</p>
<p>I think you agree that it's straightforward. Yet, please be aware that Unleash cache the feature flags values, so it takes some time to reflect the changes.</p>
]]></content:encoded></item><item><title><![CDATA[Making HTTP calls from inside Rider]]></title><description><![CDATA[I test my code with API calls all the time. Because of this, Rider HTTP Client is a lifesaver.Usually, I call some endpoint for a token and then try to get some data from the service. So let's try to use Rider for this case.
First, we have to run the...]]></description><link>https://blog.ciechowski.net/making-http-calls-from-inside-rider</link><guid isPermaLink="true">https://blog.ciechowski.net/making-http-calls-from-inside-rider</guid><category><![CDATA[C#]]></category><category><![CDATA[IDEs]]></category><category><![CDATA[http]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Wed, 26 May 2021 19:09:39 GMT</pubDate><content:encoded><![CDATA[<p>I test my code with API calls all the time. Because of this, Rider HTTP Client is a lifesaver.<br />Usually, I call some endpoint for a token and then try to get some data from the service. So let's try to use Rider for this case.</p>
<p>First, we have to run the client. We can do it from the tools menu.</p>
<p><img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1622055979148/V0H_Q_kWu.png" alt="rider_http_client.png" />
After that, it will pop up with an example request.
Let's first get a token from the service that we can use in subsequent calls.
You can do it like so:</p>
<pre><code>POST https://reqres.<span class="hljs-keyword">in</span>/api/register
Content-<span class="hljs-keyword">Type</span>: application/<span class="hljs-type">json</span>

{
  "email": "eve.holt@reqres.in",
  "password": "pistol"
}

&gt; {% client.<span class="hljs-keyword">global</span>.<span class="hljs-keyword">set</span>("access_token", response.body.token); %}
</code></pre><p>This call will send a POST request to https://reqres.in/ and save the token in a global variable called <em>access_token</em>.</p>
<p>Now let's get some data:</p>
<pre><code>GET https://reqres.in/api/users/2
<span class="hljs-section">Authorization: Bearer {{access_token}}</span>
<span class="hljs-section">Accept: application/json</span>
</code></pre><p>And that's all. We can call our services without getting out of the IDE.<br />Simple, isn't it?  </p>
<p>What's more, you can check a file with requests into your repository to always have them within reach.</p>
]]></content:encoded></item><item><title><![CDATA[Commit straight to production]]></title><description><![CDATA[How long is your deployment process? Does it take days or weeks before your code is on production? From my experience, it's at least a few days, usually weeks, until the official deployment is over.
I found such an approach wasteful. Why not commit s...]]></description><link>https://blog.ciechowski.net/commit-straight-to-production</link><guid isPermaLink="true">https://blog.ciechowski.net/commit-straight-to-production</guid><category><![CDATA[continuous deployment]]></category><category><![CDATA[ci-cd]]></category><category><![CDATA[Continuous Integration]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sat, 22 May 2021 12:35:13 GMT</pubDate><content:encoded><![CDATA[<p>How long is your deployment process? Does it take days or weeks before your code is on production? From my experience, it's at least a few days, usually weeks, until the official deployment is over.</p>
<p>I found such an approach wasteful. Why not commit straight to production? </p>
<h2 id="deployment-vs-release">Deployment vs. release</h2>
<p>What's the difference between deployment and release?<br />Deployment happens when a new version of code appears on the server. It doesn't have to be visible yet.<br />On the other hand, the release means that some new feature is available to some of our users. </p>
<p>There is no need to do both in the same step.</p>
<h2 id="feature-flags">Feature flags</h2>
<p>Taking these definitions into account, we should decouple deployment from release.
And it's easy to do so with feature flags. They are becoming more and more popular.<br />Some CI/CD tools (e.g., <a target="_blank" href="https://docs.gitlab.com/ee/operations/feature_flags.html">Gitlab</a> ) have APIs for this job.</p>
<h2 id="commit-to-production">Commit to production</h2>
<p>Assuming we can hide our code behind a toggle, nothing stops us from pushing straight to production.<br />So what can we gain from this?</p>
<ul>
<li>frequent deployments make our CI/CD pipeline more healthy</li>
<li>the release is now only a toggle switch</li>
<li>you can plan releases separately from deployments</li>
</ul>
<p>Of course, there is also a downside of having to maintain feature toggles. After every release, they become obsolete, and you have to clean them up.<br />But the amount of time saved on a faster deployment pipeline is more than enough to take care of old toggles.</p>
]]></content:encoded></item><item><title><![CDATA[Domain modeling in F#]]></title><description><![CDATA[How often do you see an email represented as a string? Or a currency field being a decimal type? Did you ever consider that something is wrong with this approach?
That's the usual manifestation of primitive obsession. It occurs when you use primitive...]]></description><link>https://blog.ciechowski.net/domain-modeling-in-f</link><guid isPermaLink="true">https://blog.ciechowski.net/domain-modeling-in-f</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[DDD]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Thu, 22 Apr 2021 18:44:25 GMT</pubDate><content:encoded><![CDATA[<p>How often do you see an email represented as a string? Or a currency field being a decimal type? Did you ever consider that something is wrong with this approach?</p>
<p>That's the usual manifestation of primitive obsession. It occurs when you use primitive types like strings or decimals for domain modeling. I argue that the reason behind it is laziness and being scared of introducing too many types.</p>
<h3 id="type-aliases-and-record-types">Type aliases and record types</h3>
<p>Luckly, F# got you covered!<br />Aliases and records make creating new types both enjoyable and easy.
Have a look at this code:</p>
<pre><code><span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">StationName</span></span> = StationName of string
<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">StationCode</span></span> = StationCode of string

<span class="hljs-class"><span class="hljs-keyword">type</span> <span class="hljs-title">Station</span></span> =
    { Name: StationName
      StationCode: StationCode }
</code></pre><p>We just defined Station that consists of a name and a code.<br />It's plain English! I like how obvious and readable it is. In the end, we don't have to care what's behind these fields. That should be an implementation detail.</p>
<p>If someday we want to change StationCode to a number instead of a string, we do it in one place, and the rest of the code should stay the same.<br />Yes, it's that helpful!</p>
<h3 id="custom-types-requires-custom-code">Custom types requires custom code</h3>
<p>There is a caveat, of course.<br />We can't use the usual string methods on such alias types.<br />How to deal with this? I will try to address this in another post.</p>
]]></content:encoded></item><item><title><![CDATA[Abstract current time using function in C#]]></title><description><![CDATA[I've seen many ways to deal with date and time. Hiding it behind an interface, a static class with a single property, ambient context, you name it. I never liked any of them.
Then the enlightenment came. In one of the projects, I've seen a function u...]]></description><link>https://blog.ciechowski.net/abstract-current-time-using-function-in-c</link><guid isPermaLink="true">https://blog.ciechowski.net/abstract-current-time-using-function-in-c</guid><category><![CDATA[C#]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Fri, 09 Apr 2021 19:19:27 GMT</pubDate><content:encoded><![CDATA[<p>I've seen many ways to deal with date and time. Hiding it behind an interface, a static class with a single property, ambient context, you name it. I never liked any of them.</p>
<p>Then the enlightenment came. In one of the projects, I've seen a function used to get the current time.<br />I've never thought of that! It doesn't need much code to put into use and is simple to test.<br />Take a look at an example.  </p>
<p>First, you create a function for getting the current time and then pass it to the DateRangeCalculator.</p>
<pre><code>public <span class="hljs-keyword">void</span> ConfigureServices(IServiceCollection services)
{
    Func&lt;<span class="hljs-built_in">DateTime</span>&gt; getCurrentTime = () =&gt; <span class="hljs-built_in">DateTime</span>.Now;
    services.AddSingleton(_ =&gt; <span class="hljs-keyword">new</span> DateRangeCalculator(getCurrentTime));
}
</code></pre><p>Our calculator implementation can look like this:</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-keyword">class</span> <span class="hljs-title">DateRangeCalculator</span> {
    <span class="hljs-keyword">readonly</span> Func&lt;DateTime&gt; _getCurrentTime;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DateRangeCalculator</span>(<span class="hljs-params">Func&lt;DateTime&gt; getCurrentTime</span>)</span> =&gt;
       _getCurrentTime = getCurrentTime;

    <span class="hljs-function"><span class="hljs-keyword">public</span> DateTime <span class="hljs-title">GetLastMonth</span>(<span class="hljs-params"></span>)</span>
    {
        <span class="hljs-keyword">var</span> currentTime = _getCurrentTime();
        <span class="hljs-keyword">var</span> previousMonth = currentTime.Date.AddMonths(<span class="hljs-number">-1</span>);

        <span class="hljs-keyword">return</span> previousMonth;
    }
}
</code></pre><p>If you prefer a more functional approach, change GetLastMonth method to static and drop the constructor. I will leave it to you as an exercise.</p>
<p>How to test a class with such dependency?<br />Just replace the implementation in the test like so:</p>
<pre><code>[Fact]
public <span class="hljs-keyword">void</span> PreviousMonthRangeCalculator()
{
    Func&lt;<span class="hljs-built_in">DateTime</span>&gt; currentTime = () =&gt; <span class="hljs-keyword">new</span> <span class="hljs-built_in">DateTime</span>(<span class="hljs-number">2021</span>, <span class="hljs-number">1</span>,<span class="hljs-number">1</span>);

    <span class="hljs-keyword">var</span> result = DateRangeCalculator.GetLastMonth(currentTime);

    result.Month.Should().Be(<span class="hljs-number">12</span>);
}
</code></pre><p>I like this idea because it doesn't require an interface with one method.<br />When it comes to tests, there is no need to create a mock class.<br />Less boilerplate, more readable code, what more do you need?</p>
]]></content:encoded></item><item><title><![CDATA[Table driven development]]></title><description><![CDATA[How do you start a new project? From my experience, most of the projects begin with a search for a verb. Not any verbs. The important ones!
The question arises, how do you spot the important one? That depends on the domain, of course. 
As an example,...]]></description><link>https://blog.ciechowski.net/table-driven-development</link><guid isPermaLink="true">https://blog.ciechowski.net/table-driven-development</guid><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Tue, 30 Mar 2021 19:39:37 GMT</pubDate><content:encoded><![CDATA[<p>How do you start a new project? From my experience, most of the projects begin with a search for a verb. Not any verbs. The important ones!</p>
<p>The question arises, how do you spot the important one? That depends on the domain, of course. </p>
<p>As an example, imagine we start modeling a new system for an insurance company. The usual suspects are insurance, policy, the insured person, insured object, and so on. Add user and privileges into the mix and, we are done!  We discovered all our database tables. </p>
<p>What's the next step?<br />We have to add more flavor to our models. The policy will have some end dates, an insured person, and insured objects. The insurance will have insurance amounts and particular cases it covers, e.g., broken leg. Call this risk.<br />Does it make sense so far? Our model is almost ready!</p>
<p>Finally, we can add behavior. Policy end validation, checking if the policy covers the incident, paying money to the correct person. We are ready to put it somewhere inside our model.</p>
<p>Does it sound familiar? I did many systems like that.</p>
<p>It leads to spaghetti code. It leads to losing information. It leads to generic services. It's throwing up roadblocks for your project. And you did it to yourself.</p>
<p>How to avoid that? Focus on behavior from day one. Try to come up with a way to model business processes. Work on a common language.<br />Maybe give EventStorming a try? At least try to visualize usages of your system.</p>
<p>After that, try to  <a target="_blank" href="https://blog.ciechowski.net/why-you-need-a-domain-model">create a domain model</a> ? </p>
]]></content:encoded></item><item><title><![CDATA[Improve class coherency with local functions]]></title><description><![CDATA[I was full of doubt about local functions at first. They break some dogmas for me. For example, return from the method isn't the last statement anymore.
Then I started to use them. Now I can say that this idea makes code more readable and keep classe...]]></description><link>https://blog.ciechowski.net/improve-class-coherency-with-local-functions</link><guid isPermaLink="true">https://blog.ciechowski.net/improve-class-coherency-with-local-functions</guid><category><![CDATA[C#]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Tue, 09 Mar 2021 07:37:24 GMT</pubDate><content:encoded><![CDATA[<p>I was full of doubt about local functions at first. They break some dogmas for me. For example, return from the method isn't the last statement anymore.</p>
<p>Then I started to use them. Now I can say that this idea makes code more readable and keep classes more coherent.</p>
<p>Before introducing local functions in C# 7, extracting part of the code required a private method. Of course, one can say that it's still hidden from the outside, but it always felt awkward.</p>
<p>Take this code:</p>
<pre><code><span class="hljs-keyword">class</span> <span class="hljs-title">PersonCreator</span> {
  <span class="hljs-function"><span class="hljs-keyword">public</span> Person <span class="hljs-title">CreatePerson</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> login, <span class="hljs-keyword">string</span> email</span>)</span>
  {
    <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrWhiteSpace(login) &amp;&amp; EmailIsValid(email))
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(login, email);

    <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;
  }

  <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">bool</span> <span class="hljs-title">EmailIsValid</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> email</span>)</span> =&gt;
    Regex.IsMatch(email,
        <span class="hljs-string">@"^[^@\s]+@[^@\s]+\.[^@\s]+$"</span>);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> record <span class="hljs-title">Person</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> Login, <span class="hljs-keyword">string</span> Email</span>)</span>;
</code></pre><p>This approach isn't flawed. But like <em>EmailIsValid</em> method shouldn't be part of the <em>PersonCreator</em> class, even a private one.</p>
<p>How can we refactor this to a local function? </p>
<p>Our method could look like this:</p>
<pre><code><span class="hljs-function">Person <span class="hljs-title">CreatePerson</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> login, <span class="hljs-keyword">string</span> email</span>)</span>
{
  <span class="hljs-keyword">if</span> (!<span class="hljs-keyword">string</span>.IsNullOrWhiteSpace(login) &amp;&amp; EmailIsValid())
    <span class="hljs-keyword">return</span> <span class="hljs-keyword">new</span> Person(login, email);

  <span class="hljs-keyword">return</span> <span class="hljs-literal">null</span>;

  <span class="hljs-function"><span class="hljs-keyword">bool</span> <span class="hljs-title">EmailIsValid</span>(<span class="hljs-params"></span>)</span> =&gt;
    Regex.IsMatch(email,
        <span class="hljs-string">@"^[^@\s]+@[^@\s]+\.[^@\s]+$"</span>);
}
</code></pre><p>We can skip a parameter because of closure. </p>
<p>In the end, it will get compiled to the private method anyway. But I found this code cleaner and easier to maintain.</p>
<p>What's your approach to local functions?</p>
]]></content:encoded></item><item><title><![CDATA[Using collections with MemberData attribute in F#]]></title><description><![CDATA[Working with collections of custom types in xUnit always felt clumsy. To pass such a set of data, you had either create a property or a whole class.
No matter which options you choose, it's a lot of boilerplate.
What a pleasant surprise was how less ...]]></description><link>https://blog.ciechowski.net/using-collections-with-memberdata-attribute-in-f</link><guid isPermaLink="true">https://blog.ciechowski.net/using-collections-with-memberdata-attribute-in-f</guid><category><![CDATA[Functional Programming]]></category><category><![CDATA[unit testing]]></category><category><![CDATA[.NET]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sun, 21 Feb 2021 19:09:23 GMT</pubDate><content:encoded><![CDATA[<p>Working with collections of custom types in xUnit always felt clumsy. To pass such a set of data, you had either create a property or a whole class.
No matter which options you choose, it's a lot of boilerplate.</p>
<p>What a pleasant surprise was how less cumbersome it is to do in F#.</p>
<p>The plan is to compare two value objects defined as a type alias:</p>
<pre><code><span class="hljs-keyword">type</span> StationName = StationName of <span class="hljs-keyword">string</span>
</code></pre><p>The test doesn't require much code as well.</p>
<pre><code>[<span class="hljs-meta">&lt;Theory&gt;</span>]
[<span class="hljs-meta">&lt;MemberData(nameof (stationsData))&gt;</span>]
<span class="hljs-keyword">let</span> ``compare stations correctly`` (station, otherStation, expected) =
    <span class="hljs-keyword">let</span> result = station = otherStation
    Assert.Equal(expected, result)
</code></pre><p>C# developers, watch out for <code>=</code> comparison!</p>
<p>And now the clou. 
Take a look at <code>stationsData</code> definition:</p>
<pre><code>let stationsData: seq&lt;<span class="hljs-keyword">array</span>&lt;<span class="hljs-keyword">Object</span>&gt;&gt; =
    seq {
        <span class="hljs-keyword">yield</span>
            [| <span class="hljs-string">"Sopot"</span> |&gt; StationName
               <span class="hljs-string">"Sopot"</span> |&gt; StationName
               <span class="hljs-literal">true</span>
               |]
        <span class="hljs-keyword">yield</span>
            [| <span class="hljs-string">"Sopot"</span> |&gt; StationName
               <span class="hljs-string">"Gdynia"</span> |&gt; StationName
               <span class="hljs-literal">false</span> |]
    }
</code></pre><p>Instead of the type definition for <code>stationsData</code> you could omit it and box every value using <code>|&gt; box</code>. I found the former approach more readable.</p>
<p>Anyway, that's all the code you need. Simple, isn't it?</p>
]]></content:encoded></item><item><title><![CDATA[Using tuples for validations]]></title><description><![CDATA[Many functional techniques are proving their ground in C# codebases. One of my favorites is the Result type. The most basic form consists of a boolean flag indicating success and an array of errors. But in many cases, tuples are just enough. 
I fall ...]]></description><link>https://blog.ciechowski.net/using-tuples-for-validations</link><guid isPermaLink="true">https://blog.ciechowski.net/using-tuples-for-validations</guid><category><![CDATA[C#]]></category><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Tue, 09 Feb 2021 20:03:31 GMT</pubDate><content:encoded><![CDATA[<p>Many functional techniques are proving their ground in C# codebases. One of my favorites is the <code>Result</code> type. The most basic form consists of a boolean flag indicating success and an array of errors. But in many cases, tuples are just enough. </p>
<p>I fall in love with value tuples since their introduction in C# 7. They are perfect when you need a local data structure with a concise syntax.
One of the most common usages of this feature is validation. Add to this switch expression, and we have a great combo.</p>
<p>Validating PIN was never so easy:</p>
<pre><code>(<span class="hljs-keyword">bool</span> Success, <span class="hljs-keyword">string</span> ErrorMessage) ValidatePIN(<span class="hljs-keyword">string</span> pin) =&gt;
    pin <span class="hljs-keyword">switch</span>
    {
        <span class="hljs-literal">null</span> =&gt;
            (<span class="hljs-literal">false</span>, <span class="hljs-string">"Missing value"</span>),
        <span class="hljs-keyword">var</span> p when p.Length &gt; <span class="hljs-number">4</span> =&gt;
            (<span class="hljs-literal">false</span>, <span class="hljs-string">"PIN is too long"</span>),
        <span class="hljs-keyword">var</span> p when !<span class="hljs-keyword">int</span>.TryParse(p, out _) =&gt;
            (<span class="hljs-literal">false</span>, <span class="hljs-string">"PIN has to be a number"</span>),
        _ =&gt;
            (<span class="hljs-literal">true</span>, <span class="hljs-keyword">string</span>.<span class="hljs-keyword">Empty</span>)
    };
</code></pre><p>I'm a big fan of such an approach. I admit it was intimidating at first. But after a few tries of writing code in such a manner, I think this is the way.</p>
]]></content:encoded></item><item><title><![CDATA[Creating tasks in batches]]></title><description><![CDATA[Recently I've learned that you have no control over tasks after initialization. Awaiting a job is just a way to synchronize and get a response. That naturally brings a question. How to split asynchronous calls into batches?
A case from the trenches
L...]]></description><link>https://blog.ciechowski.net/creating-tasks-in-batches</link><guid isPermaLink="true">https://blog.ciechowski.net/creating-tasks-in-batches</guid><category><![CDATA[C#]]></category><category><![CDATA[asynchronous]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Tue, 26 Jan 2021 09:45:10 GMT</pubDate><content:encoded><![CDATA[<p>Recently I've learned that you have no control over tasks after initialization. Awaiting a job is just a way to synchronize and get a response. That naturally brings a question. How to split asynchronous calls into batches?</p>
<h3 id="a-case-from-the-trenches">A case from the trenches</h3>
<p>Let's say we have a collection of some newly created entities. We want to send them to an external service. But it's API isn't convenient. It requires one save call per element.</p>
<p>Sadly, we don't know how numerous our collection is. Therefore it's hard to reckon how many calls we will have to make. I had no idea how to solve this issue.</p>
<p>Bright colleagues to the rescue! They have pointed me to unique code in one of our repositories. Then, they explained it to me until I finally caught it. That part was tricky. It took me a few tries. 
And the solution goes like that:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">async</span> Task <span class="hljs-title">ExecuteWithMaxParallelism</span>&lt;<span class="hljs-title">T</span>&gt;(<span class="hljs-params">
    IEnumerable&lt;T&gt; items,
    Func&lt;T, Task&lt;T&gt;&gt; externalCall
</span>)</span> {
    <span class="hljs-keyword">const</span> <span class="hljs-keyword">int</span> maxParallelism = <span class="hljs-number">10</span>;
    <span class="hljs-keyword">var</span>       queue          = <span class="hljs-keyword">new</span> ConcurrentQueue&lt;T&gt;(items);

    <span class="hljs-keyword">var</span> tasks = Enumerable.Range(<span class="hljs-number">0</span>, maxParallelism)
        .Select(
            _ =&gt; Task.Run(
                <span class="hljs-keyword">async</span> () =&gt; {
                    <span class="hljs-keyword">while</span> (queue.TryDequeue(<span class="hljs-keyword">out</span> <span class="hljs-keyword">var</span> item)) {
                        <span class="hljs-keyword">await</span> externalCall(item);
                    }
                }
            )
        );

    <span class="hljs-keyword">await</span> Task.WhenAll(tasks);
}
</code></pre><p>The idea behind this piece of code is straightforward. It creates a determined number of tasks and allows them to make external calls in their tempo. </p>
<p>Let's go through it step by step.</p>
<p>First, we create a <code>ConcurrentQueue</code> with all items we have to save.
By using the concurrent version of the Queue, we avoid sending the same item more than once.<br />After that, we spawn a collection of 10 tasks.<br />Subsequently, those ten tasks will try to pick an item from the Queue and make the request.<br />Finally, we call <code>Task.WhenAll</code> to synchronize the result. </p>
<p>Using this method, we were able to limit the number of requests. Which, in turn, improved the performance of our service.</p>
]]></content:encoded></item><item><title><![CDATA[Partial file staging with git]]></title><description><![CDATA[After typing git status you can see files in three states:

added to the index
not added to the index
not tracked at all  

It's likely to have the same file added and not added to the index.
How is that possible?
Let me introduce partial file stagin...]]></description><link>https://blog.ciechowski.net/partial-file-staging-with-git</link><guid isPermaLink="true">https://blog.ciechowski.net/partial-file-staging-with-git</guid><category><![CDATA[Git]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Tue, 12 Jan 2021 12:02:30 GMT</pubDate><content:encoded><![CDATA[<p>After typing <code>git status</code> you can see files in three states:</p>
<ul>
<li>added to the index</li>
<li>not added to the index</li>
<li>not tracked at all  </li>
</ul>
<p>It's likely to have the same file added and not added to the index.
How is that possible?</p>
<p>Let me introduce partial file staging. What does it do?
It allows you to add only specific changes to the index.
For example, you want to add only new code without format changes in the whole file.</p>
<p>I'm a big fan of this approach because it allows you to create small semantic commits. 
There is one catch that always makes me search the docs, though. 
Git will try to split all the changes for you. You will see each change and decide if you want to stage it or not.
But what happens when git is wrong or the change is too big, and it can't split it further?</p>
<p>Of course, you can edit the so-called <em>hunk</em> manually. And this is the place where I always fail.</p>
<p>Let's take a look at an example.
After typing <code>git add -p</code>, we see this.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610451983193/xTLabvNAk.png" alt="change.png" /></p>
<p>I want to add only one endpoint. This change is too big, so I press <code>e</code> and edit hunk manually.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610451995265/U5bc4F7f7c.png" alt="edited-hunk.png" /></p>
<p>This picture always looks scary to me.
There is some manual under the code, but I never understood it.
What to do to keep just one of the changes?
Just delete the parts that you don't need!
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610452018516/eAJMYWyYe.png" alt="edited-hunk.png" /></p>
<p>Now we can save it and close the editor.
The current status looks like this:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610452024665/tIi-4uzP-.png" alt="status-after-edit.png" /></p>
<p>I have two changes, and only one ready to be committed. I can verify it with <code>git diff --cached</code>
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610452030614/E23_bJKKO.png" alt="diff-cached.png" /></p>
<p>Perfect!
And where is the other change?
You should see it after <code>git diff</code>.
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610452036932/cLI8MaaFg.png" alt="diff.png" /></p>
<p>I'm ready to create two distinct commits.<br /><code>git commit -m 'Added default endpoint'</code><br />And after adding the second change to the index.<br /><code>git add .; git commit -m 'Ping endpoint'</code><br />The final stage looks like this:
<img src="https://cdn.hashnode.com/res/hashnode/image/upload/v1610452801084/dekkDFiBV.png" alt="git-log.png" /></p>
<p>Partial file staging is a powerful feature. At first glance, it can look cumbersome and not very intuitive. I use it daily, and after a few tries, it became my second nature.</p>
]]></content:encoded></item><item><title><![CDATA[Tuple vs multiple params in F# functions]]></title><description><![CDATA[In my mind, the F# code was almost braceless. I enjoyed reading it because it felt so natural.Recently, I wrote a bit of F# code. And guess what? There were way too many braces for my taste.Take a look at this code:
let extractNumbers (numbers: Input...]]></description><link>https://blog.ciechowski.net/tuple-vs-multiple-params-in-f-functions</link><guid isPermaLink="true">https://blog.ciechowski.net/tuple-vs-multiple-params-in-f-functions</guid><category><![CDATA[Functional Programming]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Sat, 19 Dec 2020 10:33:24 GMT</pubDate><content:encoded><![CDATA[<p>In my mind, the F# code was almost braceless. I enjoyed reading it because it felt so natural.<br />Recently, I wrote a bit of F# code. And guess what? There were way too many braces for my taste.<br />Take a look at this code:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">let</span> <span class="hljs-title">extractNumbers</span> (<span class="hljs-params">numbers: Input, delimiterType: DelimiterType</span>)
<span class="hljs-keyword">let</span> numbers</span> = extractNumbers (input, delimiterType)
</code></pre><p>Braces all over the place! How did it happen? Was my initial feeling wrong?</p>
<p>Not at all. I've used it wrong. I didn't know how to declare a function with multiple params. Instead, I've defined a tuple as an input.<br />An improved version could look like this:</p>
<pre><code><span class="hljs-function"><span class="hljs-keyword">let</span> <span class="hljs-title">extractNumbers</span> (<span class="hljs-params">numbers: Input</span>) (<span class="hljs-params">delimiterType: DelimiterType</span>)
<span class="hljs-keyword">let</span> numbers</span> = extractNumbers input delimiterType
</code></pre><p>Can you spot the difference?<br />I've changed the definition of the function. Instead of a tuple, now it takes two parameters. I've only skipped coma between the params. And now I feel much better about this code. </p>
]]></content:encoded></item><item><title><![CDATA[Emberace MemberData attribute.]]></title><description><![CDATA[Naming is hard. Well described test suites are even harder. I've seen a lot of tests that goes like this:
[MemberData(nameof(Data))]
public void EmailValidator_Should_Validate_Correctly(
    string data, bool expected)
{
  var emailValidator = new Em...]]></description><link>https://blog.ciechowski.net/emberace-memberdata-attribute</link><guid isPermaLink="true">https://blog.ciechowski.net/emberace-memberdata-attribute</guid><category><![CDATA[C#]]></category><category><![CDATA[unit testing]]></category><dc:creator><![CDATA[Kuba Ciechowski]]></dc:creator><pubDate>Mon, 14 Dec 2020 15:47:50 GMT</pubDate><content:encoded><![CDATA[<p>Naming is hard. Well described test suites are even harder. I've seen a lot of tests that goes like this:</p>
<pre><code>[<span class="hljs-meta">MemberData(nameof(Data))</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">EmailValidator_Should_Validate_Correctly</span>(<span class="hljs-params">
    <span class="hljs-keyword">string</span> data, <span class="hljs-keyword">bool</span> expected</span>)</span>
{
  <span class="hljs-keyword">var</span> emailValidator = <span class="hljs-keyword">new</span> EmailValidator();
  <span class="hljs-keyword">var</span> result = emailValidator.Validate(data);

  Assert.Equal(expected, result);
}
</code></pre><p>As you may expect, I wasn't happy with this boilerplate code as well.<br />But let's focus on something else. I see a few issues with the name of the test:</p>
<ul>
<li>it doesn't describe any business behavior</li>
<li>it's hard to read because it doesn't follow English grammar</li>
<li>it includes the name of the service  </li>
</ul>
<p>Sadly, this is the desired template of any test you wrote in that specific codebase.</p>
<p>How can we convey any meaning in such a situation?
Embrace the MemberData attribute!</p>
<p>Usually, our data collection has a few entries. It can look like this:</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> IEnumerable&lt;<span class="hljs-keyword">object</span>[]&gt; Data =&gt;
    <span class="hljs-keyword">new</span> <span class="hljs-keyword">List</span>&lt;<span class="hljs-keyword">object</span>[]&gt;
    {
        <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[] {
            <span class="hljs-string">"donatello@example.com"</span>, <span class="hljs-literal">true</span>,
            <span class="hljs-string">"donatello.turtles@example.com"</span>, <span class="hljs-literal">true</span>,
            <span class="hljs-string">"leonardo@examplecom"</span>, <span class="hljs-literal">false</span>,
            <span class="hljs-string">"leonardo.example.com"</span>, <span class="hljs-literal">false</span>
        }
    };
</code></pre><p>Do you see the pattern? Try to make use of it and split the entries.<br />Divide it  as follows:</p>
<pre><code><span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> IEnumerable&lt;<span class="hljs-keyword">object</span>[]&gt; ValidEmails =&gt;
 <span class="hljs-keyword">new</span> <span class="hljs-keyword">List</span>&lt;<span class="hljs-keyword">object</span>[]&gt;
 {
   <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[] {
    <span class="hljs-string">"donatello@example.com"</span>, <span class="hljs-literal">true</span>,
    <span class="hljs-string">"donatello.the.turtle@example.com"</span>, <span class="hljs-literal">true</span>,
   }
 };
<span class="hljs-keyword">public</span> <span class="hljs-built_in">static</span> IEnumerable&lt;<span class="hljs-keyword">object</span>[]&gt; InvalidEmails =&gt;
 <span class="hljs-keyword">new</span> <span class="hljs-keyword">List</span>&lt;<span class="hljs-keyword">object</span>[]&gt;
 {
   <span class="hljs-keyword">new</span> <span class="hljs-keyword">object</span>[] {
    <span class="hljs-string">"leonardo@examplecom"</span>, <span class="hljs-literal">false</span>,
    <span class="hljs-string">"leonardo.example.com"</span>, <span class="hljs-literal">false</span>
 }
};
</code></pre><p>Follow by the test:</p>
<pre><code>[<span class="hljs-meta">MemberData(nameof(ValidEmails))</span>]
[<span class="hljs-meta">MemberData(nameof(InvalidEmails))</span>]
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Should_Validate_Correctly</span>(<span class="hljs-params"><span class="hljs-keyword">string</span> data,<span class="hljs-keyword">bool</span> expected</span>)</span>
{
    <span class="hljs-keyword">var</span> emailValidator = <span class="hljs-keyword">new</span> EmailValidator();
    <span class="hljs-keyword">var</span> result = emailValidator.Validate(data);

    Assert.Equal(expected, result);
}
</code></pre><p>Of course, one could argue that it won't change much. We can't see that modification in a test runner window. And that's true. We have to open the file and read its content anyway. But it's a step in the right direction.</p>
]]></content:encoded></item></channel></rss>