<?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 Ben Seager on Medium]]></title>
        <description><![CDATA[Stories by Ben Seager on Medium]]></description>
        <link>https://medium.com/@ben_seager?source=rss-e909ffd4c3ec------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*5y97xLFmh4DB5RU7-BkVcg.png</url>
            <title>Stories by Ben Seager on Medium</title>
            <link>https://medium.com/@ben_seager?source=rss-e909ffd4c3ec------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 15:56:07 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ben_seager/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[Creating a Pure CSS Sidebar]]></title>
            <link>https://medium.com/swlh/creating-a-pure-css-sidebar-463ce30c1609?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/463ce30c1609</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[html]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[web-design]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Fri, 18 Sep 2020 20:51:17 GMT</pubDate>
            <atom:updated>2020-09-19T18:47:41.911Z</atom:updated>
            <content:encoded><![CDATA[<h4>Leave the JavaScript at the Door and Create a Collapsing Sidebar with CSS and HTML</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*j_hde_8pMVCYKH12" /><figcaption>Photo by <a href="https://unsplash.com/@florianolv?utm_source=medium&amp;utm_medium=referral">Florian Olivo</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I’ve lost count of the times I’ve had to implement some kind of sidebar menu that can collapse. Often, when faced with this task, our first thought will be to delve into our JavaScript toolbox and either roll our own solution, or reach for one of the many third-party offerings.</p><p>But what if it didn’t have to be this way?</p><p>Well, it doesn’t! Using just HTML and CSS we can create a collapsable sidebar <em>and</em> a content area that expands to fill the vacant space. Neat huh.</p><p>This is what we’re going to create.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/630/1*O0zq2CNUojTQAMtAtKgJzw.gif" /><figcaption>Collapsable Menu — no JavaScript here!</figcaption></figure><p>First, lets create an index.html file and put some markup down. We’ll go through it shortly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BG61jqrcS0qdMbqYxDhV7g.png" /><figcaption>index.html</figcaption></figure><p>Ok — let’s take a look at what’s going on here. We can ignore the head tag as there’s nothing really of interest (other than I’m using the fantastic <a href="https://fontawesome.com/">Font Awesome</a> for icons).</p><p>The first thing to notice is that everything is in a label. Our entire layout, contained within a label. Why is this?</p><p>Look at the first child. Its a checkbox. <strong>This</strong> is how we’re going to achieve the collapse/expand functionality without using any JavaScript.</p><p>How does this magic work?</p><p>Well, if you click on the label that click event is propogated to the checkbox and its checked state is changed. We can use the :checked pseudo-class selector, and some trickery with sibling selectors, to alter the width properties of the sidebar and content divs.</p><p>Right, let’s turn to css and look at how we go about implementing the expand/collapse functionality.</p><p><em>I’m using scss, so if you’re following along you’ll want to install something that can compile scss into css. I used </em><a href="https://www.npmjs.com/package/node-sass"><em>node-sass</em></a><em>.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DJijTTqdfpqliUjN2VsvlA.png" /><figcaption>The full site.scss</figcaption></figure><p>Ok — so there’s quite a bit going on here. Don’t worry, we’re going to break it down and walk through the important bits.</p><p>Firstly, how is it arranged? Well, we’re using flex and we’re aligning the items to the flex-start. This means the sidebar and content divs flow one after the other.</p><p>The label itself fills the screen, with the sidebar and content taking up small and larger portions respectively.</p><p>There are some transitions, to make a nice smooth animation, and the sidebar and content are have different colours — so we can easily see what is going on.</p><p>Now we’ll take a look at the input&#39;s style as this is the most important part of the implementation. It is what gives us the desired functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CoT91MQAsHtNkzUk58e6CQ.png" /><figcaption>The input’s styling (checked state)</figcaption></figure><p>The first thing to note is the positioning (lines 2 and 3). We don’t <em>acually</em> want a checkbox, so we’ll shunt it off the screen.</p><p>On line 5 we use the :checked pseduo-class selector to set up the style for the sidebar and content elements <em>for a collapsed state</em>. If the checkbox is checked, the sidebar will collapse and the content will expand. If the checkbox is unchecked, the opposite will be true.</p><p>As the sidebar div is a sibling of the input we can use the sibling selector, the +, to select and style it. On lines 7 and 25 the widths for the collapsed state are set.</p><p>We also toggle the icon — setting the hamburger to display:none and the chevron to display:block.</p><p>To implement the expanded state, we simply do the reverse (shown below).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/962/1*T0iv1C-NIAfSJj6n1ZSq7w.png" /><figcaption>The input’s styling (unchecked state)</figcaption></figure><p>And that’s it.</p><p>Almost.</p><p>As everything is contained within a label, clicking anywhere on the screen will toggle the checkbox. This is not desired behaviour!</p><p>To tackle this problem we make use of the pointer-events CSS property. This property sets which circumstances elements can become a target of, well, pointer events.</p><p>We only want the icon to be clickable so we set the label’s pointer-events property value to none, and the icon’s to auto.</p><h4>Conclusion</h4><p>There you have it — a very neat and simple way to create a collapsing sidebar using just CSS and HTML.</p><p>One final point — this is almost certainly <strong>not</strong> suitable for a lot of use-cases. We’re putting all of the content inside a label, and this really doesn’t feel right and certainly isn’t right semantically. This is a nice hack, that <em>can</em> be useful in certain situations. For a small, static site this approach can work really well but for other projects you may be best off with a different approach. This example also does not consider accessibility.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=463ce30c1609" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/creating-a-pure-css-sidebar-463ce30c1609">Creating a Pure CSS Sidebar</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Tip: Configure WebStorm for Deno]]></title>
            <link>https://levelup.gitconnected.com/quick-tip-configure-webstorm-for-deno-9490cd785de3?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/9490cd785de3</guid>
            <category><![CDATA[deno]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Fri, 05 Jun 2020 13:15:46 GMT</pubDate>
            <atom:updated>2020-06-05T13:38:56.203Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Have your IDE configured in minutes</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q-Dv1bCnFmJn---yqcq9sQ.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@cottonbro?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">cottonbro</a> from <a href="https://www.pexels.com/photo/three-wooden-dinosaur-3661193/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Out of the box, Deno and WebStorm work almost flawlessly together and you don’t <em>need</em> to do anything in order to be productive.</p><p>There are a few quality of life enhancements that we can make, however. Enhancements that address a couple of issues, namely:</p><ul><li>WebStorm complaining about file extensions in import paths</li><li>Resolution and completion of the Deno API</li></ul><p>Thanks to <a href="https://github.com/justjavac">justavac</a>, a Deno contributor, we have access to a TypeScript plugin that, when used and combined with WebStorm, addresses these issues and it only takes a matter of minutes to set up</p><ol><li><strong>Create a package.json</strong></li></ol><p>I know what you’re thinking — we’re using Deno not Node, so why do we need a package.json? Well we’re going to need to install and use the TypeScript plugin, so we need a package.json. This can be <em>very</em> small though.</p><pre>{<br>  &quot;devDependencies&quot;: {<br>    &quot;typescript&quot;: &quot;^3.9.5&quot;,<br>    &quot;typescript-deno-plugin&quot;: &quot;^1.31.0&quot;<br>  }<br>}</pre><p>That’s it. Six lines.</p><p>Once this file is created, run npm install.</p><p>2. <strong>Create a tsconfig.json</strong></p><p>Depending on what you need from Deno, you might already have one of these. If not, you’re going to need to create one from scratch. As with the package.json, this is really small too.</p><pre>{<br>  &quot;compilerOptions&quot;: {<br>    &quot;plugins&quot;: [{<br>      &quot;name&quot;: &quot;typescript-deno-plugin&quot;,<br>      &quot;enable&quot;: true,<br>      &quot;importmap&quot;: &quot;import_map.json&quot;<br>    }]<br>  }<br>}</pre><p>All we’re doing is adding the plugins array to the compilerOptions object, and telling the compiler to use the typescript-deno-plugin.</p><p>3. <strong>Change WebStorm’s Language Service</strong></p><p>Tell WebStorm’s TypeScript language service to use the locally installed TypeScript, rather than the built-in version.</p><p>Open WebStorm’s Languages and Frameworks settings for TypeScript</p><p>Settings/Preferences | Languages &amp; Frameworks | TypeScript</p><p>and change the <strong>TypeScript</strong> value to the path of the TypeScript folder installed in your local <strong>node_modules</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/986/1*ZtbqJyFQ6ZOBO13Y2Rdz1w.png" /><figcaption>Using locally installed TypeScript, rather than the built-in compiler</figcaption></figure><p>And that’s it!</p><p>No more marking imports with // @ts-ignore and no more erroneously unrecognised calls to the Deno API.</p><p><em>If you’d like to run </em><strong><em>fmt</em></strong><em> automagically, then you can </em><a href="https://levelup.gitconnected.com/quick-tip-deno-fmt-in-webstorm-aa3e6d3b034d"><em>find instructions here</em></a><em> — again this is a really simple process.</em></p><p>The team at JetBrains are working on fully native support for Deno within their IDEs but until then, thanks to the awesome work of <a href="https://github.com/justjavac">justjavac</a>, we can already get a really smooth experience.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9490cd785de3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/quick-tip-configure-webstorm-for-deno-9490cd785de3">Quick Tip: Configure WebStorm for Deno</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Quick Tip: Deno Fmt in WebStorm]]></title>
            <link>https://levelup.gitconnected.com/quick-tip-deno-fmt-in-webstorm-aa3e6d3b034d?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/aa3e6d3b034d</guid>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[deno]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Thu, 04 Jun 2020 14:12:51 GMT</pubDate>
            <atom:updated>2020-06-05T00:13:22.028Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Configuring a FileWatcher to format your code in three easy steps</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l6T0NVvUjbtsPRHJSJqj2A.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@magda-ehlers-pexels?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Magda Ehlers</a> from <a href="https://www.pexels.com/photo/white-dinosaur-figurine-on-wood-log-1319581/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>Now that <a href="https://deno.land/">Deno</a> has hit version 1, more developers are starting to experiment and see what it has to offer.</p><p>For me one of the coolest things that comes out of the box with a Deno install is <strong>fmt</strong>.</p><p>This format tool standardises deno code. No more arguments about tabs or spaces, dangling commas, or anything else! Happy days, we can concentrate on code, not code style.</p><p>Incidentally, this is the same idea as Co fmt, and this is one of the reasons I like Go so much too (it’s the little things).</p><p>I use WebStorm as my primary JavaScript/TypeScript IDE. I’ve nothing against alternatives like VSCode — use whatever you like, and whatever helps you to be productive is my mantra, but for me Webstorm offers a few quality of life things that VSCode et al don’t.</p><h4>Setting up a FileWatcher</h4><p>I like fmt to run while I’m editing — I don’t want to have to manually kick something off when I’ve finished doing a piece of work. This is where a FileWatcher comes in handy, and here is how I set one up.</p><ol><li>Open Settings/Preferences and Navigate to File Watchers</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*oGd5XrI1vkZc1o04adlFpg.png" /><figcaption>The File Watchers Pane</figcaption></figure><p>2. Add a new watcher, choosing <strong>custom template</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/701/1*xHu6-KOHAfIYmmERymyLmQ.png" /><figcaption>New Watcher window</figcaption></figure><p>3. Populate the required options. Give the watcher a name (I’ve gone with <strong>Deno Fmt</strong>). For <em>Program</em> use deno and for <em>Arguments </em>use fmt $FileName$. For <em>File Type</em> make sure you select <strong>TypeScript </strong>from the list, and limit the <em>Scope </em>to <strong>Project Files</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/702/1*3ils152Zw0fGXYUpD286Tg.png" /></figure><p>$FileName$ is a built-in macro. All it does is pass the current file name, extension included, to the watcher.</p><p>4. Enjoy your formatted code!</p><p>That’s it — three easy steps and your code will be formatted as you work. The first time it runs on a file you may get a dialogue warning you that the file has changed, if so just accept the changes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aa3e6d3b034d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/quick-tip-deno-fmt-in-webstorm-aa3e6d3b034d">Quick Tip: Deno Fmt in WebStorm</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Logging with Decorators in TypeScript]]></title>
            <link>https://medium.com/swlh/logging-with-decorators-in-typescript-1c3ce13576d5?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/1c3ce13576d5</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[typescript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Tue, 02 Jun 2020 22:12:44 GMT</pubDate>
            <atom:updated>2020-06-03T13:55:27.283Z</atom:updated>
            <content:encoded><![CDATA[<h4>Avoid tangled code by encapsulating cross-cutting concerns.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xr95amIoj4IUPCez7QOH5Q.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/snd63-2441173/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1484387">snd63</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=1484387">Pixabay</a></figcaption></figure><p>As codebases grow, so does the complex web of dependencies and concerns that individual modules rely on. Managing these can cause us headaches — even in the most well engineered applications.</p><p>Logging is a prime example of one such concern. We may have a logging functionality in one module, that is used across the application —<strong> cross-cutting</strong> it.</p><p>Consider the following example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DkmtSLKvbCeLSSxTBSNtBg.png" /><figcaption>Two classes with an injected Logger dependency</figcaption></figure><p>On the face of it, there isn’t too much wrong here. We’re injecting implementations of <em>Logger</em> (which happens to be an interface, we’ll see it shortly) so that’s a tick in the SOLID box.</p><p>There are some improvements we can make though. The <em>Logger</em> is a cross-cutting concern. It weaves its way through our application like ivy. Yes, we’re injecting it but consider the maintenance burden. If the <em>log</em> method’s signature changes that is an awful lot of refactoring that needs to be handled.</p><h4>Decorators to the Rescue</h4><p>If you use Angular you’ll already be very familiar with decorators in TypeScript but if not, don’t worry — this article presumes exactly zero knowledge. So, we’ll start at the beginning.</p><p>A decorator “decorates” a class or method and provides some extra functionality at initialisation time, i.e. when a class is instantiated. In this example we’re going to implement a decorator that logs a message whenever a method is invoked, so that we can remove the injected <em>Logger </em>dependencies and calls to <em>lo</em>g.</p><p>In TypeScript decorators look like this:</p><pre>@decorator()<br>public class Foo { ... }</pre><p>Ok, before we dive into writing a decorator let’s do some setup. We’re going to need some logging functionality. This will be handled by two classes, <em>ConsoleLogger</em> and <em>LoggerFactory</em> and an interface <em>Logger</em>. Let’s take a look at them:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ITglv9GYqFtI-3sJLztP1w.png" /><figcaption>Logger Interface</figcaption></figure><p>The <em>Logger</em> interface has a single method, <em>log</em>, which takes a string. Simple.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C2wVYGGzxE8Fx56WK2eP9g.png" /><figcaption>ConsoleLogger class</figcaption></figure><p>The <em>ConsoleLogger</em> class implements the <em>Logger</em> interface and, well, logs a message to the console (this is a <em>very</em> simple example, after all).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BydBwCO9E3Kj1hCqO_KaHg.png" /><figcaption>LoggerFactory</figcaption></figure><p>The <em>LoggerFactory</em> is responsible for creating and returning a single instance of the <em>ConsoleLogger</em>. If you’re familiar with the singleton pattern, then you’ll recognise this. If not - this is a quick, crude, example of implementing the singleton pattern.</p><p>Right — that’s the setup done. We’ve got a means of logging to the console. Now let’s look at implementing a decorator.</p><p>If you’re thinking that this kind of meta-programming is going to be complex, think again. TypeScript makes it really quite simple to implement some powerful functionality.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*D8UW16vw-JqjMabcx29EKA.png" /><figcaption>A simple decorator</figcaption></figure><p>Ok, let’s step through this. Some of it is obvious but some requires a little explanation.</p><p>On line 3 we’re using the <em>LoggerFactory</em> to get an instance of <em>Logger </em>that we’ll be using to write messages to the console. So far, so straightforward.</p><p>The fun starts on line 5.</p><p>We’re creating a function that returns a function. The “outer” function, the one declared on line 5, is actually the <strong>decorator factory</strong>. This is a function which creates, and returns, the actual decorator. We can use a decorator factory to customise how a decorator is applied, but in this example we’re just returning the decorator.</p><p>So, the decorator itself. This is the function on lines 6, 7 and 8. As you can see all it does is call the <em>log</em> method. This type of decorator is a <strong>method decorator</strong>. It should only be applied to a class’s methods.</p><p>You can see that there are three arguments - <em>target, propertyKey</em> and <em>descriptor</em>. Let’s define what these are:</p><ul><li><strong>target</strong>: The class that the member is part of</li><li><strong>propertyKey:</strong> The name of the member</li><li><strong>descriptor:</strong> This is, essentially, the object that you would pass to Object.defineProperty if you we’re writing this class in JavaScript</li></ul><p>OK — that’s our decorator up and running. Let’s implement it in the <em>Counter</em> class we saw right at the start of the article.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GG_hNrGJa45UnFtDCpU82g.png" /><figcaption>A simple node app’s index.ts file</figcaption></figure><p>The code above is the entry point for a very simple node app. It creates a new instance of <em>Counter</em> and does a loop, and in each iteration it prints the current count and then increments.</p><p>On lines 7 and 12 we’ve implemented the <em>simpleLog</em> (remember the @ syntax for a decorator). We’ve also been able to remove the injected logger from the class (yay, no cross-cutting concerns) and the hard-coded calls to <em>log</em> from each of the methods.</p><p>This will perform the same as before, logging that we’re calling each method on each iteration.</p><p>Right?</p><p>Let’s look at the output…</p><pre>❯ node index<br>Calling currentCount<br>Calling incrementCount<br>0<br>1<br>2<br>3<br>4<br>5<br>6<br>7<br>8<br>9</pre><p>Hmm…</p><p>Well the correct method names have been logged, so that’s a start — but we’re not getting anything logged from the decorators on each iteration.</p><p>Remember at the start of the article we learned that decorators are called at instatiation time and <strong>not</strong> when their decorated methods are called. That’s what we’re seeing here. An instance of <em>Counter </em>is being instatiated so the decorator is called.</p><p>So, how can we replicate the functionality we had originally.</p><p>Let’s create a slightly more useful decorator…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lKpLxpAAUO1sEQjbHp_34Q.png" /><figcaption>A second decorator, this time a little more useful</figcaption></figure><p>So similar to before, we’re using a decorator factory which returns a function and the arguments <em>target</em>, <em>propertyKey </em>and <em>descriptor </em>are the same. The difference is in the guts of the decorator function itself.</p><p>On line 3 we’re creating a copy of the descriptor’s <em>value </em>property. This is the decorated method that will actually be executed.</p><p>We then set <em>descriptor.value </em>to a new function, one which wraps the original. You can see this on lines 5 to 8. On line 6 we call <em>log </em>and on line 7 we call the copy of the original method and return the result.</p><p>Let’s implement this in <em>index.ts</em> and see what the output looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*y4HBDghLxQ_6mHVd6IYXjg.png" /><figcaption>Refactored entry point using usefulLog</figcaption></figure><p>The only change is to use our new <em>usefulLog</em> decorator.</p><p>And the output…</p><pre>Calling currentCount<br>0<br>Calling incrementCount<br>Calling currentCount<br>1<br>Calling incrementCount<br>Calling currentCount<br>2<br>Calling incrementCount<br>Calling currentCount<br>3<br>Calling incrementCount<br>Calling currentCount<br>4<br>Calling incrementCount<br>Calling currentCount<br>5<br>Calling incrementCount<br>Calling currentCount<br>6<br>Calling incrementCount<br>Calling currentCount<br>7<br>Calling incrementCount<br>Calling currentCount<br>8<br>Calling incrementCount<br>Calling currentCount<br>9<br>Calling incrementCount</pre><p>Much better!</p><h4>Conclusion</h4><p>We’ve seen how we can implement a simple decorator to log whenever a method is called and how this helps to alleviate cross-cutting concerns. If we ever needed to change the method signature of <em>log</em> we would only need to refactor one place — the decorator.</p><p>This was, of course, a very simple example but it has hopefully given you an insight into what decorators are and how they work.</p><p>As of right now (June 2020) decorators in JavaScript, and therefore TypeScript, are still experimental. Their final implementation in JS hasn’t been formally agreed. Personally I’m happy using the in TypeScript — where the compiler does an awesome job of abstracting experimental features away — but I’m less happy using them in un-transpiled JavaScript applications.</p><p>That being said this is very powerful functionality available to us, familiar to those from the C# or Java worlds, and can really help solve some problems (such as cross-cutting concerns).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1c3ce13576d5" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/logging-with-decorators-in-typescript-1c3ce13576d5">Logging with Decorators in TypeScript</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Data Transformation Using the Decorator Pattern]]></title>
            <link>https://levelup.gitconnected.com/data-transformation-using-the-decorator-pattern-d94441d13b66?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d94441d13b66</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Wed, 27 May 2020 21:15:13 GMT</pubDate>
            <atom:updated>2020-05-28T02:50:08.133Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kSSQLSBS__r_yPlPIOA1Eg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@gustavo-fring?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Gustavo Fring</a> from <a href="https://www.pexels.com/photo/anonymous-female-cook-in-uniform-and-latex-gloves-decorating-cake-with-macaroons-in-light-kitchen-3983660/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>The decorator pattern is one of the most versatile design patterns available to us in software engineering. It allows for behaviour to be added to an object dynamically while still obeying the Single Responsibility Principle. It is similar to the Chain of Responsibility pattern, <a href="https://levelup.gitconnected.com/validation-using-the-chain-of-responsibility-pattern-236a6ded7078">which I wrote about here</a>, but a key difference is that instead of a single class (or link in the chain) handling a particular request or action, all classes handle the request or action.</p><p>This article shows how useful this can be when transforming data, typically as part of an Extract, Transform, and Load pipeline. In the example, we’ll see how the decorator pattern can be applied to extend the functionality of an object all while maintaining compliance with the Single Responsibility Principle.</p><p>Ok — let’s crack on.</p><p>In this example imagine a system that stores and processes commodity data — data about oil, gold, silver, etc. Specifically, we’ll be looking at a Data Transfer Object, a DTO, that holds data retrieved from the database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yzJusmSwnCRBJIKIWmd5yA.png" /><figcaption>The Commodity model</figcaption></figure><p>This class, <em>Commodity</em>, stores the name of the commodity and some time-series data in a dictionary.</p><p>Our system needs to process instances of this model and produce an output in JSON. Pretty simple huh?</p><p>Well, almost…</p><p>You see the output needs to include values for <em>ValueAtEndOfYear</em> for years in the future. Somewhere in our pipeline, we’re going to need to do some maths and trend some new values.</p><p>This is where the decorator pattern can shine.</p><p>Before we go any further though let’s ask the question “can we put the functionality to do that maths in the model class itself?”</p><p>The short answer is an emphatic “No.”</p><p>The longer answer is — yes, you can. But you wouldn’t want to. Doing this would violate the single responsibility principle (<em>Commodity</em>’s responsibility is transferring data and <strong>nothing else</strong>) and introduce functionality that would change its own state in an encapsulated, obfuscated way. That way bugs and unexpected results lie…</p><p>Right, with that out of the way let’s move on and start implementing the decorator pattern.</p><p>First, let’s take a look at the expected output — it’s a simple JSON object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I_v-RB2YB4_CcTStMyOnrg.png" /><figcaption>The desired output</figcaption></figure><p>Ok — this is obviously different from the structure of the DTO so we’re going to need a decorator to do some transforming, along with some maths. It doesn’t matter too much which way round we do things, but it would seem to make sense to do the maths first. So that’s what we’re going to do.</p><p>First, we’re going to need an interface or a base class. I’m using an interface in this example — ymmv, for some situations a base class may be more suitable. We need this because our decorators need to implement the same methods as our decorated objects.</p><p>Here’s our interface, and we’ll assume that we’ve implemented this in the <em>Commodity </em>class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BeFf3m9sdVHr_ca1aHc-fw.png" /><figcaption>The ICommodity interface</figcaption></figure><p>Now we need to implement a base decorator class. This abstracts away common functionality. When doing this for real, make sure you keep your focus narrow — you don’t want to end up with a <a href="https://softwareengineering.stackexchange.com/questions/368797/sample-code-to-explain-banana-monkey-jungle-problem-by-joe-armstrong#368798">banana, gorilla, jungle problem</a>!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vbiHhvah47DWeavBJHnoGw.png" /><figcaption>Our abstract base class</figcaption></figure><p>For our little example, this base class might seem a little superfluous (and it is, to be honest) but if you were implementing this for real you would almost certainly want to pop common functionality in a base class.</p><p>Ok, that’s the base class done. Now let’s implement a decorator that calculates trended values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*96CHFVo6TOLDHwr4CeBRQQ.png" /><figcaption>Our first decorator implementation — which calculates trended values</figcaption></figure><p>Let’s have a quick look at what’s going on here.</p><p>The constructor takes an instance of <em>ICommodity</em> — which could be another decorator or an instance of the <em>Commodity</em> class. It also takes an instance of <em>ITrend</em>. We won’t go into detail about what this is but, essentially, it performs the maths to trend the values.</p><p>The main action is happening in the property <em>ValueAtEndOfYear</em>. We’re overriding the implementation in the base class (which in turn just gets/sets the decorated commodity’s properties). Instead of just returning the value from the base class we call the method <em>TrendValues</em>. This method uses the <em>ITrend</em> instance to trend values and then return them, along with the values stored in the base class.</p><p>Right — on to the second decorator. This one will handle the data transformation so that our output matches the required schema.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kVJGfihBTo0Qd91Ij8aZrw.png" /><figcaption>The format decorater</figcaption></figure><p>In this decorator, we’re overriding the <em>ToJsonString</em> method. We pass in an instance of <em>IFormatter</em> and use this to get a string in the correct format. As with <em>ITrend</em> above we’re treating this as a black box for this example, just assume it works as we’d want ;)</p><p>You’ll notice that both decorators have something in common — they override methods. This is pretty much key to understanding what and how we’re achieving what we are. We use the decorator classes to provide extra data, or manipulate existing data, and we do this by providing overrides of existing methods.</p><p>Ok, good stuff. We’ve now got our two decorators, to trend values and create the correctly formatted output, and all we need to do is wire it up.</p><p>Below is a snippet of a class that handles the export. We’ll walk through it in a second.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ku2qfn8QUYG-aAzjcnTuRg.png" /><figcaption>Wiring it all up in an exporter class</figcaption></figure><p>The method we’re interested in here is <em>ExportAsJson</em>. It takes an instance of <em>Commodity </em>as its argument, we’re only interested in passing this method DTOs so we don’t use an interface.</p><p>Then, on line 10, we create an instance of the <em>CommodityTrendDecorator</em> class and pass this the commodity to export and implementation of <em>ITrend</em> (in this instance we’re predicting that this commodity is going to increase in value exponentially).</p><p>On line 11 we create an instance of <em>CommodityFormatDecorator</em> and pass this our instance of the trend decorator and an instance of <em>IFormatter</em>.</p><p>Finally, we get the desired output — for brevity I’ve not shown what we actually do with this nicely formatted JSON.</p><p>You’ll notice how similar the code in the <em>ExportAsJson</em> method looks to a chain of responsibility. I said at the beginning that the decorator and chain of responsibility patterns were similar, and now you can see why!</p><p>The difference is also clear — to complete our operation we use every decorated class, each one performs some action and they don’t hand off responsibility to another.</p><h4>Conclusion</h4><p>In this article, we’ve seen how we can add behavior to a class, how we can extend it’s functionality, without violating the Single Responsibility Principle.</p><p>We’ve taken a simple DTO and provided a mutation of its state in a controlled, manageable way. We’ve also implemented a way of formatting that data for export without having to pollute the DTO with a lot of extraneous methods.</p><p>This kind of thing is a reasonably common one that we face in our day to day, and using decorators is not the only solution. What we’ve done here could be done by passing the DTO through a chain of responsibility, for example. That being said if you combine the decorator pattern with the strategy pattern, you can create flexible yet robust systems.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d94441d13b66" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/data-transformation-using-the-decorator-pattern-d94441d13b66">Data Transformation Using the Decorator Pattern</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Arrays: 5 Useful Recipes]]></title>
            <link>https://levelup.gitconnected.com/javascript-arrays-5-useful-recipes-3551a7d32c3?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3551a7d32c3</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[javascript-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Tue, 26 May 2020 20:59:35 GMT</pubDate>
            <atom:updated>2020-05-27T01:55:26.121Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*boI8UnSVtNmd_zC4S5iq9w.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@enginakyurt?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Engin Akyrut</a> from <a href="https://www.pexels.com/photo/cast-iron-skillet-on-table-with-species-1435909/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>JavaScript is an incredibly powerful and versatile language. As it has matured through ES5, ES2015, and beyond it has evolved from a scripting language confined to the web to the backbone of large applications — powering web-servers capable of handling many thousands of HTTP requests efficiently and quickly.</p><p>Whether you’re working with Node, Angular, React, Vue or even vanilla JS you’ll often be presented with problems that require sets of data to be manipulated.</p><p>This mini cookbook gives you five useful recipes for you to apply when posed with a problem involving arrays, all without the use of a third-party library.</p><h4>1. Calculate a Sum</h4><p><strong>Key Ingredient: </strong>reduce</p><p>We can use the reduce method to execute a function (a reducer) on each element of the array and return a single output. Using this technique we can sum numerical values.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*18YAAcabM5w37iiElFh0TA.png" /><figcaption>What a midfield, and what a bargain</figcaption></figure><p>The reducer (a, b) =&gt; a + b.price on line 8 takes the accumulated value, a, and adds it to the current iterations value’s price property. The 0 is the initialisation value, the first value of a.</p><h4>2. Combine Two or More Arrays</h4><p><strong>Key Ingredient:</strong> concat</p><p>We can use the concat function to combine two or more arrays.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XfypmTPXc3Yt0adl_mOB_A.png" /><figcaption>Quite the collection…</figcaption></figure><p><strong>Alternative Ingredient</strong>: Spread operator</p><p>We can use the spread operator to create a new array from two or more arrays, in a similar way to concat. Be aware however that the spread operator and concat do differ, especially when working with non-array objects. Performance should also be considered — using the spread operator can be <a href="https://jsperf.com/spread-vs-concat-vs-push">significantly slower than concat</a>.</p><p>Replace line 13 in the example above with the following to see the spread operating in action</p><p>const menagerie = [...suitablePets, ...unsuitablePets];</p><h4>3. Transforming Elements of an Array</h4><p><strong>Key Ingredient</strong>: map</p><p>We can use the map method to execute a function on each element of the array and return an array of that function’s output.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2QKy1aTTios0sIuU-gZ21w.png" /><figcaption>Using map to discount some games (that I like)</figcaption></figure><p>The function passed into map on line 8 takes the current iteration’s value, g, and returns a new object based on the discountRate constant. The result is an array of new objects.</p><h4>4. Joining Data from Two Arrays</h4><p><strong>Key Ingredients</strong>: map and reduce</p><p>We can combine the map and reduce methods to implement functionality akin to a SQL join.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0os-oMf6Ma5D6NZTAyPCMQ.png" /><figcaption>You can’t go, boldly or otherwise, if you don’t know who is on which ship</figcaption></figure><p>In this recipe, map and reduce are combined to impersonate a SQL join. On line 16 we call the map method on the crew array. As seen in recipe three, map allows a function to be applied to each element of the array and returns a new array.</p><p>The function implemented here, on lines 16 to 20, takes the current iteration’s value and returns the result of the Object.assign method. Using assign like this takes care of merging properties.</p><p>On line 20 reduce is used. Recipe one shows how reduce can be used to return a single value from an array. Here we’re using that functionality to populate our return object’s properties. The reducer goes through each of the elements in the ships array and returns the object which forms the <em>accumulator </em>( a in this example). When a match between the crew element’s shipId property and the ship element’s id property the complete matched object is returned.</p><h4>5. Grouping Data</h4><p><strong>Key Ingredient</strong>: reduce</p><p>We can use the reduce method to group objects of the same type by the value of one of the object’s properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EfrQ0JehQbtev34jEZRvVQ.png" /><figcaption>Grouping furry friends</figcaption></figure><p>In order to select elements of an array into distinct groupings the reduce function can be leveraged.</p><p>Let’s break down the reducer function:</p><p>Line 10: acc[val.type] = acc[val.type] || [];</p><p>This line ensures that the object to be returned from the reducer has a key with the value of the current iteration’s type. If one exists, the current value is maintained. If one does not exist, one is created and initialised with an empty array.</p><p>Line 11: acc[val.type].push(val);</p><p>This line pushes the current value into the array that was just initialised.</p><p>Line 12: return acc;</p><p>The accumulator, complete with new value, is returned.</p><p>On line 15 a new array is created by calling reduce on the animals array. The reducer is initialised with an empty object.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3551a7d32c3" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/javascript-arrays-5-useful-recipes-3551a7d32c3">JavaScript Arrays: 5 Useful Recipes</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fancy Checkboxes in Svelte]]></title>
            <link>https://levelup.gitconnected.com/fancy-checkboxes-in-svelte-d633a2a31619?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/d633a2a31619</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[svelte]]></category>
            <category><![CDATA[css]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Fri, 22 May 2020 22:00:41 GMT</pubDate>
            <atom:updated>2020-05-26T08:23:17.796Z</atom:updated>
            <content:encoded><![CDATA[<h3>Custom Checkboxes in Svelte</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gr3kgm0McAm1eeJJog7jfg.png" /><figcaption><a href="https://github.com/sveltejs/svelte">Svelte Logo</a></figcaption></figure><p>Normal checkboxes are dull. They do a job, of course, but they can’t be styled and their native appearance varies between browser and device.</p><p>There is a relatively straightforward solution to this problem — we can create custom checkboxes using CSS which match the rest of the UI in our app.</p><p><a href="https://svelte.dev/">Svelte</a> is a framework for building web apps that is rapidly gaining traction. I won’t cover any of the benefits of Svelte in this article, that would be out of scope, but suffice it to say that I like it. I <em>really</em> like it.</p><p>In this article we’re going to be building a Svelte component. A fancy checkbox component.</p><p>Right, let’s go!</p><h4>Step One: Setup</h4><p>First things first — set up a new project. The easiest way to do this is with the <a href="https://www.npmjs.com/package/npx">npx</a> and <a href="https://github.com/Rich-Harris/degit">degit</a>:</p><pre>npx degit <a href="https://github.com/sveltejs/template">sveltejs/template</a> fancy-checkbox-article</pre><p>This command creates an empty project ready for us to start coding. Well, almost everything.</p><p>I’m going to be using SCSS for this example, so we need to install a few more tools to help.</p><pre>npm i -D node-sass svelte-preprocess autoprefixer</pre><p>If you haven’t already done so, run npm install to make sure everything needed is installed.</p><p>The final set up step is to wire up a SCSS preprocessing. Don’t worry, this is really quick. We need to make a small change to our rollup.config.js.</p><p>First we add the following import:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x4F5-OxUNPQ8w3TLxKr3yw.png" /><figcaption>Importing the svelte preprocess package</figcaption></figure><p>Next we create a constant that holds some configuration details for the preprocessor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gWxif5cj75kWb0AGx9nTQ.png" /><figcaption>PreProcessor configuration constant</figcaption></figure><p>Finally we plumb our new constant into the rollup configuration — specifically in the Svelte config section. The complete rollup.config.js should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N_zjAa5litDYQ9-vW7Z1Fg.png" /><figcaption>Complete rollup.config.js</figcaption></figure><p>You can see on line 33 that we’ve added the preprocess constant we created.</p><h4>Step Two: Markup</h4><p>Right, with the setup out of the way we can actually write some code.</p><p>Create a new file in the src directory — this will be our fancy checkbox component. We’ll call it <strong>fancy-checkbox.svelte</strong>.</p><p>The first thing we’ll do is create the markup. There really isn’t much here, and I like to tackle low-hanging fruit first.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAyDtktBGlpzQK84JWtGDw.png" /><figcaption>The markup for our fancy checkbox component</figcaption></figure><p>So, what’s going on here? We’ve created a label and inside the tags we have a checkbox and two spans. This is a reasonably common pattern for creating a custom, CSS-only, checkbox.</p><p>The span with the class checkmark contains two image tags. As this is a fancy checkbox, we’re going to use images for the checked and unchecked states. I’m using these, but feel free to use whatever you feel like!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*x1olmgG9fx6n8G0BizCBUQ.jpeg" /><figcaption>A bear will be the unchecked state</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/1*VFC5YduR6_-xGutIBa_unQ.jpeg" /><figcaption>A kitten will be the checked state</figcaption></figure><p>Save these images, or ones of your own choosing, in the public directory of your app and set the images’ src attributes to the pictures’ URLs:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sdJpHl6xzp8OHSbJ4aqu0w.png" /><figcaption>Populated src attributes</figcaption></figure><p>Now that the markup is done let’s wire it into the main component, App.svelte and take a look.</p><p>Open and modify App.svelte so that it looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hCiwxars-uuFG_UZ0IZPrQ.png" /></figure><p>Ok — let’s fire up the dev server and see what things are looking like. Run the following command and head to a new tab in your browser, pointed to localhost:5000</p><pre>npm run dev</pre><p>You should see two nice pictures (a kitten and a bear if you’re using the ones from this article) and a little checkbox. If your images aren’t displaying, check the src attribute values.</p><h4>Step Three: Style</h4><p>This is where the real heavy lifting is done — the style tag. We’re keeping things as pure css (yes, were using SCSS but that compiles to CSS) so it makes sense that most of the work happens here.</p><p>Here is the complete style tag. We’ll step through it in a moment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmcJi9Gv6wNlfaVMnjIGuA.png" /><figcaption>The complete style section of the fancy checkbox component</figcaption></figure><p>The first thing to note is on line 1. As we’re using SCSS we need to tell the compiler that the code in the style tag is SCSS and not just plain old CSS. This is what lang=&quot;scss&quot; does.</p><p>I won’t walk through each and every line of this tag but an overview of the key sections will be useful.</p><p>At a high level what we’re doing here is hiding the checkbox input and, based its checked state, showing or hiding an image. As everything is contained in a label a click on the label is counted as a click on the checkbox input itself.</p><p>Lines 14 to 24 uses the checkbox’s :checked attribute to show and hide the correct images. Lines 26 to 37 work in the same way, but make use of the CSS not selector on the checked attribute.</p><p>Lines 56 to 64 set up the “label” for our fancy checkbox. We’ll deal with that now.</p><h4><strong>Step Four: Adding a Label</strong></h4><p>If we’re asking a user to select something from a list, it would be a good idea to give them some kind of textual information as to what it is they’re selecting.</p><p>Let’s add a label.</p><p>Add the following to the script tag:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KE5fLM5tv6sDNne0TSL97w.png" /><figcaption>Setting up a prop for our label content</figcaption></figure><p>As we’re creating a reusable component we can’t hard code a text value, we need to pass one in. This is where this variable comes in.</p><p>Alter App.svelte so that our checkbox has a label.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VyJgeFNtiBkTUm-qsSHRHw.png" /><figcaption>Passing a value from the App component to the fancy checkbox</figcaption></figure><p>The final step is to render the value we’re passing, <em>“Kitten or Bear”</em>, in our fancy checkbox component. This is super easy in Svelte.</p><p>Change the markup section of fancy-checkbox.svelte so that the labelContent variable is rendered.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JBb6WdfvjfZVZmTOA-KImQ.png" /><figcaption>Rendering the label text</figcaption></figure><p>If you haven’t already done so check your browser — you should now have a nice fancy checkbox with a label value. Clicking it should change the image.</p><h4>Step Five: Reactivity</h4><p>A checkbox, or any input for that matter, isn’t really any use if we can’t get its value. So, let’s add some reactivity.</p><p>Add a variable to the fancy checkbox’s script tag. This will store the checked value, and will forward it to the app component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iF2E9c_8XvJBCqbiAQTXGw.png" /><figcaption>Declaring an export variable — a prop — to store and forward the checked state</figcaption></figure><p>Now we bind that variable to the input’s checked state. We do that like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_GwK5CAgyKbpQ-UBOe6zRQ.png" /><figcaption>Checked is now bound to, well, checked</figcaption></figure><p>Brilliant, we’re almost there. We now need to forward the bound value to the app component. Svelte makes this really easy.</p><p>Go back to the app component and make the following additions to the script section.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wTfTZxuoAW84nEPTjpQxpw.png" /><figcaption>A variable to hold the checked value, and a reactive variable which uses it</figcaption></figure><p>If you’re unfamiliar with the syntax then no worries, we can skip over it for now — but do check out the tutorial on the <a href="https://svelte.dev/">Svelte website</a>. Simply put though using the label syntax indicates that we’re going to be doing something that needs reactivity.</p><p>Finally — make a couple of extra additions to App.svelte, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wWXdq8ic4GEl1ARMRvJzyg.png" /><figcaption>The final state of App.svelte</figcaption></figure><p>You’ll notice the addition to the FancyCheckbox tag on line 9. We bind the fancy checkbox component’s checked prop to the checked prop declared on line 4.</p><p>On line 11 we provide some output by using the reactive variable declared on line 5— has the user selected a kitten, or a bear?</p><h4>et voilà</h4><p>Jump back to the browser and admire the handywork. A custom checkbox in pure css, and a little Svelte sugar to wire things up. Lovely stuff.</p><p><em>A quick note regarding accessbility. For the purposes of this example the input is “hidden” by using </em><em>display:none and for an example this is fine. Be careful using it in production however, as screen-readers may have difficulty translating your site for those with visual impairments.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d633a2a31619" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/fancy-checkboxes-in-svelte-d633a2a31619">Fancy Checkboxes in Svelte</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Adapter Pattern by Example]]></title>
            <link>https://levelup.gitconnected.com/the-adapter-pattern-by-example-3f5b85aec76d?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f5b85aec76d</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Fri, 22 May 2020 17:04:56 GMT</pubDate>
            <atom:updated>2020-05-23T18:41:01.051Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U-JhWSTlBgkOUBso1yq-Zg.jpeg" /><figcaption>Photo by <a href="https://www.pexels.com/@expect-best-79873?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Expect Best</a> from <a href="https://www.pexels.com/photo/architectural-design-architecture-banks-barclays-351264/?utm_content=attributionCopyText&amp;utm_medium=referral&amp;utm_source=pexels">Pexels</a></figcaption></figure><p>First described by the Gang of Four, the adapter pattern is a really useful weapon in our software engineering arsenal. Often when integrating systems, either of our own creation or from a third party, we will encounter libraries that do the same thing but have different APIs.</p><p>This is where the adapter pattern rides to our rescue, but it can sometimes be a little tricky to envisage exactly how.</p><p>A lot of examples rely on UML or really abstract concepts (if I read about another inheritance chain involving shapes I think I’ll go mad) so what I’m going to do here is try to provide an example that is reasonably realistic.</p><p>Consider a payment system that must integrate with three, or more, banks. Each bank provides an SDK (happy days), but each SDK has a different interface (sad times), and we can’t modify any of them.</p><p>Right — let’s take a look at what the SDKs give us:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yWD6RZAredMM2Dy2IIcJUA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DeOxqg2ojndoEe2kXdX_xA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ij4G3FHQvmx7J5g8wwQm0g.png" /></figure><p>Ok — this is pretty straightforward. They all do similar things, namely processing a payment or transfer of some kind. Each method takes a “model” of some kind as its argument, which encapsulates the data that needs to be processed — as we can see below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SdQAXuQnZU-2FzuwDhMLnA.png" /></figure><p>Now let’s take a look at the class, along with two supporting structures, that integrates with the SDKs, and we’ll get an idea of how the adapter pattern can help.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W5qhxPXq7xqiY0qIJybIYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ih7mnYCJiUjRrp0uN9jmqQ.png" /></figure><p>The <em>Bank</em> enum and the <em>PaymentModel are</em> under our control — they’re part of our system and they’re used by the processor, shown below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H38uroOb323zWWdDK-XNnQ.png" /></figure><p>Urgh. What. A. Mess.</p><p>What problems, and potential problems, can we see going on here?</p><ul><li>That switch statement is unpleasant to say the least. Every new SDK, or change to an existing SDK, is going to mean getting into the guts of the <em>MakePayment</em> method — and that increases the risk of introducing bugs not to mention the testing burdon.</li><li>It has an instance of each SDK. This is going to result in a maintainability nightmare. New SDK? Refactor the class to include it and (manually) retest. Soon you’ve got something that is growing out of control.</li><li>Hard-coded dependencies mean this class can’t be unit tested.</li></ul><p>So what can we do about this, and does the adapter pattern help?</p><p>The hard-coded dependencies for example, do we need a pattern to resolve this — can’t we just inject them? Well, yes, we could do that (even if we ignore for a moment that two of them have methods with dependencies on statics). This just shifts the problem though — it doesn’t make it go away. We have to get those dependencies into our class somehow.</p><p>Dependency injection doesn’t resolve the maintainability issues either. We’d still need to add a new property, or change the property type, for every SDK addition or change. And that switch statement — DI doesn’t help us there at all.</p><p>Talking of that switch statement. I’m sure we’ve all come across this kind of thing in our careers — at the early stages where things are nice, neat and clean and in the latter stages of a class’s life where the conditional logic has grown into an unwieldy mess.</p><p>Clean, readable code is important — from a maintainability point of view of course, but also from a productivity point of view. Indeed, for some clean code is just as important as working code (you can sign the <a href="http://manifesto.softwarecraftsmanship.org/">manifesto here</a>).</p><p>So — how can the adapter pattern help? Can we make our <em>Processor</em> class more maintainable, readable and robust? Yes — we can. Let’s do some refactoring and see how.</p><p>First we need to create a common interface — something that we can pass our <em>PaymentModel</em> into without a load of hassle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u2I6yPIWtKqBBCO1cg6p4g.png" /></figure><p>The next step is to create an adapter class for each of our three SDKs which implements <em>IPaymentAdapter</em>. We’ll see what they look like below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YHPjXroNCEtNPxrtwa-bXg.png" /></figure><p>Ok — this is pretty easy to follow. Our adapter class implements the <em>MakeThirdPartyPayment</em> and calls the SDK’s <em>MakePaymentToAccount</em> method. What we’ve done here is take the conditional block from the <em>Processor</em> class and encapsulate it in this class.</p><p>Let’s see what the other adapters look like (spoiler alert — they’re very similar).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FrrO0Pcgz6O0lrtcnY2Pnw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IGyLrfp1rDh0Dz-vdnNoHg.png" /></figure><p>Great. We’ve now abstracted away the functionality for each of the SDKs, along with their instantiation, and have provided a common interface. Job done? Time for a cuppa? Not quite unfortunately.</p><p>Remember our processor class? It had dependencies on the three SDKs. We <em>could</em> now just inject our three adapters. It would definitely be an improvement — we could at least provide mocks for them and write some unit tests — but we’d still be left with both the switch statement and the maintenance requirement of adding a new dependency for each adapter.</p><p>Let’s deal with those two issues now, and then pop the kettle on.</p><p>We’re going to create a factory which will resolve the type of adapter we need, based on the <em>Bank</em> value passed to the processor’s <em>MakePayment</em> method. We’ll also create an interface for the factory. These are shown below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*z3McvOlDV2omORC9_gXRyg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hFN7hKdrd5uOBIUnSz8zrQ.png" /></figure><p>In the factory’s <em>GetAdapterByType</em> method we’ve got a very slimmed down version of the switch statement from the <em>Processor</em> class. As a result of encapsulating both the creation and functionality of the SDK classes we don’t need to faff around in each of the conditional blocks. This is <strong>a lot</strong> more readable and, because our case blocks are nice and thin, a lot more maintainable.</p><p>Note that there are many ways to skin this particular cat. I’ve chosen to implement the factory using a switch statement because it is the quickest and clearest to demonstrate. The approach holds in general though — the factory, regardless of specific implementation, provides a thin layer to resolving adapter instances.</p><p>We’re now ready to put this all together. Let’s refactor the <em>Processor</em> class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*r7_NMh24b4TryCuSOdB-5Q.png" /></figure><p>Wow. Loads cleaner. We inject a single dependency (that can be mocked) and the <em>MakePayment</em> method is down to two lines of code — we started with thirty.</p><h3>Conclusion</h3><p>We’ve taken a class which was messy, unmaintainable and not unit-testable and created something which is none of those things. Using the adapter pattern we’ve resolved the three issues highlighted previously:</p><ul><li>The maintenance headache that was the switch statement</li><li>The maintainability and extensibility issues around hard coding of dependencies</li><li>The lack of dependency injection</li></ul><p>A sensible-sounding criticism might be that all we’ve done is move all of those problems into the <em>AdapterFactory </em>and the individual adapters and we’ve not really solved anything, just brushed the issues under the carpet of abstraction.</p><p>This might sound sensible, but it is not a valid criticism of this approach.</p><p>Using a factory in this manner is a well trodden path (regardless of how the factory is implemented) and will be familiar to you and future developers looking through your code.</p><p>The individual adapters themselves are responsible solely for a single external library and any changes are confined to a single class.</p><p>Now, time for a cuppa.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f5b85aec76d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/the-adapter-pattern-by-example-3f5b85aec76d">The Adapter Pattern by Example</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Interface Segregation: The Final Frontier]]></title>
            <link>https://levelup.gitconnected.com/interface-segregation-the-final-frontier-70e6f781cc92?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/70e6f781cc92</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[dotnet]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Tue, 19 May 2020 00:37:05 GMT</pubDate>
            <atom:updated>2020-05-21T17:10:45.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PlTm_tK-MUA1aYk3wfs_FQ.jpeg" /></figure><p>The interface segregation principle is the <strong>I</strong> in SOLID and, in my opinion, is one of the easiest to get to grips with. However, it is often overlooked.</p><p>I’ve been watching <strong>a lot</strong> of Star Trek lately — and it is a well-known snowclone from the show that has inspired me to write this quick article:</p><blockquote>Dammit Jim, I’m a doctor not a …</blockquote><p>Leonard McCoy is a Starfleet officer on a five year mission as part of a crew exploring strange new worlds; but he’s also doctor that is frequently asked to take on tasks for which he is not trained, much to his consternation.</p><p>Let’s model Bones in some code, and see what we come up with.</p><p>Firstly we’ll create an interface describing the functions a typical Starfleet officer can perform.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wn3Zbbvpv1k9wcWEud675g.png" /><figcaption>IStarfleetOfficer defines the contract for a Starfleet officer</figcaption></figure><p>OK — seems sensible enough. These are all functions executed by members of the Enterprises crew at one time or another, so let’s model the good doctor and implement this interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*X-Vi2cj173paccAwvRQqbg.png" /><figcaption>The Doctor class, implementing IStarfleet officer</figcaption></figure><p>Ah. <em>NotImplementedExceptions</em> abound. Bones is a doctor and nothing else.</p><p>This is a deliberately obtuse example of course but I’m sure we’ve all come across this sort of thing in codebases that we’ve worked on. A one-size-fits-all interface, either by design or through organic growth, with classes explicitly not implementing functionality that doesn’t apply.</p><p>This is what that the interface segregation principle seeks to solve.</p><p>Before we go any further though let’s deal with <em>why</em> this is a problem. Surely if you’ve got good exception handling then this isn’t an issue? Yeah it might look a little untidy, but it isn’t hurting anyone.</p><p>Unfortunately — regardless of how exceptions are handled or how tidy, or otherwise, the code appears to you — it is a problem, for two reasons.</p><p>Firstly clean, tidy code matters — almost as much as working code (you can sign the <a href="http://manifesto.softwarecraftsmanship.org/">manifesto here</a>, if you like). This is not a style thing — we have style guides and house rules for that — rather this is about maintainability. Simple, self-explanatory code is <strong>much</strong> easier to work with; to extend and maintain, or remove.</p><p>Secondly the example above couples a <em>Doctor </em>class tightly to all functions available to anything that implements <em>IStarfleetOfficer</em>. We don’t like tight coupling. After a while, as systems grow (either deliberately or through organic changes) the complexity of making even a simple change to a tightly-coupled design becomes increasingly burdensome.</p><p>Ok — that’s a summary of the issues, now how do we resolve them.</p><p>Simple — we segregate our interfaces. Let’s do this for McCoy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Rga0aio2ehwr2oNjjy3Xg.png" /><figcaption>Segregating McCoy’s functions</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4Oba3_mbykwlEd3TaUU9fA.png" /><figcaption>A much cleaner Doctor implementation</figcaption></figure><p>Much better! No <em>NotImplementedException</em>s and no need to keep adding new implementations every time the <em>IStarfleetOfficer</em> interface is changed to keep account of new requirements. The code is cleaner, more maintainable and is not tightly coupled to things it has no business being coupled to.</p><p>The thing with McCoy, however, is that after protesting with Kirk, Scotty, or Spock he would often actually be able to do the thing he said he couldn’t. It’s almost as though he was just cantankerous…</p><p>How can we model this? Well, we just create another interface.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SXhHVU_nXFQRCuaeW2UGmQ.png" /><figcaption>IStarfleetEngineer interface, nicely segregated</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hMLDa9CqAix9yG1Kjbk6Hw.png" /><figcaption>Looks like McCoy <em>can work miracles after all</em></figcaption></figure><p>Perfect. Bones can save the day, and the crew can head to Risa for some well earned R and R.</p><p>Now I’ve experienced some criticism of this approach — namely that the codebase gets “polluted” with numerous interfaces, often describing very few functions, and you end up having to manage too many files.</p><p>This criticism doesn’t hold water though. The trade-offs, cleaner and more maintainable code, easily outweigh any minor (and it is minor) inconvenience of having more files in your codebase.</p><p>Split your interfaces so that classes that implement them implement <strong>all</strong> of the contracts. You’ll appreciate it at the time, and future developers working on your code will thank you.</p><p>Oh — and before I get <em>too</em> much heat I’m aware that McCoy never said “Dammit, Jim. I’m a doctor not a …”</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=70e6f781cc92" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/interface-segregation-the-final-frontier-70e6f781cc92">Interface Segregation: The Final Frontier</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Validation using the Chain of Responsibility Pattern]]></title>
            <link>https://levelup.gitconnected.com/validation-using-the-chain-of-responsibility-pattern-236a6ded7078?source=rss-e909ffd4c3ec------2</link>
            <guid isPermaLink="false">https://medium.com/p/236a6ded7078</guid>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Ben Seager]]></dc:creator>
            <pubDate>Tue, 19 May 2020 00:22:29 GMT</pubDate>
            <atom:updated>2020-05-20T00:46:40.483Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zv99SMd32F8wNzXr6FnR2g.jpeg" /></figure><p>The chain of responsibility pattern is one of the most useful design patterns available to us in software engineering. It is also one of the most rarely implemented, in my experience at least. Only once have I encountered it in the wild in a commercial application that I have been involved in developing — and I think that is a shame.</p><p>The chain of responsibility pattern can be described as the object orientated version of <em>if … else if … else … end if </em>blocks; but it is much more than that — it allows, indeed encourages, loose coupling which in turn delivers numerous benefits.</p><p>One place where we can implement the chain of responsibility pattern for fun, profit and a better codebase is validators.</p><p>I have put together a really quick (and quite convoluted and dirty) example of what that could look like.</p><p>In this example we’ve got a service that “inserts” an instance of a <em>VehicleModel</em>. It’s reasonably sensible to validate stuff that we’re going to be putting in the database, so this seems like a decent example.</p><p>Let’s take a look at the models we could insert.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MZdd3SLfoHzIsqQjGZEBPw.png" /><figcaption>Model classes</figcaption></figure><p>So far, so straightforward. All four implement the <em>IVehicleModel</em> interface, show below, and have the same basic properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bF8l6dlf0oKmSgTwhCtLjg.png" /><figcaption>IVehicleModel interface. If we were implementing this for real, we’d probably use an abstract base class. An interface is fine for this example though.</figcaption></figure><p>Now lets look at the service.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kkMkj6xlZynt_M65UUSKdw.png" /><figcaption>The VehicleService — we validate then insert</figcaption></figure><p>This service has a single dependency — an instance of <em>IVehicleValidator</em> (we’ll see the what that looks like in a moment). The validator’s <em>Validate</em> method is called on line 9, and if the model fails validation the <em>InsertVehicleModel </em>method returns. For the purposes of the example the validation result is written to the console.</p><p>Again — this is all pretty straighforward, and I’m sure it’s a concept that is familiar to all of us. Validate the input — if validation passes then proceed and if not, return.</p><p>So, what does <em>IVehicleValidator </em>look like? Well, it looks like this. A single method, <em>Validate</em>, that takes an instance of <em>IVehicleModel </em>as its argument and returns a <em>VehicleValidationResult</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MOjsuFeWx4lZWreZtVGMQg.png" /><figcaption>Simple IVehicleValidator interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CCP9JMGn-mahh_djM7awwg.png" /><figcaption>ValidationResult class</figcaption></figure><p>The <em>VehicleValidationResult</em> has a boolean property to indicate whether a model is valid, and a list of strings for messages — reasons why validation has failed. Instead of strings, we could quite easily have exceptions here if our implementation called for it.</p><p>Ok — that’s our setup out of the way. We have a service, some models and some interfaces. Now we need to put some meat on these bones. Let’s implement a validator <strong>without</strong> using the chain of responsibility. The following code shows how you could do this — and for the purposes of this example is somewhat clunky.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/965/1*tDZSP1ukRloC2YlCCWY40Q.png" /></figure><p>As this validator needs to cater for the different model types we have <em>if</em> blocks which check a model’s type before performing the required validation. If our execution falls through everything, because an unsupported or unexpected type is passed to the validate method, a <em>NotImplementedException</em> is thrown.</p><p>On the face of it, this seems fine. For small applications that are never going to grow or be modified, it might be. Be honest though — how many small applications that are never going to grow or be modified have you worked on?</p><p>There are some potential headaches awaiting us with this “monolithic” approach:</p><ul><li>Extensibility — what happens when a new model type has to be supported? That’s right — we need to modify the class and retest it and as we’ve modified this class, we also need to retest anything that depends on it.</li><li>Extensibility (again) — let’s assume this is part of a mult-tenant application and different tenants start to vary the validation rules for different types of vehicle. One may allow cars with only <a href="https://duckduckgo.com/?q=reliant+robin&amp;iax=images&amp;ia=images">three wheels</a>, another may allow <a href="https://duckduckgo.com/?q=flintsones+car&amp;iar=images&amp;iax=images&amp;ia=images">engine-free cars</a>. Implementing this is going to mean either a per-tenant validator or a mess of <em>if</em> statements within <em>if </em>statements. Neither is desirable.</li><li>Maintainability — any change to the validator is going to increase the cyclomatic complexity of the <em>Validate</em> method, making it ever harder to maintain. New rules, or changing rules, means more conditional code. Changes mean more tests, and more tests for any class which depends on it.</li></ul><p>This validator also violates the <em>Single Responsibility Principle</em> — something validating cars has no business validating boats.</p><p>We can solve these issues if we implement a validator using the chain of responsibility pattern.</p><p>The first step is to break the validator down into individual validators, each responsible for a single implementation of <em>IVehicleModel</em>. We’ll implement three and they’ll all follow the same basic pattern. Shown below is the <em>CarValidator</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Aaq7mBMk7j9BkVWTOY_u3w.png" /><figcaption>CarValidator class — the first link in the chain</figcaption></figure><p>As can be seen the class implements <em>IVehicleValidator</em> just like the monolithic validator and uses the same rules for validating a car model. There are a couple of extras though.</p><p>Firstly the constructor — we now have one, other than the default, and it takes an argument. We’re forming a<em> </em>chain, so each link will need access to the next. We pass the next link in the chain into each validator instance.</p><p>Secondly take a look at lines 11 to 14. There’s an <em>if</em> statement that looks an awful lot like the conditions in the first validator class we implemented. There’s a difference though — instead of doing the validation for a specific model type responsibility is passed to the next validator if the current does not have responsibility for the model type.</p><p>Shown below are the two other model validators — the follow the same pattern. If the model is not that validator’s responsibility, it is passed to the next link in the chain.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yZiOD1K73oLae-WOiVY52A.png" /><figcaption>BikeValidator class</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*euG3zPJy67_2TAPvy0IeQQ.png" /><figcaption>BoatValidator class</figcaption></figure><p>Ok — this pretty much replaces the monolithic validator but there is one thing missing. What happens if a model falls through all conditions? What happens if it reaches the end of the chain and no link has taken responsibility.</p><p>That’s where the following class comes in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eL4dMgouAkdkoxfDqjH-dw.png" /><figcaption>NoResultValidator — a way to end our chain</figcaption></figure><p>We replace the <em>NotImplementedException</em> from the <em>VehicleValidator</em> and create a link soley for the purpose of ending the chain. In this example nothing is done aside from returning a <em>NoResultVehicleValidationResult</em> (naming things, the hardest thing is software…). This “default” result looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*j_M_sN3_dimgefqGC95UxA.png" /><figcaption>Yeah — naming stuff…</figcaption></figure><p>Nothing to see here… In an actual implementation we might check the result type and output something useful to a log. Be that validation failure messages, or the fact that there is a model type could not be validated.</p><p>Well — that’s our chain of responsiblity done. We have three validators with each responsible for a single model type, and a class which ends the chain.</p><p>It solves the maintainability problems — there is a lot less code in each validator, and any changes require that only that validator is retested, and only its unit tests are refactored.</p><p>It solves the extensibility problems in two ways. The first — namely what happens when we need to validate a new model — is simple to explain. We create a new validator and add it to the chain. That’s it. Done. No refactoring of other validators and no extensive re-writing of unit tests.</p><p>The second extensibility problem — described above with the postualtion of a multi-tenant application — requires another code snippet to explain…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2WMtjw1hXGPBL9nfTg1CBg.png" /><figcaption>Using Unity to create the chain. There’s a cross-over here with the strategy pattern, especially when we talk about multi-tenant applications</figcaption></figure><p>What we have here is one way you can implement the validation chain using an IoC provider (in this example Unity is used, but pretty much anything can be used). Each validator is registered, with each validator recieving the next link in the chain via its constructor. The service is registered with the first link in the chain, in this example the <em>CarValidator</em>.</p><p>As an aside — if you were implementing this in Real Life™ you’d probably want to create a factory to do this wiring up unless you’re a fan of massive IoC configuration files (I’m really not).</p><p>Now about the mulit-tenant application issue. For one, cars with three wheels are valid and for another cars with no engines are valid. How does IoC help with this?</p><p>Quite simply, actually.</p><p>You implement per-tenant IoC configurations. This is a topic on it’s own so I won’t cover it in detail now but briefly this is how I would achieve it using Unity (ymmv with other providers):</p><ul><li>All common registrations would be in code</li><li>Tenant-specific registrations would be implemented in XML</li><li>At run-time code would determine which XML file to load and tenant specifc registrations would override common ones</li></ul><h3>Conclusion</h3><p>This brief, and somewhat clunky, example has hopefully shown the advantages that using the chain of responsibility pattern can bring. We can write cleaner, more maintainable, more extensible and more SOLID compliant code without too much of an overhead. As we’re using multiple classes, and need to link the chain together, there is a slight increase in the amount of bootstrapping required but this is an insignificant price to pay for the gains achieved.</p><p>The example code is written in C# but this pattern is applicable in pretty much any language — including those with weak typing and no concept of interfaces (JavaScript, I’m looking at you).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=236a6ded7078" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/validation-using-the-chain-of-responsibility-pattern-236a6ded7078">Validation using the Chain of Responsibility Pattern</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>