<?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 Ali Ashoori on Medium]]></title>
        <description><![CDATA[Stories by Ali Ashoori on Medium]]></description>
        <link>https://medium.com/@ali-ashoori?source=rss-be953983bfa7------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*rZdDa_DGbNHgPVzjbK2rgA.jpeg</url>
            <title>Stories by Ali Ashoori on Medium</title>
            <link>https://medium.com/@ali-ashoori?source=rss-be953983bfa7------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 06 Dec 2026 11:29:01 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ali-ashoori/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[The Anatomy of a futures contract]]></title>
            <link>https://ali-ashoori.medium.com/the-anatomy-of-a-futures-contract-66bfc3839890?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/66bfc3839890</guid>
            <category><![CDATA[options-trading]]></category>
            <category><![CDATA[futures-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[finance]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Tue, 29 Dec 2020 14:17:32 GMT</pubDate>
            <atom:updated>2020-12-29T14:17:32.861Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*A3BQmcb7rv0mmfBSFGPu0A.png" /></figure><h4>Understanding the basic attributes of a futures contract</h4><p>In my previous story, <a href="https://medium.com/@ali.ashoori/futures-forwards-and-options-introduced-with-examples-1bb2abca1d35">Futures, Forwards, and Options introduced with examples</a>, I tried to explain the basics of Futures, Options, and Forwards contracts with a few examples to demonstrate the details. This time, I’d like to bring a futures contract under some investigation so we can learn more about its structure. The exchange is the one responsible to specify these attributes or the way I call it, the futures contract anatomy. I enjoyed learning this myself, hope we’ll be on the same boat once you’ve read this article.</p><h3>Road map</h3><ol><li>The underlying asset</li><li>The contract size</li><li>Delivery — the arrangement and the timing</li><li>Price</li></ol><h3>1. The underlying asset</h3><p>Futures are the oldest way of investing in commodities. When the asset is a commodity, there is a possibility of having quite a various range of qualities that would be available through the marketplace at each point in time. Hence, the exchange has this responsibility to clearly specify the levels or grades at which a commodity is found acceptable. In other words, grade defines the quality at which the underlying asset will be delivered. In contrast, in financial assets, the grade loses its color as it makes no sense to have a grade against a currency such as the Japanese Yen.</p><h3>2. The contract size</h3><p>The size of a futures contract specifies the amount of the asset that must be delivered through that. For example, in a commodity futures contract that the underlying is sweet crude oil, the quantity could be 1,000 barrels which reflects the contract size. Or, to take another example, if this is about a stock or equity option, the usual size of a contract equals 100 shares. That means the party with the long position has to buy 100 shares per option contract.</p><p>Basically, specifying the contract size is of high importance for the exchange. Mainly because if it goes too small, then, it may not be cost-effective as there is always a cost for each contract to be traded. From another angle, if the contract size tends to be too large, then, those investors intending to go for small speculations would find it difficult to do so. And yet it proves again the crucial impact it could have on the exchange.</p><h3>3. Delivery — the arrangement and the timing</h3><p>Yet, another important job for the exchange is to define the delivery location for the assets that the party with the short position needs to send the assets to. They usually introduce warehouses under the license of the exchange as delivery locations. In some cases though, the location could change which consequently will affect the cost of the delivery too, that is, the further the location is from the commodity source, the higher the cost will likely to happen.</p><p>Now, the timing — basically the exchange must clear the exact period of the month that the delivery can be made. In most cases, that becomes the whole month. As a matter of fact, the exchange specifies the starting month that a contract can get traded, and also, the last day at which a trade can take place. The delivery month is usually what a contract is referred to by. For example, the March corn futures contract traded by CME Group.</p><h3>4. Price</h3><p>This comes with two different sections: Price Quotes and Price Limits. The former is when the exchange has to specify how the prices will be quoted. For example, dollars and cents in the US crude oil futures contract is the quote. The latter, Price Limits, specify the price boundary within which a trade can be done on a trading day — its main goal is to control the volatility that goes against a commodity each day. Let’s bring this into more detail below.</p><p><strong>Limit up</strong> — as the name suggests, this is the maximum price a futures contract is allowed to rise to in the scope of a trading day. The exchange will specify this and it differs from contract to contract. Usually, when the limit up price is reached, the exchange will automatically cease the contract from being traded for that trading day. Alternatively, the exchange may decide to increase the limit-up price to allow further trading. One of the biggest advantages of the limit-up price is to make it difficult for those traders who intend to manipulate the market, that is, they could make a massive number of orders with high prices to bid up the initial price.</p><p><strong>Limit down</strong> — as the name implies, this is the minimum price that a futures contract can decline to and being traded in a day. Again, the exchange will automatically halt the trading if the limit-down price is reached. And yet, they can step in to alternate the price and allow further trading for the day. One of the advantages of the limit-down price is to prevent the panic selling that would generate declines against the actual price.</p><p>Thanks for reading — keep learning :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=66bfc3839890" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Futures, Forwards, and Options introduced with examples]]></title>
            <link>https://ali-ashoori.medium.com/futures-forwards-and-options-introduced-with-examples-1bb2abca1d35?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/1bb2abca1d35</guid>
            <category><![CDATA[capital-markets]]></category>
            <category><![CDATA[stock-market]]></category>
            <category><![CDATA[futures-trading]]></category>
            <category><![CDATA[trading]]></category>
            <category><![CDATA[options-trading]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Fri, 17 Jul 2020 14:53:59 GMT</pubDate>
            <atom:updated>2020-07-17T14:53:59.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*_ouPESGUmmtlKNvgH2-hkA.jpeg" /></figure><p>The promise to this article is to secure an understanding of Futures and Forward contracts also Options. This article studies the theory definition for each of which, then, challenges them through practical scenarios. So, let’s focus on this very paramount yet interesting subject and learn it once and for all.</p><h3>Road Map</h3><ol><li>Forwards and Futures contracts</li><li>Options</li><li>Practicing a couple of scenarios</li></ol><h3>Forwards and Futures Contracts</h3><p><strong><em>Definition </em></strong><em>— </em>In its most simple form, a forward contract is an agreement between two parties to buy or sell an <a href="https://en.wikipedia.org/wiki/Asset#:~:text=It%20is%20anything%20(tangible%20or,is%20also%20considered%20an%20asset).">asset</a> at a certain time for a certain price in the future. This is usually traded on the <a href="https://en.wikipedia.org/wiki/Over-the-counter_(finance)#:~:text=Over%2Dthe%2Dcounter%20(OTC,the%20supervision%20of%20an%20exchange.&amp;text=OTC%20trading%2C%20as%20well%20as,and%20derivatives%20of%20such%20products.">over-the-counter</a> (OTC) market. The parties to this agreement could be either two financial entities or with one of their clients.</p><p><strong><em>Application</em></strong><em> — </em>Forward contracts are quite popular in Forex trading (currency trading). One can consider that to minimize the risks of foreign currencies.</p><p><strong><em>Scenario 1</em></strong><em> — </em>Let’s say company ABC who trades in the United States has to make a large payment of £1,000,000 in 6-months forward. The following table depicts the currency rates for the next 6 months with some example data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sZugLrvQfq1wmNDjBMuLlA.png" /><figcaption>Figure 1 — Spot &amp; Future quotes for USD/GBP exchange</figcaption></figure><p>Surely, there could be fluctuation in the two currencies during this time. The company can minimize the risk and hedge against the exchange rate using Forward Contracts. In our case, the ABC company has agreed to buy £1 million pounds for the rate of 1.5532 after 6 months. In other words, the company will buy £1m from the bank when 6-month time matures. Hence, the company has a <em>long</em> forward contract. On the other hand, the bank has a <em>short</em> forward contract — in every forward contract, one party goes long and the other one goes short.</p><p><strong><em>Calculating the payoffs for long positions</em></strong><em> — </em>Remember, forward contracts do not guarantee not losing money. Consider the sport price declines to 1.5000 when the maturity date comes — no doubt the contract would have a negative value for the company as it requires them to buy GBP for a price more than what the agreement states.</p><p>Basically, the payoff or the profit for a <em>long</em> position in a <em>forward contract</em> is formulated as the below (for one single unit of course):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IKw9sc00ju7Pi49iYylRFw.png" /><figcaption>Figure 3 — The payoff formula for a long position in forwards contracts</figcaption></figure><p>Therefore, once the spot price declines, we would have the following results:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GD7AWm8uGdHKf-kNJVVBww.png" /><figcaption>Figure 4 — The negative value of the contract for the <strong>ABC company</strong> after 6 months (per unit of an asset)</figcaption></figure><p>Now, if the spot price rises, our contract would have a positive value. This is because we can then buy the GBP for the smaller price where the actual market price is bigger.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ce4VoQ9H33ah_Iiwz-V5QQ.png" /><figcaption>Figure 5 — The positive value of the contract for the <strong>ABC company</strong> after 6 months (per unit of an asset)</figcaption></figure><p><strong><em>Calculating the payoffs for short positions</em></strong><em> — </em>Now let’s see it from the bank point of view from whom our ABC company is obliged to buy GBP at the maturity date. The following formula shows how their payoffs are calculated:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMuZOCKQg5ycCcRUILpzFQ.png" /><figcaption>Figure 6 — The payoff formula for a short position in forwards contracts</figcaption></figure><p>Therefore, when the ABC company loses money the bank would gain money.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rCL7d5TjfmBixEX6OnALdQ.png" /><figcaption>Figure 6 — The positive value of the contract for the <strong>bank</strong> after 6 months (per unit of an asset)</figcaption></figure><p>And the bank will lose money when the company has a positive profit.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5Osl8mHhsDe8zMf-OfN1HQ.png" /><figcaption>Figure 7 — The negative value of the contract for the <strong>bank</strong> after 6 months (per unit of an asset)</figcaption></figure><p>At this point, we will close off the Forward Contract topic and will move on with Future Contracts in the next section.</p><p><strong><em>Scenario 2 — </em></strong>Let’s consider a fabric factory Ed’s Fabric that produces cotton fabrics and sells it to a clothes factory Tim’s Clothes that sell cotton shirts. Obviously they profit on the products that they sell to each other. Let’s say the price for every square meter of fabric is £150.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQx3eJRerzd8cSuBW-sdsQ.png" /><figcaption>Figure 8 — Ed’s cotton prices</figcaption></figure><p>After a while, a new fabric factory joins the market named Lisa’s Fabric. This causes the price of cotton to drop to £100. Therefore, Ed’s now sells its cotton to Tim’s for £100 per square meter.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-fciGk1A7AgSqGm9T_s3Zg.png" /><figcaption>Figure 9 — Ed’s cotton price has dropped for £50</figcaption></figure><p>When this happens, Tim’s will profit from that for £50 on each unit. Now, imagine the opposite situation where the cotton price has gone up for £50. In this case, it’s Ed’s time to enjoy the profit as they can seel each unit of the fabric for £200 now while Tim’s has to buy it now more expensively than before.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WbcmHfD0TKQunQ5dLQ6K9A.png" /><figcaption>Figure 10 — Ed’s cotton price has gone up for £50</figcaption></figure><p>Obviously, these volatilities can cost the parties remarkably when the volume of the transaction is huge. Thus, in order to secure their business against these fluctuations in the future, they go to an investor who will help them to hedge against the market changes. The investor will agree with Ed’s that if the price of a unit of cotton falls below £150, he would pay the difference to Ed’s. And as such if the price rises above £150, he would collect the profits from it. This way, Ed’s Fabric has secured itself against the future volatility with a fixed price — they lock the market at a fixed price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ft5wXls8tpmw7oEmxKaCtg.png" /><figcaption>Figure 11 — the investor will collect the price difference when it goes upper than £150</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W8HVFZTzEBAgx20CgtEzEA.png" /><figcaption>Figure 12 — the investor will pay the price difference when it goes below £150</figcaption></figure><p>Adversely, the investor agrees with Tim’s that if the price of a cotton unit goes above £150, he will pay the extra money, hence Tim’s will pay only £150 as predicted. On the other hand, if the price falls below £150, Tim’s still has to pay it at £150 as agreed and the investor will benefit from the difference.</p><p>In conclusion, Ed’s and Tim’s have secured themselves against the potential risks of the market rate, and they have conveyed these risks to the investor now.</p><p><strong><em>Futures contracts — </em></strong>A futures contract is basically an agreement between two parties to buy or sell an asset at a certain time in the future and for a certain price. Hence, this is essentially so much alike the forwards contracts except that they are traded at an <a href="https://en.wikipedia.org/wiki/Clearing_house_(finance)">Exchange Clearing House</a>, rather, the forwards are traded at an OTC.</p><h3>Options</h3><p>Options also are quite appealing to traders. One can trade options both on OTC and an exchange. They come in two different types:</p><ol><li><em>Call options — </em>This gives the right to the holder to <em>buy</em> an underlying asset at a certain date for a certain price.</li><li><em>Put options — </em>This gives the right to the holder to <em>sell</em> an underlying asset for a certain date and for a certain price.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*msPTd_9vY7XMQMSGUM4kPw.png" /></figure><p>The price in an options contract is called <em>exercise or strike price</em> and the date mentioned there is called <em>expiration or maturity date.</em></p><p>Options that are traded on an exchange by the majority are the American options, but, there also are the European ones. The main difference between the two is that the American options can be traded at any time up to the maturity date whereas the European ones can only be exercised on the expiration date.</p><p>And the main difference between <em>options</em> and <em>futures or forwards</em> is that in options the holder has the right not to exercise the contract, whilst, in a futures or forwards contract, the hold is obliged to exercise the contract when it expires.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OUhsOHDXxiyLWn47NHjbVw.png" /></figure><p><strong><em>The Scenario — </em></strong>Let’s say it’s the middle of July and Joe wants to buy a Call Options contract (usually of 100 shares) for December on Tim’s Factory with a strike price of £700. From the table below, the offer price for December is £55.87. This indicates the price for an option to buy one share.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kPuYnoEHU0kr6dx6aWZB6g.png" /><figcaption>Figure 13 — Tim’s Factory bid and offer for December</figcaption></figure><p>For this, Joe talks to an exchange and then he will have to pay them for £5,587 as per 100 * £55.87 so they can transfer this for the other party. What’s happened so far is that Joe has honored the right to buy 100 shares of Tim’s Factory each priced for £700. Once the December arrives, he’s going to experience either of these scenarios:</p><ol><li>The price has gone above £700</li><li>The price has not gone above £700</li></ol><p>In the first case, Tim’s Factory would have been rocking the market as the price has gone up, hence, the option will be exercised. So, let’s say now that the Bid price for the stock is now £900, Joe is now able to <em>buy</em> 100 shares for £700 where the market price is now £200 more than that. Therefore, he will profit for £20,000.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mpHLzr5-eF8oKhfkyFKyzg.png" /><figcaption>Figure 14 — Joe’s profit if the stock price goes above the strike price by December (maturity date)</figcaption></figure><p>On the other hand, when the second scenario is the case, the options won’t be exercised. And this is one of the main differences that an options contract has with a futures or forwards one, that, the holder has the right not to exercise the contract.</p><h3>Practicing a couple of scenarios</h3><p>In this section, we will practice a few more scenarios so we hopefully nail our understanding from previous sections a little bit more.</p><p><strong><em>Scenario1 — Using Put Options to protect against value fall</em></strong></p><p><em>Usecase — </em>Assume that Joan owns 2,000 shares of Ed’s Factory that each worth £20. There’s a prediction that in the course of 6 months, there will be some decline in the value of the shares. How would you advise Joan to minimize the risk against this decline?</p><p><em>Solution — </em>One possible solution for Joan is to buy 2,000 <em>Put Options</em> (equals to 20 contracts as to 20 * 100) with the strike price of £20 and the maturity date of six months. In this way, on the expiration date, if the price goes under £20, Joan can exercise the contract and then sell her shares each for £25. Hence, she would profit for £5 on each share.</p><p><strong><em>Scenario 2 — Susanna and Short Forwards Contract</em></strong></p><p><em>Usecase — </em>Susanna runs her own business for years now. She recently enters into a short forward contract on 150 million GBP. The exchange rate is $1.5300 per GBP. She wants to know how much of gain or loss she would once the contract is ended upon the following conditions:</p><p>A) The exchange rate is $1.1500 per GBP</p><p>B) The exchange rate is $1.1550 per GBP</p><p><em>Answer — </em>When the exchange rate is $1.1500, that is, $0.03 less than the strike price, Susanna sells its shares for $1.5300. Therefore she profits as to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jr0wDzDews0Llan48W_pWA.png" /><figcaption>Figure 14 — Total profit for Sussan as of the maturity date</figcaption></figure><p>On the other hand, when the rate is $1.1550, that is, $0.02 more than the strike price, Susanna sells its shares for $1.5300. Therefore she loses money as to:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3KRQmgOPuYdewJQjPuHqZg.png" /><figcaption>Figure 15 — Total loss for Sussan as of the maturity date</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*T4vh-HIhEqFNk6jAIXWyFA.png" /></figure><p>And we’re done at this step. I hope this article has given few insights to this amazing world of Capital Market and Investments to those who are interested and new to this area.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/832/1*EiXdefF1hV9yVl7CKcWMxA.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1bb2abca1d35" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Graphs everywhere —  Finding the minimum swaps required to sort an array]]></title>
            <link>https://levelup.gitconnected.com/graphs-everywhere-finding-the-minimum-swaps-required-to-sort-an-array-b8dea0a3af52?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/b8dea0a3af52</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[arrays]]></category>
            <category><![CDATA[graph]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Thu, 09 Jul 2020 13:31:08 GMT</pubDate>
            <atom:updated>2020-07-09T13:31:08.521Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/946/1*-0bJnBYpK1nkwVdupGdVjg.jpeg" /></figure><h3>Graphs everywhere — Finding the minimum swaps required to sort an array</h3><p>Graphs are one of the most fundamental concepts in Computer Science. And they play the part perfectly in solving a tremendous number of problems. In this article, we’re going to bring into the light an algorithm question that at first glance one may not even think that graphs can be of any use to drive a solution for. But first, let’s have a look at our journey today. <em>Please kindly note, we won&#39;t go deep with the Graphs concepts in this article, rather, a shallow introduction over that and then to focus on its applications to tackle arrays algorithms questions.</em></p><h3><strong>Road Map</strong></h3><ol><li><em>A quick introduction to Graphs — Structure, Paths, and Cycles</em></li><li><em>The problem to solve — Finding the minimum required swaps to sort an array</em></li><li><em>Coding time</em></li><li><em>Always unit test your algorithms</em></li></ol><h3><strong>An Introduction to Graphs</strong></h3><ol><li><strong>The structure of a graph</strong></li></ol><p>A graph is a data structure that in its most compact form is made up of a single vertex (also called a node). Here’s a simple representation of it:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/221/1*Wp1C9rEBm4r74dvFbJV9Kg.png" /><figcaption>Figure 1 — A single node graph</figcaption></figure><p>We can obviously extend this graph by adding more properties to it. For example, another connected node to this where the direction between the nodes is not important, just like the below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/831/1*lS1iOJ1kyW18mW2njijBBQ.png" /><figcaption>Figure 2 — An undirected graph (direction does not matter)</figcaption></figure><p>Now, if we simply add a direction to the edge between the two nodes above, we would then turn it into a directed graph which also is important for the problem we are going to solve shortly. Here’s how it looks like:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/807/1*HEu0tYpQoxEtsjJxbkrrGA.png" /><figcaption>Figure 2 — A directed graph (direction matters)</figcaption></figure><p>It really sounds easy so far, yet, we need to cover the Paths and Cycles of a graph so we get our backpack ready to solve our algorithm question.</p><p><strong><em>2. </em>Paths</strong></p><p>To understand the path theoretically, we need to first have a touch on the Walks within a graph. So let’s see what that is:</p><p><strong>2.1. Walk <em>—</em></strong><em> </em>A Walk is basically a sequence of edges where each edge, except the first one, starts with a node (vertex) where the previous edge ended<em>. </em>For example, the following graph demonstrates a walk:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BRHsngzRrzA4wDbxQ4X73A.png" /><figcaption>Figure 3 — A walk on a graph</figcaption></figure><p>Here, if we traverse through A &gt; B &gt; C that would give us a walk — same if we travel A &gt; B &gt; C &gt; D, or even, A &gt; B &gt; <strong>C</strong> &gt; D &gt; <strong>C</strong>.</p><p>The crucial note to remember here is that a Walk could have repeated edges and that would not have any interference with the definition of a Walk.</p><p><strong>2.2. Path — </strong>A path is simply a walk where you would never go through an edge more than once. Hence, all the edges and vertices are distinct. Going back to the previous example, A &gt; B &gt; C would give us a path but not <br>A &gt; B &gt; C &gt; D &gt; C.</p><p><strong>2.3. Cycle — </strong>A cycle can be detected when the <em>first </em>and the <em>last</em> node on a path are the same. That would give distinct edges but not distinct nodes which would lead to a Cycle. The following figure shows us a cycle of <br>A &gt; B &gt; C &gt; D &gt; A.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dt8q0l_32VKf0Kv1HSmT2A.png" /><figcaption>Figure 4 — Representing a cycle for A &gt; B &gt; C &gt; D &gt; A</figcaption></figure><p>Up to this point, we have covered all we needed to know so we can tackle the algorithm question we have. So without any further details let’s read on to find out more about the question.</p><h3>The problem to solve — Finding minimum swaps to sort an array</h3><ol><li><strong>The problem statement</strong></li></ol><p>We are given an array of <em>distinct</em> integers which are <em>not</em> sorted. We are allowed to swap any of the two items of the array to eventually make it sorted in <em>ascending</em> order. Our task is to write a piece of an algorithm that works out the minimum number of swaps that are required to sort the array as expected.</p><blockquote>When I faced this question for the first time, I couldn’t think of anything like graphs to be turning out quite helpful so I could drive the skeleton of a solution with. But, I started to realize taht when I started to walk myself through the problem and to also visualize it over a piece of paper which is what we want to experience in the rest of the article.</blockquote><p><strong>2. A walkthrough over the problem</strong></p><p>Let’s start with an array of integers as our program input. Here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xd07paXmNz8lsxu3XXUWBA.png" /><figcaption>Figure 5 — An array of integers as the input of the program</figcaption></figure><p>As it’s obvious our numbers are not placed in their correct position. So, let’s see a representation of our final array — the sorted one.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*siH7_ryUJ0J11fJx354Fig.png" /><figcaption>Figure 6 — The expected final result — the sorted array</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/239/1*Xqf_QnZ9Em0s-e56xnX0WA.jpeg" /></figure><p>Now, we need to give us some time, stare into this figure, and try to showcase some creativity so that we can find a relation between the numbers and their positions.</p><p><strong><em>2.1. Finding the correct (final) positions of each number</em></strong></p><p>If you look into each cell of the above figure, the <em>sorted</em> one, you would realize that the value of each cell would equal its final cell index, if, it is subtracted by 1. For example, the first cell holds number one; if we subtract it by 1 that would give us 0 representing the correct index (or the correct position) where 1 belongs to. The same rule applies to every other cell of the array too.</p><p><strong>Note</strong>, it is important to do the above on the expected result. Because our main intention here is two things:</p><p>1) To find out the correct (final) position of each number within the array<br>2) To apply that finding against the input of the program, the unsorted array, so we can then design an algorithm to move the items into their correct positions.</p><p>Please look at the following figure that visualizes what we have just achieved.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yxu1BCvmRwoilz1rIwdFYg.png" /><figcaption>Figure 7 — Finding out the correct position (final position) of each number in the array</figcaption></figure><p><strong><em>2.2. Considering the final positions on the unsorted (input) array</em></strong></p><p>Now that we know who should be where; let’s have a look at our input array one more time and to see how we can apply our findings against that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Xd07paXmNz8lsxu3XXUWBA.png" /><figcaption>Figure 8 — The input array</figcaption></figure><p>It’s getting interesting actually — look at the first number: 2. It must be placed at index or cell 1. Applying the graphs knowledge from the early sections, we can denote a path from index 0 to index 1; in other words, the value of index 0 which is number 2, must be placed in index 1, hence, 0 &gt; 1 is the path. Give it some time to think over that if needed and make sure you’re confident with this up to this point.</p><p>This should give us some inspiration to draw out the paths against our array. The following figure visualizes these paths until they reach a cycle.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD24rif7aphoHZc5GrT5WQ.png" /><figcaption>Figure 9 — Solution representation; looking at the array from a graph point of view and detecting cycles in that</figcaption></figure><p>This figure is the actual solution to the problem. Consider that first cycle: <br>0 &gt; 1 &gt; 0. This is saying that the element at index 0 must be placed at index 1 and the element at index 1 must be placed at index 0, hence, swapping the elements will make them sorted in ascending order. The total swaps needed on this cycle would be 1. This logic applies to the second cycle too, <br>2 &gt; 4 &gt; 3 &gt; 2 for which a total swap of 3 will make it sorted. Therefore, we can conclude that <em>f(swaps) = number(nodes) -1</em>. If we simply sum up the swaps for each cycle, we will end up with the minimum swaps required to get the array sorted in ascending order.</p><p>Woop! Good job — it may be worth it to go through this one more time on your own before burning the code for that if you find that helpful.</p><h3>Coding time — C#</h3><p>We would like to implement our solution, figure 9, in a way that we can test it unit by unit. Hence, we break our solution into two different major parts:</p><ol><li>A method responsible to generate the cycles</li><li>A loop against the input array so that for each item we would consider the cycles</li></ol><p>We also want to keep track of our visited nodes so we avoid computing the same subproblem over and over again, hence, optimizing the performance. For more information on this, please read <a href="https://levelup.gitconnected.com/understanding-dynamic-programming-in-theory-and-practice-7835610ca485">my article on Dynamic Programming</a>. Let’s see how the magic looks like.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3RjB4gCLYOy7hnTBzVDJ6Q.png" /><figcaption>Figure 10 — The method responsible for detecting the cycles and returning the path to each of which</figcaption></figure><p>The <em>FindCyclesPaths </em>method does one single thing against which we can easily write a unit test to prove its correctness. Needless to say that, the <em>while </em>loop will break once we reach a cycle which is when the first node gets equal to the destination node. For example, in Figure 9, the destination of the first index is the second cell of the array. This function returns a list of nodes denoting a cycle path as per Figure 9. The computation of the swaps is not within the boundary of this method, hence, building up testable codebase.</p><p>Now, we need to settle our main method that travels through the input array calling the <em>FindCyclesPaths </em>for each un-visited node.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/1*zbGY3MeoUPjwbv8i75Ckrw.png" /><figcaption>Figure 11 — The actual method for finding the minimum required swaps</figcaption></figure><p>As explained before, we would like to introduce a data structure in which to store the visited nodes. We use a boolean array for this with the same length as that of the input array, here named numbers. By default, C# will populate <em>false </em>values for each index, hence, no need to do it manually. Next, we walk through our items and we compute the <em>swaps </em>for each cycle path we visited. Finally, the swaps variable gets returned as the result of our procedure.</p><p>Well done! we’ve got this implemented and <a href="https://www.hackerrank.com/challenges/minimum-swaps-2/problem?h_r=internal-search">HackerRank</a> loves it too as it gives full score to this solution. Now, let’s confirm the correctness of our code using unit tests.</p><h3>Always unit test your algorithm</h3><p>At this step, we would write a few test cases merely to prove the basic scenarios and I would like to leave the edge cases for the readers to explore more on this. Here’s our first unit test for the cycle detection function verifying the two cycles detected in Figure 9.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8wANMvF0JLHbpkl0H_Mzg.png" /><figcaption>Figure 12 — Unit tests for FindCyclesPath method</figcaption></figure><p>And finally, one for our main function:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*AN5fS5dbx18JjOk9I4rC9Q.png" /><figcaption>Figure 13 — Unit test for FindMinSwaptoSortArray method</figcaption></figure><p>And that’s all really — we have covered few concepts of the graphs theory, we went through a medium level algorithm questions, looked at an array sorting problem from graphs perspective, a quick touch on <a href="https://levelup.gitconnected.com/understanding-dynamic-programming-in-theory-and-practice-7835610ca485">DP Programming</a>, and eventually proved the correctness with some unit tests.</p><p>Thanks for reading this through and happy coding! 🐱‍🏍</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b8dea0a3af52" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/graphs-everywhere-finding-the-minimum-swaps-required-to-sort-an-array-b8dea0a3af52">Graphs everywhere —  Finding the minimum swaps required to sort an array</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Dynamic Programming in theory and practice]]></title>
            <link>https://levelup.gitconnected.com/understanding-dynamic-programming-in-theory-and-practice-7835610ca485?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/7835610ca485</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[memoization]]></category>
            <category><![CDATA[dynamic-programming]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Thu, 02 Jul 2020 13:41:01 GMT</pubDate>
            <atom:updated>2020-07-02T20:00:29.718Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/980/1*E2zEou-7zbPpNPMjieTG6A.jpeg" /></figure><p>Dynamic Programming is one of the challenging algorithmic paradigms that require proper and consistent practice to get comfortable with. In this article, I&#39;m going to first explain the principles of Dynamic Programming (DP) and then try to apply that through an example that we initially will solve it using recursion. And then applying dynamic programming against that — I believe this will give us the opportunity to better understand the benefits of dynamic programming.</p><p>Please note that this is assumed that a basic understanding of the recursion approach is already obtained as this article does not focus on that. Also, our solutions are coded in my very favorite programming language, C#. So, without any further due let&#39;s get it started!</p><h3><strong>Our Road Map</strong></h3><p>If you stay with me during this article, I will cover the following:</p><ol><li><em>What is Dynamic Programming?</em></li><li><em>What are the techniques to identify a DP problem?</em></li><li><em>Putting identification techniques into practice - Rod Cutting Problem</em></li><li><em>Formulating a solution for Rod Cutting problem</em></li><li>Coding time (Plain recursive, Memoization, and Tabulation)</li></ol><p>I enjoyed this myself and hope you will too.</p><h3>What is Dynamic Programming?</h3><p>In nutshell, Dynamic Programming simplifies a complicated problem into smaller sub-problems and then combines the solutions of each of which to form the ultimate solution to the original problem.</p><p><strong><em>Where is the difference between Divide-and-Conquer and Dynamic programming then? 👀</em></strong></p><p>There is a tiny yet important difference between the two: In Dynamic Programming, the sub-problems overlap each other whereas, in the Divide-and-Conquer paradigm, we deal with disjoint subproblems.</p><p>Also, in a dynamic programming approach, we save time and level up the efficiency by storing the previously computed values so that next time the same subproblem will not be computed again, rather, retrieving its value from the storage. There are two approaches to this: Memoization (top to bottom) and Tabulation (bottom to top). In this article, we cover both of which with explanations.</p><h3>What are the techniques to identify a DP problem?</h3><p>It&#39;s quite important to be able to identify if a given problem could have a Dynamic Programming solution, otherwise, we won&#39;t be able to practice the advantages of this approach. Here we firstly mention two major techniques for this and then we put them into practice through an example coming afterward.</p><ol><li><strong><em>Overlapping subproblems: </em></strong>Put it simply, overlapping subproblems must satisfy these two conditions: <br>A) a problem can be broken down into subproblems and <br>B) the result (the solution) of each subproblem could be of use at a later stage<br>Hence, if the given problem does not meet the above, that means we shouldn&#39;t consider DP as our algorithm approach. As that would be pointless to cache the results (solutions) where they won&#39;t be needed later on.</li><li><strong><em>Optimal substructure: </em></strong>In essence, that means, if the optimal solution to a problem has resulted from the optimal solutions of its subproblem, then, the given problem has Optimal Substructure characteristics too. Most of the classical DP problems are attributed to this principle.</li></ol><h3>Putting identification techniques into practice — Rod Cutting Problem</h3><p>In this part, we will consider one of the classical DP problems called Rod Cutting. To begin with, let’s get familiar with the problem first.</p><p><strong>Rod Cutting problem explained</strong></p><p>Steve has a steel rod which has a length of N inches. He also is given a list of prices that relates to each of the rod pieces smaller than size N. The task is to obtain the maximum revenue resulted from cutting the rod and selling the pieces.</p><p>Assume that the rod is of length <strong>10</strong> and a price list of <strong>{ 1, 5, 8, 9, 10, 17, 17, 20, 24, 30 } </strong>is given. Having this said, we can have the following table showing the relation between the rod pieces and the prices:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZ5GQxe6IQWh2qrjJxaTfQ.png" /><figcaption>Figure 1 — The rod pieces and their prices</figcaption></figure><p>Hence, we can understand that for a piece of the rod which is of length 2, we have a price number of 5. And as such, for a piece of length 3, the price number would be 8.</p><p>So far so good.</p><p>Now let&#39;s put some light on the task for the problem - cutting the rod into pieces to obtain the maximum revenue. Assume we would like to calculate the maximum profit for the length of 4. For this, we first need to understand how many combinations of four pieces are achievable. So, let&#39;s see how we can visualize it here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G7bpOjtRZsuzi4v7nIPeug.png" /><figcaption>Figure 2 — The rod pieces combinations of the length four</figcaption></figure><p>So now it&#39;s easier to figure out which of the combinations suggests the maximum profit for Steve. In other words, <em>the combination that its pieces sum up to the biggest value would be the optimal solution for us</em>, that is, number 3 which suggests cutting the rod in two pieces which results in 10 as per</p><p>P2 + P2 = 5 + 5 = 10.</p><p>Sounds good - so far we have understood (hopefully☺) what the Rod Cutting problem is and what this is asking for. So, it&#39;s time now to see how we can apply the identification techniques against this problem.</p><p><strong>Applying DP identification techniques on Rod Cutting problem</strong></p><p>Right - let&#39;s focus on the <em>Optimal Substructure</em> first. As explained earlier, we obtain the maximum profit by cutting the rod into pieces and then comparing the values out of each combination. That is to say, the optimal solution to the subproblems (each combination) will lead to the optimal solution for the original problem. Hence, the Rod Cutting problem is attributed to the <em>Optimal Substructure</em> principle.</p><p>At this time, the <em>Overlapping Subproblems </em>principle should also be clear to notice. That is to say, we need to repeat the same comparison against the maximum value once our algorithm forms a new combination. The important point here is that the subproblems will require the result computed out of the previous subproblems, hence, the maximum value can be computed against the most optimal one acquired so far. In other words, our subproblems are overlapping with each other in this problem.</p><blockquote>My approach to identifying a DP problem is to first understand the problem properly. And then to see if the problem can be broken down into smaller ones. And finally to figure out if there&#39;s any relationship (or dependency) between the subproblems. If these conditions apply, then, I would conclude that the given problem is a DP problem.</blockquote><h3>Formulating a solution for Rod Cutting Problem</h3><p>Now that we have covered an explanation over the problem also have understood how Overlapping Subproblems and Optimal Substructure apply against the Rod Cutting problem, it&#39;s a good time to drive a solution and burn some code on it 😎</p><p>Our program needs to compute the maximum profit for each subproblem it considers, therefore, at each point in time, it will have the maximum value up to that stage.</p><p>That is, we can formulate this into the following where 1 ≤ i ≤ n</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MI-OT6FO7dvQu6mo16Icmw.png" /></figure><p>Here the BestPrice function computes the most optimal value up to the ith point. Now, we need to repeat this formula for all the pieces of our rod. That is, from 0 to the Rod size - {0, 1, 2, 3, ..., n-1 }.</p><p>At this time, the only thing remaining is to bring up some code editor and script out the actual algorithm. 🤖</p><p><strong><em>First - Considering the recursive approach as promised</em></strong></p><p>As stated in the very beginning, we first consider a recursive approach, and then we will apply DP against that to hopefully understand better the optimization benefits it delivers to us. Let&#39;s see how it looks like in C#.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1015/1*wXYA0qpf4IRXnkIQjh168g.png" /><figcaption>Figure 3 — The rod cutting solution using a recursive approach</figcaption></figure><p>This small piece of code solves the problem for us in a recursive manner. It&#39;s all good except that our program here computes the results of the same subproblems over and over again which eventually will hurt the time complexity of the algorithm. Let&#39;s better understand this by visualizing the recursion graph of the algorithm. For simplicity here, we only consider the length of four.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sTp24-vMnZnJXyU1S4apLA.png" /><figcaption>Figure 4 — The rod cutting recursion tree considering the length of four</figcaption></figure><p>As the figure illustrates, some nodes have repeated the computation. For example, nodes 2 or 1 have been computed more than once which could lead to serious algorithmic inefficiencies if the problem input goes large. Now, it&#39;s time to apply DP against this recursion and to enjoy the improvement of our algorithm.</p><p><strong><em>Second - Optimizing the performance using Dynamic Programming</em></strong></p><p>There are two different approaches to store computed values in dynamic programming, namely, <em>Memoization</em> and <em>Tabulation</em>. The former initializes the storage data structure with default values and then to update that with the latest value during the execution of the algorithm. Whereas the latter, Tabulation, does not require us to initialize the storage in the beginning. To save time here, I would like to refer to <a href="https://awjin.me/algos-js/dp/tab-memo.html">this article</a> for further reading on Tabulation and Memoization. Also, the reference given at the end of the article provides great content around this.</p><p><strong><em>Rod Cutting DP solution with Memoization (top to bottom)</em></strong></p><p>The following code discloses part of the solution using the Memoization approach. Here, we first declare an array of integers and then we fill in every index of which with the minimum value of an integer. The next step would be to call out a helper function that does the recursion for us. And it uses the storage array to avoid recomputation of the same subproblems as promised by DP.</p><p><em>Note: you can use a simple for loop instead of Enumerable Range method - they would both do the same job for us in here.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mGac2k6lF40yx3vPJUj41Q.png" /><figcaption>Figure 5 — The rod cutting the main function with Memoization</figcaption></figure><p>Now let&#39;s see the other primary part of the algorithm which is our recursive function that demonstrates how the storage array comes handy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iPh0gVv3Rd-Ggi54AW6vxA.png" /><figcaption>Figure 6 — The rod cutting recursive helper function doing the Memoization</figcaption></figure><p>It&#39;s needless to say that every recursive function requires a base case that determines whether the execution must continue or not. In our helper function that would be the length or the size of the pricing table. Now, let&#39;s see how the Tabulation (bottom to top) approach would look like for this Rod Cutting problem.</p><p><strong><em>Rod Cutting DP solution with Tabulation (bottom to top)</em></strong></p><p>This solution does not utilize any sort of recursion to solve the problem. Indeed, it uses nested loops to achieve the same result. The other important difference is that our storage array is not initialized with the default values in the beginning as opposed to the Memoization approach.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FD7KePDAoDrbSJtM25aVDg.png" /><figcaption>Figure 7 — The rod cutting DP solution with Tabulation technique</figcaption></figure><p>The main logic behind the loops is to move towards the whole Rod length and to compute the optimal value up until that point. For example, if at a point in time, the program is at piece 4 (the i = 4), then, it considers all the previous values up to 4 (from 0 to 3 as j increments until it&#39;s smaller than i) to always compute the latest maximum price.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/728/1*XsBFFHLY2Tc2eB2j9y6UHg.png" /></figure><p>Dynamic programming is a challenging concept where it surely requires much practice so that one can first identify the sort of the problem and then to also identify the subproblems, figuring out where they overlap, picking up a storage technique, and finally to drive the solution.</p><p>I hope you all who have gone through this article up to this line have found this helpful.</p><p>Please feel free to leave your comments if you may think there&#39;s room for improvements where I have missed or more importantly if you find something which is incorrect. Although I may not be instant in reading and replying to the comments I&#39;m sure I will come back to this piece sooner or later. ☺</p><p>Happy coding and thanks for reading!</p><p><strong><em>My Reference for this article which I also highly recommend to those interested in algorithms:</em></strong></p><p><a href="https://www.amazon.co.uk/gp/product/0262033844?pf_rd_r=S9R8Y42G5XHYC9DHCCPK&amp;pf_rd_p=e632fea2-678f-4848-9a97-bcecda59cb4e">Introduction to Algorithm (The MIT Press)</a></p><p><a href="https://skilled.dev/">Coding Interview Questions + Land Your Dev Job | Skilled.dev</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7835610ca485" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/understanding-dynamic-programming-in-theory-and-practice-7835610ca485">Understanding Dynamic Programming in theory and practice</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Open/Closed Principle and Backward Compatibility]]></title>
            <link>https://levelup.gitconnected.com/open-closed-principle-and-backward-compatibility-cab2f462bc0f?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/cab2f462bc0f</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[solid-principles]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Tue, 28 Jan 2020 00:18:04 GMT</pubDate>
            <atom:updated>2020-01-30T20:20:19.722Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*VTTQMRvVRxdIYsRIEL5M8A.jpeg" /></figure><p><strong>Background: </strong>There are already plenty of resources around the web, articles, and books explaining <a href="https://en.wikipedia.org/wiki/SOLID">S.O.L.I.D principles</a> and <a href="https://www.oreilly.com/library/view/97-things-every/9780596809515/">coding best practices</a>, but I couldn’t stop myself from sharing a short example about the concept that I greatly have a passion about, S.O.L.I.D principles and <a href="https://en.wikipedia.org/wiki/Design_Patterns">design patterns</a>. So, here is another example of the Open/Closed Principle which indeed was part of a coding challenge interview I had from one of the Banks so it shows the importance of it — let’s nail it once for all.</p><p><strong>Introduction: </strong>The principle states that a class should be open to extensions but closed to modifications. This especially helps when the requirements or the rules change frequently or at least are probable to be. Conforming to OCP will protect your code against backward compatibility concerns. In other words, if the new requirements must be handled by a class, then there’s no need to modify it rather we would only need to introduce a subclass for it which will then introduce the new logic independently. Purely simple, now we want to take a closer look at this through an example.</p><p><strong>The case study </strong>demonstrates processing a payment request with attention to the value of the property <em>amount</em>. This is about having four different gateways of <em>Default, Regular, Priority, and Premium</em> — each of which processes the payment differently based on the value of the amount coming from the payload request. Here’s how these should process the payment:</p><ul><li>Default — values from 1 to 50 having a service cost of 15%</li><li>Regular — values from 50 to 100 having a service cost of 10%</li><li>Priority — values from 100 to 300 having a service cost of 5%</li><li>Premium — value above 300 no service cost considered</li></ul><p>Simple but interesting enough to kick off implementation. First, we will see how the logic can be implemented naively and then after how we can protect our code against <a href="https://en.wikipedia.org/wiki/Backward_compatibility">backward compatibility</a> issues using OCP.</p><p><strong>The Naive Approach</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EyzXK25R-OUjpa8uob0M_Q.png" /><figcaption>Figure 1 — Naive approach with three explicit If’s and one implicit for values greater than 300</figcaption></figure><p><strong>The Better Approach with attention to OCP</strong></p><p>We now need to abstract away these if statements so that we will stop modifying the code with any new changes introduced besides that we need to test each of the conditions separately. Remember that in a real-world example these conditions could be much complicated and more lengthy than what is shown in Figure 1 which means we will need to have a better strategy to handle backward compatibility as well as modular coding practices. We will do it together through the following steps.</p><p>Step 1 — We create an interface that would the only point of contact for any consumer of our function above. This will give us a starting point for abstracting away the logic and separate them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1003/1*te5ukkbWkEYibAlOd3M2nw.png" /><figcaption>Figure 2 — The interface responsible to be communicating with the clients</figcaption></figure><p>Step 2 — Now we define the gateway interface which comes with two operations one to see if the incoming request matches the criteria and the second operation would be the actual payment processor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/939/1*7ErTtUMBge3uWAfeUxaHsg.png" /><figcaption>Figure 3 — Payment Gateway interface with Is Match method to resolve proper payment processor</figcaption></figure><p>Step 3 — Now it’s time to implement the four different gateways that earlier mentioned each carries a different logic against the amount value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1016/1*E7oGc1I9OIn4MX9jx4-F7A.png" /><figcaption>Figure 4 — Payment Gateways hosting the actual logics independently (ready for <em>Unit Testing)</em></figcaption></figure><p>Step 4 — And finally, the Payment Processor class which is responsible to process the payment coming from the request. This class will host all of the gateway rules and applies the one which accurately meets the required conditions.</p><p><em>Note: Adding the gateways itself could be also refactored using </em><a href="https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/concepts/reflection"><em>reflections </em></a><em>so that every single time a new rule gets added to the system a developer would not need to manually add that in the Payment Processor or any other module which depends on them. But for the sake of simplicity and focusing on the subject it has been ignored.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*69KG-9gRzMmLnFL3wCUdQw.png" /><figcaption>Figure 5 — The Payment Processor class (no if statement used anymore — Open for extension Closed to modification)</figcaption></figure><p>Awesome, isn’t it? I like this piece of code that amazingly abstract away all of those if statements into independent separate classes ready for unit testing. As it is shown, our Payment Processor class is now open to extension as we can add endless payment gateways and closed to modifications as we won’t need to make any changes in this class regardless of the number of gateways that might be added.</p><p>And here is a dummy class showing how the caller would invoke the code above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TW7lVy0xQsrG2-vyt6BRgw.png" /><figcaption>Figure 6 — The consumer class which invokes the calculations</figcaption></figure><p>Hopefully, now this proves how easy it is to implement OCP and with a bit of practice and challenge to apply it also in real-world scenarios.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cab2f462bc0f" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/open-closed-principle-and-backward-compatibility-cab2f462bc0f">Open/Closed Principle and Backward Compatibility</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fluent APIs and cleaner Unit Tests]]></title>
            <description><![CDATA[<div class="medium-feed-item"><p class="medium-feed-image"><a href="https://ali-ashoori.medium.com/fluent-apis-and-cleaner-unit-tests-d4c272858a6a?source=rss-be953983bfa7------2"><img src="https://cdn-images-1.medium.com/max/760/1*Cm4mT_R5S0WCmkdbhBTIdg.jpeg" width="760"></a></p><p class="medium-feed-snippet">This post and its examples use C# to demonstrate the solutions but the overall approach (or mindset) is applicable using other programming&#x2026;</p><p class="medium-feed-link"><a href="https://ali-ashoori.medium.com/fluent-apis-and-cleaner-unit-tests-d4c272858a6a?source=rss-be953983bfa7------2">Continue reading on Medium »</a></p></div>]]></description>
            <link>https://ali-ashoori.medium.com/fluent-apis-and-cleaner-unit-tests-d4c272858a6a?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/d4c272858a6a</guid>
            <category><![CDATA[c-sharp-programming]]></category>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[design-patterns]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Sun, 26 Jan 2020 21:01:46 GMT</pubDate>
            <atom:updated>2020-01-26T21:01:46.888Z</atom:updated>
        </item>
        <item>
            <title><![CDATA[How to avoid fat controllers in ASP.NET Web API (.net framework)]]></title>
            <link>https://levelup.gitconnected.com/how-to-avoid-fat-controllers-in-asp-net-web-api-net-framework-45acb45ba6f0?source=rss-be953983bfa7------2</link>
            <guid isPermaLink="false">https://medium.com/p/45acb45ba6f0</guid>
            <category><![CDATA[netframework]]></category>
            <category><![CDATA[aspnet]]></category>
            <category><![CDATA[csharp]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[webapi]]></category>
            <dc:creator><![CDATA[Ali Ashoori]]></dc:creator>
            <pubDate>Sat, 11 Jan 2020 16:38:41 GMT</pubDate>
            <atom:updated>2020-02-05T01:19:44.746Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gX43WgUS4jDY6YuSLKm-ew.png" /></figure><p><em>This has been assumed that some basic knowledge and experience of ASP.NET WEB API, C#, and SOLID principals are already acquired as this article will not focus on these but rather a solution to avoid writing big controllers.</em></p><h3>Background</h3><p>Building rich web-based applications using <a href="https://www.asp.net/web-api">ASP.NET WEB API</a> is no longer something new and it has been reliably around for years now. Implementing <a href="https://restfulapi.net/">RESTful APIs</a> and building up powerful services communicating over <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/Basics_of_HTTP">HTTP</a> and exchanging in <a href="https://en.wikipedia.org/wiki/SOAP">SOAP</a> or <a href="https://www.json.org/">JSON</a>, configuring custom API routes, applying custom filters against controllers and actions, all and all are just primarily parts of this framework which have resulted in massive popularity through the entire market.</p><p>But, when it comes to coding and scripting out the logic, that, is another story and regardless of how powerful the target framework is, writing out proper, cohesive, and clean code is more a matter of techniques, knowledge, and of course experience.</p><h3>The challenge</h3><p>One of the challenges that could potentially make our Web API Controllers unnecessarily big is the number of objects that each controller needs to embrace so that its actions can utilize them to invoke the target operation exposed via those particular objects. Basically, the more of these objects our controller depends upon, the more growing and messy it will likely to be.</p><p>One may immediately think of IoC and applying DI pattern in order to sort this problem out. But, that, unfortunately, takes care of totally another concept (as we all probably know) which is instantiating objects via another responsible component so that more decoupling will happen in an application which is quite appreciated. But, those objects should get injected into the consumer somehow, either through the constructors or properties, or even methods based on the needs of the program and of course the IoC library in hand. And, this is when the controllers get noisy.</p><p>Throughout this article, this has been attempted to demonstrate this problem via some code snippets and then to consider a solution-driven approach to tackle this problem and to actually abstract away all of those objects on which our Web API Controller depends.</p><h3>The Scenario</h3><p>The practice scenario here is to implement Create, Delete, and Update APIs using ASP.NET and C#. In favor of focusing only on the article&#39;s purpose, the repository database components have left with no implementation and they only expose interfaces and operations through which the Create, Update, and Delete functionalities can take place.</p><p>In this example, we have been asked to apply the above operations on a Student object. The following will show the main participants of this scenario one by one through code snippets and then will go into more detail about the problem and the solution.</p><h3>The Participants</h3><p>First and foremost, we need to have our Student model class.</p><p><em>The Student Entity Model</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KAzYZR4uQFuweveKBROhvg.png" /><figcaption>Figure 1 — Student Entity Model</figcaption></figure><p><em>The Repository Classes (each of which to be as a separate class file)</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*o-JaY_3sgTCYN5LYY4fS-w.png" /><figcaption>Figure 2 — Student Repositories</figcaption></figure><p>Now, some may ask why having these many classes and interfaces separately and not having them all wrapped within a single StudentRepository class which even could be implemented as a Generic one so that it would cover any other possible entity classes in the application. Well, that sounds like a good question but actually not a good practice, especially when it goes to an actual production level. Although this discussion goes out of the scope of this article, some of the reasons can be pointed out quickly. First and foremost, having all operations within one single repository class could violate the <a href="https://en.wikipedia.org/wiki/Single_responsibility_principle">SRP</a>. Besides, what would happen if our application requires more than just Create, Delete, and Update? Then, we would have to implement every single new operation within our very lengthy repository class which of course could bring all sorts of problems; from difficulties in unit testing to maintenance and anti-pattern problems.</p><p>Putting the above discussion aside, we now need to have our Web API Controller in which we write our Create, Update, and Delete actions that would execute the desired functionalities against our database. We will use Autofac for Web API in order to practice IoC in our program. For more information, please read through <a href="https://autofaccn.readthedocs.io/en/latest/integration/webapi.html">this website</a>.</p><p>So, let’s quickly see how to register our types using this IoC framework.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bNmIWsJkjh53-CtOkhsuBg.png" /><figcaption>Figure 3 — Global.asax.cs</figcaption></figure><p>Now that classes with their interfaces have been registered, we just need to inject them through the controller constructor and utilize them as needed. The controller class looks like the below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jbFDDNYHK0fdgs3DNa0vHQ.png" /><figcaption>Figure 4 — Student Controller with three objects injected into the constructor</figcaption></figure><p>And that’s it. These are all the basic participants in this scenario.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/337/1*B2BZRI1TvNaqnuTyXR3_AQ.jpeg" /></figure><h3>The Problem</h3><p>But, have you noticed the problem that already is there? Yes, that’s right — our controller now is very likely to extend and gets bigger as it may need to have more dependencies injected into its constructor (if not already enough). In a real application, this can easily happen and make every single controller more messy and lengthy. Another kind of problem here is that the very first component that our controller communicates with is our repository classes which from the design point of view is not like the best practice. Indeed, we better to have some handlers who actually would handle our incoming requests and pass them to any successor which in our case let’s say are the repository classes.</p><p>So the question is what ways are out there to avoid such a problem and always keeping our controllers as sexy and as thin as possible?</p><h3>The Solution</h3><p>One way that we will discuss in this article is to delegate the responsibility of processing the API requests into another component (or participant) and try to train that component to resolve the desired handler based upon the incoming request from the API. In this way, our Student Controller (or any other one in the program) would probably only depend on this newly joined component (processor) and the controller only needs to send the request out to this processor so that it will take care of the rest itself. That sounds cool so let’s see how we can implement this.</p><p>In order to step into the solution, we may need to firstly have a very basic understanding of the <a href="https://docs.microsoft.com/en-us/azure/architecture/patterns/cqrs">CQRS Pattern which stands for Command Query Responsibility Segregation</a>. Martin Fowler very well explained this at his website <a href="https://martinfowler.com/bliki/CQRS.html">here</a> but just to come up with an initial idea CQRS believes that the requests are either Commands or Queries. In our simple scenario, we can conclude that Delete, Update, and Create are basically the commands that the user can make and retrieve the data from the database would be our queries (if there was any).</p><p>But, how is this going to help us to make our controller in shape? Let’s begin with figuring out our command classes.</p><p><em>The Commands</em></p><p>Now that we have the concept of commands we need to reflect that in our codebase as well. According to what briefly mentioned above, we will have the following commands in our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ZA8RmZ77FsCEVsPyXIJGBg.png" /><figcaption>Figure 5 — The ICommand interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IEXURIcgNWAxoHOL_9BE5Q.png" /><figcaption>Figure 6 — Register New Student Command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SFmzW6EgO1Pzq9zs7Oh71w.png" /><figcaption>Figure 7 — Update Student Info Command</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0NHrXwVgeUzHFsln7UgzFg.png" /><figcaption>Figure 8 — Remove Student Command</figcaption></figure><p>So far so good! We have now some commands that are the actual requests coming from the users. But why not having public properties with usual get and set? Well, the answer commands are by nature messages which are immutable. Unfortunately, discussing this would go out of the context and that is why we may just better end it here. But, <a href="http://www.cqrs.nu/Faq/commands-and-events">this link</a> may come helpful to find out more about this reason.</p><p>These command classes are actually one of the factors based on which our aforementioned component would utilize in order to resolve the target handlers, which then, would invoke the desired repository to apply the command against the database. So, let’s have a look at our command handlers and how they should get implemented.</p><p><em>The Command Handlers</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*04eSXfeTHz0skuPhL63o4g.png" /><figcaption>Figure 9 — Command Handler Interface</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VRIFWB9LiiSTRPbkCI4BHg.png" /><figcaption>Figure 10 — Register New Student Command Handler</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HCj49jE1ngsLhU8jY7v22Q.png" /><figcaption>Figure 11 — Update Student Info Command Handler</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*lPR7Ei7r91yO_QJ485JWcA.png" /><figcaption>Figure 12 — Remove Student Command Handler</figcaption></figure><p>By this point, we have a new set of classes exposing our commands and command handlers. These are the ones that indeed should place between the repository and the controller class. But again, if we just try to replace them we would still have the problem of fatty controllers. This is when the other component comes in play which would be responsible to sit between our student controller and the actual command handlers so that our controller would be needless of having all the handlers injected.</p><p>In fact, the basic idea is for the controller to send out the command objects to this processor so that it will then resolve or find the associated handler according to the contract (the command handler interface) and would eventually ask the handler to take care of the request from that point on.</p><p>So, let’s see now how this command resolver would look like and that how we can implement this once only so it can deal with the future added handlers as well.</p><p><em>The Command Processor</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*enjAr31JJSnDgjovYZ6hcw.png" /><figcaption>Figure 13 — Command Processor responsible for resolving the handlers at runtime</figcaption></figure><p>Lovely!</p><p>We now have a processor that would be the middleware between the controller and handlers which is able to resolve the handlers (that all, of course, follow the command handler contract) using the powerful feature of .NET, <a href="https://docs.microsoft.com/en-us/dotnet/framework/reflection-and-codedom/reflection"><em>Reflection</em></a>.</p><p>Next is to first register our command handlers and the processors from within the Global.asax file and then to inject them directly into the student controller for further consumption. We just need to update the file in the following format.</p><p><em>The Global.asax</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m8fgrUqt_-8bM13ZHgpHBQ.png" /><figcaption>Figure 14 — Registering Handlers in Global.asax</figcaption></figure><p>Now, let’s see how different our controller would look like using this solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dbik7Df1oaRXWtR1IylaQ.png" /><figcaption>Figure 15 — Controller with only one dependency injected regardless of how many different actions it exposes</figcaption></figure><p>Beautiful isn’t it?! We can now add as many as commands and command handlers to our program and our new controller would be needless of knowing them and having every single of them injected into the constructor. This solution also somehow could be respecting the <a href="https://code.tutsplus.com/tutorials/solid-part-2-the-openclosed-principle--net-36600">Open Close Principle</a> which says a class should be open for extension but close to modification.</p><p>And that’s all about it!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=45acb45ba6f0" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-avoid-fat-controllers-in-asp-net-web-api-net-framework-45acb45ba6f0">How to avoid fat controllers in ASP.NET Web API (.net framework)</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>