<?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 Watts on Medium]]></title>
        <description><![CDATA[Stories by Ben Watts on Medium]]></description>
        <link>https://medium.com/@canvascodebw?source=rss-930170a3370f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*COknPcEk0U114xNLzoYDvg.png</url>
            <title>Stories by Ben Watts on Medium</title>
            <link>https://medium.com/@canvascodebw?source=rss-930170a3370f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 03:22:39 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@canvascodebw/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[My Pokémon Deck Builder — A JS Application I Built For Fun]]></title>
            <link>https://canvascodebw.medium.com/my-pok%C3%A9mon-deck-builder-a-js-application-i-built-for-fun-8a650f942663?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a650f942663</guid>
            <category><![CDATA[cards]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[nodejs]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Mon, 18 May 2026 12:21:09 GMT</pubDate>
            <atom:updated>2026-05-18T21:41:30.812Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*olY3uSI6fSahWiiq7NNQSw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thimo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thimo Pedersen</a> on <a href="https://unsplash.com/photos/brown-wooden-framed-photos-on-brown-wooden-table-TWCnHKKhqSo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>From my childhood years to today, I’ve been purchasing Pokémon card boosters. Why? Well firstly, I very much enjoy Pokémon and secondly, I do like myself a card game! One Piece, Digimon, Rift Bound, Slay the Spire etc.</p><p>With the amount of Pokémon cards I’ve gathered from a wide range of sets/series, I’ve found it hard to organise my collection. Some cards I have stuffed in a box while some might be part of a deck which I’m currently playing with. So for a few years now, I’ve had a plan to create an app which can help me organise my cards. So this blog post is about the outcome of my little application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t3EfG3IJRmrkGZDX6wBndA.png" /></figure><p>If you would prefer to see the application itself and the code repositories, you can find them right here and at the end in the references.</p><p>Web Application — <a href="https://mrapproved.github.io/mypkmndeck-app/index.html">https://mrapproved.github.io/mypkmndeck-app/index.html</a><br>NodeJS Express API — <a href="https://github.com/MrApproved/mypkmndeck_api">https://github.com/MrApproved/mypkmndeck_api</a><br>NodeJS Web Scraper — <a href="https://github.com/MrApproved/mypkmndeck_scraper">https://github.com/MrApproved/mypkmndeck_scraper</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JKjiCilvA5ad-XQMDIDqvg.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@thimo?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Thimo Pedersen</a> on <a href="https://unsplash.com/photos/red-and-white-ladybug-toy-on-white-and-yellow-book-dip9IIwUK6w?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Before I got started the first think I needed to do was create some sort of database of all existing Pokémon cards. There are some public services which can do this for you, but where is the fun in that? So using the well known site <a href="https://pkmncards.com/">https://pkmncards.com/</a> I decided to create a NodeJS scraper. Why NodeJS? Well, I wanted to play around with NodeJS, so I used this as an excuse to have a little fun.</p><p>The scraper is designed to process a list of series and sets: it uses the series and sets to generate a URL, that URL is then requested, and the page result is used. It then scrapes most of the information and the image of the cards. I did want to gather everything, but I wanted to keep it a little simple for my first version.</p><p>With my Pokémon card database files, I now wanted to create a Web API so anyone including myself could query the database with a few filter values. For the Web API, I decided for NodeJS and Express. I found Express very simple and easy to configure (I will admit, I didn’t need to do anything fancy, so my knowledge is still lacking for Express). I did run into the dreaded CORS issue, but I was able to solve this by adding the following:</p><pre>const cors = require(&quot;cors&quot;);<br><br>const corsOptions = {<br> origin: &quot;*&quot;,<br> optionsSuccessStatus: 200,<br>};<br><br>app.use(cors(corsOptions));</pre><p>For the Web API I needed to expose some actions to allow the gathering of the card specific types such as Series, Types, Colours, Stages, Resource and, of course, the Cards themselves. All of the actions above are just simple GET methods, but the Cards action allows some query options which you can use to filter.</p><p>The Cards action is the main action of the Web API. The action itself allows the following query values:</p><ul><li>Name</li><li>Series</li><li>Sets</li><li>Types</li><li>Colours</li><li>Stages</li></ul><p>None of this was hard to filter because the actions above, such as Stages, returns a list of Stage values from all the cards loaded in from the scraper files.</p><p>Scraper done and Web API done, it was time for the App itself. As this is my first iteration, I wasn’t aimming for the sky! This is just a small side project to help me organise my collection and decks. So knowing this, I limited my requirements to just the following few:</p><ul><li>Accept filter options to be provided to allow the full use of the Web API Cards action</li><li>Display all cards as images only and no information</li><li>Allow a custom deck to be created (add cards, remove cards, custom name, download and upload)</li><li>Show some basic statistics about the deck</li><li>Custom deck builder can be maximised and minimised for ease</li><li>Ignore mobile styling as I would be using this App on desktop</li></ul><p>Knowing all of the above, I started with simply displaying a list of cards. Then I allowed a custom deck to be created, statistics came next, and then the filtering to display the results of the Web API Cards action.</p><p>All of the above took me about a month of random evenings, and I do think I could have allowed some more filtering etc, but I’m super happy that with the following requirements above, I did achieve and am pleased with the results.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mVXDeSXORIPo8SAcYAtK1w.gif" /></figure><p>This sounds like it went quite smoothly and straightforward, but did I hit some bumps in the road! Straight off the bat, when I started to create the NodeJS Scraper, it all looked good when I was pulling information off the page and into a JSON file, but once I got to downloading the images… Did it go weird!</p><p>JS Promises… I haven’t worked with these for a little while, but my previous knowledge did start to come back. To download an image, I needed to fire a new HTTP Request with the image URL, then with the result from the request, save that data into a file. What started to happen was my scraper would stop half way through scraping the images because the original request of scraping card information was done.</p><p>I played around with Promises, which then resulted in NodeJS throwing this error “Error: socket hang up…”. After much digging it would seem my requests were never being closed. Adding “request.destroy” in the “end” event fixed this issue. This then allowed me to wait on gathering the card information and then awaiting the image of each card to be downloaded and saved locally.</p><p>For NodeJS Express, there wasn’t much of an issue, but as you may have read above, I did run into the standard CORS issue. Thankfully, this was quite easy to fix in Express. One issue I did have was some of the series/sets have unicode characters which were not playing nice with Express due to the request parsing. So I did need to use JS’s encodeURIComponent and decodeURIComponent. Not a massive issue, just something that caught me off guard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*OPsX_m-rdEAQQEc_bxbg-w.png" /><figcaption><a href="https://upload.wikimedia.org/wikipedia/en/1/19/Pok%C3%A9mon_Trading_Card_Game_Coverart.png">https://upload.wikimedia.org/wikipedia/en/1/19/Pok%C3%A9mon_Trading_Card_Game_Coverart.png</a></figcaption></figure><p>Now, silly me, I wanted to make the Web API public just so I could get Azure DevOps to build and deploy. This all seemed good at first, of course I ran into some issues trying to deploy to a NodeJS 24 server, but this was just me not setting config values or permissions. But after a few days of updates and deploys I started to get a generic 400 error after a deployment had completed!</p><p>I didn’t want to pay for a Web APP, so I went for a free tier web app in Azure. Now, first off, the free tier only allows 1gb of storage, so I did have to reduce the quality of the card images, but due to how the Web API loads the json files into memory on start up, the free tier ran out of CPU cycles and was no longer serving the Web API. This then also seemed to be the reason it was throwing a generic HTTP 400 result after deployment.</p><p>I’m happy I was able to get Azure DevOps to do all the building and deploying, but was annoyed it ran out of juice so quickly! Due to this I had to move the entire Web API code base into my single page application. It wasn’t difficult, but I really wanted to host the Web API! Yes, I could have paid, so this is my own doing. But nevertheless, I moved it across, adapted the code and got it all working.</p><p>Two things I will take away from this, even though it was just a small side project: it would have gone way smoother if I would have created generic code and not just one big JS file. The cleaness of these projects are horrible at best. No tests and just random JS files. Not a good presentation of my work. However still, the application works and I’m able to organise my collection, which was the original aim.</p><p>Second is next time I plan to host something, I now know the limits of the free tier Azure Web APPs. Might be a small learn, but it’s still something I can take away from this whole experience.</p><p>I would like to carry on with adding new features and improving the overall application, but for now I’m happy with the current result and hope if anyone else stumbles across it, they’ll have a blast!</p><p>Thank you for reading. Feel free to provide feedback, positive or negative.</p><p>Application URL — <a href="https://mrapproved.github.io/mypkmndeck-app/">https://mrapproved.github.io/mypkmndeck-app/</a></p><p>Web Application Repository — <a href="https://github.com/MrApproved/mrapproved.github.io/tree/master/mypkmndeck-app">https://github.com/MrApproved/mrapproved.github.io/tree/master/mypkmndeck-app</a></p><p>NodeJS Web Scraper — <a href="https://github.com/MrApproved/mypkmndeck_scraper">https://github.com/MrApproved/mypkmndeck_scraper</a></p><p>NodeJS Web API — <a href="https://github.com/MrApproved/mypkmndeck_api">https://github.com/MrApproved/mypkmndeck_api</a></p><p>Image — <a href="https://unsplash.com/photos/brown-wooden-framed-photos-on-brown-wooden-table-TWCnHKKhqSo">https://unsplash.com/photos/brown-wooden-framed-photos-on-brown-wooden-table-TWCnHKKhqSo</a></p><p>Image — <a href="https://unsplash.com/photos/red-and-white-ladybug-toy-on-white-and-yellow-book-dip9IIwUK6w">https://unsplash.com/photos/red-and-white-ladybug-toy-on-white-and-yellow-book-dip9IIwUK6w</a></p><p>Image — <a href="https://upload.wikimedia.org/wikipedia/en/1/19/Pok%C3%A9mon_Trading_Card_Game_Coverart.png">https://upload.wikimedia.org/wikipedia/en/1/19/Pok%C3%A9mon_Trading_Card_Game_Coverart.png</a></p><p>Card Database — <a href="https://pkmncards.com/">https://pkmncards.com/</a></p><p>Pokémon Cards — <a href="https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards">https://www.pokemon.com/uk/pokemon-tcg/pokemon-cards</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a650f942663" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pokémon Triple Triad — Fun Little Project]]></title>
            <link>https://canvascodebw.medium.com/pok%C3%A9mon-triple-triad-fun-little-project-49881366bd77?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/49881366bd77</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[pokemon]]></category>
            <category><![CDATA[triple-triad]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[final-fantasy]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Tue, 06 Jan 2026 22:19:38 GMT</pubDate>
            <atom:updated>2026-01-07T20:31:25.495Z</atom:updated>
            <content:encoded><![CDATA[<h3>Pokémon Triple Triad — Fun Little Project</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*1QchIwdL3DQ_eRkB7oUrhQ.png" /><figcaption>Final Fantasy 8 Triple Triad</figcaption></figure><p>I’ve always been a huge fan of Pokémon when it first game out back in 1999 on the Nintendo Gameboy. I’m also a huge fan of Final Fantasy 8, especially the Triple Triad mini game. So I thought why can’t I have both? So I decided to create a short and simple version of just that!</p><p>First off, before I get into my thoughts and ideas etc, here is the link to play it: <a href="https://mrapproved.github.io/Pokemon-Triple-Triad/">https://mrapproved.github.io/Pokemon-Triple-Triad/</a>. Your browser may warn you it needs access to your storage - it requires this so it can save what cards you unlock. Also, it may not be suitable for mobile as I just designed it like the original.</p><p>So you might be asking, what is this Triple Triad? Well, Final Fantasy 8 had a mini game where you would select five cards. These cards would have four values and sometimes an element. The aim is to have as many cards on the board to be yours. The board was a three by three grid, each player would take it in turns to place a card. Now, how do you have more cards on the board than the other player? Wouldn’t the person who goes first always have more? Well…</p><p>Each card has a up, right, down and left value. These values are used to determine if you are stronger than an opponent’s card in that direction. So if you placed a card in the top right corner which has a 3 for its left value, and then I placed a card on the left hand side of that card which has a number greater than 3 on the right hand side, I would now own your card. And if not, then the cards would remain to the original owners.</p><p>Below you can see the bot places a Koffing in the bottom left corner. I stick my Squirtle card above it. So it checks to see if my bottom value (4) is greater than Koffing’s top value (2), which it is. So it changes the colour to blue to state the card is now mine.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*MMPtdp-hhd0eCe4F-IlwbA.gif" /><figcaption>Squirtle card beating Koffing, to claim it as player 1&#39;s</figcaption></figure><p>The reason I started this project was because I wanted to play around and just do a little coding. I felt it was a nice project I could start and finish within a month or so in my spare time. Like normal the CSS was a pain, compared to any other aspect of the project.</p><p>Overall though it was great fun, just playing around and not holding myself to any standards or what not, I was free to do whatever. Shame I didn’t make who goes first random.</p><p>One aspect of the game is each card has four different values. Now I didn’t just randomly assign values to random cards. Each Pokémon has base stats, so I determined that up would be health, right would be attack and special attack, down would be defense and special defense and finally left would be speed.</p><p>Using pokemondb gen 1 database, I could determine the max base attribute for each of those directions. Doing that I could then calculate what 10 (best direction value) would be and then calculate the values. So Electrode has the highest base speed stat of 150, so if I then divided 150 by 10, that would give 15. I could then determine how many 15s would go into any Pokémon’s speed attribute.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UYYRgH4nI49WlrpiD2CgOA.png" /><figcaption>Pokémon and their base stats</figcaption></figure><p>So doing this I could then take any Pokémon from the database and determine the direction value. So for Dugtrio above, it has 120 speed. Divide 120 by 15 = 8. So the right value for Dugtrio is 8. I did this for hp, attack and defense the same way, just the max values were a little different for attack and defense as I had to add both of those values to determine the best.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uQzbluVTGzTLJD-bmmXWxw.png" /><figcaption>Cards and their power values</figcaption></figure><p>The project from my side is probably done, however I feel more could have been done if I wanted to spend more time on it.</p><p>Firstly, the bot could have been updated to use easier cards as you start out and not just random. Also, the placing of the cards could have been better than just random.</p><p>Secondly, if you take a look at the cards, the circle which holds the values are a colour. The reason they are a colour is because I wanted a type of Pokémon to affect the value it had. So if you had a fire type Pokémon card placed and I placed a water type Pokémon next to it, it would have double the value against it. This would have made it much easier to defeat higher cards but at the same time make the board a little more interesting to play against.</p><p>Thirdly, multiplayer would have been a nice touch, be it in the same browser or over some sort of network would have been quite cool. But still, overall I’m very happy with what I’ve done in the time I spent, which wasn’t a huge amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Dko3FP2dn4j8luPEtqnl-A.gif" /><figcaption>Mewtwo!</figcaption></figure><p>Quick note, if you want to delete your card collection to start a fresh, you can click the little blue cross at the bottom of the site - it should pop up an alert warning you, this way you don’t accidently lose all of your hard work!</p><p>If you want to take a look at the source code you can via my Github page here: <a href="https://github.com/MrApproved/mrapproved.github.io/tree/master/Pokemon-Triple-Triad">https://github.com/MrApproved/mrapproved.github.io/tree/master/Pokemon-Triple-Triad</a>. If you would like the card creator which uses the canvas tag to display the image and write the necessary values in the top right corner, feel free to comment. If I get enough requests I may just update my repository.</p><p>Thank you for reading. Feel free to provide feedback, positive or negative.</p><p>References:</p><p>Game: <a href="https://mrapproved.github.io/Pokemon-Triple-Triad/">https://mrapproved.github.io/Pokemon-Triple-Triad/</a><br>Banner: <a href="https://finalfantasy.fandom.com/wiki/Triple_Triad_(Final_Fantasy_VIII)">https://finalfantasy.fandom.com/wiki/Triple_Triad_(Final_Fantasy_VIII)</a><br>Pokémon Database: <a href="https://pokemondb.net/pokedex/stats/gen1">https://pokemondb.net/pokedex/stats/gen1</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=49881366bd77" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Knowing Too Much — The Pain & Agony Of Knowing Too Much — C# Examples]]></title>
            <link>https://canvascodebw.medium.com/knowing-too-much-the-pain-agony-of-knowing-too-much-c-examples-a35d547a406e?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/a35d547a406e</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[dont-repeat-yourself]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[dot-net-core]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Thu, 27 Mar 2025 17:11:23 GMT</pubDate>
            <atom:updated>2025-03-27T17:11:23.868Z</atom:updated>
            <content:encoded><![CDATA[<h3>Knowing Too Much — The Pain &amp; Agony Of Knowing Too Much — C# Examples</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1RDedT959H20QoPnM5xvkQ.jpeg" /></figure><p>Knowing too much might sound like a great idea, but in code it can cause you a huge headache. Ever update a class and all of a sudden something you thought was not related just suddenly starts to break, be it a runtime error, compile error or a unit test failing? Well this could be because the class you updated knows too much.</p><p>So what do I mean by a knowing too much? How can a class know too much? What I’m referring to is the class itself, be it the methods, properties, fields etc. Does this class know about something it shouldn’t know about?</p><p>A simple example would be a lunch box. You have a lunch box and you can put whatever you want in it, fruit, snacks, a sandwich etc. Now should that lunch box know what it may contain? Well not really, we could stick sand in it if we wanted. The lunch box should only know what it needs to know I.E. its capacity, size, colour etc.</p><p>Right, so I’m now going to attempt to show you how knowing too much can cause you problems and how we may get around it.</p><p>So for our first example we are going to create a class which can take a list of items which will return them in alphabetical order, might sound basic, but we will see what happens as we progress and how the sorter may know something it shouldn’t.</p><p>Below is our Item class, ItemSorter class and Program</p><pre>public class Item<br>{<br>    public string Name { get; set; }<br>}<br><br>public class ItemSorter<br>{<br>    public IEnumerable&lt;Item&gt; OrderItemsAlphabetically(IEnumerable&lt;Item&gt; items)<br>        =&gt; items.OrderBy(x =&gt; x.Name);<br>}<br><br> public class Program<br> {<br>     static void Main(string[] args)<br>     {<br><br>         var items = new List&lt;Item&gt;<br>         {<br>             new Item() { Name = &quot;Potion&quot; },<br>             new Item() { Name = &quot;Food&quot; },<br>             new Item() { Name = &quot;Rune&quot; }<br>         };<br><br>         var itemSorter = new ItemSorter();<br><br>         foreach (var item in itemSorter.OrderItemsAlphabetically(items))<br>             Console.WriteLine(item.Name);<br>     }<br> }</pre><p>So, quite simple to understand. We have an Item class which has a single property Name. A class ItemSorter which exposes one method. Method OrderItemsAlphabetically takes an IEnumerable of Items, which then uses the Linq OrderBy and returns the result. The Program class creates a new list of Items, invokes the OrderItemsAlphabetically and displays the output</p><pre>Food<br>Potion<br>Rune</pre><p>Awesome. Well now lets say we also have a list of Weapons we would like to order? How would we do this? Should we just duplicate our ItemSorter code and create a new WeaponSorter like so?</p><pre>public class Weapon<br>{<br>    public string Name { get; set; }<br>    public int MiniumDamage { get; set; }<br>    public int MaxiumDamage { get; set; }<br>}<br><br>public class WeaponSorter<br>{<br>    public IEnumerable&lt;Weapon&gt; OrderWeaponsAlphabetically(IEnumerable&lt;Weapon&gt; weapons)<br>        =&gt; weapons.OrderBy(x =&gt; x.Name);<br>}<br><br>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br><br>        var items = new List&lt;Item&gt;<br>        {<br>            new Item() { Name = &quot;Potion&quot; },<br>            new Item() { Name = &quot;Food&quot; },<br>            new Item() { Name = &quot;Rune&quot; }<br>        };<br><br>        var itemSorter = new ItemSorter();<br><br>        foreach (var item in itemSorter.OrderItemsAlphabetically(items))<br>            Console.WriteLine(item.Name);<br><br>        var weapons = new List&lt;Weapon&gt;<br>        {<br>            new Weapon() { Name = &quot;Sword&quot; },<br>            new Weapon() { Name = &quot;Axe&quot; },<br>            new Weapon() { Name = &quot;Dagger&quot; }<br>        };<br><br>        var weaponSorter = new WeaponSorter();<br><br>        foreach (var weapon in weaponSorter.OrderWeaponsAlphabetically(weapons))<br>            Console.WriteLine(weapon.Name);<br>    }<br>}</pre><p>Now this will work, but we broke a coding principle known as DRY (Don’t repeat yourself). This may not seem like an issue, but if we found a bug in our sorting algorithm, we would need to fix that issue in both places because the code is identical, we may even forget the code is duplicated and we may just fix it in one area.</p><p>Just think if we repeated this for a list of Armour, we would have the same code in three places. So how could we satisfy the DRY principle? Well lets take a look at what code we’ve repeated.</p><p>Well we have two sorter classes, so this is breaking the DRY principle. But why do we have two sorters? Well we have an Item class and a Weapon class so we need two sorters to handle each class right? Well this is a side effect of knowing too much.</p><p>Our main issue is we have two sorters, we have two sorters because we have two classes, but why should the sorter know what specific Item or Weapon it is using? Why can’t we just have one sorter? Well lets see a solution which will allow us to have just one sorter which the Item and Weapon class can both use. No more repeated code!</p><p>Lets create an interface which will expose a Name property, this way we can update our sorter to just use that interface.</p><pre>public interface NamedEntity<br>{<br>    string Name { get; }<br>}</pre><p>Lets go ahead and make sure our Item and Weapon class implement that interface</p><pre>public class Item : NamedEntity<br>{<br>    public string Name { get; set; }<br>}<br><br>public class Weapon : NamedEntity<br>{<br>    public string Name { get; set; }<br>    public int MiniumDamage { get; set; }<br>    public int MaxiumDamage { get; set; }<br>}</pre><p>The changes above now allows us to create a new NamedEntitySorter class, this will sort a list of NamedEntities instead of a specific object. We can also delete our ItemSorter and WeaponSorter as those are no longer needed. Below is our new NamedEntitySorter</p><pre>public class NamedEntitySorter<br>{<br>    public IEnumerable&lt;NamedEntity&gt; OrderEntitiesAlphabetically(IEnumerable&lt;NamedEntity&gt; items)<br>        =&gt; items.OrderBy(x =&gt; x.Name);<br>}</pre><p>With the changes above, we can change our Program class to the following</p><pre>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var namedEntitySorter = new NamedEntitySorter();<br>  <br>        var items = new List&lt;Item&gt;<br>        {<br>            new Item() { Name = &quot;Potion&quot; },<br>            new Item() { Name = &quot;Food&quot; },<br>            new Item() { Name = &quot;Rune&quot; }<br>        };<br>  <br>        foreach (var item in namedEntitySorter.OrderEntitiesAlphabetically(items))<br>            Console.WriteLine(item.Name);<br>  <br>        var weapons = new List&lt;Weapon&gt;<br>        {<br>            new Weapon() { Name = &quot;Sword&quot; },<br>            new Weapon() { Name = &quot;Axe&quot; },<br>            new Weapon() { Name = &quot;Dagger&quot; }<br>        };<br>  <br>        foreach (var weapon in namedEntitySorter.OrderEntitiesAlphabetically(weapons))<br>            Console.WriteLine(weapon.Name);<br>    }<br>}</pre><p>If we run our code now, we should get this output!</p><pre>Food<br>Potion<br>Rune<br>Axe<br>Dagger<br>Sword</pre><p>So recap, we started with a simple Item class and a specific ItemSorter which when given a list of Items, it would order them alphabetically and return them. We then wanted to do the same with our Weapon class. We did this by duplicating the ItemSorter, naming it WeaponSorter and updating its method to take a list of the Weapon class.</p><p>Due to this change, we broke the DRY rule (Don’t repeat yourself), even though we did break the rule, the actual hidden issue was our sorter classes knew too much, they both sorted alphabetically and they both used a property of Name. So our ItemSorter and WeaponSorter knew too much. They knew the specific object type they wanted to work with.</p><p>Removing the hard typed object and replacing them with an interface such as NamedEntity, we were able to just implement one sorter which we called NamedEntitySorter. Now any class that implements the NamedEntity interface can be sorted via the NamedEntitySorter.</p><p>With this our sorter only knows what it needs to know I.E. NamedEntity. We can create any object we like, such as Cake, Colour, Weather, Element, Planet etc. As long as they implement the NamedEntity interface our NamedEntitySorter can sort it and not give a poop about what the object may actually be!</p><p>Now this example was quite a simple one, but lets try something a little more complex which isn’t just about sorting a list of things.</p><p>For this example we’re gonna create a simple library which will be used by an insurance registration app. The application will allow customers to apply for car insurance. Once the insurance form has been filled out and submitted we will send them an email asking for feedback etc. The email will only go out if the customer chose to receive promotional emails and what make of car they provided (we currently only want to send emails for specific car manufacturers).</p><p>We can ignore the car insurance application code, but we do need to create our survey library code. Lets first create the object which we would like to receive from the registration app.</p><pre>public class SendSurveyRequest<br>{<br>    public string EmailAddress { get; set; }<br>    public string CarManufacturer { get; set; }<br>    public bool AllowPromotionalEmails { get; set; }<br>}</pre><p>Let’s create our car manufacturer survey class, this will hold the subject and body of the email which will be sent. It will also hold the manufacturer so we can match it against the request from above.</p><pre>public class CarManufacturerSurvey<br>{<br>    public string Subject { get; set; }<br>    public string Body { get; set; }<br>    public string CarManufacturer { get; set; }<br>}</pre><p>With our SurveyService, we want to be given a list of CarManufacturerSurveys so we can attempt to match the CarManufacturer proprety against the request CarManufacturer property, if a CarManufactuerSurvey is found we then send out the email. For this we will need a SMTP client, so lets create one in our constructor.</p><pre>public class SurveyService<br>{<br>    private readonly SmtpClient _smtpClient;<br>    private readonly IEnumerable&lt;CarManufacturerSurvey&gt; _carManufacturerSurveys;<br><br>    public SurveyService(<br>        IEnumerable&lt;CarManufacturerSurvey&gt; carManufacturerSurveys)<br>    {<br>        var emailDirectory = $&quot;{AppDomain.CurrentDomain.BaseDirectory}/temp-emails&quot;;<br><br>        // This is just to help you locate your email directory, feel free to delete this line when not needed<br>        Console.WriteLine(emailDirectory);<br><br>        if (!Directory.Exists(emailDirectory))<br>            Directory.CreateDirectory(emailDirectory);<br><br>        _smtpClient = new SmtpClient();<br>        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;<br>        _smtpClient.PickupDirectoryLocation = $&quot;{AppDomain.CurrentDomain.BaseDirectory}/temp-emails&quot;;<br><br>        _carManufacturerSurveys = carManufacturerSurveys;<br>    }<br>}</pre><p>Now lets expose a SendSurvey method, this will take our SendSurveyRequest object and use that for calculating if an email should be sent or not.</p><pre>public void SendSurvey(SendSurveyRequest request)<br>{<br>    if(request.AllowPromotionalEmails)<br>    {<br>        var carManufacturerSurvey = _carManufacturerSurveys.First(x =&gt; x.CarManufacturer.ToLower() == request.CarManufacturer.ToLower());<br><br>        if(carManufacturerSurvey != null)<br>            _smtpClient.Send(&quot;knowingtomuch@medium.com&quot;, request.EmailAddress, carManufacturerSurvey.Subject, carManufacturerSurvey.Body);<br>    }<br>}</pre><p>Ignore the car insurance registration app, we can still use our code in isolation.</p><pre>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var surveyService = new SurveyService(<br>            new List&lt;CarManufacturerSurvey&gt;()<br>            {<br>                new CarManufacturerSurvey() {<br>                    CarManufacturer = &quot;Fiat&quot;,<br>                    Body = &quot;Fiat Survey Link&quot;,<br>                    Subject = &quot;Fiat Survey&quot;<br>                }<br>            });<br><br>        surveyService.SendSurvey(new SendSurveyRequest()<br>        {<br>            AllowPromotionalEmails = true,<br>            CarManufacturer = &quot;FIAT&quot;,<br>            EmailAddress = &quot;test@medium.com&quot;<br>        });<br>    }<br>}</pre><p>Small explanation, this code is creating our SurveyService and providing a hard coded list of CarManufacturerServeys which just contains one record for the car manufacturer Fiat. Once that has been constructed we then invoke our SurveyService by providing a request object which should send an email.</p><p>If we execute our program, the console should output the directory which is used to store our emails. If you open that directory you should see an EML file which has a random GUID as its filename. Open this file and you should see something like below (this may vary in apperance depending on your SMTP application — I used Outlook).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/1*ru7l_6TuFsZhrUf4-QGc1A.png" /></figure><p>So what do we think, does this SurveyService know too much? Well of course, this does depend on the developer, but in a general sense, does SurveyService know too much? Lets answer that with a question from the client!</p><p>The car insurance application is going to be upgraded so users can also apply for mobile phone insurance. The client now wants to also send out surveys depending on the mobile manufacturer the user provided.</p><p>So from the above statement they want to expose mobile manufacturer surveys. Now we could copy and paste our code to make a new MobileSurveyService like we did in example 1, however if we do this we have to manage the same code in two different places, remember the Don’t Repeat Yourself rule.</p><p>We’re gonna go for a more professional choice and not duplicate our code. Lets take a look at what we already have and what would need to be modified to allow the same SurveyService to be used for both car and mobile manufacturer survey sending.</p><p>So in our constructor we take a list of CarManufacturerSurveys so this is gonna need to be changed, our SurveyService probably shouldn’t know its working with car manufacturers because why would a survey service know about car manufacturers?</p><p>Our SendSurvey method uses the list of CarManufacturerSurveys to filter by car manufacturer, if a result is found the result Subject and Body is used to send an email. Again why should this know about car manufacturers?</p><p>Right so our CarManufacturerSurvey object needs to be replaced by an interface so anything that would implement that interface can be used, also our SurveyService should know about Surveys, not car manufacturers. The Subject and Body properties are fine, but the filtering is gonna be a little difficult as the filtering will change depending on the implemented interface.</p><p>Anyways, for now, let’s first create our interface and just update our CarManufacturerSurvey so we can see that part working first</p><pre>public interface Survey<br>{<br>    string Subject { get; set; }<br>    string Body { get; set; }<br>    string CarManufacturer { get; set; }<br>}<br><br>public class CarManufacturerSurvey : Survey<br>{<br>    public string Subject { get; set; }<br>    public string Body { get; set; }<br>    public string CarManufacturer { get; set; }<br>}</pre><p>With this small interface we can go ahead and update our SurveyService to use the Survey interface like so.</p><pre>public class SurveyService<br>{<br>    private readonly SmtpClient _smtpClient;<br>    private readonly IEnumerable&lt;Survey&gt; _surveys;<br><br>    public SurveyService(<br>        IEnumerable&lt;Survey&gt; surveys)<br>    {<br>        var emailDirectory = $&quot;{AppDomain.CurrentDomain.BaseDirectory}temp-emails&quot;;<br><br>        // This is just to help you locate your email directory, feel free to delete this line when not needed<br>        Console.WriteLine(emailDirectory);<br><br>        if (!Directory.Exists(emailDirectory))<br>            Directory.CreateDirectory(emailDirectory);<br><br>        _smtpClient = new SmtpClient();<br>        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;<br>        _smtpClient.PickupDirectoryLocation = $&quot;{AppDomain.CurrentDomain.BaseDirectory}/temp-emails&quot;;<br><br>        _surveys = surveys;<br>    }<br><br>    public void SendSurvey(SendSurveyRequest request)<br>    {<br>        if(request.AllowPromotionalEmails)<br>        {<br>            var survey = _surveys.First(x =&gt; x.CarManufacturer.ToLower() == request.CarManufacturer.ToLower());<br><br>            if(survey != null)<br>                _smtpClient.Send(&quot;knowingtomuch@medium.com&quot;, request.EmailAddress, survey.Subject, survey.Body);<br>        }<br>    }<br>}</pre><p>Feel free to execute the code and you should see a new EML file appear in your directory. So with a simple change our SurveyService can now be given a list of anything that implements the interface Survey.</p><p>So to allow mobile manufacturers should be very simple, and, dare I say it, anything really. The object just needs to implement our Survey interface. Our SurveyService works with Surveys! This sounds much better than before, where our SurveyService works with CanManufacturerSurveys.</p><p>There is still one issue sadly, if you take a look at our SendSurvey method you can see it does a .First where it looks for the request.CarManufacturer is equal to Survey.CarManufacturer. Now this is breaking the knowing too much rule because why would a Survey know about car manufacturer?</p><p>So how could we allow a custom filter but also allow the request to provide a filter to that custom filter? Well why don’t we create a SurveyRepository interface which can be used to search for a Survey from a record of Surveys?</p><pre>public interface SurveyRepository<br>{<br>    Survey Search(string filter);<br>}</pre><p>As our SurveyRepository will handle the filtering we can now remove our Filter property on our Survey interface</p><pre>public interface Survey<br>{<br>    string Subject { get; set; }<br>    string Body { get; set; }<br>}</pre><p>Using our SurveyRepository interface we can go ahead and create a new CarManufacturerSurveyRepository. This will act as the list of CarManufacturerSurveys but expose the Search method from the implemented interface.</p><pre>public class CarManufacturerSurveyRepository : SurveyRepository<br>{<br>    private readonly IEnumerable&lt;CarManufacturerSurvey&gt; _surveys;<br>    public CarManufacturerSurveyRepository(IEnumerable&lt;CarManufacturerSurvey&gt; surveys) <br>    {<br>        _surveys = surveys;<br>    }<br><br>    public Survey Search(string filter)<br>        =&gt; _surveys.First(x =&gt; x.CarManufacturer.ToLower() == filter.ToLower());<br>}</pre><p>Before we update our SurveyService lets go and update our SendSurveyRequest model to rename CarManufacturer to Filter</p><pre>public class SendSurveyRequest<br>{<br>    public string EmailAddress { get; set; }<br>    public string Filter { get; set; }<br>    public bool AllowPromotionalEmails { get; set; }<br>}</pre><p>Now we can update our SurveyService</p><pre>public class SurveyService<br>{<br>    private readonly SmtpClient _smtpClient;<br>    private readonly SurveyRepository _surveys;<br><br>    public SurveyService(<br>        SurveyRepository surveys)<br>    {<br>        var emailDirectory = $&quot;{AppDomain.CurrentDomain.BaseDirectory}temp-emails&quot;;<br><br>        // This is just to help you locate your email directory, feel free to delete this line when not needed<br>        Console.WriteLine(emailDirectory);<br><br>        if (!Directory.Exists(emailDirectory))<br>            Directory.CreateDirectory(emailDirectory);<br><br>        _smtpClient = new SmtpClient();<br>        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;<br>        _smtpClient.PickupDirectoryLocation = $&quot;{AppDomain.CurrentDomain.BaseDirectory}/temp-emails&quot;;<br><br>        _surveys = surveys;<br>    }<br><br>    public void SendSurvey(SendSurveyRequest request)<br>    {<br>        if(request.AllowPromotionalEmails)<br>        {<br>            var survey = _surveys.Search(request.Filter);<br><br>            if(survey != null)<br>                _smtpClient.Send(&quot;knowingtomuch@medium.com&quot;, request.EmailAddress, survey.Subject, survey.Body);<br>        }<br>    }<br>}</pre><p>Our final change needs to happen in the Program, this is just because we updated our SurverService to take a SurveyRepository in the constructor, not a list of CarManufacturerSurveys.</p><pre>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var carManufacturerSurveyRepository = new CarManufacturerSurveyRepository(new List&lt;CarManufacturerSurvey&gt;()<br>        {<br>            new CarManufacturerSurvey() {<br>                CarManufacturer = &quot;Fiat&quot;,<br>                Body = &quot;Fiat Survey Link&quot;,<br>                Subject = &quot;Fiat Survey&quot;<br>            }<br>        });<br><br>        new SurveyService(carManufacturerSurveyRepository).SendSurvey(new SendSurveyRequest()<br>        {<br>            AllowPromotionalEmails = true,<br>            Filter = &quot;FIAT&quot;,<br>            EmailAddress = &quot;test@medium.com&quot;<br>        });<br>    }<br>}</pre><p>If you execute the program, you should see a new EML file appear in your directory! So what on earth did we do and why? Well lets go over the changes.</p><p>Our original SurveyService had two major issues. The first was it depended on a list of a concrete class CarManufacturerSurvey which worked before, however that wouldn’t work if we wanted to support mobile manufacturer surveys or any other type of surveys. So we created an interface that would allow our SurveyService to work directly with the interface not the concrete class.</p><p>The second change we had to implement was how we filtered our surveys. Originally we used the request object CarManufacturer property, however this wouldn’t work for a mobile manufacturer because they are both different properties. So to allow this we create a simple interface which would expose one single Search method. This might seem a little pointless but it is very important. This interface allows any class that implements it to be used in our SurveyService as a record of Surveys.</p><p>Currently our code has been updated to use these new interfaces, but didn’t we need to allow mobile manufacturer surveys? Well lets see how easy that is now.</p><p>We’re gonna need two new classes, first our MobileManufacturerSurvey object and then a MobileManufacturerSurveyRepository</p><pre>public class MobileManufacturerSurvey : Survey<br>{<br>    public string Subject { get; set; }<br>    public string Body { get; set; }<br>    public string MobileManufacturer { get; set; }<br>}<br><br>public class MobileManufacturerSurveyRepository : SurveyRepository<br>{<br>    private readonly IEnumerable&lt;MobileManufacturerSurvey&gt; _surveys;<br>    public MobileManufacturerSurveyRepository(IEnumerable&lt;MobileManufacturerSurvey&gt; surveys) <br>    {<br>        _surveys = surveys;<br>    }<br><br>    public Survey Search(string filter)<br>        =&gt; _surveys.First(x =&gt; x.MobileManufacturer.ToLower() == filter.ToLower());<br>}</pre><p>Done! Yep would you believe it, this is all we need to do to allow our SendSurvey to work with MobileManufacturerSurveys. All we need is the object and a repository of that object. You might be thinking isn’t the filter a little similar? Well yes it is, but this is just an example. The client may want the first survey in the list to be sent out if no survey is found via a filter I.E.</p><pre>public Survey Search(string filter)<br>{<br>    var survey = _surveys.FirstOrDefault(x =&gt; x.MobileManufacturer.ToLower() == filter.ToLower());<br>    return survey == null ? _surveys.First() : survey;<br>}</pre><p>Feel free to use the above code if you like, you can test it via the below code, but remember if it can’t match by the filter, it will return the first Survey from the list.</p><p>Here is a small updated Program so you can see the MobileManufacturerSurveyRepository working.</p><pre>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var mobileManufacturerSurveyRepository = new MobileManufacturerSurveyRepository(new List&lt;MobileManufacturerSurvey&gt;()<br>        {<br>            new MobileManufacturerSurvey() {<br>                Filter = &quot;Sony&quot;,<br>                Body = &quot;Sony Survey Link&quot;,<br>                Subject = &quot;Sony Survey&quot;<br>            }<br>        });<br><br>        new SurveyService(mobileManufacturerSurveyRepository).SendSurvey(new SendSurveyRequest()<br>        {<br>            AllowPromotionalEmails = true,<br>            Filter = &quot;SonY&quot;,<br>            EmailAddress = &quot;test@medium.com&quot;<br>        });<br>    }<br>}</pre><p>Just before we call this library done, it’s change time! As the client, I want to send a survey as a text message (SMS) directly to the users mobile number which they provide as part of the insurance application, instead of an email.</p><p>Well that is a little different from sending an email, so can we do this with ease? Well not really because silly us we forced our SurveyService to know about SMTP. We coupled our SurveyService code to SMTP architecture which is bad because… Well we have to change our core library code to allow the above feature, if this was a real project, our testers would need to check SMS and SMTP, even though SMTP was originally working (the change would move/modify the SMTP code, so we can’t expect it to work without regression tests).</p><p>Now no one can tell the future, so hard coding the SMTP client as part of the SurveyService wasn’t truly a bad idea, but you can see because of it, modifying the code now is gonna take much longer than just implementing a new interface.</p><p>So our code is gonna need to change, this is fine because it is software, soft is malleable and flexible compared to hardware. So what is gonna have to change to allow our SurveyService to work with both SMTP and SMS?</p><p>First the SendSurveyRequest class is gonna need a new property of Mobile, then we should probably update our AllowPromotionalEmails to just be AllowContacting.</p><pre>public class SendSurveyRequest<br>{<br>    public string EmailAddress { get; set; }<br>    public string Mobile { get; set; }<br>    public string Filter { get; set; }<br>    public bool AllowContacting{ get; set; }<br>}</pre><p>Lets first work with the impression we are going to be sending an email, we should work with what we know is currently working to confirm all the changes we do, don’t break existing features. Our SurveyService simply invokes the SMTP Send method. We should create an interface which exposes a Send method which can be provided the SendSurveyRequest and Survey as parameters.</p><pre>public interface SurveySender<br>{<br>    void Send(SendSurveyRequest request, Survey survey);<br>}</pre><p>Using the interface we can go ahead and create our SmtpSpecifiedPickupDirectorySurveySender, which will replace the entire SmtpClint inside of our SurveyService</p><pre>public class SmtpSpecifiedPickupDirectorySurveySender : SurveySender<br>{<br>    private readonly SmtpClient _smtpClient;<br>    public SmtpSurveySender()<br>    {<br>        var emailDirectory = $&quot;{AppDomain.CurrentDomain.BaseDirectory}temp-emails&quot;;<br><br>        // This is just to help you locate your email directory, feel free to delete this line when not needed<br>        Console.WriteLine(emailDirectory);<br><br>        if (!Directory.Exists(emailDirectory))<br>            Directory.CreateDirectory(emailDirectory);<br><br>        _smtpClient = new SmtpClient();<br>        _smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory;<br>        _smtpClient.PickupDirectoryLocation = $&quot;{AppDomain.CurrentDomain.BaseDirectory}/temp-emails&quot;;<br>    }<br><br>    public void Send(SendSurveyRequest request, Survey survey)<br>        =&gt; _smtpClient.Send(&quot;knowingtomuch@medium.com&quot;, request.EmailAddress, survey.Subject, survey.Body);<br>}</pre><p>I think with this change our SurveyService is gonna look very small. Let’s go and update it to use the new SurveySender.</p><pre>public class SurveyService<br>{<br>    private readonly SurveySender _sender;<br>    private readonly SurveyRepository _surveys;<br><br>    public SurveyService(<br>        SurveySender sender,<br>        SurveyRepository surveys)<br>    {<br>        _sender = sender;<br>        _surveys = surveys;<br>    }<br><br>    public void SendSurvey(SendSurveyRequest request)<br>    {<br>        if(request.AllowContacting)<br>        {<br>            var survey = _surveys.Search(request.Filter);<br><br>            if(survey != null)<br>                _sender.Send(request, survey);<br>        }<br>    }<br>}</pre><p>Wow! That is incredibly small compared to the original code. All our SurveyService relies on now is a SurveyRepository and a SurveySender! Might look like a pointless class but don’t be fooled. This can be mocked for all sorts of unit tests and it keeps the related items coupled together nicely.</p><p>Time to update our Program so we can see all of these changes work together.</p><pre>static void Main(string[] args)<br>{<br>    var mobileManufacturerSurveyRepository = new MobileManufacturerSurveyRepository(new List&lt;MobileManufacturerSurvey&gt;()<br>    {<br>        new MobileManufacturerSurvey() {<br>            Filter = &quot;Sony&quot;,<br>            Body = &quot;Sony Survey Link&quot;,<br>            Subject = &quot;Sony Survey&quot;<br>        }<br>    });<br><br>    new SurveyService(new SmtpSpecifiedPickupDirectorySurveySender(), mobileManufacturerSurveyRepository).SendSurvey(new SendSurveyRequest()<br>    {<br>        AllowContacting = true,<br>        Filter = &quot;SonY&quot;,<br>        EmailAddress = &quot;test@medium.com&quot;<br>    });<br>}</pre><p>If you execute this program you should see a new EML file in your directory.</p><p>For our final change we want to send a text message instead of an email. I’m not going to actually implement a SMS class, but I will create a ConsoleSurveySender so you can see, we can use any class we like as long as it implements the SurveySender interface.</p><p>Here is the basic console implementation for a SurveySender.</p><pre>public class ConsoleSurvenSender : SurveySender<br>{<br>    public void Send(SendSurveyRequest request, Survey survey)<br>        =&gt; Console.WriteLine($&quot;knowingtomuch@medium.com - {request.EmailAddress}. Subject: {survey.Subject} - {survey.Body}&quot;);<br>}</pre><p>We can update our program code like so to use the new ConsoleSurveySender.</p><pre>public class Program<br>{<br>    static void Main(string[] args)<br>    {<br>        var mobileManufacturerSurveyRepository = new MobileManufacturerSurveyRepository(new List&lt;MobileManufacturerSurvey&gt;()<br>        {<br>            new MobileManufacturerSurvey() {<br>                Filter = &quot;Sony&quot;,<br>                Body = &quot;Sony Survey Link&quot;,<br>                Subject = &quot;Sony Survey&quot;<br>            }<br>        });<br><br>        new SurveyService(new ConsoleSurveySender(), mobileManufacturerSurveyRepository).SendSurvey(new SendSurveyRequest()<br>        {<br>            AllowContacting = true,<br>            Filter = &quot;SonY&quot;,<br>            EmailAddress = &quot;test@medium.com&quot;<br>        });<br>    }<br>}</pre><p>Running the application should produce the console output below.</p><pre>knowingtomuch@medium.com - test@medium.com. Subject: Sony Survey - Sony Survey Link</pre><p>Now that was much longer of an example than what I expected, but hopefully this might help you understand more about the “knowing too much” issue. For this example we first created a SurveyService which would take a list of CarManufacturerSurveys in the constructor. We then implemented one method SendSurvey which would take a SendSurveyRequest.</p><p>Our SurveyService was tightly coupled to our CarManufacturerSurvey object which means our SurveyService could only be used for that specific requirement, but as we saw the client wanted to allow mobile surveys to be sent.</p><p>This requirement could have been solved by duplicating code or by adding a new method to our SurveyService, but the bigger issue is our SurveyService known too much. If it didn’t know about the CarManufacturerSurvey and only knew about an abstraction such as Survey, anything could be used inside of our SurveyService which implemented that abstraction.</p><p>Again this was true for the SMTP client which was constructed in the SurveyService constructor. This is another example of the class knowing too much. Because of this it means our SurveyService is coupled to an SMTP client or at least knowing what SMTP is. This became an issue when the client wanted to send surveys via SMS.</p><p>Like our Survey interface, we created a new interface which would act as our SurveySender (SMTP, SMS, Console, etc). This then allows our SurveyService to use the SurveySender interface, which means our SurveyService can be extended I.E. it can handle any Survey and any SurveySender.</p><p>A thing to try and remember from this is; as a class, the more things I know about, means when one may change, I may also need to change. Another example would be, If your car needed a new tire, you wouldn’t expect to need a whole new car to fix your tire? Same applies to our code.</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>References</p><p>Repository: <a href="https://github.com/MrApproved/Medium_KnowingTooMuch">https://github.com/MrApproved/Medium_TestProjectStructure</a></p><p>Image: <a href="https://www.pexels.com/photo/pile-of-covered-books-159751/">https://www.pexels.com/photo/pile-of-covered-books-159751/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a35d547a406e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Phantasy Star Online Episode I & 2 2D Interactive Map Viewer]]></title>
            <link>https://canvascodebw.medium.com/phantasy-star-online-episode-i-2-2d-interactive-map-viewer-414146ad5ab7?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/414146ad5ab7</guid>
            <category><![CDATA[speedrun]]></category>
            <category><![CDATA[gamecube]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[speedrunning]]></category>
            <category><![CDATA[games]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Thu, 16 Jan 2025 21:03:52 GMT</pubDate>
            <atom:updated>2025-01-17T21:01:52.224Z</atom:updated>
            <content:encoded><![CDATA[<h3>Phantasy Star Online Episode 1 &amp; 2 2D Interactive Map Viewer</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o1nkuq5BASSaHwqCXWPcVA.png" /></figure><p>Many many years ago I played a game known as Phantasy Star Online on the Sega Dreamcast. I instantly fell in love with this game. There were three different classes: Hunter, which focused on melee attacks and they had high attack power and health; Ranger, which focused on ranged attacks and had medium health and attack power; and Force, which focused on techniques, but had the lowest health and defense attributes.</p><p>I played the game a lot. I reached max level (which was 100 at the time) and we were even lucky enough to have the option to play the game online. Yes, you could play the game online, on the Dreamcast! We played the game so much it even killed our first Dreamcast motor, so the discs would no longer spin.</p><p>A version 2 was released on the Dreamcast which we skipped, but they released a 3rd version known as Phantasy Star Online Episode 1 &amp; 2. This was released for Gamecube and Xbox. Ver 3 added 4 player split screen, so you no longer needed to play online. Although we never played this version online and I never reached max level, I still played this game a ton.</p><p>Around 2020 I watched my first Awesome Games Done Quick (<a href="https://gamesdonequick.com/">https://gamesdonequick.com/</a>), AGDQ for short. This is a charity event that hosts speed runs, usually a couple of times a year. A speed run, basically, is playing a game really quickly under specific rules. One time I saw someone do a glitched Phantasy Star Online Episode 1 &amp; 2 speed run. After watching this I thought to myself, why don’t I try it? So I did.</p><p>I currently run the Episode 1 glitched category and I’m planning to get 1st place, which would mean I’m the fastest player of this game in the world (under particular rules). But, more to the point of this post, there are a few resources floating around that can help with speed runs, which you can find here: <a href="https://www.speedrun.com/pso">speedrun.com</a>, typically in the form of images and videos. So then I thought, maybe I could create some sort of interactive map?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNEmQ8MXDeiK-bCLBt3djg.jpeg" /></figure><p>I’ve used the canvas tag a few times, once for a university project and a couple of times for just random personal projects. So let’s use the canvas tag again for another personal project!</p><p>The project in its current state can be viewed here <a href="https://mrapproved.github.io/Phantasy-Star-Online/Map-Viewer/index.html">https://mrapproved.github.io/Phantasy-Star-Online/Map-Viewer/index.html</a>. If you want to edit the map you can execute “enableMapMaker()” in your browser developer console. You can zoom in and out via your mouse wheel (if you have one) and move around by left clicking and dragging the map.</p><p>My main aim was to provide the map of an area and then provide all other details such as item box placements, doors, switches and other objects. Enemies on the other hand were a little more complicated because a room would have a wave of monsters, but some waves would be completely optional. Now this information is quite important when you are trying to complete the game ASAP, since you don’t want to waste time on enemies that aren’t required to progress.</p><p>The first issue I had was the map. I wanted to draw the map by rooms, which allows objects, enemies and anything else related to that room to be associated with the room. This would give better control of disabling and enabling objects for a specific room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*45mq0lCFAyGKF4ewkAqDMQ.jpeg" /><figcaption>Forest</figcaption></figure><p>The map object would contain its name and contain an array of scenarios. A scenario is a version of the map which can differ later on as not all maps have the same layout.</p><p>A scenario contains rooms and its route. It also contains a name and the average completion time in seconds. The name and average time are just displayed at the top of the viewer, but the rooms array is a list of custom room objects and the route is an array of 2D points which is used to draw the route for the map: this is a dotted line which has a gradient from green to red (start to finish).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*rfYSIPpn-ZKOcKqFwuk_AQ.jpeg" /><figcaption>Caves</figcaption></figure><p>A room object would contain its order, start flag, finish flag, src for the image to be displayed, an array of objects, an array of waves, active state and selected state. The active state is for the viewer to display all necessary objects related to that room and select state is for editing the map.</p><p>For enemies, I created an object called “wave”, which contains a list of encounters (this allowed me to mark an encounter as optional). An encounter would contain an array of enemies. Some waves are triggered by the player when they enter a specific part of the map, such as a spawn area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*kPwBVxdQriXsJIT-15jEAA.jpeg" /><figcaption>Mines</figcaption></figure><p>The encounter object would contain a list of enemies, an enemy would just contain the name of the enemy and the 2D position of where it spawns enemies.</p><p>Markers on the map use the BaseMapMarker. This was implemented to try and make it easier to draw specific markers without having to keep typing the necessary properties to draw a box, a line, etc. It was a way to have custom makers for specific objects.</p><p>A map would also contain an array of enemies. An enemy object would just contain the name, health points and the colour of the marker when rendered on the map viewer. The marker, colour and position would all be combined using all the map, scenario, room, wave, encounter, and enemies properties.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*ejCOJgB9k6W2PUJVcQLQZA.jpeg" /><figcaption>Ruins</figcaption></figure><p>I’m not finished with this project, but it has been pushed down my priority list. It requires a lot of manual recording by myself and then translating that information into my custom JSON scenario object. This can take hours for a map and the specific scenario, so there are many days’ worth of work to be done.</p><p>This isn’t an informative blog post or my take on something, it’s more just something I enjoyed doing and wanted to share.</p><p>Thank you for reading. Feel free to provide feedback, positive or negative.</p><p>References</p><p><a href="https://mrapproved.github.io/Phantasy-Star-Online/Map-Viewer/index.html">https://mrapproved.github.io/Phantasy-Star-Online/Map-Viewer/index.html</a><br><a href="https://github.com/MrApproved/mrapproved.github.io">https://github.com/MrApproved/mrapproved.github.io</a><br><a href="https://www.speedrun.com/pso">https://www.speedrun.com/pso</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=414146ad5ab7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Tests — Where Do You Put ‘Em? — C# Example]]></title>
            <link>https://canvascodebw.medium.com/unit-tests-where-do-you-put-em-c-example-38bd916f8d80?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/38bd916f8d80</guid>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[csharp]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Thu, 06 Jun 2024 12:24:52 GMT</pubDate>
            <atom:updated>2024-06-06T12:24:52.179Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Tests — Where Do You Put ‘Em? — C# Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4fJg08M-ZoSYxrIV0meqpQ.jpeg" /></figure><p>Unit tests, where should they go? In a separate project? Should they have the same namespace for easy access/referencing? Should they exist in the same class file? Should the test class have the same name as the class it is testing? These are all questions we have when we start to think about unit testing our code.</p><p>If we take a look at the Microsoft’s <a href="https://learn.microsoft.com/en-us/visualstudio/test/walkthrough-creating-and-running-unit-tests-for-managed-code?view=vs-2022">Create and run unit tests</a> or Microsoft’s <a href="https://learn.microsoft.com/en-us/visualstudio/test/getting-started-with-unit-testing?view=vs-2022&amp;tabs=dotnet%2Cmstest">Get started with unit testing</a>. You can see they have their library code in one project and then their unit test code in another project. This seems to be the most common approach while searching around online and the pattern myself and the team follow at work. But is there another approach? Of course, but lets continue with this common approach first.</p><p>So the common approach is one project for our logic code and another for our unit tests. So lets say we have a StringExtensions class which sits in our library project and a StringExtensions_Tests which sits in our test project. The file name may differ depending on your testing structure, but looking around this seems to be a common approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*zKbcd1-qSXZoffsDFw3B4w.png" /><figcaption>Library in a separate project while our Library_Tests sit in another project</figcaption></figure><p>So why is this a common pattern for structuring unit tests? Well having two projects helps with separating out your logic code and your test code. Your test project would reference the library project. Test classes, Tests methods, 3rd party packages required for tests etc will only be included in your test project, so these won’t be included in your library output build. You don’t want to distribute your library with a bunch of test classes/test libraries, this would just bloat your build output. If you are creating a .NET Standard library you will need a .NET Core or .NET Framework project to execute the code (.NET Standard is a set of APIs that all .NET platforms have to implement).</p><p>Are there issues with this approach? Of course, like anything with coding. If you have a complex library which contains 30+ classes which live in different namespaces etc, do you mirror the folder structure from your library project to the test project? Or do you have a custom structure? If you copy the project structure, navigating the test project could be easier as it mirrors the library project (a class would sit under the same folder in the project structure and have the same namespace). But if you come up with a custom structure, you must follow it and so do other team members. If not, test classes/methods could start to get duplicated and exist in multiple areas, which may lead to maintaining duplicated tests.</p><p>If you aren’t following TDD (test driven development, tests are written first), when a new class is added in your library project, you then need to make the corresponding test class in your test project and keep to the same project structure, another thing to keep in mind.</p><p>If your following the same structure as the Library project, what happens if the structure of the library project changes? The test classes would then not longer mirror the structure of the library project, you would then have to move all corresponding tests to the correct folder, well yes, but if you have custom structure you may need to do other things.</p><p>As you can see, making a unit test project is quite simple, but the issues start to appear when you start to structure the test project, you will start to see, when things change in the library code, how it may affect your test project structure.</p><p>Now I understand I may have made some assumptions on how people may structure their test projects, I just wanted to take you through the issues I have found following the above. I do apologize if these assumptions don’t reflect your structure, but technically I just want to show you a different way to maintaining and structuring your tests. Let’s have a look at that approach which I use for my personal projects, so far it seems to work quite nicely. It does require a little setup, but then so does creating a unit test project etc.</p><p>The approach I take allows your tests to sit in a separate file, in the same project and also be excluded on your release builds (this includes excluding NuGet packages). This means you don’t need a separate project with references to the code base, or duplicated NuGet packages in both projects. It also allows you to access and see the tests much easier than having to navigate the solution explorer or test explorer.</p><p>We are going to structure the follow three projects, .NET Core, .NET Framework SDK style and .NET Framework. I will explain why I skipped .NET Standard at the end.</p><p>For the examples we are going to use the same code snippet, these examples are more about project structure than code. We are going to create one single string extension method and then write three unit tests to confirm our extension method works. Below is our string extension code and then followed by our string extension unit test code.</p><pre>public static class StringExtensions<br>{<br>    public static string SafeTrim(this string s)<br>        =&gt; string.IsNullOrEmpty(s) ? &quot;&quot; : s.Trim();<br>}</pre><pre>[TestClass]<br>public class StringExtensions_Tests<br>{<br>    [TestMethod]<br>    public void NullString_EmptyStringIsReturned()<br>    {<br>        string value = null;<br>        Assert.AreEqual(value.SafeTrim(), &quot;&quot;);<br>    }<br><br>    [TestMethod]<br>    public void EmptyString_EmptyStringIsReturned()<br>        =&gt; Assert.AreEqual(&quot;&quot;.SafeTrim(), &quot;&quot;);<br><br>    [TestMethod]<br><br>    public void ValueWithLeadingAndTrailingSpace_ValueIsTrimmed()<br>        =&gt; Assert.AreEqual(&quot; hello world &quot;.SafeTrim(), &quot;hello world&quot;);<br>}</pre><p>First example will be a .NET Core project, first we create our new .NET Core library project (any version of .NET Core is fine). I’m going to call it NETCore_Library. Once we have our project we can delete the Class1.cs. Create a new class called StringExtensions and copy the code from above. You should then have something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/390/1*ohH9G462QaRxdpmhzhvdWg.png" /></figure><p>So there are two things we need to setup, first how can we execute our tests in our library project and second, how do we exclude our tests and test NuGet packages on release build.</p><p>First step is we need to get our unit tests runnable in our library project. Create a new class and copy the test code from above, feel free to name the file what you like, but make sure the file ends with _Tests.cs (this is important later on). Now You should get some compile errors because TestClass, TestMethod and Assert is not found.</p><p>To fix the test class we need to install three NuGet packages to our project, these are Microsoft.NET.Test.Sdk, MSTest.TestAdapter and MSTest.TestFramework. I would always install the latest or the latest that is supported for your targeted framework. Microsoft.NET.Test.Sdk is required for your MSBuild to target .NET test projects. The other two packages MSTest.TestAdapter and MSTest.TestFramework are for writing MSTest tests. If you prefer a different test library such as xUnit, I will go over that at the end, however for these examples we will be using MSTest.</p><pre>Install-Package Microsoft.NET.Test.Sdk<br>Install-Package MSTest.TestAdapter<br>Install-Package MSTest.TestFramework</pre><p>Once you have installed the above packages, you will need to add the missing using statement in the test class to fix the compile issue.</p><pre>using Microsoft.VisualStudio.TestTools.UnitTesting;</pre><p>We should now be able to compile and execute our unit tests to confirm the extension method works correctly, you can use test explorer to execute the tests or if you are in the _Tests.cs file you should be able to right click the code and select Run Tests (CTRL + R, T). I have noticed on some occasions, you may need to close and reopen Visual Studio after installing the test NuGet packages, some times the test explorer just won’t see our tests, we should only have to do this once to fix the issue. Now we have our test explorer working, your current project should look like this</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*i4tuXSdJr-EQn8lATH4fhA.png" /></figure><p>On to step two, how do we exclude our test class and the NuGet packages which are only required for testing? Well you will need to modify the csproj file, to do this you can double click your project NETCore_Library or right click the NETCore_Library and select Edit Project File. This should display a very basic XML file, you can ignore must of it, but what we want to do is inform our csproj to exclude our test classes and exclude the NuGet packages on a Release build. Below is the original csproj XML from the example.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;17.10.0&quot; /&gt;<br>    &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;3.4.3&quot; /&gt;<br>    &lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;3.4.3&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Let’s now update our csproj using the XML below.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Debug&#39;&quot;&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;*&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>  &lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>    &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>So what changed? Well two parts have changed. First part is our ItemGroup which contained our PackageReferences for the test NuGet packages, has been updated with a Condition property. this checks to see if the current configuration is Debug, this means if the configuration isn’t Debug, then those PackageReferences will be excluded (the Configuration is populated from your Visual Studio build, in Visual Studio if you take a look at the top, you should see it state Debug).</p><p>A minor change which you can skip is, I’ve updated the Version property for the PackageReferences to be an *, this informs NuGet to always install the latest version of that package, if you want to use a specific version or the one you installed for this example, then just copy the Condition property across and ignore the * version replacement.</p><p>The second change we did was when the configuration is Release, we want to exclude every single file which ends with _Tests.cs, this way as long as we suffix our test classes with _Tests.cs, then that file will be excluded on a Release build. The **\*_Tests.cs translates to, look in the current directory and all other directories relevant to this path for any file that ends with _Tests.cs.</p><p>To confirm this works what we can do is in Visual Studio, if we change the build from Debug to Release, we will notice the _Tests.cs class disappears, also the test explorer states there are no tests and the three NuGet packages are no longer installed (check under Dependencies).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/794/1*p_SAnFmfS9JfS3UTHnkD3w.png" /><figcaption>Debug</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/803/1*EfAH951UAhPsQ0j6r7nXcQ.png" /><figcaption>Release</figcaption></figure><p>So with this setup you can now write your tests along side your library code and keep them all in one place, you don’t have to manage two separate projects. Everything can be done in the same place. With our csproj compile remove **\*_Tests.cs, any file which ends with _Tests.cs will be ignored on a Release build, so as long as we name our files correctly, our release will only include our logic code.</p><p>If you are thinking, well what about my NuGet packages which are required for Debug and Release builds? Well all you need to do is move those specific PackageReferences in your csproj into a new ItemGroup with no Condition, like so.</p><pre>&lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Debug&#39;&quot;&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;*&quot; /&gt;<br>  &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot; Version=&quot;*&quot; /&gt;<br>  &lt;PackageReference Include=&quot;MSTest.TestFramework&quot; Version=&quot;*&quot; /&gt;<br>&lt;/ItemGroup&gt;<br><br>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Serilog&quot; Version=&quot;4.0.0&quot; /&gt;<br>  &lt;PackageReference Include=&quot;Serilog.Sinks.File&quot; Version=&quot;5.0.0&quot; /&gt;<br>&lt;/ItemGroup&gt;</pre><p>This way Serilog and Serilog.Sinks.File will also be included in Debug and Release builds. The test NuGet packages are still within the ItemGroup with the Debug Condition so those will still be excluded in a Release build.</p><p>I’ve found this approach much easier to manage, my tests are close to the class it is testing, it’s much easier for me to maintain and for others to see if a test class already exists for a class. NuGet packages are all handled in the csproj so any modifications can be done when needed, even test files can be added and excluded on specific builds just by using the Condition property on the ItemGroup.</p><p>I’ve only been using this for a year or so, so I’m sure somethings will appear at some point, but as developers we learn, adapt and improve on iteration.</p><p>So what about a .NET Framework library? So lets first target a .NET Framework SDK style project. What do I mean by a SDK style project? Basically it allows an old .NET Framework project to follow the same csproj structure as a .NET Core project. How to do this? Well you can Google around for “Migrate .NET Framework to SDK style” but I will provide the steps I take for old .NET Framework projects.</p><p>Open up your Visual Studio (I’m using 2022), select Extensions from the menu bar and then Manage Extensions. With the Browse tab selected search “.NET Upgrade Assistant”, once found click the Install button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qJnG2cztnHi2I_X08EMCWA.png" /></figure><p>Once the install is done, it should prompt you to close Visual Studio to finish it off (You should see a message at the top of Visual Studio which states “Your changes are scheduled. The modification will begin when Microsoft Visual Studio is closed.”). When you close all instances of Visual Studio, you should see a VSIX Installer, it will state that you are wanting to install the .NET Upgrade Assistant, if everything looks good, just click that Modify button. Once done it should come up with a Modification Complete window, you can just click the Close button.</p><p>Now to start the process of upgrading to a SDK style, we should first open our .NET Framework library in Visual Studio. If we right click our project we should see a new option Upgrade.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/1*6JFGiuq51e59QV3zUGIIrg.png" /></figure><p>If you select Upgrade it will take you to a new window, this window should have two options. The first is to upgrade from .NET Framework to .NET Core, we can ignore this option. The second open which is Upgrade project features is what we are after, so select this option, this should then provide us an option labeled Convert project to SDK style. You can then either select Next or double click the option. Once done you should see something like this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MXt77cbdee2gLT29mR-v7w.png" /></figure><p>Beware: this failed for me first time, I had to make sure my Visual Studio 2022 was up to date, so if you get an error, make sure to update your Visual Studio to the latest. To do this, in the menu bar select Help and then select Check for Updates, follow the necessary steps if an update is available.</p><p>Another issue I had, is if you have Microsoft.NET.Test.Sdk, MSTest.TestAdapter and MSTest.TestFramework installed already and try to upgrade the project, you may get a failed message because of an “info: ‘ProjectName.csproj’ has invalid Project Type Guids for test projects and is not supported”. I would suggest just uninstalling any test NuGet packages, run the upgrade and then reinstall those NuGet packages.</p><p>So after the upgrade to the SDK style is complete, what you should be able to do is double click your project in Visual Studio, and behold you can see something very similar to the above csproj XML which was taken from the .NET Core project example. They may differ a little, but nothing to worry about.</p><p>All you have to do now is follow the same steps as the .NET Core example above, install the test NuGet packages and then by modifying your csproj XML you can exclude/include necessary NuGet packages and files for Debug and Release builds.</p><p>Final example is for a .NET Framework library which still uses the old csproj XML style. Before we tackle NuGet packages lets first exclude our _Tests.cs files. Unfortunately in Visual Studio you can’t just double click an old .NET Framework project and modify it’s contents, you sadly have to right click your project and select the Open Folder in File Explorer, there you then have to right click on your .csproj and modify with a program (feel free to use anything, I will be using Notepad).</p><p>If your project contains a packages.config your csproj XML is gonna look ugly, but ignoring the horrible mess, you should be able to append the below anywhere in your csproj XML.</p><pre>...<br>&lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>  &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>...</pre><p>This does the same as the above examples, however I have noticed in my Visual Studio 2022, when I switch to Debug/Release the files in solution explorer can get a little confused, however on compile I have confirmed that the test class is not included (You won’t be able to compile until you install the NuGet packages in the next step).</p><p>Now for the NuGet packages there is an issue, because some of you may use the old style of packages.config and some may use the PackageReferences that are stored in the csproj XML (PackageReferecnes in the csporj are the “latest” way to reference NuGet packages for .NET Framework).</p><p>Anyway first we have to install our required test NuGet packages, you can get the list from the first example above, after those three packages are installed, you should have a packages.config file appear. With those packages installed you should be able to build and run our tests, you can also switch between Debug and Release to see the file disappear etc.</p><p>If you want to upgrade your packages.config to PackageReferences, you should be able to right click on your packages.config file in Vistual Studio and then select Migrate packages.config to PackageReference… when the window appears you should be good to just hit OK.</p><p>Let’s go through the steps for using PackageReferences instead of the old packages.config, doing it this way you will be able to achieve the same output as the previous examples. So after upgrading to using PackageReferences, if we save all and then open our csproj in Notepad we should see something like the below.</p><pre>...<br>&lt;ItemGroup&gt;<br>  &lt;Compile Include=&quot;StringExtension.cs&quot; /&gt;<br>  &lt;Compile Include=&quot;Properties\AssemblyInfo.cs&quot; /&gt;<br>  &lt;Compile Include=&quot;StringExtensions_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>  &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;ItemGroup&gt;<br>  &lt;None Include=&quot;app.config&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot;&gt;<br>    &lt;Version&gt;17.10.0&lt;/Version&gt;<br>  &lt;/PackageReference&gt;<br>  &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot;&gt;<br>    &lt;Version&gt;3.4.3&lt;/Version&gt;<br>  &lt;/PackageReference&gt;<br>  &lt;PackageReference Include=&quot;MSTest.TestFramework&quot;&gt;<br>    &lt;Version&gt;3.4.3&lt;/Version&gt;<br>  &lt;/PackageReference&gt;<br>  &lt;PackageReference Include=&quot;NuGet.Frameworks&quot;&gt;<br>    &lt;Version&gt;5.11.3&lt;/Version&gt;<br>  &lt;/PackageReference&gt;<br>&lt;/ItemGroup&gt;<br>&lt;Import Project=&quot;$(MSBuildToolsPath)\Microsoft.CSharp.targets&quot; /&gt;<br>...</pre><p>To exclude these specific PackageReferences on Release, we need to wrap it around a Choose and When element like so.</p><pre>...<br>&lt;ItemGroup&gt;<br>  &lt;Compile Include=&quot;StringExtension.cs&quot; /&gt;<br>  &lt;Compile Include=&quot;Properties\AssemblyInfo.cs&quot; /&gt;<br>  &lt;Compile Include=&quot;StringExtensions_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>  &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;ItemGroup&gt;<br>  &lt;None Include=&quot;app.config&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>&lt;Choose&gt;<br>  &lt;When Condition=&quot;&#39;$(Configuration)&#39; == &#39;Debug&#39;&quot;&gt;<br>    &lt;ItemGroup&gt;<br>      &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot;&gt;<br>        &lt;Version&gt;*&lt;/Version&gt;<br>      &lt;/PackageReference&gt;<br>      &lt;PackageReference Include=&quot;MSTest.TestAdapter&quot;&gt;<br>        &lt;Version&gt;*&lt;/Version&gt;<br>      &lt;/PackageReference&gt;<br>      &lt;PackageReference Include=&quot;MSTest.TestFramework&quot;&gt;<br>        &lt;Version&gt;*&lt;/Version&gt;<br>      &lt;/PackageReference&gt;<br>    &lt;/ItemGroup&gt;<br>  &lt;/When&gt;<br>&lt;/Choose&gt;<br>&lt;ItemGroup&gt;<br>  &lt;PackageReference Include=&quot;NuGet.Frameworks&quot;&gt;<br>    &lt;Version&gt;5.11.3&lt;/Version&gt;<br>  &lt;/PackageReference&gt;<br>&lt;/ItemGroup&gt;<br>&lt;Import Project=&quot;$(MSBuildToolsPath)\Microsoft.CSharp.targets&quot; /&gt;<br>...</pre><p>When we switch our build to Release, it may take a little while but if we take a look at our References we should see the test NuGet packages disappear and if we check our output folder the packages are not included (I found building the project also can help refresh the solution explorer). The reason I excluded the NuGet.Frameworks is because if you remove all PackageReference elements in the csproj XML, it will convert back to using packages.config which seems odd, I have no idea why it does this but be aware of this (I would assume if it can’t see a PackageReference element in the csproj XML, just fallback to the old style of packages.config).</p><p>Now if you are using the old style of packages.config, then excluding specific NuGet packages can be done in the csproj XML, but due to how it is structured with EnsureNuGetPackageBuildImports, References and Imports etc. it is quite a bit of work and if you install a new NuGet package it can reset all of your manual modifications or cause conflicts. The easiest thing I would suggest is provide the below to your csproj XML, this will at least exclude your tests from your Release output, however your output builds will also include the test DLLs which are technically not required.</p><pre>...<br>&lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>  &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>&lt;/ItemGroup&gt;<br>...</pre><p>Maybe for old styled .NET Framework libraries which use packages.config, you should just stick with a separate test project, trying to tailor the csproj XML for those specific scenarios is just a massive pain and any modification via Visual Studio can undo changes you have done manually, I’ve seen it happen sadly.</p><p>.NET Standard, why did I exclude this from the examples? Well .NET Standard is just a bunch of APIs which speak to .NET Framework / .NET Core implementations, so technically .NET Standard doesn’t compile into a runtime, so if you are creating a .NET Standard library then you will need to create a new test project with the desired runtime, then you can write your tests against that specific target framework referencing your .NET Standard library code.</p><p>What about using a different test library than MSTest, lets take our .NET Core library example, now all we have to do is instead of installing the NuGet packages for MSTest (MSTest.TestAdapter and MSTest.TestFramework). We can just install the required specific test library NuGet packages, for example xUnit. To use xUnit we need to install the following NuGet packages.</p><pre>Install-Package Microsoft.NET.Test.Sdk<br>Install-Package xunit<br>Install-Package xunit.runner.visualstudio</pre><p>With that done, we can then modify our csproj to look something like this.</p><pre>&lt;Project Sdk=&quot;Microsoft.NET.Sdk&quot;&gt;<br><br>  &lt;PropertyGroup&gt;<br>    &lt;TargetFramework&gt;net8.0&lt;/TargetFramework&gt;<br>    &lt;ImplicitUsings&gt;enable&lt;/ImplicitUsings&gt;<br>    &lt;Nullable&gt;enable&lt;/Nullable&gt;<br><br>    &lt;IsPackable&gt;false&lt;/IsPackable&gt;<br>    &lt;IsTestProject&gt;true&lt;/IsTestProject&gt;<br>  &lt;/PropertyGroup&gt;<br><br>  &lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Debug&#39;&quot;&gt;<br>    &lt;PackageReference Include=&quot;Microsoft.NET.Test.Sdk&quot; Version=&quot;*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;xunit&quot; Version=&quot;*&quot; /&gt;<br>    &lt;PackageReference Include=&quot;xunit.runner.visualstudio&quot; Version=&quot;*&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>  &lt;ItemGroup Condition=&quot;&#39;$(Configuration)&#39; == &#39;Release&#39;&quot;&gt;<br>    &lt;Compile Remove=&quot;**\*_Tests.cs&quot; /&gt;<br>  &lt;/ItemGroup&gt;<br><br>&lt;/Project&gt;</pre><p>Right, you are all setup with xUnit test library and NuGet packages which are included/excluded on Debug/Release builds.</p><p>Quick note, if you install a new NuGet package, a new ItemGroup with no condition will be added, so if you want that NuGet package only for Debug, you will need to move the PackageReference into the Debug Condition ItemGroup.</p><p>The approach I have provided works for all project setups, be it a web app, console app, winforms app, whatever. You can use the above in any sort of application you have, the modifications we do just informs the project to include and exclude specific things on specific builds. I used a library project for the examples because the code wasn’t the focus.</p><p>I have put all of the examples above into a repository which you can download from <a href="https://github.com/MrApproved/Medium_TestProjectStructure">https://github.com/MrApproved/Medium_TestProjectStructure</a>. Each project as its own solution to keep it simple.</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>References</p><p>.NET Upgrade Assistant: <a href="https://dotnet.microsoft.com/en-us/platform/upgrade-assistant">https://dotnet.microsoft.com/en-us/platform/upgrade-assistant</a></p><p>Create a .NET Framework SDK style project from scratch: <a href="https://stackoverflow.com/questions/62255602/how-do-i-create-an-sdk-style-project-for-a-net-framework-4-7-2-project-in-using">https://stackoverflow.com/questions/62255602/how-do-i-create-an-sdk-style-project-for-a-net-framework-4-7-2-project-in-using</a></p><p>Repository: <a href="https://github.com/MrApproved/Medium_TestProjectStructure">https://github.com/MrApproved/Medium_TestProjectStructure</a></p><p>Image: <a href="https://www.pexels.com/photo/photo-of-pathway-surrounded-by-fir-trees-1578750/">https://www.pexels.com/photo/photo-of-pathway-surrounded-by-fir-trees-1578750/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38bd916f8d80" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Wrapper Classes — A Little Helper For Everyone — C# Example]]></title>
            <link>https://canvascodebw.medium.com/wrapper-classes-a-little-helper-for-everyone-c-example-07706b3d67ab?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/07706b3d67ab</guid>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[wrapper]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Wed, 10 Apr 2024 12:30:28 GMT</pubDate>
            <atom:updated>2024-06-18T21:51:00.537Z</atom:updated>
            <content:encoded><![CDATA[<h3>Wrapper Classes — A Little Helper For Everyone — C# Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N-Yo6xyy6OBPjmzZeb_Gbw.jpeg" /></figure><p>A Wrapper class, what is it and what can it help us with? Well have you had some code which relies on some framework library which you would like to unit test?, add new features to an object you don’t have permission to modify?, or you have an existing object you would like to act as a different object? Well the wrapper class is here to help!</p><p>The wrapper class can be used to expose specific methods around an existing class or functionality. This allows existing classes/functions to be simplified or extended with ease, they can also be used to modify the accessible to specific properties/methods via security/authentication.</p><p>Now why would you want to do any of the above? Well if you remember the first paragraph, sometimes we want to unit test code which uses framework code/3rd party libraries, extend existing functionality or make an existing type be compatible with another type. Well anyways, lets have a look at a few examples.</p><p>First example — We have a FileStorage class which uses the System.IO.File static class. So here is our original code.</p><pre>public class FileStorage<br>{<br>    public void DeleteFile(string fileName)<br>        =&gt; File.Delete(fileName);<br>    <br>    public string LoadFile(string fileName)<br>        =&gt; File.ReadAllText(fileName);<br>    <br>    public void SaveFile(string fileName, string fileContents)<br>        =&gt; File.WriteAllText(fileName, fileContents);<br>}</pre><p>We have some basic functions, delete, save and load. Now what if we wanted to unit test this? What if we wanted to update these methods to use cloud storage? Or even post the contents to a WebApi? Do we want to create a whole new class which has its own methods or create new methods against our existing FileStorage? If we created a whole new class, we would then have to construct the correct class when required, if we created new methods, we would to update the code to call the those new methods, and what about unit testing? This doesn’t sound good for maintenance at all.</p><p>Why don’t we extract an interface from our FileStorage class? This will give us the interface definition to allow any type of file storage to be created and used. So lets create our interface first.</p><pre>public interface IFileStorage<br>{<br>    void SaveFile(string fileName, string fileContents);<br>    string LoadFile(string fileName);<br>    void DeleteFile(string fileName);<br>}</pre><p>Now all we have to do is apply this interface to our existing FileStorage like so</p><pre>public class FileStorage : IFileStorage<br>{<br>    public void DeleteFile(string fileName)<br>        =&gt; File.Delete(fileName);<br><br>    public string LoadFile(string fileName)<br>        =&gt; File.ReadAllText(fileName);<br><br>    public void SaveFile(string fileName, string fileContents)<br>        =&gt; File.WriteAllText(fileName, fileContents);<br>}</pre><p>So currently all we have done is create an interface, well yes that is true, but what have we actually gained from wrapping our FileStorage with an interface? Well first off we now have an interface which can be used when necessary, this means we no longer have to rely on the FileStorage which relies on the System.IO.File implementation, for example we could now mock our IFileStorage so it can be unit tested. We could even use a whole new implementation of our IFileStorage like the one below.</p><pre>public class InMemoryFileStorage : IFileStorage<br>{<br>    private IDictionary&lt;string, string&gt; Files { get; set; }<br><br>    public InMemoryFileStorage()<br>    {<br>        Files = new Dictionary&lt;string, string&gt;();<br>    }<br><br>    public void DeleteFile(string fileName)<br>    {<br>        if(Files.ContainsKey(fileName))<br>            Files.Remove(fileName);<br>    }<br><br>    public string LoadFile(string fileName)<br>    {<br>        if (Files.ContainsKey(fileName))<br>            return Files[fileName];<br>        return string.Empty;<br>    }<br><br>    public void SaveFile(string fileName, string fileContents)<br>        =&gt; Files[fileName] = fileContents;<br>}</pre><p>Instead of using our FileStorage, we could use our InMemoryFIleStorage, this way we don’t actually write files to disk, we write them to memory. Also remember, as we have an interface for our IFileStorage requirements, we can create any implementation and use it when/where ever we want.</p><p>I will admit this isn’t the best example for a wrapper class, yes it is just an interface, but it does allow us to wrap framework code using an interface. This way we don’t have to rely on the framework code under specific requirements such as System.IO.File. If it helps, mentally replace the System.IO.File with a System.Net.Http.HttpClient, the HttpClient is used to create HTTP requests, we wouldn’t want to actually invoke a web request in our actual unit tests and also what if we move away from HTTP and start to use a service bus? Its best to wrap that in an interface so you can unit test it and change the implementation when necessary.</p><p>Second example — Auditing. We have a BankAccount class which deals with adding funds, removing funds and updating the account name. Here is the example code</p><pre>public interface IBankAccount<br>{<br>    string AccountId { get; }<br>    string AccountName { get; }<br>    decimal CurrentFunds { get; }<br>    void AddFunds(decimal funds);<br>    void RemoveFunds(decimal funds);<br>    void UpdateDetails(string name);<br>}<br><br>public class BankAccount : IBankAccount<br>{<br>    public string AccountId { get; private set; }<br>    public string AccountName {  get; private set; }<br>    public decimal CurrentFunds { get; private set; }<br><br>    public BankAccount(string accountId, string accountName, decimal currentFunds)<br>    {<br>        AccountId = accountId;<br>        AccountName = accountName;<br>        CurrentFunds = currentFunds;<br>    }<br><br>    public void AddFunds(decimal funds)<br>        =&gt; CurrentFunds += funds &lt; 0 ? 0 : funds;<br><br>    public void RemoveFunds(decimal funds)<br>        =&gt; CurrentFunds -= funds &lt; 0 ? 0 : funds;<br><br>    public void UpdateDetails(string name)<br>        =&gt; AccountName = string.IsNullOrWhiteSpace(name) ? AccountName : name;<br>}</pre><p>We’ve been asked to allow auditing to take place on all three of these methods. Auditing will be configurable by the account holder, this means not all bank accounts will need to be audited, so we need to leave the existing functionality alone. So first we don’t want to duplicate the original class because if we had to add a new method or modify a method, we would have to remember to update our BankAccount and our new AuditingBankAccount, we would also need to update any other IBankAccount classes.</p><p>We could add a boolean flag for auditing in our BankAccount, but do we really want to add a flag? What if we wanted to add more flags? Our BankAccount class could get bloated and the code could start to look really messy with if statements everywhere. I think it is best to implement the same interface as BankAccount and call the original object.</p><p>So a way for us to get around this problem is to create an audit wrapper which will implement our IBankAccount interface, this way it follows the rules of our BankAccount, but we also extend the existing methods of our BankAccount. Lets see how we can achieve our new AuditingBankAccount</p><pre>public class AuditingBankAccount : IBankAccount<br>{<br>    public string AccountId =&gt; _bankAccount.AccountId;<br>    public string AccountName =&gt; _bankAccount.AccountName;<br>    public decimal CurrentFunds =&gt; _bankAccount.CurrentFunds;<br><br>    public ICollection&lt;string&gt; Audit { get; private set; }<br><br>    private readonly IBankAccount _bankAccount;<br><br>    public AuditingBankAccount(BankAccount bankAccount)<br>    {<br>        _bankAccount = bankAccount;<br>        Audit = new List&lt;string&gt;();<br>    }<br><br>    public void AddFunds(decimal funds)<br>    {<br>        var audit = new StringBuilder();<br>        audit.AppendLine($&quot;Current funds [{CurrentFunds}]&quot;);<br>        audit.AppendLine($&quot;Funds to add [{funds}]&quot;);<br>        _bankAccount.AddFunds(funds);<br>        audit.Append($&quot;New current funds [{CurrentFunds}]&quot;);<br>        Audit.Add(audit.ToString());<br>    }<br>    <br>    public void RemoveFunds(decimal funds)<br>    {<br>        var audit = new StringBuilder();<br>        audit.AppendLine($&quot;Current funds [{CurrentFunds}]&quot;);<br>        audit.AppendLine($&quot;Funds to remove [{funds}] &quot;);<br>        _bankAccount.RemoveFunds(funds);<br>        audit.Append($&quot;New current funds [{CurrentFunds}]&quot;);<br>        Audit.Add(audit.ToString());<br>    }<br>    <br>    public void UpdateDetails(string name)<br>    {<br>        var audit = new StringBuilder();<br>        audit.AppendLine($&quot;Current account name [{AccountName}]&quot;);<br>        _bankAccount.UpdateDetails(name);<br>        audit.AppendLine($&quot;New account name [{AccountName}]&quot;);<br>        Audit.Add(audit.ToString());<br>    }<br>}</pre><p>With our AuditingBankAccount above, all we have done is wrapped our original BankAccount class, but we have added an extra feature which simply just audits each method. This was achieved by two things, first we implemented the same interface as our BankAccount and second, in our constructor we took an existing BankAccount. The interface allowed us to extend the methods by putting our audit code in each method and we kept the original functionally by invoking our BankAccount which was provided on construction.</p><p>This example shows that we can extend the functionally of an existing object without changing the original object itself. All we have to do is wrap the original object and expose the same methods (interface or abstract class) and invoke the same method against the original object. This is super useful when you may not have access to modify the original object, for example an object from the framework library or 3rd party code.</p><p>Third example — We have a Printer class which can be given a Job which is added to a collection, once we are ready we can invoke the Print method against our Printer which will invoke the Print method against the Jobs which are present in the collection. Here is the example code.</p><pre>public class Printer<br>{<br>    private ICollection&lt;Job&gt; Jobs;<br><br>    public Printer() =&gt; ResetJobs();<br><br>    public void Add(Job job)<br>        =&gt; Jobs.Add(job);<br><br>    public void Print()<br>    {<br>        var output = new StringBuilder();<br>        foreach (var job in Jobs)<br>            output.AppendLine(job.Print());<br><br>        ResetJobs();<br>        Console.Write(output.ToString());<br>    }<br><br>    private void ResetJobs()<br>        =&gt; Jobs = new List&lt;Job&gt;();<br>}<br><br>public class Job<br>{<br>    public string Content { get; set; }<br>    public string Print() =&gt; Content;<br>} </pre><p>We have some existing objects which we would like to be able to provide to our Printer so they can be printed. So first off here are our existing objects.</p><pre>public class Employee<br>{<br>    public string Name { get; set; }<br>    public string EmployeeReference { get; set; }<br>    public decimal YearlySalary { get; set; }<br>}<br><br>public class Sqaure<br>{<br>    public int Size { get; set; }<br>}<br><br>public class Weapon<br>{<br>    public string Title { get; set; }<br>    public WeaponType Type { get; set; }<br>    public Rarity Rarity { get; set; }<br>    public int BaseDamage { get; set; }<br>}<br><br>public enum WeaponType<br>{<br>    Sword,<br>    Axe,<br>    Bow,<br>    Mace,<br>    Staff<br>}<br><br>public enum Rarity<br>{<br>    Uncommon,<br>    Common,<br>    Rare,<br>    Epic,<br>    Legendary<br>}</pre><p>For each of these objects we would like them to be printable and each one will print differently. So how can we make our Employee, Square and Weapon classes usable by our Printer class? Well we do have a Job class. We could create a new method against each of the objects above, that would return a new Job, like so</p><pre>public class Employee<br>{<br>    public string Name { get; set; }<br>    public string EmployeeReference { get; set; }<br>    public decimal YearlySalary { get; set; }<br><br>    public Job Print()<br>    {<br>        return new Job()<br>        {<br>            Content = $&quot;Name: {Name} ({EmployeeReference}) - Yearly Salary: {YearlySalary}&quot;<br>        };<br>    }<br>}</pre><p>But then we would have to maintain that method three times and this could get messy if we allow more objects to return a new Job object.</p><p>Well we could create an interface and implement that, but why don’t we mark our Job class as an abstract class instead, so any class that can be printable can inherit Job, that way they will be forced to implement the Print method. Lets update our Job class like so</p><pre>public abstract class Job<br>{<br>    public abstract string Print();<br>} </pre><p>That was a big change! Right so lets go and update our three classes which we would like to be printable to our Printer class.</p><pre>public class Employee : Job<br>{<br>    public string Name { get; set; }<br>    public string EmployeeReference { get; set; }<br>    public decimal YearlySalary { get; set; }<br><br>    public override string Print()<br>        =&gt; $&quot;Name: {Name} ({EmployeeReference}) - Yearly Salary: {YearlySalary}&quot;;<br>}<br><br>public class Square : Job<br>{<br>    public int Size { get; set; }<br><br>    public override string Print()<br>    {<br>        var sb = new StringBuilder();<br>        for (var y = 0; y &lt; Size; y++)<br>        {<br>            for (var x = 0; x &lt; Size; x++)<br>            {<br>                sb.Append(&quot;#&quot;);<br>            }<br><br>            if(y != (Size -1))<br>                sb.AppendLine();<br>        }<br><br>        return sb.ToString();<br>    }<br>}<br><br>public class Weapon : Job<br>{<br>    public string Title { get; set; }<br>    public WeaponType Type { get; set; }<br>    public Rarity Rarity { get; set; }<br>    public int BaseDamage { get; set; }<br><br>    public override string Print()<br>    {<br>        var sb = new StringBuilder();<br>        sb.AppendLine(Title);<br>        sb.AppendLine($&quot;Type: {Type}&quot;);<br>        sb.AppendLine($&quot;Rarity: {Rarity}&quot;);<br>        sb.AppendLine($&quot;Power: {BaseDamage}&quot;);<br>        return sb.ToString();<br>    }<br>}</pre><p>Our Printer class won’t need to change because our Job class still has the method Print and overall, all we did was mark it as abstract.</p><p>Nice work, so what have we actually done? Well we have made three existing objects that our system might be using for whatever reason, to now be printable by simply inheriting from the abstract Job class. We have simply wrapped the Job class with our original three classes. Our three classes can be modified in anyway shape or form, as long as they implement the Print method which is inherited from the Job class, they can be used by the Printer class. Thank you polymorphism.</p><p>I have put all of the examples above into a repository which you can download from <a href="https://github.com/MrApproved/Medium_WrapperClass">https://github.com/MrApproved/Medium_WrapperClass</a>. Each project as its own solution to keep it simple.</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>References</p><p>Repository — <a href="https://github.com/MrApproved/Medium_WrapperClass">https://github.com/MrApproved/Medium_WrapperClass</a><br>Image — <a href="https://www.pexels.com/photo/close-up-of-a-wrapped-gift-5913997/">https://www.pexels.com/photo/close-up-of-a-wrapped-gift-5913997/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=07706b3d67ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing — Pros and Cons — Understanding why testing code is a good practice]]></title>
            <link>https://canvascodebw.medium.com/unit-testing-pros-and-cons-understanding-why-testing-code-is-a-good-practice-47a81d67ccde?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/47a81d67ccde</guid>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[unit-testing]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Thu, 29 Feb 2024 13:30:55 GMT</pubDate>
            <atom:updated>2024-02-29T20:54:04.260Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing — Pros and Cons — Understanding why testing code is a good practice</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8MwvuwonRZePjowxmNZDZA.jpeg" /></figure><p>What is unit testing? Well a unit test should aim to test a specific feature in our code, be it a function which calculates a value, or a value that is gathered from some source. The key word is “unit”, it should test one thing.</p><p>This blog post we will take a look at the pros and cons of unit testing, and yes there are cons to unit testing. I did a previous post about unit testing, but it was more of a coding example. If you would like to take a look at that post, just follow this link — <a href="https://canvascodebw.medium.com/unit-testing-why-write-code-to-test-my-code-seems-a-little-redundant-c-example-25a0d0202c5f">https://medium.com/@canvascodebw/unit-testing-why-write-code-to-test-my-code-seems-a-little-redundant-c-example-25a0d0202c5f</a></p><p>This post I’m going to focus more on the advantages and disadvantages of writing unit tests. This post is also going to ignore TDD (Test Driven Development), I’m choosing to ignore this as TDD isn’t something developers start with, this is a discipline which you may adopt later in your career.</p><p>So a few years ago, I was creating some game logic in C#, I had many classes which all spoke to each other to work out damage, attributes, monsters etc, I had unit tests for all of my code. Now with this code I had no game platform, just code. I built my game logic into a DLL and referenced it in a Unity project. After I wired up my game logic to be invoked by Unity, something magical happened. I will remember the feeling as it was pure magic. The game just worked, damge, attributes, monster etc. All of the game logic was created without a “game” per se and I tested it all with unit tests.</p><p>Next time you have a personal project or time, try creating the logic code in a library with unit tests, then once it is all done, wire it into your desired architecture. I hope you experience the same magical moment as myself.</p><p>Right, anyways, back to the post. Yes, testing your our code with unit tests is always a good idea, it provides evidence your code works and security on future changes, but there are disadvantages… Firstly let’s go over the benefits you get from testing your code.</p><p>Detecting Bugs — By writing unit tests to test specific parts of our application, we can provide whatever parameters we like and confirm the output is correct. Someone said to me “The ClientId value will never be null in production”, however in the code the ClientId was marked as nullable, after they wrote some tests with this value as null, they noticed the logic was wrong. Don’t work off of assumptions.</p><p>Overall Cost — Maintaining and improving code can be very costly, especially when something hasn’t been touched in a good while. If you don’t have unit tests you have no proof the changes haven’t broken anything, also knowing what the system does could be hard to understand without tests to prove you are on the right track. Testing manually will increase the time spent, if we had unit tests to prove the latest changes we did haven’t broken anything, we can then test those specific parts in the test environment instead of the entire application.</p><p>Confidence in changes allows for a smoother release process — Unit tests give us the confidence that any new changes to the system haven’t broken any pre-existing features. This provides evidence to the business that with the latest release, all existing features will work without a problem. This is also a massive load off when a new developer comes into a new project and has to do a change. The unit tests will back them up and prove they haven’t broken any original features.</p><p>Code Refactoring — Upgrading a system to use a new library or to just remove redundant code, this happens to applications at some point in its lifespan. Having unit tests can once again prove to us that the latest library still works as intended or even that huge refactor from using a custom object to a simple Array hasn’t broken anything.</p><p>Debugging at a click of a finger — When a bug is experienced in an environment, the first thing most developers will do is update their application to use the same configuration, run the application and then do whatever they have to, to replicate the steps (this can be super long and very repetitive). Having tests written, we can find the specific method which is causing the problem and replicate the parameters. To run a unit test is as simple as right click &gt; run test, this will always be faster than running the entire application.</p><p>Cleaner Code — Code that has been designed with testing in mind will be cleaner, to make code testable can sometimes be a struggle, but as you resolve these struggles you will learn how to avoid them in the future. This in turn will make you think more about the design of an interface, class, function etc. You will start to see what should be provided as a parameter and what may need to become an interface to get around a specific part of the system. Your start to notice how annoying the “new” keyword is.</p><p>Documentation — Well this is a tricky one, first off I’m sure most of you will imagine documentation as a document of some sorts which states the requirements, flows, architecture etc. But documentation is the code, code doesn’t go out of date (at an application level), a document will go out of date within a day, business requirements never stop changing. Unit tests provide us documentation of our application, the tests themselves will state features like so “WhenAUserLogsInForTheFirstTime_DisplayAWelcomeMessage” or “WhenClientPurchasingXAmountOfItems_SendThemAVoucher”. I don’t even need to tell you what the application is, you can probably guess from the unit test method names. Our tests define to all developers what this application does and doesn’t do.</p><p>So what are these disadvantages? I mean with those excellent advantages what could be the disadvantages? Well let’s go over some below.</p><p>Fake Confidence — Unit tests give us confidence that our code works under all provided circumstances… “Provided” circumstances. What if we didn’t think of every circumstance? Did we check a specific if statement is hit or if we provide an invalid parameter? This can happen and will happen, at some point a specific path won’t be tested, why? Because you’re human and something will slip through the gap at some point. I’ve had this happen to me several times.</p><p>Discipline — All new code or refactored code should be unit tested, this sounds quite simple, but many developers forget or choose not to write unit tests, due to the setup either being “impossible” or the code is hard to understand and they aren’t sure what needs to be setup. I will repeat this, all new code or refactored code should be unit tested, this helps yourself and others in the future to understand the feature and confirm changes haven’t broken old features. Also, you want to make sure the changes you did actually worked yeah?</p><p>Regular Reviewing — If the project’s unit tests aren’t part of the build/deployment pipeline (build/deployment should fail if a single unit test fails), they lose most of their benefits, yes a developer can use the unit tests to understand the code and debug, but if something isn’t telling you about failed tests or if the development team aren’t educated to write unit tests for the code they write/modify, the existing unit tests will become out dated and will fall into the Fake Confidence section.</p><p>Experience — Writing unit tests is one thing, but also creating your code to be testable in the first place can be quite a big learning curve, especially for new developers. Learning to write effective unit tests will take time and practice. Learning how to set up a specific function to return the correct outcome when it has dependencies can be another problem. Learning about Stubs, Mocks, Spies and Dummies to manipulate your state/dependencies can take time. Testing is a whole skill in itself.</p><p>Overall unit testing is a massive benefit. Looking at the advantages above you gain a huge amount. Detecting early bugs, Confidence in changes and releasing, Debugging at a single click, Documentation etc. Don’t forget my entire game logic that was wrote outside of Unity, just slipping into Unity without a single problem.</p><p>Now the disadvantages I provided can all be overcome. To overcome most of them you just have to start writing unit tests for all the code you write from now on. This will help with the experience and discipline disadvantages. For the regular reviewing, your build/release pipeline should invoke your unit tests and fail if a single unit test fails. This will stop a broken build from being published, enforce developers to write passing tests and to fix any tests if they are broken. Code Coverage is also a great tool to enforce a percentage of the code base is tested.</p><p>Fake Confidence, now this one will forever remain, no matter what you do, if you write your code and then write unit tests afterwards, this can still be an issue. Of course you can create X amount of unit tests to test everything and you could remove this disadvantage, but the best way to remove this is to follow TDD. Test Driven Development is a discipline, with TDD the basis is you write your test before any logic code is written. I’m not going to go into TDD, but I will put a reference at the bottom for you to peruse.</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>TDD — <a href="https://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html">https://blog.cleancoder.com/uncle-bob/2014/12/17/TheCyclesOfTDD.html</a></p><p>Image — <a href="https://www.pexels.com/photo/mechanical-computer-keyboard-671629/">https://www.pexels.com/photo/mechanical-computer-keyboard-671629/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=47a81d67ccde" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Unit Testing — Why write code to test my code? Seems a little redundant — C# Example]]></title>
            <link>https://canvascodebw.medium.com/unit-testing-why-write-code-to-test-my-code-seems-a-little-redundant-c-example-25a0d0202c5f?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/25a0d0202c5f</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[unit-testing]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Wed, 31 Jan 2024 13:15:48 GMT</pubDate>
            <atom:updated>2024-01-31T13:15:48.732Z</atom:updated>
            <content:encoded><![CDATA[<h3>Unit Testing — Why write code to test my code? Seems a little redundant — C# Example</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YDPIerqRBVpu25gOOO1-CA.jpeg" /></figure><p>What is unit testing? Well a unit test should aim to test a specific feature in our code, be it a function which calculates a value, or a value that is gathered from some source. The key word is “unit”, it should test one thing.</p><p>This blog post is gonna be in two parts, the first part is going to be a C# example and the second part will be a more detailed blog post about unit testing as a tool. One thing unit testing does provide is a safety net, this safety net shows us, our team, business, etc that our code produces the correct outputs with the specific inputs and changes in the future have not broken any existing features. The safety net also allows us to refactor/optimise the code, if we refactor/optimise and all tests still pass, then we know all current features still work as expected.</p><p>Example time. At the bottom of this blog post is a link to a repository which contains all the sources from V1 to Refactoring. If you want to skip the coding part and just take a look then feel free to download the repository and run it yourself. This example I’m gonna use Visual Studio 2022, C# .NET 6</p><p>Specification Version 1<br>We want a customer to be able to add/remove an item from their basket. The item will have a unique reference code, name and a price. We should also be able to get a readonly list from the basket. We haven’t chosen a front end tech for the app yet.</p><p>So looking at the specification the first thing we should create is a class library project (this allows a future frontend to be selected without requiring changes to our library code). In VS2022 create a new project &gt; in “Search for templates” search for “library” and then select “Class Library” C#. Feel free to call the project what you like but I will be going with the ShoppingCart. The Framework will be .NET 6.0 (Long-term support). Now lets start by adding a Basket class and a BasketItem class to fulfill the specification.</p><pre>public class BasketItem<br>{<br>    public string ReferenceCode { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>}</pre><p>BasketItem simply has three properties, ReferenceCode, Name and Price. This reflects the specification.</p><pre>public class Basket<br>{<br>    public IReadOnlyCollection&lt;BasketItem&gt; Items<br>        =&gt; _items.ToList().AsReadOnly();<br><br>    private readonly ICollection&lt;BasketItem&gt; _items;<br><br>    public Basket()<br>    {<br>        _items = new List&lt;BasketItem&gt;();<br>    }<br><br>    public void AddItem(string referenceCode, string name, decimal price)<br>    {<br>        _items.Add(new BasketItem()<br>        {<br>            ReferenceCode = referenceCode,<br>            Name = name,<br>            Price = price<br>        });<br>    }<br><br>    public void RemoveItem(string referenceCode)<br>    {<br>        _items.Remove(Items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode));<br>    }<br>}</pre><p>Basket has a few things, so first off we have a private ICollection of BasketItem, we make this private as it should be hidden from the outside. This is also a readonly property as we only set it in the constructor. _items will simply store what items are in our basket. We then have our AddItem method which takes in three parameters, which we then use to create a new BasketItem with those values. RemoveItem takes a ReferenceCode which we then attempt to find the record (because we used FirstOrDefault, if a record couldn’t be found, it will just return null and no exception will be thrown when Remove is invoked with a null) and remove it. We then have a get property at the top called Items, this just reads from our private _items list and creates a new ReadOnlyCollection.</p><p>Now we have our code, how can we prove to our client that the code will work as they expect without using a front end tech? More importantly how can we even prove to ourselves that this code works?</p><p>This sounds like a problem that unit testing can fix! Now to create a “test project” in VS2022 you right click your solution &gt; Add &gt; New Project… &gt; search for “test” &gt; You can choose between MSTest, NUnit or xUnit (if you would like to know the difference, please take a look at the link below for a comparison between the test frameworks). I will be using MSTest and I will name the project after my class library, so the name will be ShoppingCart_UnitTests. Make sure to reference you ShoppingCart class library to your testing project. You can do this by right clicking on “Dependencies” in your MSTest project and then select “Add Project Reference…”, then simply check the checkbox next to your class library.</p><p>Now you have yourself a “test project” with a reference to your class library code, we can now start to write tests for our library code. So we don’t need to test our BasketItem because it just has 3 properties (this object just stores value), however our Basket has some interesting methods which would be good to prove they work. This will show to us and anyone else that the code written will work correctly.</p><p>So lets start from top to bottom with our Basket class, so what can we test? Well two basic things we can test is our Basket and the AddItem method. Create a new class in your testing project and provide the below. You will need to include your namespace to fix the Basket reference.</p><pre>[TestClass]<br>public class Basket_Tests<br>{<br>    private class Apple<br>    {<br>        public string ReferenceCode = &quot;AA000&quot;;<br>        public string Name = &quot;Apple&quot;;<br>        public decimal Price = 0.70m;<br>    }<br><br>    private Basket Basket { get; set; }<br><br>    [TestInitialize]<br>    public void Init()<br>    {<br>        Basket = new Basket();<br>    }<br><br>    [TestMethod]<br>    public void WhenABasketIsConstructed_ItShouldBeEmpty()<br>    {<br>        Assert.IsTrue(Basket.Items.Count == 0);<br>    }<br><br>    [TestMethod]<br>    public void AddOneAppleToOurBasket_BasketItemsShouldContainOneApple()<br>    {<br>        var apple = new Apple();<br>        Basket.AddItem(apple.ReferenceCode, apple.Name, apple.Price);<br><br>        Assert.IsTrue(Basket.Items.Count == 1);<br>        Assert.AreEqual(Basket.Items.First().Name, apple.Name);<br>        Assert.AreEqual(Basket.Items.First().Price, apple.Price);<br>        Assert.AreEqual(Basket.Items.First().ReferenceCode, apple.ReferenceCode);<br>    }<br>}</pre><p>To inform VS2022 that this class is a test class you must provide the TestClass attribute to the top of the class (if you don’t have TestClass at the top, VS2022 will not see any of the tests in this class). Before our test methods we create a new private Apple class. This is just a fake product that could be added to the Basket, we will be using this for our tests. We define a private property for our Basket, this will be used to confirm the state of the Basket is correct in our tests.</p><p>The Init method which has the attribute TestInitialize, is invoked before every single test in this class, so our Basket property will always be set to a new Basket before every test, this just makes it easier for all our tests as we don’t have to new the Basket in every single test.</p><p>To flag a method as a test method you just have to flag it using the TestMethod attribute. If the method throws an exception the test method will be flagged as failed, to confirm our tests we can use the Assert static class (Assert will just evaluate a statement we provide and if it doesn’t match it will throw an exception).</p><p>The first test WhenABasketIsConstructed_ItShouldBeEmpty might seem a little redundant, I mean all this test does it checks to make sure our Items list is empty on construction. The main reason for this test is to make sure the object does construct correctly and any future changes doesn’t break this functionally.</p><p>The second test AddOneAppleToOurBasket_BasketItemsShouldContainOneApple does the following, we create a new Apple, using the Apple we then provide its values to our AddItem method. After we have invoked our AddItem, we can then use the Assert method to confirm our Basket is in the correct state (basket contains one item and that item in the basket is an apple).</p><p>Now we have our first tests, lets go ahead and view/run our tests. In VS2022 you can do this by opening the View &gt; Test Explorer. Once you have this open you should see your one test, if you don’t you may need to do a build. Once you can see the test you can ever highlight that test and hit the Run button or you can simply click the Run All Tests button. If you followed the code above the test should pass, if it fails for some reason, you can click on the test and see the result, if you need to test further you can right click on the test in the Text Explorer and select Debug (make sure to put breakpoints in your code). Being able to debug your code without having to run the entire application is a huge bonus (no more remembering login details, or user journeys to get to what you want to test).</p><p>Before we go ahead and create some new tests, lets clean up our test class as I feel we are gonna be duplicating a lot of code to add/remove apples from our baskets. We will also update our current tests to reflect the changes</p><pre>private static class Apple<br>{<br>    public static string ReferenceCode = &quot;AA000&quot;;<br>    public static string Name = &quot;Apple&quot;;<br>    public static decimal Price = 0.70m;<br>}<br><br>private Basket Basket { get; set; }<br><br>[TestInitialize]<br>public void Init()<br>{<br>    Basket = new Basket();<br>}<br><br>[TestMethod]<br>public void WhenABasketIsConstructed_ItShouldBeEmpty()<br>{<br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void AddOneAppleToOurBasket_BasketItemsShouldContainOneApple()<br>{<br>    AddAppleToBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnApple(Basket.Items.First());<br>}<br><br>private void AddAppleToBasket()<br>    =&gt; Basket.AddItem(Apple.ReferenceCode, Apple.Name, Apple.Price);<br><br>private void RemoveAppleFromBasket()<br>    =&gt; Basket.RemoveItem(Apple.ReferenceCode);<br><br>private void AssertBasketItemIsAnApple(BasketItem item)<br>{<br>    Assert.AreEqual(item.Name, Apple.Name);<br>    Assert.AreEqual(item.Price, Apple.Price);<br>    Assert.AreEqual(item.ReferenceCode, Apple.ReferenceCode);<br>}</pre><p>Our Apple class has now became static, this allows us to just use Apple.propertyname instead of having to new an Apple object. At the bottom we then created three new helper methods. AddAppleToBasket simple adds an Apple to our basket via the AddItem method, RemoveAppleFromBasket simply removes an Apple from our basket via the RemoveItem method and finally we have AssertBasketItemIsAnApple, this one might seem a little complex, but all this does is take a BasketItem we provide as the parameter and checks all properties match an Apple. Sorry if this makes it harder to understand, but you will see the benefits as our code changes (also this is a cleaner way of doing it, no one wants to new an Apple object in X amount of tests).</p><p>Right, so now the clean up is done, lets go ahead and add a few more tests to make sure our code logic works as intended.</p><pre>    ...<br>    AssertBasketItemIsAnApple(Basket.Items.First());<br>}<br><br>[TestMethod]<br>public void AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples()<br>{<br>    var quantity = 3;<br>    for(var i = 0; i &lt; quantity; i++)<br>        AddAppleToBasket();<br><br>    for (var i = 0; i &lt; quantity; i++)<br>        AssertBasketItemIsAnApple(Basket.Items.ElementAt(i));<br><br>    Assert.IsTrue(Basket.Items.Count == 3);<br>}<br><br>[TestMethod]<br>public void RemoveAnItemThatIsNotInOurBasket_NoExceptionShouldBeThrown()<br>{<br>    Basket.RemoveItem(&quot;ReferenceCode&quot;);<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void RemoveAnItemThatIsNotInOurBasket_ItemsInBasketShouldNotBeModified()<br>{<br>    AddAppleToBasket();<br>    Basket.RemoveItem(&quot;ReferenceCode&quot;);<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>}<br><br>[TestMethod]<br>public void RemoveAnItemThatIsInOurBasket_ItemIsRemovedAndOurBasketShouldBeEmpty()<br>{<br>    AddAppleToBasket();<br>    RemoveAppleFromBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void RemoveOneItemFromOutBasket_BasketHasItemRemovedButItemsStillRemain()<br>{<br>    for(var i = 0; i &lt; 2; i++)<br>        AddAppleToBasket();<br>    RemoveAppleFromBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnApple(Basket.Items.First());<br>}<br><br>[TestMethod]<br>public void RemoveAllItemsFromBasket_BasketShouldBeEmpty()<br>{<br>    var quantity = 10;<br>    for (var i = 0; i &lt; quantity; i++)<br>        AddAppleToBasket();<br><br>    foreach (var item in Basket.Items)<br>        RemoveAppleFromBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>private void AddAppleToBasket()<br>    ...</pre><p>We now have a total of 8 tests, each test tests for something specific. Our entire test suite for our Basket class is made up of the following:<br> — Basket is setup correctly on construction<br> — Add a single item to our basket<br> — Add multiples of an item to our basket<br> — Attempt to remove an item from an empty basket<br> — Attempt to remove an item that is not in our basket<br> — Remove an item that is in our basket so it is now empty<br> — Remove an item that is in our basket and other items still remain<br> — Remove all items from our basket so it is now empty<br>Feel free to add any more unit tests your believe would benefit you (no harm in having more tests, just remember you will need to maintain them), for the moment I’m gonna leave those five.</p><p>So after all that work we have a Basket and a BasketItem class. We have written the logic to the specification which was provided to us and we can prove it works to our client as we have unit tests. Having these unit tests now gives us a safety net as we know these tests were passing on release of our library, it also allows us to debug our code with ease (we shouldn’t have to start the entire application to make sure we can add an apple to our basket).</p><p>Specification Version 2<br>We want to be able to increment/decrement quantities for a specific item in the basket, also if the quantity becomes 0 we want to remove that item from the basket.</p><p>This seems like quite a simple change, first lets add a new Quantity property to our BasketItem so we can keep a record.</p><pre>public class BasketItem<br>{<br>    public string ReferenceCode { get; set; }<br>    public string Name { get; set; }<br>    public decimal Price { get; set; }<br>    public int Quantity { get; set; }<br>}</pre><p>Now we have Quantity exposed from our BasketItem, we can now modify our Basket class. Now V1 simply just added a new BasketItem to our _items. Now our code will only need to add a new BasketItem if the ReferenceCode can’t be found, if the ReferenceCode can be found, we simply increment the quantity. We also need to update our RemoveItem method so it will attempt to find the item and if its found, then reduce the quantity by 1. Also if the Quantity is 0 or below we should remove it from our _items. Lets update our AddItem and RemoveItem method.</p><pre>public void AddItem(string referenceCode, string name, decimal price)<br>{<br>    var item = _items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode);<br><br>    if (item != null)<br>        item.Quantity += 1;<br>    else<br>    {<br>        _items.Add(new BasketItem()<br>        {<br>            ReferenceCode = referenceCode,<br>            Name = name,<br>            Price = price,<br>            Quantity = 1<br>        });<br>    }<br>}<br><br>public void RemoveItem(string referenceCode)<br>{<br>    var item = _items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode);<br><br>    if (item != null)<br>    {<br>        item.Quantity -= 1;<br><br>        if(item.Quantity &lt;= 0)<br>            _items.Remove(Items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode));<br>    }<br>}</pre><p>So not much had to change to add Quantity into our Basket methods. Lets run our existing tests to see if anything has broken. So it seems 2 tests have failed. AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples and RemoveAllItemsFromBasket_BasketShouldBeEmpty no longer pass.</p><p>AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples is failing because in our test we are using ElementAt(i). This fails because when we invoke AddItem this no longer adds a new element to list, if a BasketItem with the ReferenceCode already exists it will just increment the quantity, lets update our test.</p><pre>[TestMethod]<br>public void AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples()<br>{<br>    var quantity = 3;<br>    for (var i = 0; i &lt; quantity; i++)<br>        AddAppleToBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnApple(Basket.Items.First());<br>    Assert.IsTrue(Basket.Items.First().Quantity == quantity);<br>}</pre><p>This test has changed a little, we still for loop our AddAppleToBasket but then for the AssertBasketItemIsAnApple we no longer have to use a for loop. We can simple check the Items have one item and then we can check the Quantity property matches the quantity that was used for the test.</p><p>If we then run this single test it will now pass. Now this fixes one of our tests but our RemoveAllItemsFromBasket_BasketShouldBeEmpty is still failing. If you put a break point on Assert.IsTrue(Basket.Items.Count == 0); in that specific test and debug the test, you can see the Quantity of the BasketItem is 9. Well this is because in our test we iterated the Items in our Basket, this worked before because our Basket would have 10 Apples (10 BasketItems), but now our Basket will have one BasketItem and that item will have a Quantity of 10. So lets go ahead and fix this test by using a for loop instead.</p><pre>[TestMethod]<br>public void RemoveAllItemsFromBasket_BasketShouldBeEmpty()<br>{<br>    var quantity = 10;<br>    for (var i = 0; i &lt; quantity; i++)<br>        AddAppleToBasket();<br><br>    for (var i = 0; i &lt; quantity; i++)<br>        RemoveAppleFromBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}</pre><p>By changing our foreach into a for loop using the quantity, this will remove an Apple X amount of times and we should then have no items in our Basket. If you run the test this now passes. Perfect all of our tests are passing again.</p><p>Now here is where you we have to be careful, so just because all our tests pass, are we finished updating our tests? No we are not, why? Because our BasketItem now has a new Quantity property, our tests should check the state of Quantity when necessary. So lets first update our little helper method AssertBasketItemIsAnApple by changing the name and its logic</p><pre>private void AssertBasketItemIsAnAppleWithQuantity(BasketItem item, int quantity)<br>{<br>    Assert.AreEqual(item.Name, Apple.Name);<br>    Assert.AreEqual(item.Price, Apple.Price);<br>    Assert.AreEqual(item.ReferenceCode, Apple.ReferenceCode);<br>    Assert.AreEqual(item.Quantity, quantity);<br>}</pre><p>This does exactly the same as it did before, with one little extra change. We now allow the quantity that should match the BasketItem to be provided. If we attempt to build our code we now get 3 errors, this is because we renamed our method and added a new parameter, so lets just update our tests to compile and check the quantity.</p><pre>[TestMethod]<br>public void AddOneAppleToOurBasket_BasketItemsShouldContainOneApple()<br>{<br>    AddAppleToBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), 1);<br>}<br><br>[TestMethod]<br>public void AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples()<br>{<br>    var quantity = 3;<br>    for (var i = 0; i &lt; quantity; i++)<br>        AddAppleToBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), quantity);<br>}<br><br>...<br><br>[TestMethod]<br>public void RemoveOneItemFromOutBasket_BasketHasItemRemovedButItemsStillRemain()<br>{<br>    for (var i = 0; i &lt; 2; i++)<br>        AddAppleToBasket();<br>    RemoveAppleFromBasket();<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), 1);<br>}</pre><p>So now our code builds again, if we run all our tests they all pass. Overall we did have to change three of our tests to reflect the new Quantity property, however the original tests which didn’t need to change still passed. This proves to us, our code changes haven’t broken those specific features of the code.</p><p>Specification Version 3<br>We want the ability to modify the quantity of an existing item, add an item with a quantity amount and remove an entire item from the basket.</p><p>Currently we just allow an item to be added and removed one at a time, so lets update our AddItem method so we can provide a quantity parameter, this will allow the user to add an item with X quantity to their basket in one go.</p><pre>public void AddItem(string referenceCode, string name, decimal price, int quantity = 1)<br>{<br>    if (quantity &lt;= 0)<br>        return;<br><br>    var item = _items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode);<br><br>    if (item != null)<br>        item.Quantity += quantity;<br>    else<br>    {<br>        _items.Add(new BasketItem()<br>        {<br>            ReferenceCode = referenceCode,<br>            Name = name,<br>            Price = price,<br>            Quantity = quantity<br>        });<br>    }<br>}</pre><p>So the other two features are modify the quantity of an item and remove an entire item from our basket. So lets delete our RemoveItem method and lets go ahead and create a new RemoveEntireItem method like so.</p><pre>public void RemoveEntireItem(string referenceCode)<br>    =&gt; _items.Remove(Items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode));</pre><p>The reason we deleted the RemoveItem method is because it was doing two things, one it was modifying the quantity and second it would remove the item if the quantity is 0 or below, this method should not modify the quantity, why would a method labeled RemoveItem reduce the quantity? So by removing it and create a more specific method RemoveEntireItem it makes it much more clearer on what is actually happening.</p><p>Our RemoveEntireItem method will allow an entire item with a specific ReferenceCode to be removed from our _items. Now for the last requirement which is the modify quantity of an item in the basket.</p><pre>...<br><br>public void ModifyQuantity(string referenceCode, int value)<br>{<br>    var item = _items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode);<br><br>    if (item != null)<br>    {<br>        item.Quantity += value;<br><br>        if (item.Quantity &lt;= 0)<br>            RemoveEntireItem(referenceCode);<br>    }<br>}<br><br>public void RemoveEntireItem(string referenceCode)<br>    ...</pre><p>ModifyQuantity will attempt to find an item in our _items by the ReferenceCode, if found it will simply add the value to the quantity. Afterwards we check to see if the quantity is 0 or below, if so we then invoke our RemoveEntireItem as that item is no longer required in the Basket.</p><p>Now due to these changes we can’t even compile our unit tests, so lets go ahead and update them (we should just fix the compile issues first, if a test has no compile issues we can ignore for now, we can update the asserts once the code compiles).</p><p>So as we deleted the RemoveItem method from our Basket class lets remove all our tests which invoked this method (these methods can be deleted RemoveAnItemThatIsNotInOurBasket_NoExceptionShouldBeThrown, RemoveAnItemThatIsNotInOurBasket_ItemsInBasketShouldNotBeModified, RemoveAnItemThatIsInOurBasket_ItemIsRemovedAndOurBasketShouldBeEmpty, RemoveOneItemFromOutBasket_BasketHasItemRemovedButItemsStillRemain, RemoveAllItemsFromBasket_BasketShouldBeEmpty and RemoveAppleFromBasket). These tests were originally required, so they did have a purpose, but due to our code changing from requirements they are no longer fit for purpose. Now lets create our new tests to confirm our logic works. Below is what our test class now looks like.</p><pre>[TestClass]<br>public class Basket_Tests<br>{<br>    private static class Apple<br>    {<br>        public static string ReferenceCode = &quot;AA000&quot;;<br>        public static string Name = &quot;Apple&quot;;<br>        public static decimal Price = 0.70m;<br>    }<br><br>    private Basket Basket { get; set; }<br><br>    [TestInitialize]<br>    public void Init()<br>    {<br>        Basket = new Basket();<br>    }<br><br>    [TestMethod]<br>    public void WhenABasketIsConstructed_ItShouldBeEmpty()<br>    {<br>        Assert.IsTrue(Basket.Items.Count == 0);<br>    }<br><br>    [TestMethod]<br>    public void AddOneAppleToOurBasket_BasketItemsShouldContainOneApple()<br>    {<br>        AddAppleToBasket();<br><br>        Assert.IsTrue(Basket.Items.Count == 1);<br>        AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), 1);<br>    }<br><br>    [TestMethod]<br>    public void AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples()<br>    {<br>        var quantity = 3;<br>        for (var i = 0; i &lt; quantity; i++)<br>            AddAppleToBasket();<br><br>        Assert.IsTrue(Basket.Items.Count == 1);<br>        AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), quantity);<br>    }<br><br>    private void AddAppleToBasket()<br>        =&gt; Basket.AddItem(Apple.ReferenceCode, Apple.Name, Apple.Price);<br><br>    private void AssertBasketItemIsAnAppleWithQuantity(BasketItem item, int quantity)<br>    {<br>        Assert.AreEqual(item.Name, Apple.Name);<br>        Assert.AreEqual(item.Price, Apple.Price);<br>        Assert.AreEqual(item.ReferenceCode, Apple.ReferenceCode);<br>        Assert.AreEqual(item.Quantity, quantity);<br>    }<br>}</pre><p>If we run our tests they should all pass. So first off with our remaining three tests do they still test the logic correctly? Yep they still test the state correctly. So our tests that survived won’t need to change. However we now have three new things to test. AddItem can now be provided a Quantity, the ModifyQuantity method and our RemoveEntireItem method. So lets first test our new Quantity parameter for our AddItem method. Add the following tests below AddMultipleApplesToOurBasket_BasketItemsShouldContainMultipleApples.</p><pre>    ...<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), quantity);<br>}<br><br>[TestMethod]<br>public void AddAnAppleWithAQuantityAmount_BasketItemsShouldContainAnAppleWithTheCorrectQuantity()<br>{<br>    var quantity = 6;<br>    AddAppleWithQuantityToBasket(quantity);<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), quantity);<br>}<br><br>[TestMethod]<br>public void AddAnAppleAndThenAnAppleWithQuantity_AppleBasketItemHasCorrectQuantity()<br>{<br>    var quantity = 7;<br>    AddAppleToBasket();<br>    AddAppleWithQuantityToBasket(quantity);<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), 1 + quantity);<br>}<br><br>[TestMethod]<br>[DataRow(0)]<br>[DataRow(-10)]<br>public void AddAnAppleWithAnInvalidQuantity_ItemIsNotAddedToBasket(int quantity)<br>{<br>    AddAppleWithQuantityToBasket(quantity);<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>private void AddAppleToBasket()  <br>    ...</pre><p>To make these tests easier we can create a new AddAppleWithQuantityToBasket method, this will just add an Apple to our Basket with the provided quantity, this just keeps our tests cleaner. We can also just update our AddAppleToBasket helper method to just invoke the AddAppleWithQuantityToBasket and provide the quantity of one.</p><p>So our first new test is AddAnAppleWithAQuantityAmount_BasketItemsShouldContainAnAppleWithTheCorrectQuantity. This just adds an Apple to the basket with a quantity of 6, this confirms the quantity can be set when invoking AddItem.</p><p>Our second test<br>AddAnAppleAndThenAnAppleWithQuantity_AppleBasketItemHasCorrectQuantity is testing to make sure if we invoke AddItem with a ReferenceCode which already exists in the Basket, the Quantity we provided is added to the BasketItem.Quantity.</p><p>Our third test AddAnAppleWithAnInvalidQuantity_ItemIsNotAddedToBasket simply adds an item to our Basket with an invalid quantity such as 0 or below, this test makes sure that the item isn’t added and no exception is thrown. One keynote about this test method is we are using the attribute DataRow, what this will do is using the value provided in the attribute, it will set the parameter in our test method (quantity). So this test will be ran twice, once with the value 0 and once with the value -10. We could have two tests for this, but because 0 and -10 are both invalid values while invoking AddItem, we can just make use of the DataRow attribute and test both scenarios.</p><p>If you haven’t noticed the three new tests we added are attempting to invoke AddAppleWithQuantityToBasket. This is a new helper method, lets update our AddAppleToBasket and create our AddAppleWithQuantityToBasket helper method</p><pre>    ...<br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>private void AddAppleToBasket()<br>    =&gt; AddAppleWithQuantityToBasket(1);<br><br>private void AddAppleWithQuantityToBasket(int quantity)<br>    =&gt; Basket.AddItem(Apple.ReferenceCode, Apple.Name, Apple.Price, quantity);<br><br>private void AssertBasketItemIsAnAppleWithQuantity(BasketItem item, int quantity)  <br>    ...</pre><p>The reason we updated AddAppleToBasket to invoke AddAppleWithQuantityToBasket(1) is just to make our unit tests read clearer. Anyway lets test our new ModifyQuantity method</p><pre>    ...<br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>[DataRow(1, 5)]<br>[DataRow(1, 0)]<br>[DataRow(10, -5)]<br>public void ModifyTheQuantityOfAnExistingBasketItem_BasketItemQuantityReflectsTheChange(int initialQuantity, int modifyQuantity)<br>{<br>    AddAppleWithQuantityToBasket(initialQuantity);<br>    Basket.ModifyQuantity(Apple.ReferenceCode, modifyQuantity);<br><br>    Assert.IsTrue(Basket.Items.Count == 1);<br>    AssertBasketItemIsAnAppleWithQuantity(Basket.Items.First(), initialQuantity + modifyQuantity);<br>}<br><br>[TestMethod]<br>[DataRow(15, -15)]<br>[DataRow(1, -100)]<br>public void ModifyTheQuantityOfAnExistingItemToZeroOrBelowZero_BasketItemIsRemoved(int initialQuantity, int modifyQuantity)<br>{<br>    AddAppleWithQuantityToBasket(initialQuantity);<br>    Basket.ModifyQuantity(Apple.ReferenceCode, modifyQuantity);<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void ModifyTheQuantityOfAnItemThatDoesNotExistInBasket_NothingHappens()<br>{<br>    Basket.ModifyQuantity(&quot;ReferenceCode&quot;, int.MaxValue);<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>private void AddAppleToBasket()  <br>    ...</pre><p>Our first test ModifyTheQuantityOfAnExistingBasketItem_BasketItemQuantityReflectsTheChange uses the DataRow attribute to provide the initial quantity and the quantity we want to add to our initial quantity, so we add an Apple with the initial quantity, we then invoke our ModifyQuantity using the modifyQuantity parameter and then we assert the Basket.Items to make sure it has the correct Quantity. Once again instead of writing three specific tests, we can use a more generic scenario and just provide parameters via DataRow.</p><p>Second test ModifyTheQuantityOfAnExistingItemToZeroOrBelowZero_BasketItemIsRemoved this just confirms if we reduce the Quantity of a BasketItem to 0 or below, that item is removed from our Basket.</p><p>Third test ModifyTheQuantityOfAnItemThatDoesNotExistInBasket_NothingHappens this confirms if you provide a reference code for an item that doesn’t exist in the Basket, nothing happens.</p><p>Finally we just need to test our RemoveEntireItem.</p><pre>    ...<br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void RemoveAnEntireItemFromBasket_BasketIsNowEmpty()<br>{<br>    AddAppleWithQuantityToBasket(int.MaxValue);<br>    Basket.RemoveEntireItem(Apple.ReferenceCode);<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>private void AddAppleToBasket()<br>    ...</pre><p>Quite a simple test, we add an Apple with the maximum integer value and then invoke the RemoveEntireItem and confirm our Basket is empty.</p><p>Phew! Such a small change to our logic caused quite a big change to our unit tests. This may seem like a pain, but once again all of our tests pass and we can prove to anyone this logic works correctly.</p><p>Specification Version 4<br>We would like a feature which allows the user to empty their Basket. This should just remove all items from the basket.</p><p>A nice simple requirement. Now we could just expect the code that invokes our Basket etc could just use “new Basket()”, but lets make our library simple to use and allow the user to use “new” or a public method which we will expose, the exposed method will empty our items. So lets go and update our code to allow this.</p><p>Lets create a public method in our Basket which will empty our _items list</p><pre>...<br>    =&gt; _items.Remove(Items.FirstOrDefault(x =&gt; x.ReferenceCode == referenceCode));<br><br>public void Empty()<br>    =&gt; _items = new List&lt;BasketItem&gt;();</pre><p>As our _items are flagged as readonly (can only be set at declaration or constructor), we will have to remove this flag as we would like to set this variable in a public accessible method.</p><pre>public class Basket<br>{<br>    public IReadOnlyCollection&lt;BasketItem&gt; Items<br>        =&gt; _items.ToList().AsReadOnly();<br><br>    private ICollection&lt;BasketItem&gt; _items;<br><br>    public Basket() =&gt; Empty();<br><br>    public void AddItem(string referenceCode, string name, decimal price, int quantity = 1)<br>    {<br>      ...</pre><p>Taking a look at the code above, we also changed our Basket constructor, all this does now is invoke the Empty method. So technically the “new” and Empty method do the same thing now.</p><p>If we run all of our current tests everything should still pass. This is awesome because we know for a fact from the test results the change we just did has broken nothing! You may think, well all we did was add a method, but no we changed our constructor, the part which sets up the entire object and all our tests still work. Now lets test our new Empty method.</p><p>We do have our WhenABasketIsConstructed_ItShouldBeEmpty test, however this tests the constructor. So lets leave this test alone and create a new one, now for this test to confirm it is working we are gonna need to first create a new Banana and Coconut mock class so we can use those to populate our Basket (just like our static Apple class).</p><pre>    ...<br>    public decimal Price = 0.70m;<br>}<br><br>private static class Banana<br>{<br>    public static string ReferenceCode = &quot;BA000&quot;;<br>    public static string Name = &quot;Banana&quot;;<br>    public static decimal Price = 0.80m;<br>}<br><br>private static class Coconut<br>{<br>    public static string ReferenceCode = &quot;CA000&quot;;<br>    public static string Name = &quot;Coconut&quot;;<br>    public static decimal Price = 0.95m;<br>}<br><br>private Basket Basket { get; set; }<br>...</pre><p>Now we have some more items to play with, lets create our new test for our Empty method</p><pre>    ...<br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>[TestMethod]<br>public void EmptyOutBasket_BasketShouldBeEmpty()<br>{<br>    AddAppleToBasket();<br>    AddBananaToBasket();<br>    AddCoconutToBasket();<br>    Basket.Empty();<br><br>    Assert.IsTrue(Basket.Items.Count == 0);<br>}<br><br>...<br><br>private void AddAppleWithQuantityToBasket(int quantity)<br>    =&gt; AddItemWithQuantityToBasket(Apple.ReferenceCode, Apple.Name, Apple.Price, quantity);<br><br>private void AddBananaToBasket()<br>    =&gt; AddItemWithQuantityToBasket(Banana.ReferenceCode, Banana.Name, Banana.Price, 1);<br><br>private void AddCoconutToBasket()<br>    =&gt; AddItemWithQuantityToBasket(Coconut.ReferenceCode, Coconut.Name, Coconut.Price, 1);<br><br>private void AddItemWithQuantityToBasket(<br>    string referenceCode, string name, decimal price, int quantity)<br>    =&gt; Basket.AddItem(referenceCode, name, price, quantity);<br></pre><p>With a few extra nicely named helper methods we can now add a Banana and a Coconut to our Basket, also make sure to update the AddAppleWithQuantityToBasket as that can now also use the AddItemWithQuantityToBasket helper method.</p><p>So our test EmptyOutBasket_BasketShouldBeEmpty we add an Apple, Banana and a Coconut. We then invoke our Empty method which should remove all items from our Basket, we then confirm that by the Count of our Items.</p><p>That was our final requirement from the client and they are happy to go with the provided solution, but before we hand it over, lets go and refactor our code, I mean we did refactor our tests to make them easier to manage so we should do the same to our ShoppingCart library.</p><p>Refactoring<br>To speed up our code we can change our variable type for our _items, lets update this from an ICollection to an IDictionary. The reason we can use a dictionary is because the item ReferenceCode is only assigned to one item (we can use the unique ReferenceCode as the key). So lets go ahead and do a little refactor to our Basket code.</p><pre>public IReadOnlyCollection&lt;BasketItem&gt; Items<br>            =&gt; _items.Select(x =&gt; x.Value).ToList().AsReadOnly();<br><br>private IDictionary&lt;string, BasketItem&gt; _items;</pre><p>Changing our _items to an IDictionary required us to update our Items property, now this change will also affect our entire class, so lets go and update each method one by one.</p><pre>public void AddItem(string referenceCode, string name, decimal price, int quantity = 1)<br>{<br>    if (quantity &lt;= 0)<br>        return;<br><br>    if (_items.TryGetValue(referenceCode, out var item))<br>        ModifyQuantity(item, quantity);<br>    else<br>        AddNewBasketItem();<br><br>    void AddNewBasketItem()<br>    {<br>        _items[referenceCode] = new BasketItem()<br>        {<br>            ReferenceCode = referenceCode,<br>            Name = name,<br>            Price = price,<br>            Quantity = quantity<br>        };<br>    }<br>}</pre><p>Overall the method doesn’t change hugely but as we are using an IDictionary, we can use remove the FirstOrDefault (FirstOrDefault will iterate the list until it finds a match, if there is no match it will have iterated the entire list to find nothing. A dictionary uses a hashtable which is much quicker to access than iterating an entire list). The main benefit of this is a massive speed increase, but also it feels much better as a dictionary.</p><p>One change is where we did the FirstOrDefault, we now use the IDictionary TryGetValue method which uses the key you provide (referenceCode), and attempts to find a record. If no record is found, it simply returns a null. Now instead of doing “item.Quantity += quantity” we should just invoke ModifyQuantity, this will remove redundant code and make sure our logic runs correctly (AddItem should add an item, it shouldn’t modify the quantity per say, the method ModifyQuantity does that, so AddItem should pass on the instructions to ModifyQuantity when required).</p><p>The other change was a small tidy up job, we create an inner method called AddNewBasketItem to hide the “new BasketItem…” code. It just looks cleaner and the method can be easily understood.</p><p>So lets now take a look at our ModifyQuantity, I mean we have to change it to allow our AddItem to pass on the instructions to it.</p><pre>public void ModifyQuantity(string referenceCode, int value)<br>{<br>    if (_items.TryGetValue(referenceCode, out var item))<br>        ModifyQuantity(item, value);<br>}<br><br>private void ModifyQuantity(BasketItem item, int value)<br>{<br>    item.Quantity += value;<br><br>    if (item.Quantity &lt;= 0)<br>        RemoveEntireItem(item.ReferenceCode);<br>}<br><br>public void RemoveEntireItem(string referenceCode)<br>    ...</pre><p>Now we have two ModifyQuantity methods, the first is our public method which you provide a referenceCode and a value. This now uses the TryGetValue method instead of the FirstOfDefault (speed increase), if an item is found, it then invokes the private method ModifyQuantity.</p><p>The reason we have this private ModifyQuantity method is so our AddItem and public ModifyQuantity use the same logic. You provide a BasketItem, it will then modify the Quantity and it will also remove the item if the Quantity is 0 or below. Lets now update our final two methods which will be straight forward.</p><pre>public void RemoveEntireItem(string referenceCode)<br>    =&gt; _items.Remove(referenceCode);<br><br>public void Empty()<br>    =&gt; _items = new Dictionary&lt;string, BasketItem&gt;();</pre><p>The RemoveEntireItem no longer needs to do a FirstOrDefault and we can just simply call the Dictionary.Remove method. For our Empty method we just have to instantiate a new Dictionary.</p><p>So after that huge refactor from using an ICollection&lt;BasketItem&gt; to an IDictionary&lt;string, BasketItem&gt;, why don’t we run our tests, running our tests will prove to us if we have broken anything.</p><p>All of our tests pass! Look at that, we just did a big refactor to our code and all of our unit tests still work. All the tests we originally created to make sure our code works, still works after a huge change. This is one of the benefits that unit tests give us. Our tests prove to us that we can change anything in our Basket class and if those tests all pass, then we have no fear. We are no longer scared of our code changing. Also these tests prove with the specific inputs the correct outputs/states are as expected.</p><p>We should never be scared of our software changing, software is soft, it should be malleable and allow things to change with ease, also when do clients ever stop coming up with new requirements/features.</p><p>At one point in our project we had to delete some unit tests, this is completely valid. Remember those tests at that specific time proved a piece of functionality worked, if that functionality no longer exists then the tests are no longer required. We don’t want to maintain code that is no longer required.</p><p>If you pulled down my repository, you may have noticed I don’t have a unit test project. Instead what I did was install the following nuget packages Microsoft.NET.Test.Sdk, MSTest.TestAdapter and MSTest.TestFramework. These three packages allowed me to write tests in my class library project and VS2022 will pickup the [TestClass] attributes, then I can run the tests. Doing this just allowed me to keep the code and unit tests close and made it easier for the repository code.</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>Repository: <a href="https://github.com/MrApproved/Medium_BasicUnitTesting">https://github.com/MrApproved/Medium_BasicUnitTesting</a></p><p>NUnit, XUnit, MSTes comparison: <a href="https://www.lambdatest.com/blog/nunit-vs-xunit-vs-mstest/">https://www.lambdatest.com/blog/nunit-vs-xunit-vs-mstest/</a></p><p>Hash table: <a href="https://en.wikipedia.org/wiki/Hash_table">https://en.wikipedia.org/wiki/Hash_table</a></p><p>Images: <a href="https://www.pexels.com/photo/cargo-container-lot-906494/">https://www.pexels.com/photo/cargo-container-lot-906494/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25a0d0202c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Software Design; Architecture should be an option]]></title>
            <link>https://canvascodebw.medium.com/software-design-architecture-should-be-an-option-f0828b146087?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/f0828b146087</guid>
            <category><![CDATA[architecture]]></category>
            <category><![CDATA[code-patterns]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[design]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Tue, 01 Feb 2022 19:51:10 GMT</pubDate>
            <atom:updated>2022-02-01T19:51:10.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QwU0I9BwUbhp7ORZvS670Q.jpeg" /></figure><p>Software should allow you to choose its architecture at a later date. Now I understand some goals of software are to use a particular piece of architecture for testing purposes, such as a service provided by a 3rd party (Microsoft Azure, Amazon Web Services etc), however code should be as generic as possible so that it can be reused.</p><p>For this example we are going to use a very basic application which simply stores helpdesk tickets. The specification requires the following: A user should be able to create, read, update and delete a ticket in the system.</p><p>First off, how many of you instantly thought we better get a database designed so we can store these tickets? Or how will our users access this application? The web? A windows app? Electron app? For the moment, let’s create the basics. If we just focus on the requirements, we need a CRUD app. So let’s start on that.</p><p>For this example we’re going to create our application in C# (we do need a language for our app). First, let’s create our “HelpDeskTicket” object.</p><pre>public class HelpDeskTicket<br>{<br>    public Guid Id { get; set; }<br>    public string Title { get; set; }<br>    public string Message { get; set; }<br>    public string Answer { get; set; }<br>    public string SubmittedBy { get; set; }<br>    public string AnweredBy { get; set; }<br>    public DateTime Created { get; set; }<br>    public DateTime? Closed { get; set; }<br>}</pre><p>To allow us to choose our architecture later on, we are going to make a HelpDeskTicketsRepository which will be an interface with the CRUD operations.</p><p>HelpDeskTicketsRepository</p><pre>public interface HelpDeskTicketsRepository<br>{<br>    void Create(HelpDeskTicket record);<br>    IEnumerable&lt;HelpDeskTicket&gt; GetRecords();<br>    HelpDeskTicket GetRecord(Guid id);<br>    void Update(HelpDeskTicket record);<br>    void Delete(Guid id);<br>    void Save();<br>}</pre><p>So now that we have our HelpDeskTicketsRepository, we can go ahead and use it for a concrete class. Let’s create an in memory repository called InMemoryHelpDeskTicketsRepository.</p><pre>public class InMemoryHelpDeskTicketsRepository : HelpDeskTicketsRepository<br>{<br>    private Dictionary&lt;Guid, HelpDeskTicket&gt; Records { get; set; }<br>    private Dictionary&lt;Guid, HelpDeskTicket&gt; UpdatedRecords { get; set; }</pre><pre>    public InMemoryHelpDeskTicketsRepository()<br>    {<br>        Records = new Dictionary&lt;Guid, HelpDeskTicket&gt;();<br>        UpdatedRecords = new Dictionary&lt;Guid, HelpDeskTicket&gt;();<br>    }</pre><pre>    public void Create(HelpDeskTicket record)<br>    {<br>        if (!UpdatedRecords.ContainsKey(record.Id))<br>            UpdatedRecords.Add(record.Id, record);<br>    }</pre><pre>    public void Delete(Guid id)<br>    {<br>        if (UpdatedRecords.ContainsKey(id))<br>            UpdatedRecords.Remove(id);<br>    }</pre><pre>    public HelpDeskTicket GetRecord(Guid id)<br>        =&gt; Records[id] ?? null;</pre><pre>    public IEnumerable&lt;HelpDeskTicket&gt; GetRecords()<br>        =&gt; Records.Select(x =&gt; x.Value);</pre><pre>    public void Save()<br>    {<br>        Records = UpdatedRecords;<br>    }</pre><pre>    public void Update(HelpDeskTicket record)<br>    {<br>        if (UpdatedRecords.ContainsKey(record.Id))<br>            UpdatedRecords[record.Id] = record;<br>    }<br>}</pre><p>So, why did we create an InMemoryTicketsRepository? Well, what are the benefits of this? First off this can now be used for any application, console app, web app etc. Of course the issue is the dictionary of tickets will be lost on exit, but this will allow us to use a “real” ticket repository while testing/developing. Basically, we can replace it later because we’re using the HelpDeskTicketsRepository interface.</p><p>For example, let’s create a console app which uses the InMemoryTicketsRepository</p><pre>static void Main(string[] args)<br>{<br>        var id = Guid.NewGuid();<br>        var helpDeskTicketsRepository = new InMemoryHelpDeskTicketsRepository();<br>        helpDeskTicketsRepository.Create(new HelpDeskTicket() { Id = id, Title = &quot;Hello World&quot; });<br>        helpDeskTicketsRepository.Save();<br>        Console.WriteLine(helpDeskTicketsRepository.GetRecord(id).Title);<br>        var record = helpDeskTicketsRepository.GetRecord(id);<br>        record.Title += &quot;: Updated&quot;;<br>        helpDeskTicketsRepository.Update(record);<br>        helpDeskTicketsRepository.Save();<br>        Console.WriteLine(helpDeskTicketsRepository.GetRecord(id).Title);<br>        helpDeskTicketsRepository.Delete(id);<br>        helpDeskTicketsRepository.Save();<br>        Console.WriteLine(helpDeskTicketsRepository.GetRecords().Count());<br>}</pre><p>If you were to run the app, a new ticket will be added, its title is updated, and then we delete the ticket. Once this is done we exit the app.</p><p>So let’s say we want the tickets to be persistent after exit, however we aren’t sure where we would like to store them? You see that question!? That question is about architecture, not about the design of the application. “However we aren’t sure where we would like to store them?”.</p><p>The answer to that question is irrelevant, because we have a repository which simply provides us the operations for handling tickets. We don’t care where they come from or where they get stored.</p><p>For simplicity of this article let’s say we want to store the tickets in a JSON file. Here is what the JsonHelpDeskTicketsRepository may look like</p><pre>public class JsonHelpDeskTicketsRepository : HelpDeskTicketsRepository<br>{<br>    private IDictionary&lt;Guid, HelpDeskTicket&gt; Records { get; set; }<br>    private const string JsonFileName = &quot;helpdesktickets.json&quot;;</pre><pre>    public JsonHelpDeskTicketsRepository()<br>    {<br>        LoadTicketsFromFile();</pre><pre>        void LoadTicketsFromFile()<br>        {<br>            try<br>            {<br>                Records = JsonConvert.DeserializeObject&lt;IDictionary&lt;Guid, HelpDeskTicket&gt;&gt;(System.IO.File.ReadAllText(JsonFileName));<br>            }<br>            catch<br>            {<br>                Records = new Dictionary&lt;Guid, HelpDeskTicket&gt;();<br>            }<br>        }<br>    }</pre><pre>    public void Create(HelpDeskTicket record)<br>    {<br>        if (!Records.ContainsKey(record.Id))<br>            Records.Add(record.Id, record);<br>    }</pre><pre>    public void Delete(Guid id)<br>    {<br>        if (Records.ContainsKey(id))<br>            Records.Remove(id);<br>    }</pre><pre>    public HelpDeskTicket GetRecord(Guid id)<br>        =&gt; Records[id] ?? null;</pre><pre>    public IEnumerable&lt;HelpDeskTicket&gt; GetRecords()<br>        =&gt; Records.Select(x =&gt; x.Value);</pre><pre>    public void Save()<br>    {<br>        System.IO.File.WriteAllText(JsonFileName, JsonConvert.SerializeObject(Records));<br>    }</pre><pre>    public void Update(HelpDeskTicket record)<br>    {<br>        Records[record.Id] = record;<br>    }<br>}</pre><p>Now what if you simply construct a JsonHelpDeskTicketsRepository instead of a InMemoryHelpDeskTicketsRepository in our test app code above? Guess what - it works! We didn’t change any of our code, all we had to do was use our new JSON repository and the code uses it just like the in memory repository all thanks to the HelpDeskTicketsRepository interface.</p><p>We should avoid architecture making decisions for us as we design, if it does then our code will be coupled to that answer and this will produce non-reusable code and limit us. Architecture should be a choice we make nearest to the end of the project (where possible).</p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>References:<br><a href="https://cleancoders.com/">https://cleancoders.com/</a></p><p>Repository: <a href="https://github.com/MrApproved/Medium_ArchitectureHelpDeskTickets">https://github.com/MrApproved/Medium_ArchitectureHelpDeskTickets</a></p><p>Images:<br><a href="https://www.pexels.com/photo/clear-light-bulb-355948/">https://www.pexels.com/photo/clear-light-bulb-355948/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f0828b146087" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[C# EntityFramework InMemory Database for Easy Testing/Prototyping and Project sharing.]]></title>
            <link>https://canvascodebw.medium.com/c-entityframework-inmemory-database-for-easy-testing-prototyping-and-project-sharing-bfe665f7df53?source=rss-930170a3370f------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfe665f7df53</guid>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[entity-framework-core]]></category>
            <category><![CDATA[dotnet]]></category>
            <category><![CDATA[net5]]></category>
            <dc:creator><![CDATA[Ben Watts]]></dc:creator>
            <pubDate>Sat, 17 Apr 2021 15:05:08 GMT</pubDate>
            <atom:updated>2022-01-16T01:42:56.260Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WWUUPtTjYNunqp41d6VZfw.jpeg" /></figure><p>We’ve all been there: create a new project for a client, create a database in some form, share the project and include some instructions on how to create the database for the project.</p><p>They get the project, it builds — which is great! — but then it comes down to constructing the database. They may not have an instance of the database system you used (MSSQL, MYSQL, MongoDB, etc), which means they won’t be able to run the project.</p><p>Fortunately for us and for them, this isn’t the end of the world; there are ways we can get around this issue.</p><p>Let’s take advantage of the EntityFramework InMemory feature. I’ve created a Razor Page .NET 5 project and installed the following NuGet packages:</p><pre>Install-Package Microsoft.EntityFrameworkCore<br>Install-Package Microsoft.EntityFrameworkCore.InMemory</pre><p>Once these are installed, we can create a very basic database structure. Let’s first create the two tables we want to store:</p><p>Database/Tables/Movie.cs</p><pre>namespace EFInMemoryDatabase.Database.Tables<br>{<br>    public class Movie<br>    {<br>        public int MovieId { get; set; }<br>        public string Title { get; set; }<br>        public string Description { get; set; }<br>        public int GenreId { get; set; }<br>    }<br>}</pre><p>Database/Tables/Genre.cs (this isn’t used, it’s just for demonstration)</p><pre>namespace EFInMemoryDatabase.Database.Tables<br>{<br>    public class Genre<br>    {<br>        public int GenreId { get; set; }<br>        public string Label { get; set; }<br>    }<br>}</pre><p>We now need to create the actual “database”. We will create two DbSets, one for Movie and one for Genre. The DbSet class represents an entity set that can be used for the database operation, such as create, read, update, and delete (<a href="https://entityframework.net/ef-dbset">https://entityframework.net/ef-dbset</a>).</p><p>Database/MovieContext.cs</p><pre>using EFInMemoryDatabase.Database.Tables;<br>using Microsoft.EntityFrameworkCore;</pre><pre>namespace EFInMemoryDatabase.Database<br>{<br>    public class MovieContext : DbContext<br>    {<br>        public DbSet&lt;Movie&gt; Movies { get; set; }<br>        public DbSet&lt;Genre&gt; Genres { get; set; }</pre><pre>        public MovieContext(DbContextOptions options) : base(options)  <br>        {<br>            LoadMovies();<br>            LoadGenres();</pre><pre>            SaveChanges();<br>        }</pre><pre>        public void LoadMovies()<br>        {<br>            Movies.Add(new Movie()<br>            {<br>                Description = &quot;An organized crime dynasty&#39;s aging patriarch transfers control of his clandestine empire to his reluctant son.&quot;,<br>                GenreId = 1,<br>                MovieId = 1,<br>                Title = &quot;The Godfather&quot;<br>            });</pre><pre>            Movies.Add(new Movie()<br>            {<br>                Description = &quot;Two imprisoned men bond over a number of years, finding solace and eventual redemption through acts of common decency.&quot;,<br>                GenreId = 2,<br>                MovieId = 2,<br>                Title = &quot;The Shawshank Redemption&quot;<br>            });</pre><pre>            Movies.Add(new Movie()<br>            {<br>                Description = &quot;In German-occupied Poland during World War II, industrialist Oskar Schindler gradually becomes concerned for his Jewish workforce after witnessing their persecution by the Nazis.&quot;,<br>                GenreId = 2,<br>                MovieId = 3,<br>                Title = &quot;Schindler&#39;s List &quot;<br>            });<br>        }</pre><pre>        public void LoadGenres()<br>        {<br>            Genres.Add(new Genre()<br>            {<br>                GenreId = 1,<br>                Label = &quot;Crime&quot;<br>            });</pre><pre>            Genres.Add(new Genre()<br>            {<br>                GenreId = 2,<br>                Label = &quot;Drama&quot;<br>            });<br>        }<br>    }<br>}</pre><p>Now let’s update our Startup.cs so we can setup DI (dependency injection) for our application. In our Startup.cs we will need to add a database context and use the “UseInMemoryDatabase” feature which comes from Microsoft.EntityFrameworkCore.InMemory NuGet package.</p><p>Startup.cs</p><pre>...<br>public void ConfigureServices(IServiceCollection services)<br>{<br>    // Add this single line into your ConfigureServices method<br>    services.AddDbContext&lt;MovieContext&gt;(o =&gt; o.UseInMemoryDatabase(nameof(MovieContext)));</pre><pre>    services.AddRazorPages();<br>}<br>...</pre><p>Now let’s update our Index.cshtml code so we can gather our movies from the database and then display them on the page.</p><p>Pages/Index.cshtml</p><pre><a href="http://twitter.com/page">@page</a><br><a href="http://twitter.com/model">@model</a> IndexModel<br>@{<br>    ViewData[&quot;Title&quot;] = &quot;Home page&quot;;<br>}</pre><pre>&lt;div class=&quot;text-center&quot;&gt;<br>    &lt;h1 class=&quot;display-4&quot;&gt;Welcome&lt;/h1&gt;<br>    &lt;p&gt;Learn about &lt;a href=&quot;<a href="https://docs.microsoft.com/aspnet/core">https://docs.microsoft.com/aspnet/core</a>&quot;&gt;building Web apps with ASP.NET Core&lt;/a&gt;.&lt;/p&gt;</pre><pre><a href="http://twitter.com/foreach">@foreach</a> (var x in Model.Movies)<br>    {<br>        &lt;h1&gt;<a href="http://twitter.com/x">@x</a>.Title&lt;/h1&gt;<br>        &lt;span&gt;<a href="http://twitter.com/x">@x</a>.Description&lt;/span&gt;<br>        &lt;i&gt;Genre: <a href="http://twitter.com/x">@x</a>.GenreId&lt;/i&gt;<br>    }<br>&lt;/div&gt;</pre><p>Pages/Index.cshtml.cs</p><pre>using EFInMemoryDatabase.Database;<br>using EFInMemoryDatabase.Database.Tables;<br>using Microsoft.AspNetCore.Mvc.RazorPages;<br>using Microsoft.Extensions.Logging;<br>using System.Collections.Generic;<br>using System.Linq;</pre><pre>namespace EFInMemoryDatabase.Pages<br>{<br>    public class IndexModel : PageModel<br>    {<br>        private readonly ILogger&lt;IndexModel&gt; _logger;<br>        private readonly MovieContext _context;<br>        public List&lt;Movie&gt; Movies { get; set; }</pre><pre>        public IndexModel(<br>            ILogger&lt;IndexModel&gt; logger,<br>            MovieContext context)<br>        {<br>            _logger = logger;<br>            _context = context;<br>        }</pre><pre>        public void OnGet()<br>        {<br>            Movies = _context.Movies.ToList();<br>        }<br>    }<br>}</pre><p>And that’s about it! Now anyone you give this project to will be able to run it without a problem.</p><p>The database self populates on construction and is stored in memory. This does mean any changes you do in the web app I.E. add a new movie will be lost when you stop the application (add movie to database feature not implemented). But remember the InMemory feature is made for testing/prototyping.</p><p>If you just want to see the code in action you can download my code from GitHub here (you will need .NET 5 SDK installed): <a href="https://github.com/MrApproved/Medium_EFInMemoryDatabase">https://github.com/MrApproved/Medium_EFInMemoryDatabase</a></p><p>Thank you for reading, I hope this has helped you or has taught you something new. Feel free to provide feedback, positive or negative.</p><p>References:<br><a href="https://www.entityframeworktutorial.net/what-is-entityframework.aspx">https://www.entityframeworktutorial.net/what-is-entityframework.aspx</a><br><a href="https://entityframeworkcore.com/providers-inmemory">https://entityframeworkcore.com/providers-inmemory</a></p><p>Repository: <a href="https://github.com/MrApproved/Medium_EFInMemoryDatabase">https://github.com/MrApproved/Medium_EFInMemoryDatabase</a><br>Image: <a href="https://www.pexels.com/photo/industry-technology-computer-power-6310044/">https://www.pexels.com/photo/green-typewriter-with-white-typewriter-4065406/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfe665f7df53" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>