<?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 M.Furkan ARDOĞAN on Medium]]></title>
        <description><![CDATA[Stories by M.Furkan ARDOĞAN on Medium]]></description>
        <link>https://medium.com/@fmardogan?source=rss-1435b85a3ffc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*Yd6haFkxISB2leXjQbHypg.jpeg</url>
            <title>Stories by M.Furkan ARDOĞAN on Medium</title>
            <link>https://medium.com/@fmardogan?source=rss-1435b85a3ffc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 03:56:42 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@fmardogan/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[Slow Pointer and Fast Pointer (aka SPFP) Algorithm in C++]]></title>
            <link>https://medium.com/@fmardogan/slow-pointer-and-fast-pointer-aka-spfp-algorithm-in-c-ac41c56d9c5f?source=rss-1435b85a3ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac41c56d9c5f</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[cplusplus]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[M.Furkan ARDOĞAN]]></dc:creator>
            <pubDate>Tue, 09 May 2023 15:22:10 GMT</pubDate>
            <atom:updated>2023-05-09T15:22:10.099Z</atom:updated>
            <content:encoded><![CDATA[<p>Today we are going to talk about what <strong>Slow Pointer and Fast Pointer</strong> (aka. <strong>SPFP</strong>) algorithm is. This algorithm is used to find whether or not there is a loop in a linked list. Also, it can be used to find the middle node of the list as well.</p><p>So, what is a loop actually? The Loop is an illegal connection which goes from the last one to another node inside a linked list. Normally, for a singly linked list, the last node must point to nothing. When a new node will be inserted, the last node is founded through a loop that starts with the head of the list and looks if the next one points nothing sequentially.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/605/1*QZg1-5sgYWM1ImAMifBOww.jpeg" /><figcaption>A legal linked-list structure.</figcaption></figure><p>If the last one has a pointer that points to one of the other elements inside the linked list, it cannot be said that the list is proper because of the impossibility of reaching the end of the list through a sequential way like for, or while loop. The given picture below illustrates an inappropriate linked list due to the loop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/734/1*mzhKiGkRp_qMP2yYkBSDnw.jpeg" /><figcaption>An illegal linked-list structure.</figcaption></figure><p>Supposing that you have a linked list just like above. How could you insert a new node to the end of the list? You can not! Because you will never find the end of the list!</p><p>Let’s have a linked list. There is a typical Linked list data structure below.</p><pre>template &lt;typename T&gt;<br>struct Node<br>{<br>   T data;<br>   Node&lt;T&gt; *next;<br>};<br><br>template &lt;typename T&gt;<br>class Iterator<br>{<br>   Node&lt;T&gt; *head;<br><br>public:<br>   Iterator(Node&lt;T&gt; *);<br><br>   T next();<br>   bool more() const;<br>};<br><br>template &lt;typename T&gt;<br>Iterator&lt;T&gt;::Iterator(Node&lt;T&gt; *head) : head(head)<br>{<br>}<br><br>template &lt;typename T&gt;<br>bool Iterator&lt;T&gt;::more() const<br>{<br>    return head != 0;<br>}<br><br>template &lt;typename T&gt;<br>T Iterator&lt;T&gt;::next()<br>{<br>   Node&lt;T&gt; *next = head;<br>   head = head-&gt;next;<br>   return next-&gt;data;<br>}<br><br>template &lt;typename T&gt;<br>class List<br>{<br>   Node&lt;T&gt; *head;<br><br>public:<br>   List();<br>   void add(T);<br>   bool hasALoop() const;<br>   Iterator&lt;T&gt; getIterator() const;<br>};<br><br>template &lt;typename T&gt;<br>List&lt;T&gt;::List() : head(0)<br>{<br>}<br><br>template &lt;typename T&gt;<br>void List&lt;T&gt;::add(T data)<br>{<br>   Node&lt;T&gt; *node = new Node&lt;T&gt;();<br>   node-&gt;data = data;<br>   node-&gt;next = 0;<br><br>   if (!head)<br>   {<br>      head = node;<br>      return;<br>   }<br><br>   Node&lt;T&gt; *iter = head;<br>   while (iter-&gt;next != 0)<br>   {<br>       iter = iter-&gt;next;<br>   }<br><br>   iter-&gt;next = node;<br>}<br><br>template &lt;typename T&gt;<br>Iterator&lt;T&gt; List&lt;T&gt;::getIterator() const<br>{<br>   Node&lt;T&gt; *temp = head;<br>   Iterator&lt;T&gt; iterator(temp);<br>   return iterator;<br>}<br><br>template &lt;typename T&gt;<br>bool List&lt;T&gt;::hasALoop() const<br>{<br>   // it is about to be given.<br>   return false;<br>}</pre><p>Linked list above is an ordinary linked list that has a few operations called <strong>add()</strong> which will put on a new node to the list and <strong>getIterator()</strong> which creates an iterator instance and return back it in order to take nodes inside the list entirely. Also, it has <strong>hasALoop()</strong> function that returns whether or not the list has a loop which can make us get tripped up. I can sincerely say that you must already know how a new node is added to a linked list. Because of this, I will focus only how an illegal loop can be detected. Now that we are ready, let’s look at how the <strong>SPFP</strong> algorithm is applied.</p><pre>template &lt;typename T&gt;<br>bool List&lt;T&gt;::hasALoop() const {<br>   Node&lt;T&gt; *slowPointer = head;<br>   Node&lt;T&gt; *fastPointer = head;<br><br>   for (auto i = 1; fastPointer;) {<br>      fastPointer = fastPointer-&gt;next;<br>      if (fastPointer == slowPointer) {<br>         return true;<br>      }<br><br>      if (!(i++ % 2)) {<br>         slowPointer = slowPointer-&gt;next;<br>      }<br>   }<br>   return false;<br>}</pre><p>Supposing you are walking around the linked list sequentially. The fast pointer jumps to the other one every step while the slow pointer jumps to the other one in two steps. If there is a loop in the list the fast one will be catching the slow one. After that, all you have to do is test your application like below.</p><pre>#include &quot;List.cpp&quot;<br>#include &lt;iostream&gt;<br>using namespace std;<br><br>int main()<br>{<br>    List&lt;int&gt; li;<br>    li.add(1);<br>    li.add(2);<br>    li.add(3);<br><br>    auto message = li.hasALoop()<br>         ? &quot;It has a loop!\n&quot;<br>         : &quot;It has no loop...\n&quot;;<br><br>    cout &lt;&lt; message;<br><br>    return 0;<br>}</pre><p>Thanks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac41c56d9c5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Alternative Classes With Different Interfaces &]]></title>
            <link>https://medium.com/@fmardogan/alternative-classes-with-different-interfaces-bff8f8c22d22?source=rss-1435b85a3ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/bff8f8c22d22</guid>
            <category><![CDATA[adapter-pattern]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[M.Furkan ARDOĞAN]]></dc:creator>
            <pubDate>Sat, 08 Apr 2023 02:47:08 GMT</pubDate>
            <atom:updated>2023-04-08T02:57:56.380Z</atom:updated>
            <content:encoded><![CDATA[<h3>Alternative Classes With Different Interfaces</h3><p><strong>Alternative Classes With Different Interfaces</strong> which is a code smell described in <em>Martin Fowler’s Refactoring</em> <em>Book </em>occurs when similar classes have different interfaces. As we can understand easily by its name this code smell is about the client side’s increasing Coupling level as the client side have to know two or more abstraction types in order to use the classes which treat substantially the same.</p><p>This code smell occurs when a programmer wants to put it something on the system but he or she couldn’t notice that the system already has the completely or substantially the same thing. If there are two or more abstractions that have the same behavior completely you might as well remove others since one is enough. Nonetheless, seeing that the abstractions may not have the same behaviors completely, it is not easy to remove one of them immediately. Let’s have a look at the example below.</p><pre>//Code smell:<br><br>interface ICollection&lt;T&gt; {<br>    void Sort();<br>    void Add(T item);<br>    void Remove(T item);<br>}<br><br>class MyCollection : ICollection&lt;int&gt; {<br><br>    private List&lt;int&gt; numbers;<br><br>    public MyCollection() {<br>        numbers = new List&lt;int&gt;();<br>    }<br><br>    public void Add(int item) {<br>        numbers.Add(item);<br>    }<br><br>    public void Remove(int item) {<br>        numbers.Remove(item);<br>    }<br><br>    public void Sort() {<br>        numbers.Sort();<br>    }<br>}<br><br>/* <br> There are two interfaces to do something that is aproximately the same.<br> This is a code-smell which is called Alternative Classes With Different Interfaces <br> that makes client-sides more stressed. <br>*/<br><br>interface ICluster&lt;T&gt; {<br><br>    void Add(T item);<br>    void Remove(T item);<br>}<br><br>class MyCluster : ICluster&lt;int&gt; {<br><br>    private List&lt;int&gt; numbers;<br><br>    public MyCluster() {<br>        numbers = new List&lt;int&gt;();<br>    }<br><br>    public void Add(int item) {<br>        numbers.Add(item);<br>    }<br><br>    public void Remove(int item) {<br>        numbers.Remove(item);<br>    }<br>}</pre><p>So which one ought to be removed and how could you decide? As it has been mentioned before if there are two interfaces or classes which have the same sign completely one of them is able to be removed instantly. But most of time whatever kind of refactoring you are doing, it is not as easy as you have thought. Actually, ignoring something that is a code smell is easy by comparison with thinking about how could I get rid of it. Considering the example above either<strong> ICollection&lt;T&gt;</strong> or <strong>ICluster&lt;T&gt;</strong> has to be removed in order to make the system more simple. So, which one?</p><h3>The Interface Seggregation Principle(ISP)</h3><p><strong>Interface Seggregation Principle(ISP)</strong> recommends programmers to have interfaces that are atomic and focused only just one thing to do since interfaces forces to class that implements it to have all functionalities on the interface’s signature. If the interface has not been sliced according to Interface Segregation Principle, classes may have to implement some functionalities that are not needed by them. This kind of functionalities are called <strong>Dummy Functions</strong>.</p><p>Have you noticed? The main problem is that <strong>ICollection&lt;T&gt;</strong> interface violates the ISP principle as it has both basic operations such as <strong>Add </strong>or <strong>Remove </strong>and the <strong>Sort </strong>function which has a different purpose. Firstly we have to find a way to get rid of this violation as all classes that implemented this interface may not have the <strong>Sort()</strong> functionality. (See alto <strong>Refused Baquest</strong>.)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/376/1*uyBQLFKMFGShwIHQHWKCkA.jpeg" /></figure><pre>//Refactoring:<br><br>interface ICollection&lt;T&gt; {<br>   //void Sort(); =&gt; REMOVED<br>    void Add(T item);<br>    void Remove(T item);<br>}<br><br>interface ISotingCollection {<br>    void Sort();<br>}<br><br>class MyCollection : ICollection&lt;int&gt;, <br>                    ISotingCollection<br>{<br>   private List&lt;int&gt; numbers;<br><br>   public MyCollection() {<br>       numbers = new List&lt;int&gt;();<br>   }<br><br>   public void Add(int item) {<br>       numbers.Add(item);<br>   }<br><br>   public void Remove(int item) {<br>       numbers.Remove(item);<br>   }<br><br>   public void Sort() {<br>       numbers.Sort();<br>   }<br>}<br><br><br><br>class MyCluster : ICollection&lt;int&gt;<br>{<br>   private List&lt;int&gt; numbers;<br><br>   public MyCluster() {<br>       numbers = new List&lt;int&gt;();<br>   }<br><br>   public void Add(int item) {<br>       numbers.Add(item);<br>   }<br><br>   public void Remove(int item) {<br>       numbers.Remove(i);<br>   }<br>}</pre><p>To apply ISP, we created a new interface which is called <strong>ISortingCollection </strong>and moved the <strong>Sort()</strong> function from <strong>ICollection&lt;T&gt;</strong> to it. Since <strong>MyCollection </strong>should lose nothing we implemented both <strong>ICollection&lt;T&gt;</strong> and <strong>ISortingCollection </strong>together to the class. Seeing that we got rid of the interface which was not necessary and repaired the other one according to the ISP both <strong>MyCollection </strong>and <strong>MyCluster </strong>classes are allowed to implement the same interface. This is a more accurate approach than the previous one.</p><p>Sometimes you are not allowed to slice interfaces that are used by your solution as they may come from another library. In this case, the <strong>Adapter </strong>pattern will be favorable. Let’s have a look two libraries below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/1*YrCCoXERQWdEpNgg1b2lWA.jpeg" /></figure><p>Supposing that you have your own <strong>ICollection </strong>interface and <strong>MyCollection </strong>class which has implemented <strong>ICollection</strong>. As they have been written by you you have great control over them unlike the others in the external library. The <strong>ICluster </strong>and <strong>MyCluster </strong>were written by another programmer and packaged into a library that is being used in your solution. In this case, your solution still has the code smell named <em>Alternative Classes With Different Interfaces</em>. Moreover, how could you make the external library’s interface or class fit your solution? Will you use type checking or function overloading? Type checking is one of the devil’s damn which violates the <strong>Open-closed Principle(OCP)</strong> by killing Polymorphism. Or even though function overloading is a better solution than type checking it is an Ad-hoc polymorphism that should not be preferred when we have a solution that is fully fits to object-oriented programming philosophy. Let’s have a look a two silly solutions.</p><pre>//The worst approach that you have to avoid.<br><br>static void ForEach(object coll)<br>{<br>      var type = coll.GetType();<br>      if (type == typeof(ExternalLibrary.ICluster&lt;&gt;))<br>      {<br>         //do something<br>      }<br>      else if (type == typeof(ICollection&lt;&gt;))<br>      {<br>         //do something<br>      }<br>}</pre><p>This approach not only violates the <strong>Open-Closed Principle</strong> but also causes another kind of code smell since whenever a new type has been put into the system or one of the current types must be removed you would have to change this function by adding or removing the conditions. So, what could we do anything else?</p><pre>//A bit better but still a bad solution.<br>static void ForEach&lt;T&gt;(ICollection&lt;T&gt; coll)<br>{<br>    //do something<br> }<br><br>static void ForEach&lt;T&gt;(ExternalLibrary.ICluster&lt;T&gt; coll)<br>{<br>    //do something<br>}</pre><p>Function overloading demonstrates a different kind of polymorhism which is called <strong>Ad-hoc </strong>polymorhism. It seems like a better solution. Yes, it is better only when it is compared with the previous one. Just because you have used favorable compiler magic it does not mean the best solution you have. Think to yourself, is this class still open to be changed?</p><h3>The best solution is Adapter Pattern.</h3><p>The adapter is a structural <strong>Gof </strong>design pattern that makes something fit that is inappropriate to the current system. The pattern is a wrapper for the foreign system which is not appropriate.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/292/1*DAIvc-fdc5Ycs6Odd0-uug.jpeg" /></figure><p>Seeing that the <strong>ICluster </strong>interface is the piece that does not fit the current system, the Adapter class will be wrapping it while it implements the <strong>ICollection </strong>interface. As it implements the <strong>ICollection </strong>interface it is going to fully fit the current system.</p><pre>class MyClusterAdapter : ICollection&lt;int&gt; {<br><br>   private ExternalLibrary.ICluster&lt;int&gt; cluster;<br><br>   public MyClusterAdapter(<br>        ExternalLibrary.ICluster&lt;int&gt; cluster) <br>   {<br>       this.cluster = cluster;<br>   }<br><br>   public void Add(int item) {<br>       cluster.Add(item);<br>   }<br><br>   public void Remove(int item) {<br>       cluster.Remove(item);<br>   }<br>}</pre><p>Let’s use the adapter.</p><pre>class Program {<br><br>    static void ForEach(ICollection&lt;int&gt; collection) { <br>         /*<br>            Do something.<br>          */<br>    }<br><br>    static void Main(string[] args) {<br><br>        ExternalLibrary.MyCluster cluster = <br>                       new ExternalLibrary.MyCluster(); <br>       //3rd library’s class. The class that has been written by another developer.<br><br>        /* ERROR! <br><br>           DoWork(cluster); // MyCluster does not implement ICollection&lt;int&gt;!<br>         */<br><br>        MyClusterAdapter adapter = new MyClusterAdapter(cluster); //Adapter<br>        adapter.Add(1);<br>        adapter.Add(3);<br><br>        DoWork(adapter); //It’s OK..<br><br>        MyCollection collection = new MyCollection(); <br>       // The class that has been written by us. <br>        collection.Add(0);<br>        collection.Add(2);<br>        <br>        DoWork(collection); //It’s OK.<br>   }<br>}</pre><p>As you can see, in this case, we have only one ForEach function that does not make silly things such as checking.</p><p>Good luck =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bff8f8c22d22" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why programmers should avoid using static methods directly as much as possible?]]></title>
            <link>https://medium.com/@fmardogan/humble-object-pattern-7bb7da7a13f4?source=rss-1435b85a3ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/7bb7da7a13f4</guid>
            <category><![CDATA[humble-object-pattern]]></category>
            <category><![CDATA[static-cling]]></category>
            <category><![CDATA[hollywood-principle]]></category>
            <category><![CDATA[clean-code]]></category>
            <category><![CDATA[explicit-dependencies]]></category>
            <dc:creator><![CDATA[M.Furkan ARDOĞAN]]></dc:creator>
            <pubDate>Tue, 04 Apr 2023 22:23:12 GMT</pubDate>
            <atom:updated>2023-04-05T21:14:41.735Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IlQ4d7ykOyU0X_3lg-QjZA.jpeg" /><figcaption>Test driven development (Image has been taken from icomobile.com)</figcaption></figure><p>Nowadays, Programmers are more conscious than they used to be about creating more accurate software source codes. Especially working with an object-oriented programming language, there are many different design patterns or development principles that help us in order not face a big ball of mud. Oh! A big ball of mud. Whether or not you have heard this idiom so far is not important. As you can understand, a big ball of mud refers to having such a software solution as bad as nobody could understand or want to work on it. Moreover, while working on such software solutions programmers generally face stubborn difficulties when they try to add a new feature or modify an existing one and even they want to mend something. Unfortunately, so software application development is a continuous process that has been changed and improved from start to end, this situation is against the nature of software development. Most software projects are not able to continue because of bad design or poor source code quality. So every programmer must think about how this trouble can be got a rid of.</p><p>Today we will be discussing static objects and why programmers should avoid them and I am to write something that is about the <strong>Humble Object Pattern</strong> which is one of the important unit testing patterns.</p><h3>What is Static Object?</h3><p>Static objects are objects that we can use without creating an instance from them and a static class will have just a single instance during application life that can be used everywhere. Static objects are constructed once and the instance constructed is not destroyed unless the application is closed. We don’t have a trouble compiler or memory management side, as a matter of fact, there are a great number of programming languages that support static objects. But it is a known fact that using static objects causes some problems especially while unit tests are being written.</p><p><em>Simply, static objects are direct dependencies. That static classes can not be used within an abstraction level is one of the most considerable drawbacks against having clean and loose coupled software solutions.</em></p><p>Robert C. Martin recommends you prefer having non-static methods to static classes when you stay in a dilemma. <strong>The best way to decide whether or not a method behaves as static is by looking at its polymorphic situation.</strong> <strong>If the method has a probability of behaving polymorphic it mustn’t be static.</strong> For example, it is very clear that <strong>Math.Ceiling(decimal d)</strong> will never behave as polymorphic. Owing to the fact that whenever or however you use it you take the same result, there is no point having dozens of object instances from it. So, it is able to make static. But suppose that you are working on an application that has a set of complex tax calculations, according to you is it correct to use a static method for a calculation like <strong>Tax.CalculateTax(&lt;params&gt;)</strong>? Since most of tax calculations have a robust probability of behaving polymorhic, such a method must not be made static. (See also <strong>Static Cling</strong>.)</p><h3>Why programmers should avoid using static methods directly as much as possible?</h3><p>Don’t get me wrong! I’m not the biggest enemy of static methods besides I have been using static methods or entirely static classes which contain a few static methods for a long while. As I mentioned before as long as you decide correctly if or not the method should be static there is no problem. Moreover, you don’t face a problem on condition that you use a static method which doesn’t have to get isolated while testing such as <strong>Math.Pow(&lt;Params&gt;)</strong>, <strong>Guid.NewGuid()</strong> etc.</p><p><em>i. Static methods cause direct coupling. It means using static methods increases the Coupling level and makes the client-side dependent directly on the class which includes the static method. So, static methods or </em><strong><em>Singleton </em></strong><em>classes have the potential they may make our life harder.</em></p><p><em>ii. When you write a unit test for the SUT(</em><strong><em>System Under Test</em></strong><em>) which has used static methods, you won’t be able to isolate the static dependencies by mocking(</em><strong><em>Test Double</em></strong><em>) as it can not be created a mock object from static classes or the implicit dependency level. In spite of the fact that there are ways to replace dependencies at run-time, these ways are just methods to treat the symptoms.</em></p><blockquote>Do not use static or Singleton classes directly. Instead prefer normal classes that are injected as Singleton by <strong>Dependency Injection</strong>. Thus you not only get rid of a high coupling level but also keep your class’ dependencies isolable entirely according to <strong>Explicit Dependencies Principle</strong>.</blockquote><pre>//Code smell:<br>class PaymentService {<br><br>  public void Handle(Payment payment)  <br>  {<br>       // 1.) Do work.<br>       // 2.) Make log.<br><br>      Logger.Save(payment); <br>      /* STATIC! It is a hidden dependency which can <br>         not be isolated while testing. */<br>  }<br>}</pre><p>Because of <strong>Logger.Save</strong> method, the <strong>PaymentService </strong>class is directly dependent on the <strong>Logger </strong>class. This situation is called <strong>Direct Coupling/Dependency</strong> which is one of the important design problems that every programmer should avoid. In this case, the <strong>PaymentService </strong>class is open to get affected by the changes that come from the <strong>Logger </strong>class. What’s more, while unit tests are being written for the <strong>PaymentService</strong>, the <strong>Logger </strong>dependency can not be isolated as it’s an implicit dependency. (See also <strong>Explicit Dependencies Principle.</strong>) Since isolation is vital for unit testing, it is very clear that the static method may cause a considerable setback for your application’s health.</p><p>Let me make some refactoring on the previous one in order to make it easier to write unit tests and get rid of tight coupling.</p><pre>//Refactoring:<br>class PaymentService {<br><br>   private ILogger logger;<br><br>   public PaymentService(ILogger logger) { <br>        /* It is an explicit dependency <br>            which can be isolated while testing. */<br><br>       this.logger = logger;<br>   }<br><br>   public void Handle(Payment payment) {<br><br>       // 1.) Do work.<br>       // 2.) Make log.<br><br>       logger.Save(payment);  //NON-STATIC!<br>   }<br>}</pre><p>Application has been mended according to <strong>Dependency Inversion Principle</strong>. This principle recommends that high-level components should never be directly dependent on low-level components. Instead of direct coupling high-level classes must know low-level class abstractions like <strong>ILogger </strong>which is an interface (or it may be an abstract class). Thus, the high-level service class is not open to get be affected by changes that occur on real components. On the other hand, this refactoring not only applies <strong>Dependency Inversion</strong> but also applies the <strong>Explicit Dependencies Principle</strong>. Because of explicit dependencies, the <strong>ILogger </strong>dependency is able to be isolated from SUT while unit tests are being written. (See also <strong>Hollywood Principle</strong>.) Let’s see by writing a unit test.</p><pre>public class PaymentServiceTests {<br><br>   [Fact]<br>   public void Should_do_anything() {<br><br>       //arrange<br>        var mock = new Mock&lt;ILogger&gt;();<br>        mock.Setup(x =&gt; x.Save(It.IsAny&lt;Payment&gt;()));<br><br>        var service = new PaymentService(mock.Object); //isolation<br><br>        //act <br>          <br>        //assert<br>   }<br>}</pre><p>One of the most important rules of unit testing is having a solid isolation that provides focusing only on SUT. If you are not able to isolate SUT’s dependencies well enough from its own while testing, the orientation of the unit test leaves SUT’s core behaviors and proceeds toward its dependencies. One of the biggest problems in using static classes is that it is impossible to create a test double from them.</p><pre>public static class Alpha<br>{<br>    public static string DoWork()<br>    {<br>        return &quot;static&quot;;<br>    }<br>}<br><br>public class Tests<br>{<br>     [Fact]<br>     public void Should_return_a_string()<br>     {<br>         /* Wrong! Static types, cannot be a generic type parameter! */<br><br>         var mock = new Mock&lt;Alpha&gt;();  //ERROR!<br>     }<br>}</pre><p>But sometimes using static classes or methods is inevitable. Both because of a library that it must be used by your application and because of an extraordinary situation you may have had to use them. Thanks to the <strong>Humble Object Pattern</strong>, you can both use static methods or classes and keep your application testable.</p><h3>Humble Object Pattern</h3><p>Humble Object Patterns is a software design model that provides writing a unit test easily for a SUT which is hard to be tested or impossible. In this model SUT which is impossible or hard to be tested is wrapped by another class. The wrapper class is a proxy for the SUT that shows the same behavior entirely or partially.</p><pre>//You can not create a test double from it: <br>public static class Alpha<br>{<br>    public static string DoWork()<br>    {<br>        return &quot;static&quot;;<br>    }<br>}<br><br>//You can create a test double from it:<br>public interface ISomeApi<br>{<br>    string DoWork();<br>}<br><br>/* Also Dependency injection can be used: */ <br><br>class Proxy : ISomeApi //Humble Object.<br>{<br>    public string DoWork()<br>    {<br>        return Alpha.DoWork();<br>    }<br>}</pre><p>By using Humble Object Pattern you make it possible to test either too-big classes or classes that have static dependencies. The Proxy class above which has the same behavior by calling the <strong>Alpha.DoWork()</strong> is a wrapper for the Alpha class. But unlike the Alpha class, it has an abstraction level. So, it is a more precise and accurate solution inasmuch as it is able to be used with Dependency Injection or can be mocked. The <strong>Alpha </strong>class ought to no longer be used directly, instead we are going to use <strong>ISomeApi </strong>with Dependency Injection’s help and while testing we are to create a test double from the <strong>ISomeApi</strong>.</p><pre>public class Tests<br>{<br>     [Fact]<br>     public void Should_return_a_string()<br>     { <br>         var mock = new Mock&lt;ISomeApi&gt;();<br>         mock.Setup(e =&gt; e.DoWork())<br>                           .Returns(<br>                               &quot;Mock test&quot;<br>                                   );<br><br>         string val = mock.Object.DoWork();<br>         Assert.Equal(&quot;Mock test&quot;, val);<br>     }<br>}</pre><p>My example above has shown how to deal with static objects by using the Humble Object pattern for a comfortable unit testing environment. I have shown how to protect a class that as it was static is able to cause increasing coupling level and while testing it is not able to be replaced with test doubles. Good luck =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7bb7da7a13f4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Chain Of Responsibility design pattern with Kotlin example.]]></title>
            <link>https://medium.com/@fmardogan/chain-of-responsibility-df3d32f31cde?source=rss-1435b85a3ffc------2</link>
            <guid isPermaLink="false">https://medium.com/p/df3d32f31cde</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[chain-of-responsibility]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[M.Furkan ARDOĞAN]]></dc:creator>
            <pubDate>Sun, 02 Apr 2023 13:00:55 GMT</pubDate>
            <atom:updated>2023-04-02T13:23:16.040Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Chain Of Responsibility(CoR) </strong>is a behavioral design pattern. The design pattern I have used mostly is Chain Of Responsibility owing to the fact that it helps us to achieve one of the most important goals in the programming world: “The more atomic pieces, the more managementable source codes”.</p><p>Most of systems consist subsystems which talk one another. Every subsystems has its responsibilities and they just do their responsibility correctly. When that subsystem are collected an engineering system rises that makes our life easier.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/685/1*PoG7HmRoqCs-ZotCKVMatA.jpeg" /></figure><p>A typical chain of responsibility pattern is visualized above. As you can see, the system consists of three duties(it can be more). But client side does not have to struggle to understand how the system works entirely. Rather than knowing all details of the system, client side just demands to process from a closed box. When the closed box receives a request, all of subsystems are worked by the previous one sequentially. I mean every ring on the chain do its own responsibilities firstly and than calls the next one which is linked through <strong><em>bind(next: Compiler)</em></strong> function.</p><p>Have you ever thought about <strong>Linked List</strong> data structure? Not only you may have thought but also write an example from it or even you have used it on a real project. If you have an expereince with Linked List, it may be easier to understand what logic we carried while we are establishing a chain of responsibility. Sub systems that covered by the parent which is called chain of responsibility, are linked one another through a pointer(or you say a class instance). Each subsystems know only the another subsystem that is next to it.</p><p>A few benefits of using Chain of Responsibility are given below:</p><p>· It isolates a component’s complex details from the client side.</p><p>· It provides a wide area to apply the Single Responsibility Principle.</p><p>· It both reduces Coupling and increases Cohesion level.</p><p>· It provides reusable components that are atomic and entirely dedicated to a single task.</p><p>As we are software developers, probably most of us have some information about how source code is built. As we all know, source code is compiled by a compiler which is a special and low-level application that has been created to transform source codes into another form.</p><blockquote>The closer the source code is to human perception, the farther it is to computer perception. So, every source code needs to be compiled to a machine language(or an interpreted language) in order to work on a physical device.</blockquote><p>Don’t worry! I will not be driving deep into the compilers like automata theory. Actually these topics neither relevant to this book, nor you have to have a strong knowledge base about them to create robust software applications. We are going to create just a real world applications that simulate a compiler and its subsystems in order to understand what Chain of Responsibility is and how it is used.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/769/1*yoloS1JRQJisbvGpM5USIA.jpeg" /></figure><p>As a programmer we very often compile source code. Maybe thousand of thousand of thousand times in a day. But, as we can see in the picture above, compiling is not a simple process. In spite of the fact that compiling is a really hard and complex process, we don’t have to think about it. Instead of struggling with complex details of compiling, we just demand from compiler. An ordinary compiler has subsystems that are shown above. They all have different responsibilities and act different roles while source code are being compiled. One of the important points that should be known is that the compiler’s subsystems are worked sequentially. Also the Chain of Responsibility pattern has the same principle.</p><p>We have been just talking for a long while, let me cut to the chase. You may have confused but once you write the example which will be given, you won’t have any trouble. Now that you have been reading about compilers since you just came to this unit, we might as well create a <strong>Kotlin </strong>application that simulates a compiler through Chain of Responsibility pattern. A few moments later everything will be brighter than they used to be.</p><p>Let’s start with a Compiler class which is the parent class of subsystems.</p><pre>abstract class Compiler {<br>    /* The base class has a member which is the same type of own<br>       in order to handle the next one of the chain. (See also <br>       &#39;Linked list&#39;) */<br><br>    protected var next: Compiler? = null<br><br>    fun bind(next: Compiler): Compiler {<br><br>        this.next = next;   //See also Fluent Interface pattern.<br>        return this;<br>    }<br><br>    abstract fun handle()<br>}</pre><p>It is so important for the parent class to have a member which is the same type of its own that the Chain of Responsibility pattern can not be established without it. Because the member holds the current subsystem’s next subsystem reference. So, from start to end all rings that are available on the chain are linked sequentially.</p><pre>class LexicalAnalyzer : Compiler() {<br>    override fun handle() {<br>        println(&quot;The lexical analysis is being made...&quot;)<br><br>        next?.handle()<br>        <br>    /* It is so important to proceed the next one after current task <br>       is finished. Thus, client side won&#39;t have to think about   <br>       which one must be called now! */<br>    }<br>}<br><br>class IntermediateCodeGenerator : Compiler() {<br>    override fun handle() {<br>        println(&quot;The intermediate code is being produced...&quot;)<br>        next?.handle()<br>    }<br>}<br><br>class TargetCodeGenerator : Compiler() {<br>    override fun handle() {<br>        println(&quot;The target code has been produced...&quot;)<br>        next?.handle()<br>    }<br>}</pre><p>In order to save some paper and make my example easier, I did not create a class for all of a compiler’s subsystems. Three pieces is enough! All of pieces extend the <strong><em>Compiler </em></strong>class and they implement the <strong><em>handle()</em></strong> function where the subsystem’s responsibilities must be written. Responsibilities applied by derived classes must be atomic and reusable. (See also <strong><em>Single Responsibility Principle</em></strong>). For our example the responsibilities are only printing some text to the console window that shows us what happens.</p><pre>fun main(args: Array&lt;String&gt;) {<br><br>    val compiler: Compiler = LexicalAnalyzer().bind(<br>        IntermediateCodeGenerator().bind(<br>            TargetCodeGenerator()<br>        )<br>    ).also { it.handle() }<br>}<br><br>/* OUTPUT:<br>  The lexical analysis is being made...<br>  The intermediate code is being produced...<br>  The target code has been produced...<br> */</pre><p>All you have to do is create instances from classes and link them one another with a correct sequence. When you call the <strong><em>handle() </em></strong>function from the variable, all rings on the chain will be executed. So, multiple operations which are a part of the big one will be made without causing complexity. And also, we can use those classes separately as much as we need. Or we are able to change the sequence of the classes on the chain easily to have a different result. This approach is a reusable solution as much as it applies to the <strong><em>Single Responsibility Principle</em></strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/606/1*azS2sRiqnClm4lvvhX2fCg.jpeg" /></figure><p>Good luck :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=df3d32f31cde" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>