<?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" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Nash on Medium]]></title>
        <description><![CDATA[Stories by Nash on Medium]]></description>
        <link>https://medium.com/@rhenache?source=rss-9660a5b77c89------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*MhKIS-_BwdTfjlEG061B3g.jpeg</url>
            <title>Stories by Nash on Medium</title>
            <link>https://medium.com/@rhenache?source=rss-9660a5b77c89------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 19:25:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rhenache/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Resolve cyclic dependencies with Castle Windsor]]></title>
            <link>https://rhenache.medium.com/resolve-cyclic-dependencies-with-castle-windsor-5a6842b4f387?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a6842b4f387</guid>
            <category><![CDATA[ioc]]></category>
            <category><![CDATA[castle-windsor]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Wed, 05 Mar 2025 13:19:01 GMT</pubDate>
            <atom:updated>2025-03-05T13:19:01.470Z</atom:updated>
            <content:encoded><![CDATA[<h4>Although of course you should avoid this!</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0DoR5Rq_pGTLPDOfchJwyg.jpeg" /></figure><h3>First of all, what is Castle Windsor and cyclic dependencies ?</h3><p>Castle windsor is a dependency injection tool that allow you to inject real implementation of objects or services, without having to know them.</p><pre>public class ServiceA<br>{<br>}<br><br>public class ServiceB<br>{<br>    public ServiceB(ServiceA a) { }<br>}</pre><pre>var container = new WindsorContainer();<br>container.Register(<br>    Component.For&lt;ServiceA&gt;(),<br>    Component.For&lt;ServiceB&gt;()<br>);</pre><p>Like this, when you’ll need a serviceB instance, you can create it using</p><pre>var serviceB = container.Resolve&lt;ServiceB&gt;();</pre><p>ServiceB will automatically recieve a ServiceA instance as dependency.</p><p>No let’s talk about the cyclic dependency issue. Cyclic dependencies occurs when you have a service that has a dependency with another service, that itself has a dependency to it. This can be direct, like A need B, and B need A, or at some deeper level, like A need B, that need C, that need D, ect.. That need A.</p><pre>public class ServiceA<br>{<br>    public ServiceA(ServiceB b) { }<br>}<br><br>public class ServiceB<br>{<br>    public ServiceB(ServiceA a) { }<br>}<br><br>//...<br><br>var container = new WindsorContainer();<br>container.Register(<br>    Component.For&lt;ServiceA&gt;(),<br>    Component.For&lt;ServiceB&gt;()<br>);<br><br>//...<br><br>var serviceB = container.Resolve&lt;ServiceB&gt;();<br><br>Castle.MicroKernel.Handlers.HandlerException: <br>Can&#39;t create component &#39;ServiceA&#39; as it has a dependency on &#39;ServiceB&#39;, which also depends on &#39;ServiceA&#39;.</pre><p>This is of course an architectural error, this is clearly a bad design. You should absolutly avoid this kind of scenario.</p><h3>Why I needed this ?</h3><p>In my case, I created this library because I had to manage a migration from Spring to Castle Windsor, but the legacy system was full of cyclic dependencies. First I looked at how to avoid them, but this was impossible without breaking everything.</p><p>So, allow Castle to resolve these dependencies was the solution, and that may be usefull to other in some similar cases.</p><h3>The global idea to resolve cyclic dependencies</h3><p>A way to resolve this is to use Property dependency injection. Because of that, we can now create an object, without it’s dependencies, and set them latter.</p><p>For example, to resolve ServiceA, we can create serviceA, then create serviceB, set A instance to B dependency, and then set B to A instance dependency.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*ILzrKUVlAZ3m2D8KJDuFOA.png" /></figure><p>From a code point of view, we have to keep a trace of what we have already instanciated, and look into to find an instance and break the cycle.</p><pre>internal class CyclicComponentActivator : DefaultComponentActivator<br>{<br>    public CyclicComponentActivator(ComponentModel model, IKernelInternal kernel, ComponentInstanceDelegate onCreation, ComponentInstanceDelegate onDestruction) : base(model, kernel, onCreation, onDestruction)<br>    {<br>    }<br><br>    protected override object? Instantiate(CreationContext context)<br>    {<br>        var instance = base.Instantiate(context);<br>        if(instance == null)<br>            return null;<br>        <br>        context.SetContextualProperty(Model.Name, instance);<br>        foreach (var service in Model.Services)<br>        {<br>            context.SetContextualProperty(service.FullName, instance);<br>        }<br>        return instance;<br>    }<br>    <br>}<br><br><br>internal static bool TryGetContextualInstance(this CreationContext context, string name, out object? dependency)<br>{<br>    dependency = context.GetContextualProperty(name);<br>    return dependency != null;<br>}</pre><p>So we create a custom componentActivator, to set the instance we just created by calling the base method into a kind of list. Using the creationContext allow us to be sure that we keep trace of instances that are only created for this resolution context. Like that, we keep the component lifcycle safe.</p><p>Then, we have to tell Castle windsor how to resolve properties dependencies, to break the cycle if needed.</p><pre><br>    internal class CyclicPropertyResolver : ISubDependencyResolver<br>    {<br>        private readonly IKernel _kernel;<br><br>        public CyclicPropertyResolver(IKernel kernel)<br>        {<br>            _kernel = kernel;<br>        }<br><br>        public bool CanResolve(CreationContext context, ISubDependencyResolver contextHandler, <br>            ComponentModel model, DependencyModel dependency)<br>        {<br>            return true;<br>        }<br><br>        public object? Resolve(CreationContext context, ISubDependencyResolver contextHandler, <br>            ComponentModel model, DependencyModel dependency)<br>        {<br>            return string.IsNullOrEmpty(dependency.ReferencedComponentName) ? ResolveType(context, dependency) : ResolveNamedDependency(context, dependency);<br>        }<br><br>        private object? ResolveType(CreationContext context, DependencyModel dependency)<br>        {<br>            if(context.TryGetContextualInstance(dependency.TargetType.FullName!, out var instance))<br>                return instance;<br>            return dependency.TargetType.IsGenericType ? ResolveGenericType(context, dependency) : TryResolve(context, dependency);<br>        }<br><br>        private object? ResolveNamedDependency(CreationContext context, DependencyModel dependency)<br>        {<br>            if(context.TryGetContextualInstance(dependency.ReferencedComponentName, out var instance))<br>                return instance;<br>            return _kernel.HasComponent(dependency.ReferencedComponentName) ? _kernel.GetHandler(dependency.ReferencedComponentName)?.TryResolve(context) : null;<br>        }<br><br>        private object? ResolveGenericType(CreationContext context, DependencyModel dependency)<br>        {<br>            context.AddGenericArguments(dependency.TargetType);<br>            var resolved = TryResolve(context, dependency);<br>            context.CleanGenericArguments();<br>            return resolved;<br>        }<br><br>        private object? TryResolve(CreationContext context, DependencyModel dependency)<br>        {<br>            return _kernel.HasComponent(dependency.TargetType)<br>                ? _kernel.GetHandler(dependency.TargetType)?.TryResolve(context)<br>                : null;<br>        }<br>    }</pre><p>The code is pretty simple, we create a ISubDependencyResolver, then we just manage how to resolve these dependencies. We first look if they are in the creation context, if yes, we use it, and break the cycle. If not, we resolve it using the same creation context.</p><p>When Castle will try to instanciate it, it’ll use the componentActivator we created before. So this new instance will be added to the context.</p><p>Finally, we just have to integrate that code with castle by register our custom implementations :</p><pre><br>    public static IWindsorContainer ResolveCyclicDependencies(this IWindsorContainer container)<br>    {<br>        container.Kernel.Resolver.AddSubResolver(new CyclicPropertyResolver(container.Kernel));<br>        container.Kernel.ComponentModelBuilder.AddContributor(new CyclicActivatorContributor());<br>        return container;<br>    }</pre><h3>Sources and package</h3><p>You can download this package using</p><blockquote>dotnet add package CastleWindsor.CyclicResolution</blockquote><p>The source are available at <a href="https://github.com/remihenache/CastleWindsor.CyclicResolution">https://github.com/remihenache/CastleWindsor.CyclicResolution</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a6842b4f387" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Foundations of Software Architecture]]></title>
            <link>https://rhenache.medium.com/the-foundations-of-software-architecture-90fc260fc79b?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/90fc260fc79b</guid>
            <category><![CDATA[software-design]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[clean-architecture]]></category>
            <category><![CDATA[software-architecture]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Thu, 02 May 2024 14:39:50 GMT</pubDate>
            <atom:updated>2024-05-02T14:39:50.447Z</atom:updated>
            <content:encoded><![CDATA[<h4>Understanding the Notions of Dependency and Coupling</h4><p>Why do we talk about software architecture? Why do we mention best practices, design patterns, abstraction…? What is software architecture?</p><p>The goal is to maintain our code’s scalability. Poorly structured code gradually becomes more difficult to maintain and evolve. The more code and functionality the software contains, the more these building blocks intersect, and any change in one of them can/may cause problems in another.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/977/1*pts4rknVURoG2ZUlMJlyfQ.png" /><figcaption>Features by years</figcaption></figure><p>The above graph is a minimalist representation of the number of features developed per year, depending on whether the code is more or less well-structured. It’s a representation; the actual numbers depend on the team size, project complexity, their skill level, etc.</p><p>What we should take away is that over time, the number of features developed by the team will decrease if the code isn’t well-built. Mainly because poorly architectured code will generate more bugs with each code modification, and consequently, the time spent fixing these issues is time taken away from developing features. Moreover, fixing these problems can itself generate others, and so on.</p><p>Conversely, well-structured code may be slightly slower to start, due to more time spent thinking about the application’s foundations, and construction time may be slightly more costly, although generally the difference remains minimal. But then, as problems occur only locally, they are easier to find and correct.</p><p>So, what elements should be considered to regard our code as “well-structured” and benefit from these advantages?</p><h3>The Notions of Dependency and Coupling</h3><p>Software is a set of functions, classes, pieces of code communicating with each other to accomplish great things. The more these code blocks communicate with each other, the more they are coupled, dependent on each other.</p><p>The more dependent these elements are, the more a change in one function can lead to unexpected changes in another function that uses it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*4U1000uMT6SKtkfAhHj2qg.png" /><figcaption>Simple dependency between two class</figcaption></figure><p>In this example, Class <em>A</em> has a method “<em>doSomething</em>,” to perform this task, it will use the method of Class <em>B</em> “<em>helpDoSomething</em>.” We have thus created a dependency between <em>A</em> and <em>B</em>, now a modification in <em>B</em> could bring an unexpected change in <em>A</em>.</p><p>Here are the types of dependencies:</p><h4>Using new()</h4><pre>public class A<br>{<br>    public void DoSomething()<br>    {<br>      var instance = new B();<br>      b.helpDoSomething();<br>    }<br>}</pre><p>Instantiating a “complex” type oneself (meaning non-primitive types such as int, string, boolean…) creates a dependency between <em>A</em> and <em>B</em>.</p><h4>Using a static method</h4><pre>public class A<br>{<br>    public void DoSomething()<br>    {<br>      B.helpDoSomething();<br>    }<br>}</pre><p>In this example, we consider “<em>helpDoSomething</em>” as a static method of <em>B</em>. Thus, there’s no need to instantiate <em>B</em> to use this method. However, this doesn’t avoid dependency entirely. Ultimately, the <em>new()</em> keyword acts somewhat like a static creation method as well. Here, if the “<em>helpDoSomething</em>” method of <em>B</em> is modified, the result is the same as with the new keyword.</p><h4>Dependency Injection</h4><pre>public class A<br>{<br>    private readonly B instanceOfB;<br><br>    public A(B instanceOfB)<br>    {<br>      this.instanceOfB = instanceOfB;<br>    }<br><br>    public void DoSomething()<br>    {<br>      this.instanceOfB.helpDoSomething();<br>    }<br>}</pre><p>In this scenario, we no longer use new or static methods. Instead, we inject the dependency (via the constructor). In the example below, since <em>B</em> is a class, it doesn’t bring us much; we still depend on <em>B</em>, but we will see later that this technique, with some modifications, can have many advantages.</p><h4>System Dependencies</h4><pre>public class A<br>{<br>    public DateTime GetToday()<br>    {<br>      return new DateTime();<br>    }<br>}</pre><p>This case is a bit more particular. We have a dependency via new, a static method, or even injection, but on a primitive class of the system. However, this class, unlike most others (like string, int, boolean…), has a changing default value.</p><p>The problem is that we don’t know the system’s state and we don’t control these values. In itself, the dependency is weak (because it’s a primitive type), but it makes the class difficult to test. The new DateTime returning the current date changes with each call, the same goes for Randoms, Guids, etc. Without realizing it, we become dependent on the system (which calculates the date) and not only on the language/framework.</p><p>We’ll come back to this type of dependency later.</p><h3>Nested Dependencies</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*QtN2m19sAq7hlcFZ3GQOGQ.png" /><figcaption>Dependency tree between multiple class</figcaption></figure><p>Let’s complicate the diagram from earlier between <em>A</em> and <em>B</em> a bit. Now, <em>B</em> also uses other dependencies, as its task is complex; a service contains part of its code, and a repository allows data to be saved via an ORM.</p><p>Since <em>A</em> depends on <em>B</em>, A also depends on the service, repository, and ORM. Thus, <em>A</em> has a total of 4 dependencies, even if it believes it has only one.</p><p>We understand that as the code grows, this dependency tree will grow:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*ujmZG5tgo_p_ZpqNPTbHjQ.png" /><figcaption>Complexe dependency Tree</figcaption></figure><p>The more classes are nested and reused, the more a change can have a big impact. For example, in this scenario, a change in the Repository can lead to changes in <em>A, B, C</em>, and <em>D</em>! A change in the ORM too!! A change in Services can cause disruptions in <em>A, B</em>, and <em>D</em>!</p><h3>Dependency Zones</h3><p>Now that we have a better understanding of dependencies, let’s try to represent this with a two-axis graph. The number of dependencies of a class and the number of classes dependent on it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*WJRm1W5D0qEe3WPHpAD0ww.png" /><figcaption>Graphical representation of dependencies</figcaption></figure><p>Each point represents a class, positioned according to its number of dependencies and the number of classes that depend on it.</p><p>For example, our class <em>B</em> from the last diagram would have 3 dependencies (Services, Repository, and ORM) and would have 2 usages (Class <em>A</em> and Class <em>D</em>).</p><p>Now, we will create zones on this graph, representing the points of attention to have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/994/1*VOW__cvK9WKu8bJ4ZDY1aA.png" /><figcaption>Zones of dependencies</figcaption></figure><p>We have outlined 3 zones:</p><ul><li>In red, <strong>the suffering zone</strong>: our classes have many dependencies, and many classes depend on them. They are therefore susceptible to be impacted by numerous sources of change, but also they are likely to impact many classes. Any modification in this zone becomes complicated.</li><li>In orange, the <strong>uselessness zone</strong> or “Ports”: the classes in this zone are not used by others, which means that either these classes are useless because no one uses them, or they are the entry points of the program, the “Ports” to use the terms of clean architecture. In this zone, it is not so serious to have many dependencies because changes here will not be reflected on other classes. Nevertheless, the more we reduce dependencies, the more we reduce the risks of breaking this class.</li><li>In green, <strong>the comfort zone</strong>: in this zone, our classes have few dependencies, and few classes depend on them. These classes will be easily modifiable and will have little impact on the rest of the code, so they are much safer to modify.</li></ul><p>The ideal and maximum number of dependencies and usages depend on each case, but generally, it is considered that we should not have more than 3 dependencies. For usages, it’s a bit different; depending on the nature of the class and the type of service rendered, it is possible that it may have many, but the ideal is still to limit usages.</p><blockquote>The more dependencies a class has, the more it will need to be updated regularly when these dependencies are updated.</blockquote><blockquote>A class with many dependencies is said to be fragile because it can break if one of its components generates an undesired behavior.</blockquote><blockquote>The more a class is used by others, the more changes on this class will generate modifications on its callers.</blockquote><blockquote>A class that is heavily used is said to be stable because changing its signature becomes complicated.</blockquote><p>It is important to understand these two notions well. Moreover, here, the term “stable” could be taken positively, considering that if it is stable, it is good. Indeed, it’s not necessarily bad, but in reality, making modifications on a stable class quickly becomes costly and potentially heavy in consequence.</p><h3>The Third Axis</h3><blockquote>It is normal to have classes in each of these zones! We cannot escape the suffering zone!</blockquote><p>Considering this, the objective of good software architecture will be to know what to put in which zone. What type of class can/should go in the comfort zone? Or the suffering zone?</p><p>A third component to consider, in addition to usage and dependencies, is <strong>the reasons for change</strong>, or rather the frequency of these changes, although generally linked to the number of reasons. If my class has few reasons to change, then it is ultimately not so bothersome that it is in the suffering zone; after all, we will suffer little because we will go there little. If it has few reasons to change, it may be a pity to push efforts on strong decoupling to try to be in the comfort zone. If the effort is low, of course, take advantage of it, but if the effort is significant, then perhaps it is better to accept being in the suffering or near zone.</p><p><strong>Conversely, if my class has many reasons to change, then it is imperative to try to place it in the comfort zone.</strong></p><p>I am not talking about the orange zone because even if it deserves a little attention, it is either ports (like GUI, web controllers, background services, etc.) over which we ultimately have little control. Or dead code, which we can therefore delete.</p><h3>Limiting usages and dependencies</h3><p>Now that we know where to apply our efforts, let’s see what solutions there are to break the dependency cycle. As we saw earlier, the larger the program grows, the more the nesting and therefore the dependencies grow.</p><h4>Using interfaces to break the cycle</h4><p>Here I am talking about interfaces, just as I am talking about classes because I mainly work on object-oriented programming, but if you are doing functional programming, classes can be functions, and interfaces can be function pointers or delegates.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/799/1*x3Xg0VXl7Nj8mCcnznv9kA.png" /><figcaption>Usage of interface to loose couple</figcaption></figure><p>Here we find the previous diagram of dependencies between <em>A, B</em>, and <em>D</em>. Only this time, <em>A</em> and <em>D</em> no longer depend on <em>B</em>, but on an interface. What does this change? <em>A</em> and<em> D</em> now have only one dependency, the interface! They are no longer associated with <em>B</em> and all its sub-dependencies!</p><p>Similarly, <em>B</em> now has only one usage, implementing the interface!</p><p>So, we have reduced the number of dependencies of <em>A</em> and <em>D</em> and decreased the usages of <em>B</em>! It’s a double benefit! In practice, our classes <em>A</em> and <em>D</em> will have to use dependency injection. Remember at the beginning of the article, we saw the different types of dependencies. Since it is an interface, our class cannot do a “<em>new()</em>” on it or use it statically. So, we will have this interface injected:</p><pre>public class A<br>{<br>    private readonly InterfaceB instanceOfB;<br><br>    public A(InterfaceB instanceOfB)<br>    {<br>      this.instanceOfB = instanceOfB;<br>    }<br><br>    public void DoSomething()<br>    {<br>      this.instanceOfB.helpDoSomething();<br>    }<br>}</pre><p>In this scenario, <em>A</em> no longer has knowledge of <em>B</em> and therefore its dependencies. It only knows about a contract allowing it to perform actions.</p><p>Of course, at some point, someone will have to inject <em>B</em> when instantiating <em>A</em> with something like “<em>new A(new B());</em>”</p><p>But we will see this in another article; it concerns service containers, dependency injection. A system allowing to “automate” this process.</p><p>Another advantage, which we will also discuss later, is that A now uses an interface. We can imagine a class “<em>B2</em>”, or “<em>MockB</em>” to offer other implementations of the contract. Thus, <em>A</em> will still work as expected, even though <em>B</em> is implemented differently!</p><h4>Module Definition to Limit Dependencies</h4><p>A second solution to limit/break the dependency cycle is module creation.</p><p>A module is a set of classes; generally, we use the terms module or package interchangeably, meaning the same thing. It is often considered that a module must be publishable independently, like a DLL, a .Jar, or something else. This is indeed true, but we don’t have to go that far to decompose our code into modules.</p><p>The idea of a module is to define an API, in the pure sense (and not web), meaning to offer a usable system interface by the code. Roughly speaking, methods!</p><p>Imagine a class that can serialize or deserialize an object to JSON. This class would have two methods, serialize and deserialize. It can be complex to perform these two operations; the code of our class could be huge, difficult to read, to maintain. We could imagine extracting sub-concepts in the “serialization domain.” Like Fields, Object, Type, Formatter, etc. If we do such decoupling, we will get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*QnHoikYuVR5ozX3a9D5zLw.png" /><figcaption>JSon serializer module sample</figcaption></figure><p>The JsonSerializer class encapsulates many classes; it serves as an entry point. If, for example, the <em>Serialize </em>method takes an “<em>Object</em>” type parameter and returns a string, and conversely, <em>Deserialize </em>takes a string and returns an “<em>Object</em>” (or generic type), then all dependencies are hidden!</p><p>So, we end up with a clean module, where the outside world only knows about the <em>JsonSerializer</em>, and the other classes become implementation details. This component could ultimately be a monolithic class or not; no one would know. From an external point of view, it seems that we only depend on <em>JsonSerializer </em>and nothing else.</p><p>Now, what would happen if <em>Serialize </em>returns a <em>JsonObject</em>? And then we have to do <em>JObject.Compute()</em> for example? Our module now exposes two classes, <em>JsonSerializer</em>, and <em>JsonObject</em>, because the latter serves as the return type and will therefore be known externally.</p><p>This is not dramatic in itself, but it is important to be aware that if our module exposes its structure, it then becomes more difficult to change its structure. As some callers will use <em>Serialize </em>and thus <em>JsonObjects</em>, they will also depend on the latter. In fact, <em>JsonObject </em>will become “stable,” making any changes to it complicated.</p><blockquote>Modules should be as much as possible black boxes, taking primitive types as input and returning primitive types as output.</blockquote><p>This is a guiding principle; it can sometimes be interesting, even essential, to extract complex types or use complex types. But the more we can limit this, the more we limit dependencies on the structure of our module, making it easy to change/improve its implementation.</p><p>If your module export many class outside, you have to consider them as stable. It’s not really a problem, but a thing you should know when designing your module.</p><h3>Conclusion</h3><p>It is important to limit classes in the suffering zone, especially if they are destined to change regularly. Therefore, it is necessary to limit the dependencies and usages of classes subjected to frequent changes.</p><p>It is important to know when to use an interface to break the dependency tree (not to mention the other advantages of interfaces that we will see later).</p><p>It is important to understand that the types our classes take in and out can generate dependencies on our implementation. Therefore, we must be vigilant and, if possible, limit access to the “children” elements of our module.</p><p>If you have understood all this, then you have entered the world of software architecture. The world of compromises, the world of reflection on code, communication between components, but also pragmatism.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=90fc260fc79b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Mastering Code Testing: Harnessing SUT or Fixtures]]></title>
            <link>https://rhenache.medium.com/mastering-code-testing-harnessing-sut-or-fixtures-2ab3c608ba09?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ab3c608ba09</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Mon, 08 Apr 2024 13:23:24 GMT</pubDate>
            <atom:updated>2024-04-08T13:23:24.574Z</atom:updated>
            <content:encoded><![CDATA[<h4>Dive into the world of code testing with this comprehensive guide</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5y0iPqEUD_BLWinN5cCe_g.png" /><figcaption>Mastering code testing (DALL-E)</figcaption></figure><p>In the bustling arena of software development, ensuring that applications are robust and free from defects is paramount. However, the journey of writing tests is often seen as a time-consuming task that undergoes frequent revisions alongside production code changes. This issue signals a deeper problem: poor testing design.</p><p>While it’s inevitable that tests will evolve as production evolves, the impact should be minimal. If a single change in production code requires multiple tests to be updated, it might be time to reconsider how these tests are written.</p><h4>The Art of Test Writing</h4><p>Your tests should be as clean and well-structured as your production code, perhaps even more so. Tests are not just code; they encapsulate the functionality and intentions of your software. They act as the blueprint for what your application can do.</p><blockquote>If faced with the choice between deleting all my production code or all my test code, I’d opt to erase the production code.</blockquote><p>Why? Because with a comprehensive test suite in place, rebuilding the software becomes a feasible, systematic task, signaling the end of development with certainty.</p><h4>The Power of SUT or Fixture</h4><p>The concept of the System Under Test (SUT) or a fixture (beyond the xUnit definition) serves as an excellent strategy to decouple test descriptions from their implementation.</p><p>These entities should promote clarity, brevity, and comprehensibility in your tests. A well-crafted SUT or fixture keeps your tests focused and straightforward, enabling anyone to grasp the tested functionality at a glance.</p><pre><br>public class CreateAnAbsenceCommandHandlerTests<br>{<br>    private readonly CreateAnAbsenceFixture fixture;<br><br>    public CreateAnAbsenceCommandHandlerTests()<br>    {<br>        this.fixture = new CreateAnAbsenceFixture();<br>    }<br><br>    [Fact]<br>    public async Task AnAbsenceCanBeCreated()<br>    {<br>        await this.fixture<br>            .CreateAnAbsence();<br><br>        this.fixture.Should().HaveCreatedAbsence();<br>    }<br><br>    [Fact]<br>    public async Task canCreateAbsenceWithSocialSecurityNature()<br>    {<br>        await this.fixture<br>            .WithSocialSecurityNature()<br>            .CreateAnAbsence();<br><br>        this.fixture.Should().HaveCreatedAbsenceWithSocialSecurityNature();<br>    }<br><br>    [Theory]<br>    [InlineData(&quot;02-01-2022 00:00&quot;, &quot;01-01-2022 23:00&quot;)]<br>    [InlineData(&quot;02-01-2022 00:00&quot;, &quot;01-01-2022 12:00&quot;)]<br>    [InlineData(&quot;02-01-2022 13:00&quot;, &quot;02-01-2022 12:00&quot;)]<br>    public async Task ShouldNotCreateAnAbsenceWithDateEndLowerOrEqualsThanDateStart(String start, String end)<br>    {<br>        DateTime startDate = start.ToDateTimeUtc();<br>        DateTime endDate = end.ToDateTimeUtc();<br><br>        await this.fixture<br>            .WithDates(startDate, endDate)<br>            .CreateAnAbsence();<br><br>        this.fixture.Should().HaveThrowValidationException();<br>    }<br><br>    [Fact]<br>    public async Task EmployeeApplicantCantCreateAnAbsenceForAnotherEmployeeIfNoPermission()<br>    {<br>        await this.fixture<br>            .ForEmployeeId(1)<br>            .AsApplicantId(2)<br>            .WithoutPermissionToCreateForOther()<br>            .CreateAnAbsence();<br><br>        this.fixture.Should().HaveThrowSecurityException();<br>    }<br>}</pre><p>In this snippet, CreateAnAbsence is our SUT. The tests succinctly articulate the business rules around creating absences, leveraging the fixture to manage state and interactions.</p><h4>Designing an Effective Fixture</h4><p>A well-designed fixture in C# encapsulates the initial valid state of the system, reducing redundant setup code. It should offer methods to modify this state in a clear and concise manner, thus ensuring that the test remains focused on the behavior rather than the implementation details.</p><pre><br>public class CreateAnAbsenceFixture : CommandFixture<br>{<br>    private readonly AbsencePermissionRepositoryMock absencePermissionRepository;<br>    public readonly CalendarRepositoryMock calendarRepository;<br>    public readonly UserContextFactoryMock userContextFactory;<br><br>    private readonly AbsenceAddCommand absenceRequest = new()<br>    {<br>        BeginDate = &quot;01-01-2022 00:00&quot;.ToDateTimeUtc(),<br>        EndDate = &quot;25-01-2022 23:00&quot;.ToDateTimeUtc(),<br>        EmployeeId = 1,<br>        NatureId = NatureId.PaidLeave<br>        StatusId = StatusId.New<br>    };<br><br><br>    public CreateAnAbsenceFixture()<br>    {<br>        this.absencePermissionRepository = new AbsencePermissionRepositoryMock();<br>        this.calendarRepository = new CalendarRepositoryMock();<br>        this.userContextFactory = new UserContextFactoryMock();<br>    }<br><br><br>    public CreateAnAbsenceFixture WithOneSegmentOfSocialSecurityNature()<br>    {<br>        this.absenceRequest.NatureId = NatureId.SocialSecurity;<br>        return this;<br>    }<br><br>    public CreateAnAbsenceFixture ForEmployeeId(Int64 employeeId)<br>    {<br>        this.absenceRequest.EmployeeId = employeeId;<br>        return this;<br>    }<br><br><br>    public CreateAnAbsenceFixture WithDates(DateTime startAt, DateTime endAt)<br>    {<br>        this.absenceRequest.BeginDate = startAt;<br>  this.absenceRequest.EndDate = endAt;<br>        return this;<br>    }<br><br>    public CreateAnAbsenceFixture AsApplicantId(Int32 applicantId)<br>    {<br>        this.userContextFactory.User = this.userContextFactory.User with { Id = new EmployeeId(applicantId) };<br>        return this;<br>    }<br><br>    public CreateAnAbsenceFixture WithoutPermissionToCreateForOther()<br>    {<br>        this.absencePermissionRepository.UserCanEditAbsence = AuthorizeResult.NoPermissionsFor(this.userContextFactory.User.Id, AbsencePermission.Write.ToString());<br>        this.userContextFactory.SetUserRoleType(UserRoleType.Employee);<br>        return this;<br>    }<br><br>    public async Task CreateAnAbsence()<br>    {<br>        this.absenceRequest.Segments = this.segments;<br>        await CallCommand(this.absenceRequest, ConfigureServices);<br>    }<br><br>    private void ConfigureServices(IServiceCollection services)<br>    {<br>        services.AddPaidLeaveContext();<br>        services.AddScoped&lt;IUserContextFactory&gt;(_ =&gt; this.userContextFactory);<br>        services.AddScoped&lt;IAbsencePermissionRepository&gt;(_ =&gt; this.absencePermissionRepository);<br>        services.AddScoped&lt;ICalendarAggregateRepository&gt;(_ =&gt; this.calendarRepository);<br>    }<br>}</pre><p>This setup not only makes your tests more robust against changes in the implementation but also enhances their readability and expressiveness.</p><h4>Strategic Advantages</h4><ul><li>Robustness to Changes: Centralizing the modification of test state in fixtures minimizes the ripple effect of changes in production code on your test suite.</li><li>Cleaner Tests: A focus on business logic rather than technical details makes tests more understandable and relevant.</li><li>Reusability and Maintainability: Object-oriented principles allow for shared setup logic across tests, reducing duplication and fostering easier maintenance.</li></ul><h4>Conclusion</h4><p>Effective code testing is an intricate dance of balancing technical precision with business intent. By structuring your tests around business needs and using SUTs and fixtures, you create a resilient and adaptable testing environment. Keep your tests concise, business-focused, and isolated from unnecessary implementation details, and you’ll build a test suite that not only validates functionality but also embodies the core principles of your application’s design.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ab3c608ba09" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I hated Monad, and why I start to love it]]></title>
            <link>https://rhenache.medium.com/why-i-hated-monad-and-why-i-start-to-love-it-21d0055311bb?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/21d0055311bb</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Thu, 16 Nov 2023 14:36:00 GMT</pubDate>
            <atom:updated>2023-11-16T14:36:00.116Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>Exploring an alternative approach to flow and error management</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j6F-gAE-Xf2kXDz1JKUpeA.png" /></figure><p>Some time ago, <a href="https://rhenache.medium.com/clean-code-handling-exceptions-3ad9aac2ea22">I wrote about Exception Handling</a>, where I briefly mentioned monads, particularly the Result or Option types, used for handling errors as opposed to exceptions. Initially, I found myself averse to monads, despite encountering them in professional projects. My primary concern was their tendency to clutter the code.</p><p>Take, for instance, this typical command handler pattern:</p><pre><br>public class SomeCommandHandler : QueryHandler&lt;SomeCommandInput, SomeCommandResult&gt;<br>{<br>    private readonly ISomeRepository _someRepository;<br><br>    public GetPrivateIdQueryHandler(ISomeRepository someRepository)<br>    {<br>        _someRepository= someRepository;<br>    }<br><br>    public async Task&lt;Result&lt;SomeCommandResult&gt;&gt; Handle(<br>        SomeCommandInput command,<br>        CancellationToken cancellationToken)<br>    {<br>        var entityResult = await _someRepository.GetEntity(command.Id);<br>        if (!entityResult.IsSuccess)<br>            return Result.Fail(entityResult.Error);<br><br>        var someThingResult = entityResult.Value.DoSomething();<br>        if (!someThingResult.IsSuccess)<br>            return Result.Fail(someThingResult.Error);<br><br>        var saveResult = await _someRepository.Save(someThingResult.Value);<br>        if (!saveResult.IsSuccess)<br>            return Result.Fail(saveResult.Error);<br>        return Result.Success(new SomeCommandResult(saveResult.Value.Id));<br>    }<br>}</pre><p>This pattern necessitates continuous checks and wrapping of results/fails, making it cumbersome. It also leads to dependency and proliferation of similar lines in the calling code, <a href="https://rhenache.medium.com/clean-code-handling-exceptions-3ad9aac2ea22">much like issues arising with nullable types</a>.</p><h3>Misconceptions About Monads</h3><p>A commonly encountered monad is the Result object:</p><pre>public class Result&lt;T&gt;<br>{<br>    public T Value { get; }<br>    public bool IsSuccess { get; }<br>    public string Error { get; }<br><br>    private Result(T value)<br>    {<br>      Value = value;<br>      IsSuccess = true;<br>    }<br><br>    private Result(string error)<br>    {<br>      Error = error;<br>      IsSuccess = false;<br>    }<br><br>    public static Result&lt;T&gt; Success&lt;T&gt;(T value)<br>    {<br>      return new Result&lt;T&gt;(value);<br>    }<br><br>    public static Success(string error)<br>    {<br>      return new Result&lt;T&gt;(error);<br>    }<br>}</pre><p>The issue here is not the encapsulation of the result, but the public accessibility of the state. This exposure encourages direct use, leading to code pollution, similar to the nullable pattern.</p><h3>Redefining Monads</h3><p>A more effective monad should act as a black box, obscuring its state and validity checks from the user. This necessitates methods for safe status access and transformation:</p><pre>public class Result&lt;T&gt;<br>{<br>    private T _value { get; }<br>    private bool _isSuccess { get; }<br>    private string _error { get; }<br><br>    private Result(T value)<br>    {<br>      _value = value;<br>      _isSuccess = true;<br>    }<br><br>    private Result(string error)<br>    {<br>      _error = error;<br>      _isSuccess = false;<br>    }<br><br>    public static Result&lt;T&gt; Success&lt;T&gt;(T value)<br>    {<br>      return new Result&lt;T&gt;(value);<br>    }<br><br>    public static Fail(string error)<br>    {<br>      return new Result&lt;T&gt;(error);<br>    }<br><br>    public TOut Match&lt;TOut&gt;(Func&lt;T, TOut&gt; success, Func&lt;string, TOut&gt; error)<br>    {<br>        if(_isSuccess)<br>           return success(_value);<br>        return error(_error);<br>    }<br>}</pre><p>This approach ensures safe state handling without manual intervention. However, simply replacing IsSuccess checks with Match calls isn&#39;t sufficient. The key is to maintain the black box for as long as possible, introducing methods like Map to transform the state within this encapsulated context.</p><pre><br>public Result&lt;TOut&gt; Map&lt;TOut&gt;(Func&lt;T, Result&lt;TOut&gt;&gt; mapper)<br>{<br>    if(_isSuccess)<br>       return mapper(_value);<br>    return Fail&lt;TOut&gt;(_error);<br>}</pre><p>This method allows us to manipulate the state without direct exposure, <strong>eliminating the need for repeated success checks</strong>. Our refactored command handler now looks like this:</p><pre>public class SomeCommandHandler : QueryHandler&lt;SomeCommandInput, SomeCommandResult&gt;<br>{<br>    private readonly ISomeRepository _someRepository;<br><br>    public GetPrivateIdQueryHandler(ISomeRepository someRepository)<br>    {<br>        _someRepository= someRepository;<br>    }<br><br>    public async Task&lt;Result&lt;SomeCommandResult&gt;&gt; Handle(<br>        SomeCommandInput command,<br>        CancellationToken cancellationToken)<br>    {<br>        var entityResult = await _someRepository.GetEntity(command.Id);<br>        return entityResult.Map(DoSomething)<br>                .Map(await Save)<br>                .Map(ToCommandResult); <br>    }<br><br>    private Result&lt;Something&gt; DoSomething(Entity entity) =&gt; entity.DoSomething();<br><br>    private Task&lt;Result&lt;SaveOperation&gt;&gt; Save(Something something) =&gt; _someRepository.Save(something);<br><br>    private Result&lt;SomeCommandResult&gt; ToCommandResult(SaveOperation saveOperation) =&gt; new SomeCommandResult(saveOperation.Id);<br>}<br><br>// And then match on the command result:<br><br>var response = await someCommand.Handle(someCommandInput);<br>response.Match(s =&gt; Console.WriteLine(s.ToString()), e =&gt; Console.WriteLine($&quot;An error happened: {e}&quot;));</pre><p>With this approach, you no longer need to worry about null values or invalid states; the Result monad handles these internally. This concept extends beyond just operation results to other types of monads like Option, Try, Either, etc. Each serves a specific purpose, but all adhere to the principles of state encapsulation and seamless monad transitions, as demonstrated by the Map method.</p><h3>Future Considerations: Monad Integration in Object-Oriented Programming</h3><p>The examples provided in this article are simplified to illustrate the fundamental concepts and benefits of using monads and chaining. While these examples serve their purpose, the real power and versatility of monads become evident when we consider their integration into object-oriented programming (OOP). Imagine transforming our traditional class models into monadic forms, where classes themselves embody monadic properties. This transformation allows classes to not only encapsulate their state and behavior but also to seamlessly participate in monadic operations.</p><p>By embedding methods like Map, Bind, and Do into our classes, we can create objects that are inherently capable of monadic transformations. This approach leads to a more fluent and expressive style of coding, where operations can be chained in a manner that maintains encapsulation and reduces side effects. Such an integration would encourage a shift in how we think about class design, leading to systems that are more robust and easier to reason about.</p><p>Furthermore, this paradigm shift offers intriguing possibilities for enhancing code reusability and readability. It could lead to the creation of a new class of design patterns and best practices centered around monadic principles in OOP. The potential for extending these concepts to areas such as error handling, asynchronous programming, and state management is immense, opening doors to more advanced and efficient software design strategies.</p><p>In conclusion, while the concept of monads is often viewed through the lens of functional programming, their integration into OOP can significantly enrich our programming models, offering a harmonious blend of functional and object-oriented paradigms. This fusion promises a future where the clarity and safety of functional programming coexist with the structure and familiarity of OOP, leading to more maintainable, scalable, and reliable software.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=21d0055311bb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Threadsafe implementation of DbContext]]></title>
            <link>https://rhenache.medium.com/a-threadsafe-implementation-of-dbcontext-bbd9959cdc30?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/bbd9959cdc30</guid>
            <category><![CDATA[entity-framework]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet-core]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Wed, 11 Oct 2023 14:14:57 GMT</pubDate>
            <atom:updated>2023-10-12T14:15:16.394Z</atom:updated>
            <content:encoded><![CDATA[<h4>How to enable Entity Framework DbContext to multithreading</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/591/1*JxQ3XSibE5Dy7k18C8RubQ.png" /></figure><p>In concurrent environments, making your Entity Framework `DbContext` thread-safe is essential to ensure data integrity and avoid race conditions. The `DbContext` class in Entity Framework is not inherently thread-safe. This article aims to present an implementation that extends `DbContext` to make it thread-safe, allowing for smooth operations in multithreaded applications.</p><p>The source are available at <a href="https://github.com/remihenache/ThreadSafeDbContext">https://github.com/remihenache/ThreadSafeDbContext</a></p><p>And the package can be installed using nuget:</p><pre>dotnet add package ThreadSafeDbContext</pre><h4>Why is Thread-Safety Necessary?</h4><p>In multi-threaded applications, multiple threads might attempt to access the database concurrently. If `DbContext` is not thread-safe, this leads to:</p><p>- Data Corruption<br>- Deadlocks<br>- Inconsistent Reads/Writes</p><p>A thread-safe `DbContext` ensures that operations are atomic and isolated from each other, which is crucial for data integrity and application stability.</p><p>As I like Domain Events, and publish them as concurrency task, I need to share my DbContext (and the attached transaction) to these task. This is typically the case that make me create this.</p><h4>How does it work</h4><p>The thread-safety is achieved by using `SemaphoreSlim` to lock the resources. The custom implementation provides a layer over `DbContext`, ensuring that only one thread can access it at any given time for sensitive operations.</p><ol><li><strong>ThreadSafeEnumerator</strong>: Wraps around `IEnumerator` and locks the resource while the enumerator move. Enable thread safe access at each iteration.</li></ol><pre><br>internal class ThreadSafeEnumerator : IEnumerator<br>{<br>    protected readonly IEnumerator Enumerator;<br>    protected readonly SemaphoreSlim SemaphoreSlim;<br><br>    public ThreadSafeEnumerator(IEnumerator enumerator, SemaphoreSlim semaphoreSlim)<br>    {<br>        this.Enumerator = enumerator;<br>        this.SemaphoreSlim = semaphoreSlim;<br>    }<br><br>    public Boolean MoveNext()<br>    {<br>        this.SemaphoreSlim.Wait();<br>        try<br>        {<br>            return this.Enumerator.MoveNext();<br>        }<br>        finally<br>        {<br>            this.SemaphoreSlim.Release();<br>        }<br>    }<br><br>    public void Reset()<br>    {<br>        this.SemaphoreSlim.Wait();<br>        try<br>        {<br>            this.Enumerator.Reset();<br>        }<br>        finally<br>        {<br>            this.SemaphoreSlim.Release();<br>        }<br>    }<br><br>    public Object Current =&gt; this.Enumerator.Current!;<br>}</pre><p><strong>2. ThreadSafeQueryable</strong>: Wraps around `IQueryable` and use the ThreadSafeEnumerator to enable thread safe access. It also wrap the QueryProvider into a thread safe query provider.</p><pre><br><br>internal class ThreadSafeQueryable : IOrderedQueryable<br>{<br>    protected readonly SemaphoreSlim SemaphoreSlim;<br>    protected readonly IQueryable Set;<br><br>    public ThreadSafeQueryable(IQueryable set, SemaphoreSlim semaphoreSlim)<br>    {<br>        this.Set = set;<br>        this.SemaphoreSlim = semaphoreSlim;<br>    }<br><br><br>    public IEnumerator GetEnumerator()<br>    {<br>        return new ThreadSafeEnumerator(this.Set.GetEnumerator(), this.SemaphoreSlim);<br>    }<br><br>    public Type ElementType =&gt; this.Set.ElementType;<br><br>    public Expression Expression =&gt; this.Set.Expression;<br><br>    public IQueryProvider Provider =&gt; new ThreadSafeQueryProvider(this.Set.Provider, this.SemaphoreSlim);<br>}</pre><p>3. <strong>ThreadSafeQueryProvider</strong>: Implements a thread-safe `IQueryProvider`. It wrap a query provider, to lock sensitive operation around it. And wrap the create query, to encapsulate it into a ThreadSafeQueryable, as above.</p><pre><br>internal sealed class ThreadSafeQueryProvider : IAsyncQueryProvider<br>{<br>    private readonly IQueryProvider queryProvider;<br>    private readonly SemaphoreSlim semaphoreSlim;<br><br>    public ThreadSafeQueryProvider(<br>        IQueryProvider queryProvider,<br>        SemaphoreSlim semaphoreSlim)<br>    {<br>        this.queryProvider = queryProvider;<br>        this.semaphoreSlim = semaphoreSlim;<br>    }<br><br>    public IQueryable CreateQuery(Expression expression)<br>    {<br>        return new ThreadSafeQueryable(this.queryProvider.CreateQuery(expression), this.semaphoreSlim);<br>    }<br><br>    public IQueryable&lt;TElement&gt; CreateQuery&lt;TElement&gt;(Expression expression)<br>    {<br>        return new ThreadSafeQueryable&lt;TElement&gt;(this.queryProvider.CreateQuery&lt;TElement&gt;(expression),<br>            this.semaphoreSlim);<br>    }<br><br>    public Object? Execute(Expression expression)<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            return this.queryProvider.Execute(expression);<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br>    public TResult Execute&lt;TResult&gt;(Expression expression)<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            return this.queryProvider.Execute&lt;TResult&gt;(expression);<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br>    public TResult ExecuteAsync&lt;TResult&gt;(Expression expression, CancellationToken cancellationToken = new())<br>    {<br>        this.semaphoreSlim.Wait(cancellationToken);<br>        try<br>        {<br>            return (this.queryProvider as IAsyncQueryProvider)!.ExecuteAsync&lt;TResult&gt;(expression, cancellationToken);<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br>}</pre><p>4. <strong>ThreadSafeDbSet</strong>: A DbSet class extended to handle thread safety. This is probably the most sensitive wrapper. It wrap the DbSet, to make it use the ThreadSafeQueryable, and ensure that some other operations are wrap by the locker.</p><pre>internal sealed class ThreadSafeDbSet&lt;TEntity&gt; :<br>    DbSet&lt;TEntity&gt;,<br>    IQueryable&lt;TEntity&gt;,<br>    IAsyncEnumerable&lt;TEntity&gt;<br>    where TEntity : class<br>{<br>    private readonly SemaphoreSlim semaphoreSlim;<br>    private readonly DbSet&lt;TEntity&gt; set;<br><br>    public ThreadSafeDbSet(DbSet&lt;TEntity&gt; set, SemaphoreSlim semaphoreSlim)<br>    {<br>        this.set = set;<br>        this.semaphoreSlim = semaphoreSlim;<br>    }<br><br>    public override IEntityType EntityType =&gt; this.set.EntityType;<br><br>    public override LocalView&lt;TEntity&gt; Local =&gt; SafeExecute(() =&gt; this.set.Local);<br><br>    public override EntityEntry&lt;TEntity&gt; Add(TEntity entity)<br>    {<br>        return SafeExecute(() =&gt; this.set.Add(entity));<br>    }<br><br>    public override EntityEntry&lt;TEntity&gt; Attach(TEntity entity)<br>    {<br>        return SafeExecute(() =&gt; this.set.Attach(entity));<br>    }<br><br>    public override EntityEntry&lt;TEntity&gt; Update(TEntity entity)<br>    {<br>        return SafeExecute(() =&gt; this.set.Update(entity));<br>    }<br><br>    // ... All other override using SafeExecute<br><br>    private void SafeExecute(Action func)<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            func();<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br>    private T SafeExecute&lt;T&gt;(Func&lt;T&gt; func)<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            return func();<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br>    #region Queryable<br><br>    public Type ElementType =&gt; (this.set as IQueryable).ElementType;<br>    public Expression Expression =&gt; (this.set as IQueryable).Expression;<br>    <br>    public override IQueryable&lt;TEntity&gt; AsQueryable()<br>    {<br>        return new ThreadSafeQueryable&lt;TEntity&gt;(this.set.AsQueryable(), this.semaphoreSlim);<br>    }<br><br>    public override IAsyncEnumerable&lt;TEntity&gt; AsAsyncEnumerable()<br>    {<br>        return new ThreadSafeQueryable&lt;TEntity&gt;(this.set.AsQueryable(), this.semaphoreSlim);<br>    }<br><br>    public override IAsyncEnumerator&lt;TEntity&gt; GetAsyncEnumerator(CancellationToken cancellationToken = new())<br>    {<br>        return new ThreadSafeQueryable&lt;TEntity&gt;(this.set.AsQueryable(), this.semaphoreSlim).GetAsyncEnumerator(<br>            cancellationToken);<br>    }<br><br>    IEnumerator IEnumerable.GetEnumerator()<br>    {<br>        return GetEnumerator();<br>    }<br><br>    public IQueryProvider Provider =&gt;<br>        new ThreadSafeQueryable&lt;TEntity&gt;(this.set.AsQueryable(), this.semaphoreSlim).Provider;<br><br>    public IEnumerator&lt;TEntity&gt; GetEnumerator()<br>    {<br>        return new ThreadSafeQueryable&lt;TEntity&gt;(this.set.AsQueryable(), this.semaphoreSlim).GetEnumerator();<br>    }<br><br>    #endregion<br>}</pre><p>5. <strong>ThreadSafeDbContext</strong>: Extends `DbContext` and overrides methods to make them thread-safe. It use the ThreadSafeDbSet as DbSet, to ensure that associated operation are safe.</p><pre><br>public class ThreadSafeDbContext : DbContext<br>{<br>    private readonly SemaphoreSlim semaphoreSlim = new(1, 1);<br><br>    public ThreadSafeDbContext()<br>    {<br>    }<br><br>    public ThreadSafeDbContext(DbContextOptionsBuilder optionsBuilder)<br>        : base(optionsBuilder<br>            .EnableThreadSafetyChecks(false)<br>            .Options)<br>    {<br>    }<br><br>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>    {<br>        optionsBuilder.EnableThreadSafetyChecks(false);<br>        base.OnConfiguring(optionsBuilder);<br>    }<br><br>    public override DbSet&lt;TEntity&gt; Set&lt;TEntity&gt;()<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            return new ThreadSafeDbSet&lt;TEntity&gt;(base.Set&lt;TEntity&gt;(), this.semaphoreSlim);<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br><br>    public override async Task&lt;Int32&gt; SaveChangesAsync(CancellationToken cancellationToken = new())<br>    {<br>        await this.semaphoreSlim.WaitAsync(cancellationToken);<br>        try<br>        {<br>            return await base.SaveChangesAsync(cancellationToken);<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br><br>    public override Int32 SaveChanges()<br>    {<br>        this.semaphoreSlim.Wait();<br>        try<br>        {<br>            return base.SaveChanges();<br>        }<br>        finally<br>        {<br>            this.semaphoreSlim.Release();<br>        }<br>    }<br>}</pre><h4>Using SemaphoreSlim</h4><p>`SemaphoreSlim` is used as a locking mechanism. A count of one allows a single thread to enter the critical section, effectively making it thread-safe.</p><h4>The combinaison of Enumerator, Queryable and QueryProvider</h4><p>These three class work together, each thread safe implementation using the threadsafe implementation of the other, to wrap as well as possible the complexity of Entity Framework Queryable. As they share the same lock that the DbContext, each operation is thread safe.</p><h3>How to Use It</h3><p>The only available class is the ThreadSafeDbContext, so instead of making your application DbContext inherits from DbContext, make it inherits from the ThreadSafeDbContext:</p><pre>public class MyDbContext : ThreadSafeDbContext<br>{<br>}</pre><p>Then, you can use it as the standard DbContext:</p><pre>public class MyDbContext : ThreadSafeDbContext<br>{<br><br>    protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)<br>    {<br>        optionsBuilder.UseSqlServer(&quot;MyConnectionString&quot;);<br>        base.OnConfiguring(optionsBuilder);<br>    }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;MyEntity&gt;().ToTable(&quot;MyEntity&quot;);<br>        modelBuilder.Entity&lt;MyEntity&gt;().HasKey(t =&gt; t.ID);<br>        base.OnModelCreating(modelBuilder);<br>    }<br>}<br>// or use DbContextOptionBuilder constructor<br>public class MyDbContext : ThreadSafeDbContext<br>{<br><br>    public MyDbContext(DbContextOptionsBuilder&lt;ThreadSafeDbContext&gt; optionsBuilder) : base(optionsBuilder)<br>    {<br>    }<br><br>    protected override void OnModelCreating(ModelBuilder modelBuilder)<br>    {<br>        modelBuilder.Entity&lt;MyEntity&gt;().ToTable(&quot;MyEntity&quot;);<br>        modelBuilder.Entity&lt;MyEntity&gt;().HasKey(t =&gt; t.ID);<br>        base.OnModelCreating(modelBuilder);<br>    }<br>}</pre><p>Now, you can freely run your LINQ queries and CRUD operations. All of these will be thread-safe.</p><pre>var users = myDbContext.Set&lt;Users&gt;.ToList();<br>// or async<br>var users = await myDbContext.Set&lt;Users&gt;.ToListAsync();</pre><p>As you can modify your data, and persist them safely</p><pre>myDbContext.Set&lt;Users&gt;.Add(new Users(){ Id = 1 });<br>dbContext.SaveChanges();<br>// or async<br>myDbContext.Set&lt;Users&gt;.Add(new Users(){ Id = 1 });<br>await dbContext.SaveChangesAsync();</pre><h3>Pros and Cons</h3><h4>Pros</h4><p>- Guarantees data integrity in a multithreaded environment.<br>- Simple integration into existing projects.</p><h4>Cons</h4><p>- Potential for decreased performance due to locking.<br>- Complexity could increase if nested locks are involved.</p><h3>Conclusion</h3><p>Thread safety is critical for applications that require high reliability and data integrity. This implementation provides a foundational layer to ensure that your Entity Framework operations are thread-safe.</p><p>You could find the source at <a href="https://github.com/remihenache/ThreadSafeDbContext">https://github.com/remihenache/ThreadSafeDbContext</a></p><p>And the package can be installed using nuget:</p><pre>dotnet add package ThreadSafeDbContext</pre><p>— -</p><p>Note: There are various ways to achieve thread safety, and the above example is just one approach. Always measure performance impacts when implementing synchronization primitives like semaphores or locks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bbd9959cdc30" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Simplifying Dependency Injection in TypeScript with Injected-ts]]></title>
            <link>https://rhenache.medium.com/simplifying-dependency-injection-in-typescript-with-injected-ts-8ba5f75f5715?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ba5f75f5715</guid>
            <category><![CDATA[inversion-of-control]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dependency-injection]]></category>
            <category><![CDATA[typescript]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Fri, 23 Jun 2023 16:31:50 GMT</pubDate>
            <atom:updated>2023-06-23T16:31:50.126Z</atom:updated>
            <content:encoded><![CDATA[<h4>A simple DI (Dependency Injection) library for typescript</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*woeea_wEuXPQ-sBI11bDKg.png" /></figure><h3>Introduction</h3><p>Dependency injection is a powerful technique that promotes modular and loosely coupled code by managing the dependencies of an application and facilitating their injection into classes. In TypeScript, implementing dependency injection can sometimes be cumbersome and time-consuming. The main drawback of existing library is how they are coupled to your code, by using decorators, or force you to add some code in your production code to enable DI.</p><p>However, with the advent of Injected-ts, a lightweight dependency injection library, managing dependencies in TypeScript has become easier and more efficient. In this article, we will explore the motivations behind using Injected-ts, delve into its inner workings, and demonstrate how to leverage its features to simplify dependency injection in TypeScript projects.</p><p>The code is open source and available here: <a href="https://github.com/remihenache/injected-ts">https://github.com/remihenache/injected-ts</a></p><h3>Why Use Injected-ts?</h3><ol><li>Modularity and Maintainability: Injected-ts enables you to break down your code into smaller, manageable modules with clear dependencies. By decoupling dependencies from the classes that use them, you can easily replace or modify implementations without affecting other parts of the codebase.</li><li>Testability: With dependency injection, you can easily substitute dependencies with mock objects or test doubles during unit testing. This facilitates more thorough testing, improves test coverage, and enhances overall code quality.</li><li>Flexibility: Injected-ts provides a flexible and intuitive API for registering and resolving dependencies. It supports various lifecycle options, constructor parameter injection, interface injection, and scope management. This flexibility allows you to tailor the dependency injection approach to the specific needs of your project.</li></ol><h3>The Inner Workings of Injected-ts</h3><p>At the core of Injected-ts are two main classes: ServiceCollection and ServiceProvider. Let&#39;s explore how they work together to simplify dependency injection in TypeScript.</p><h4>ServiceCollection:</h4><ul><li>The ServiceCollection class serves as a container for registering dependencies. It provides methods such as addScoped, addTransient, and addSingleton to register dependencies with different lifecycles.</li><li>When registering a dependency, you can use the fluent API provided by ServiceCollection to specify the dependency type and its associated configuration, such as constructor dependencies.</li><li>The build method of ServiceCollection creates an instance of ServiceProvider with the registered dependencies.</li></ul><h4>ServiceProvider:</h4><ul><li>The ServiceProvider class is responsible for resolving dependencies and managing their lifecycles.</li><li>By calling the get method on ServiceProvider with the appropriate dependency identifier, you can resolve and retrieve an instance of the requested dependency.</li><li>ServiceProvider supports scoped lifecycles, allowing you to create and manage scopes using the startScope and endScope methods. This enables you to control the lifetime of dependencies within specific scopes.</li></ul><h3>Using Injected-ts in Practice</h3><p>To demonstrate how to use Injected-ts, let’s consider an example scenario where we have a UserService that depends on a UserRepository. Here&#39;s how we can implement it using Injected-ts:</p><h4>Create a ServiceCollection instance:</h4><pre>import { ServiceCollection } from &#39;injected-ts&#39;;<br>const services = new ServiceCollection();</pre><h4>Register dependencies:</h4><pre>services.addScoped&lt;UserRepository&gt;((builder) =&gt;<br>  builder.fromType(UserRepository)<br>);<br><br>services.addScoped&lt;UserService&gt;((builder) =&gt;<br>  builder.fromType(UserService).withDependencies(UserRepository)<br>);ty</pre><h4>Build and use the ServiceProvider:</h4><pre>const serviceProvider = services.build();<br><br>const userRepository = serviceProvider.get&lt;UserRepository&gt;(UserRepository);<br>const userService = serviceProvider.get&lt;UserService&gt;(UserService);<br><br>// Use the dependencies<br>userService.registerUser(&#39;John Doe&#39;);</pre><h3>Lifecycles</h3><p>The library can handle three lifecycle:</p><ul><li>Singleton: one instance for all the application</li><li>Transient: one instance each time you inject it</li><li>Scoped: one instance by scope</li></ul><p>You can create your own custom lifecycle if need by implementing the Lifcycle interface, then use the add method.</p><pre>class CustomLifecycle implements Lifecycle {<br>  // Implement the lifecycle methods<br>}<br><br>services.add&lt;MyService&gt;(new CustomLifecycle(), (builder) =&gt;<br>  builder.fromType(MyService).withDependencies(Dependency1, Dependency2)<br>);</pre><h3>Use the ServiceProvider inside a class or a factory</h3><p>Injected-ts provides the possibility to access the service provider instance by injecting it inside a class or a factory:</p><ul><li>Injection</li></ul><pre>class MyService {<br>  constructor(serviceProvider: ServiceProvider) {}<br>  public doSomething() {<br>      const anotherService = this.serviceProvider.get&lt;AnotherService&gt;(AnotherService.name);<br>      // Do something with the service<br>    }<br>}</pre><ul><li>Factory</li></ul><pre>services.addSingleton&lt;ServiceDependency&gt;((builder) =&gt;<br>    builder.fromType(ServiceDependency.name).withDependencies(TypeDependency)<br>);<br>services.addSingleton&lt;MyService&gt;((builder) =&gt;<br>    builder.fromName(&#39;MyService&#39;).useFactory((serviceProvider) =&gt; new MyService(&quot;Some value&quot;, serviceProvider.get&lt;ServiceDependency&gt;(ServiceDependency.name)))<br>);</pre><h3>Conclusion</h3><p>Injected-ts is a valuable tool for simplifying dependency injection in TypeScript projects. By leveraging its features, such as the fluent API for dependency registration, flexible lifecycle management, and scope support, you can enhance</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ba5f75f5715" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean code story — How to shorten your methods]]></title>
            <link>https://rhenache.medium.com/clean-code-story-how-to-shorten-your-methods-9d216cf0ba33?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/9d216cf0ba33</guid>
            <category><![CDATA[oop]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[craftsmanship]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Mon, 19 Jun 2023 14:04:28 GMT</pubDate>
            <atom:updated>2023-06-19T14:25:48.477Z</atom:updated>
            <content:encoded><![CDATA[<h3>Clean code story — How to give sense to your code</h3><h4>Using encapsulation and Tell don’t ask principle</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*RSUcokO_Mrbmal5XoyhZ4g.png" /></figure><p>Have you ever come across a method in your code that is seemingly endless? You scroll and scroll, but the brackets don’t seem to end. That’s usually a clear indication that the method is trying to do too much, and it’s high time for some cleaning.</p><p>When we talk about clean code, we’re discussing code that is easy to read, understand, and change. Long methods are often the enemies of clean code. They can be hard to understand, tricky to debug, and resistant to modification. Today, we’ll explore how encapsulation and the ‘Tell, Don’t Ask’ principle can help us shorten our methods and write cleaner, more maintainable code.</p><h3>Encapsulation for Cleaner Code</h3><p>Encapsulation is one of the four fundamental principles of object-oriented programming (OOP). It suggests that the data of an object should be hidden from outside world and can be accessed only through methods of its own class. This increases modularity and maintainability of the code.</p><p>When you encapsule your data, that means your setter are private. Ideally, your getter also are. You can then only manipulate the instance using methods that match operation you would apply on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/469/1*qbR8JQNoLifFxcBgtzRjBQ.png" /></figure><p>This simple code example show a code without encapsulation. If you want to increment your counter, you use the counter service to increment. Or maybe worse, you don’t know about this service, and duplicate the code elsewhere.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/346/1*SzDmJOaLc0QaYgwF8Wl9dg.png" /></figure><p>Now there is the same example, using encapsulation. If I want increment the counter, I have no choice except using increment(). This have many advantages.</p><ul><li>First it tell what operation are possible on this class.</li><li>Second, avoid the code duplication, as the “count” property is not accessible, no one can duplicate this behaviour.</li><li>Third, it protects the class internals, the behaviour implementation. This means that the count property can be an int, a float, or a subclass, that doesn’t matter from an external point of view. Because the fact that we call “increment” and doesn’t manipulate the count property, we don’t care about how the count is done.</li></ul><h3>The ‘Tell, Don’t Ask’ Principle</h3><p>The ‘Tell, Don’t Ask’ principle suggests that we should command objects to perform actions, rather than asking them about their state and making decisions on their behalf. By following this principle, we can further shorten our methods and make our code more readable and maintainable.</p><p>Going back to our example, we need to know if the counter is more or less than a number to decide if we make an action or not.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*_ESal51etB5orVx1KThxoQ.png" /></figure><p>The service manipulate the counter to do an action every 10 times.<br>Now there is a version using encapsulation and tell don’t ask principle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/634/1*UoS_AKBcs1nCa2nbZ8_j2g.png" /></figure><p>The count property is internal to the counter object. Code becomes more readable, cleaner, and it’s protected against duplication.</p><p>An even better approch could be to create a new object, a Timer for example, to encapsulate this behaviour instead of using a service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/643/1*QQTZlWBz1ue2rVCxS_QcqA.png" /></figure><p>This Timer use a counter as an internal dependency, but it’s hidden from an external point of view. As a timer user, we only create a timer, then call increment(). We don’t care about how increment work, and how the action will be executed. We trust the Timer, and can’t do anything against that, because all the timer behaviour is protected.</p><p>This approach not only helps us to ensures that our objects maintain their own state and behavior, adhering to the principles of OOP.</p><h3>Ecapsulation discovery</h3><p>One useful approach is to follow the principle of “high cohesion,” which suggests that methods within an object should be closely related and work together to accomplish a specific task. This means that a method should operate on the object’s internal state or collaborate with other methods of the same object.</p><p>Another consideration is to analyze the external interactions with the object. By applying the “Tell Don’t Ask” principle, we can identify opportunities for encapsulation. Instead of exposing the internal state and allowing external entities to manipulate it directly, encapsulation encourages defining methods that encapsulate the necessary operations and provide a controlled interface for interacting with the object.</p><p>Additionally, examining the parameters passed to methods can guide the creation of new methods. If a method only has one parameter, it may be an indication that the functionality it performs can be encapsulated by the type of that parameter. By encapsulating such methods within the relevant object, we enhance code organization and improve the clarity of the codebase.</p><p>Ultimately, discovering the methods to create or add to an object requires a thoughtful analysis of the object’s responsibilities, behaviors, and interactions. By considering the principles of high cohesion, encapsulation of operations, and parameter-based encapsulation, we can effectively identify and define the appropriate methods that enhance the encapsulation, modularity, and maintainability of our code.</p><h3>The Payoff</h3><p>By embracing encapsulation and the ‘Tell, Don’t Ask’ principle, we can significantly shorten our methods by dispatching code to the nearest to responsible of the data and avoiding duplication. These practices allow us to create cleaner and more modular code. In the process, we also create code that is easier to test and less prone to bugs.</p><p>Clean code might require more effort in the short run, but the benefits it provides in terms of readability, maintainability, and testability make it a worthwhile investment.</p><p>Remember, clean code is not just about shorter methods. It’s about creating a code base that your future self and other developers can read and understand with ease. It’s about code that can stand the test of time and adapt to changing requirements.</p><p>So, the next time you come across an excessively long method, consider using encapsulation and the ‘Tell, Don’t Ask’ principle. These powerful tools will go a long way in your journey towards writing clean code.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9d216cf0ba33" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean code story — No comments]]></title>
            <link>https://rhenache.medium.com/6-reasons-to-replace-comments-by-short-methods-16744287d9b6?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/16744287d9b6</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[comment]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[best-practices]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Wed, 13 Jul 2022 14:20:43 GMT</pubDate>
            <atom:updated>2023-06-19T14:48:30.480Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why you should prefer short methods to comments, even on already short methods</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*ytfm4spA8bJN_9XR6vMysA.png" /></figure><p>Recently, I tell a teammate that a method is too long, and should be refactorized to be shorter, and more explicit. I tell him that it’ll allow him to replace him comments. He responds me :</p><blockquote><em>“Why should not use comments? Why it’s better to have short methods? Even if it’s only a private method inside the same class?”</em></blockquote><p>So, for my teammate, and all of us, there is a list of WHY a short method is better, <strong>even for already small methods</strong>.</p><h3>1- No language gymnastic</h3><p>Ok, I agree, this is not the best argument, but still it’s one !</p><p>When you read code, your brain adapt himself to read short and condensed names. Used to read PascalCase or whatever naming convention you use. So, when you have comments between lines of code, your brain should change his mind to read literal english (or once again whatever language you use), then re-adapt to code reading, and then again, change to literal language… Morever each comment extends the code length, so the time to read it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*PCPSkV1rN-KcIiktDZMGXQ.png" /></figure><p>Look how it’s easier to read the version without comments:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*pANUut0xA_qChqgz1BTSSA.png" /></figure><h3>2- Use early return in short methods, to make it even shorter</h3><p>Another argument is that more you use short method, the shorter they could be !</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/897/1*yfWWsGBEQh_aP7Xm3ptAvg.png" /></figure><p>This exemple has more than comments as default for readability. But this will show how short methods and early return can improve your readability and avoid comments.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/905/1*JZbLp1UOqjz2jq6l2EFrMQ.png" /></figure><p>Even if the code contains more methods declaration, It’s still shorter than the previous version. And obviously more readable. Because methods are named, we understand clearier the context/problem the method should resolve. And because we can use early return, each methods is shorter (no ELSE). As they are shorters, they are off course more readable again.</p><h3>3- Debugging facilities</h3><p>Using submethods can help to debug. As the stacktrace will tell you in wich method the problem occurs, and as your methods are short, you can find were faster.</p><p>As your code is more readable, as each methods use only parameters they needs, you can find what happen easier.</p><p>Some of you we’ll tell me “My debugger tell me the line of code, so I don’t need short methods”. Yes generally debugger does. But when you debug from production log, you can’t have this information (as compiled code is different from source code). So a method name is a good point.</p><h3>4- Up to date comments</h3><p>Using short methods, and there names as comment (name are intent based) will create a commented code always up to date !</p><p>Let me explains. Imagine you have the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/714/1*gFhwspO5fCValpwPNz9CsQ.png" /></figure><p>This code sample is pretty simple. And we can understand what happens with comment. But now imagine the following code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/773/1*erhxzh4rR3XezfpN4DK9Sg.png" /></figure><p>We write the exact same rules, but using coding name, using methods (and constants). Of course, if we want understand how the price is calculated, we need to read the method which do it.</p><p>Now imagine, the business rule change. We don’t calculate the price from the number of items, but from their weight, and apply a price of 2.5€ by kilo. If the first version, the change is simple:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/713/1*C1yDAVreaxyzM9eMy93eZQ.png" /></figure><p>But there is a but. There is a probability that the comment upper will not be up to date. Especially if the comment is some lines distant. And if the developer think about it, and change it, he code twice. Once to write the comment, and another one for the code itself.</p><p>In the refactorized class, we have something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/733/1*2B97okEmfKcPN3EeKuSxlA.png" /></figure><p>The business rule is still apparent. And as the method CalculateSendFees has changed, the method to get the number of articles has disapear. Instead, we have a method to get the weight. Your code “reading” is still up to date with the business rule !</p><h3>5- Easier refactorization and encapsulation</h3><p>The smaller are your methods, the more understandable they are. And the more you understand what you do, the better you can make it well !</p><p>If your methods are shorts, you can then apply the encapsulation principle, and make them reutilisable.</p><p>Still on the command “SendPrice” calculation example. Imagine now, we have a new business rule, that is “If a client is at least 60 year old, he get 10% reduction on sending fees”.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/1*JFic8OleshJVZpluz-sO-A.png" /></figure><p>Still without comments, the code is always easy to read, and business rules are visible. But we can see that Discount method use client property to make a calculation. We can optimize it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*sIY1XNVWehWdB6n3MPfO9A.png" /></figure><p>Now, it look evident ! The IsOver60 method work only on a client. This should be a method of the Client class ! Off course, as the 60 years value is own by the command rules, we’ll make it a parameter of the method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*Cdq4PIRHQUv3J1iRRO5zNQ.png" /></figure><p>Now, the “IsAgedOver” can be used by many other context working with client object. May be, we can even make the client birthdate private to make better encapsulation.</p><p>Sometimes, you’ll not only add methods to existing object, but create NEW OBJECTS ! For example, if price calculation become more and more complex, we’ll add many submethods. When we think it’s too many, it’s a sign that a new notion emerge from your code. You should probably create a new object or contrat to encapsulate this notion. In this example, we can imagine create a ShipPrice class, using a command to compute the price, or offering some “fluent building interfaces”.</p><h3>6- Apply it to infinity and beyond</h3><p>As you can see from the example above, we can apply this principle even on already short methods. This mean you can always (or almost) make your method smaller, and get profits from it !</p><p>As your methods get shorter, you can make them even shorter on a next refactorizatio niteration.</p><blockquote>There is a rule saying “No more than 5 lines by method”</blockquote><p>And as you can see, 5 lines is already big ! You can do better ! Make it explicit ! Make it work for you ! As your methods are shorter, you understand them better ! You can refactorize them better !</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=16744287d9b6" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Clean code story — Exceptions handling]]></title>
            <link>https://rhenache.medium.com/clean-code-handling-exceptions-3ad9aac2ea22?source=rss-9660a5b77c89------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ad9aac2ea22</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[exception-handling]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[craftsmanship]]></category>
            <dc:creator><![CDATA[Nash]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 16:26:46 GMT</pubDate>
            <atom:updated>2023-06-19T14:51:57.531Z</atom:updated>
            <content:encoded><![CDATA[<h4>Why not returning null? And how to handle exception in a clean way</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*a4AHtaUO1UejgKZgpflQ1w.png" /></figure><h3>What is the problem with returning null, and allowing variables to be nullable?</h3><p>It’s not a big deal at first look, but that mean you should always testing if your variables are not null before accessing their properties or methods. So you have some code looking like the following :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/423/1*Qph9I8RkFs78d8rbLClpZA.png" /></figure><p>This code check if a command is sent, by checking if all items that compose this command are sent. As object instances can be null, we should check it before accessing to the “item.IsSend” property.</p><p>Worse, this code return true if a command, or command items are null and don’t return false if an item is null. That a big headache to find how to handle the null value in theses cases. What does a null command mean? How should I handle the fact that a null command is sent? What if an item inside this command is null? How to validate that this null item is sent or not?</p><p>And it’s just one problem inside too many. Your code will repeat all these null check every times you need to access properties or method of an instance, contaminating your code with many condition that have nothing to do with your business or your feature.</p><h3>How to remove nullable variables?</h3><p>It’s pretty simple, doesn’t allow your code to return null! And Consider your class/struct properties should have a default value, or value should be given by the constructor.</p><p>If your code never return a null instance, and if all your instance are correctly initialized, you can’t encouter a null reference. The only limit to it is when you interact with some external services, like a DTO from a front client received by your API, or an external API, that could have some null properties. You should create an ACL (Anti Corruption Layer), to transform the DTO or the API responses into your object, checking for null value, and mapping null value to the default value of this property.</p><p>For exemple, if you have an enum:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/213/1*4UNzb49zuC9rKgOOCVPMXg.png" /></figure><p>You can simply add an “unknown” value, to handle the case where you don’t know the correct status.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/224/1*VJgYvAIvAiJG5YnXHmYLpw.png" /></figure><h3>What nullable have to do with exception ?</h3><p>In some case, a default value, like the unknown CommandStatus could be a good option, in some other case, you may don’t want to deal with an unknown status. Considering that it should never happened. Because in your business case, you will never have to treat a command with this kind of status, and you can’t guess what to do with it. Yes, exactly like if it was a null value !</p><p>So, <strong>if a default value can’t give you a good state for your business, you should throw exception</strong>, when the problem occurs. For exemple, in your ACL, when a value of the external API cannot match to your current needs, you should throw an exception. This will ensure that your domain never have nullable variable, and ensure that you integrate only data you can work on.</p><p>ACL off course arn’t the only part of code that could raise exception. Every part of your code could. <strong>Every time your code meet a case where you don’t know what to do with this, you should raise exception</strong>.</p><h3>Before, I was afraidof raising Exception</h3><p>I don’t know if you have the same feeling, the same memory (if your are a more senior developer), but for me, when I started to code, raise an exception meaned “I have a error” ! Like I want to be a good programmer, I don’t want to have error… So I prefered returning null. Then the code will throw an exception somewhere, saying “Null reference exception”. The stacktrace give me information on where the null reference occurs, but I don’t undestand “How can I have a null value here??”.</p><p>To avoid this problem, you should raise an exception when the problem occurs. Instead of a null reference exception, I should have a nammed exception, with the stacktrace showing me the real problem, and even more, some information about the context on when/why it happened.</p><p>With these informations, I can understand the real problem, and apply a good solution to handle it. Or may be, simply ignoring it, if this exception is raised by some data the business can’t ingest.</p><blockquote>I learned that raising exception doesn’t mean “I have a error”, but it mean “The system cannot handle this case for now”. It’s not my fault as a developer, it’s just that business, system, don’t know what to do in this case. So it’s better to stop the code execution now, than continue to execute code in invalid state.</blockquote><h3>Custom exception</h3><p>Always raise custom exception, except if an existing exception match well your case, like ArgumentNullException, ArgumentOutOfRangeException, ect.</p><p>By using custom exception, you get some advantages:</p><ul><li>You can find faster where it occurs, because the name of your exception is dedicated to some use case only</li><li>You can get a name that match the reason of the error, offering some possibility for thoses who will handle it to know how to handle it !</li><li>You can give the context information you need to analyze and understand why the exception occurs</li></ul><h3>Handling exception</h3><p>There are some good practice, bad practice, and some practice to adapt to your need.</p><p>Start with the bad practice. Catching exception, and throwing.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*L1EFdP-ieJO3M5cdUTRREQ.png" /></figure><p>Why it’s bad? The problem with this kind of code is that you will log your exception many times. Because if another method, calling this one, do the same kind of try/catch, the exception will be logged two times. And each time a parent caller do the same, you will log the exception again. That will make difficult for you to analyze your logs.</p><p>An another practice is to catch, then throw a custom exception:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/338/1*oGVnMeu9eHgYuvSpDJ4tHg.png" /></figure><p>This case is opened to be discussed, because I think in some case, it could make sense.</p><ul><li>Why it could be OK? It’s ok if you can hide a system exception, like HTTP exception, to replace it by a domain exception, making more sense to the developer, and hiding the implementation detail of an interface. But you should always ensure that your custom exception take trace of the real exception (as InnerException in C# for exemple).</li><li>Why It could be bad? It’s bad if you catch custom exception, to re-throw custom exception, you’ll lost the original meaning of the exception. You can off course add the original exception to the new one, but why should you have two custom exception, for the same source of error?</li></ul><p>As we saw, catching for logging or re-trhow is not a really good option. So when should you catch an exception? The response is simple:</p><blockquote>“Catch an exception only when you can handle it and take decision about it”</blockquote><p><strong>Exemple 1</strong></p><p>What does that mean? You should handle an exception only if you can change the way your application behave when you handle it. For exemple, in an web application, inside a controller, you should catch the potential exception to return a 500 http error status code, instead of a status 200. As you see, you make decision about the error, if an error occurs, the way the application behaves change. In case you have no error, you return status 200, otherwise you return a status 500.</p><p><strong>Exemple 2</strong></p><p>An other exemple is when you can make a re-try tentative. Imagine you have an HttpTimeOutException, that means the distant server take too long time to respond, or your request has been too long to be sent. But we can imagine that if we try again, it’ll success. The server doesn’t return a 500 error, so retrying may be OK. To do this, we need to catch the HttpTimeOutException, and apply the comportement to retry. Once again, we add some value to fact of this exception occurs.</p><p><strong>Exemple 3</strong></p><p>A last exemple is when you can try something else to achieve your goal. Imagine you try to access a data in some cache space. But the cache is expired, so, as it can’t return null, it throw an exception like “DataNotFoundException”. You can catch it, and try to get the data from the original database for exemple. This kind of comportement is call “circuit breaker”, even if this exemple is simple.</p><blockquote>If you have a retry policy or a circuit breaker policy, catch only the last exception that occurs, including the originals exceptions as InnerException.</blockquote><p>These three exemple arn’t an exhaustive list. The global idea is to catch when you can do something with the exception, when you can adapt the program flow to this problem. And logging is not and adaptation ! Logging is just logging.</p><blockquote>Log when you catch if you don’t re-trhow, but don’t consider logging as taking a decision about the exception.</blockquote><h3>Using Option, Result&lt;T&gt; or Monad</h3><p>Option, Result, or Monad types represent the possibility of a value being present or absent, success or failure, or any other outcome that can occur during program execution. By embracing these constructs, developers can handle potential errors or absence in a more explicit and controlled manner.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/775/1*TXixAsYSKn3mtJnYnmMpMQ.png" /></figure><p>Unlike exceptions that can interrupt program flow and make code harder to reason about, Option, Result, or Monad types encourage a more functional and predictable approach to error handling. They promote code that explicitly handles both success and failure cases, resulting in code that is more resilient and less prone to unexpected errors.</p><p>Additionally, these constructs encourage a compositional approach, where operations and transformations can be chained together using functional programming techniques. This enables developers to express complex error-handling logic in a more concise and readable manner, avoiding nested try-catch blocks or error-propagation issues.</p><p>By using Option, Result, or Monads instead of relying solely on exceptions, developers can create code that is more modular, testable, and maintainable. These constructs provide a structured way to handle errors and absence, leading to more robust and predictable software systems. However, it’s important to note that the choice between exceptions and these constructs depends on the specific requirements and context of the application, and there may be cases where exceptions remain a suitable choice.</p><h3>How to choice</h3><p>Using default values can be a straightforward approach for handling situations where a value may be missing or unavailable. It allows the program to continue execution without interruption, providing a predetermined default value. This approach is suitable when there is a clear and reasonable default value that can be used in such cases. However, it’s essential to ensure that default values are well-defined and properly documented to avoid unexpected behavior or incorrect assumptions.</p><p>Exceptions, on the other hand, are commonly used for handling exceptional and unforeseen scenarios that may occur during program execution. They provide a way to propagate and handle errors, allowing for immediate interruption of the normal flow. Exceptions are useful when exceptional circumstances require specialized error handling or when specific actions need to be taken in response to unexpected situations. However, exceptions can introduce complexity and should be used judiciously to avoid excessive code branching, performance issues, and reduced code readability.</p><p>Constructs like Option, Result, or Monads offer an alternative approach for handling possible errors, absence of values, or different outcomes. These constructs provide explicit representations of success or failure, allowing for more controlled and predictable handling of different scenarios. They promote code that explicitly deals with both success and failure cases, enhancing code modularity, testability, and maintainability. The compositional nature of these constructs facilitates code readability and reduces error propagation, leading to more robust and reliable software systems.</p><p>Ultimately, the choice between default values, exceptions, or constructs like Option, Result, or Monads should be based on careful consideration of the specific requirements, complexity, error-handling needs, and maintainability goals of the software project. It’s important to select the approach that best aligns with the project’s context and helps create code that is clear, reliable, and maintainable in the long run.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ad9aac2ea22" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>