<?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" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ object oriented - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ object oriented - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Sun, 17 May 2026 11:36:25 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/object-oriented/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ A Guide to Object-Oriented Programming Principles ]]>
                </title>
                <description>
                    <![CDATA[ A programming language is generally classified based on its support for one or more paradigms.  Object-oriented programming is one such paradigm, where the code is organized as objects.  It is used to develop desktop and mobile applications or more c... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-guide-to-object-oriented-programming-principles/</link>
                <guid isPermaLink="false">66ba1ab52ab35c1de21292f8</guid>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Anjan Baradwaj ]]>
                </dc:creator>
                <pubDate>Tue, 18 Jun 2024 09:13:37 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/06/oop-principles.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>A programming language is generally classified based on its support for one or more paradigms. </p>
<p>Object-oriented programming is one such paradigm, where the code is organized as objects. </p>
<p>It is used to develop desktop and mobile applications or more complex web or enterprise applications. </p>
<p>Using object-oriented programming, you can build modular and scalable software that is easy to maintain.</p>
<p>In this article, you will learn about the principles of object-oriented Programming that lay the foundation for building robust systems. </p>
<p>We will use Java as the programming language for the examples provided below.</p>
<h2 id="heading-what-is-object-oriented-programming">What is Object-Oriented Programming?</h2>
<p>Object-Oriented Programming is a programming methodology that models real-world entities in the form of objects. </p>
<p>These objects are instances of classes. </p>
<p>A class can be thought of as a blueprint and each class can contain fields, which define the attributes of the object, and methods, which describe the object's behavior. Each class can be developed, tested, and debugged independently.</p>
<p>Now that you have an understanding of the basic definition of object-oriented programming, let us jump right in and learn about its core principles.</p>
<p>There are four core principles, or pillars, in the object-oriented Programming paradigm. They are:</p>
<ul>
<li>Abstraction</li>
<li>Encapsulation</li>
<li>Inheritance</li>
<li>Polymorphism</li>
</ul>
<p>What do they mean? Let us explore further with a simple explanation followed by an example for each of them in the following sections.</p>
<h2 id="heading-what-is-abstraction">What is Abstraction?</h2>
<p>Abstraction is defined as the concept of hiding the details of implementation and exposing only the necessary functionalities of the object to the user. </p>
<p>The keywords that you need to keep in mind here are: 'Implementation hiding'. </p>
<p>Abstraction in Java can be achieved through Interfaces and Abstract classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Bark"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Dog myDog = <span class="hljs-keyword">new</span> Dog();
        myDog.makeSomeNoise(); <span class="hljs-comment">// Output - Bark</span>
    }
}
</code></pre>
<p>In the above example, abstraction is achieved with the help of an abstract class named <code>Animal</code>. </p>
<p>Here, only the necessary functionality of the class is exposed via the <code>makeSomeNoise()</code> method. </p>
<p>The details of implementation are hidden in the abstract class and they are only provided in the concrete class <code>Dog</code>, which extends the <code>Animal</code> class. </p>
<p>Note that you will learn more about the <code>extends</code> keyword while we discuss Inheritance.</p>
<h2 id="heading-what-is-encapsulation">What is Encapsulation?</h2>
<p>Encapsulation refers to the concept of encapsulating or wrapping up the member variables (data) and the methods (behavior) of an object into a single unit, such as a class. </p>
<p>The internal information of the object is hidden so that we can prevent unintended modifications and allow only controlled access. The keywords that you need to keep in mind here are: 'Information hiding'.</p>
<p>Encapsulation in Java is achieved through access modifiers. We mark the fields as <code>private</code> and make them accessible via public setter and getter methods.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Person</span> </span>{
    <span class="hljs-keyword">private</span> String name;
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> age;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Person</span><span class="hljs-params">(String name, <span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getName</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setName</span><span class="hljs-params">(String name)</span> </span>{
        <span class="hljs-keyword">this</span>.name = name;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">getAge</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">setAge</span><span class="hljs-params">(<span class="hljs-keyword">int</span> age)</span> </span>{
        <span class="hljs-keyword">this</span>.age = age;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">display</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Name: "</span> + name + <span class="hljs-string">", Age: "</span> + age);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Person person = <span class="hljs-keyword">new</span> Person(<span class="hljs-string">"Raj"</span>, <span class="hljs-number">30</span>);
        person.display(); <span class="hljs-comment">// Output - Name: Raj, Age: 30</span>

        person.setName(<span class="hljs-string">"Kumar"</span>);
        person.setAge(<span class="hljs-number">25</span>);
        person.display(); <span class="hljs-comment">// Output - Name: Kumar, Age: 25</span>
    }
}
</code></pre>
<p>In the above example, the fields and methods are encapsulated within a class named <code>Person</code>. </p>
<p>You declare the fields <code>name</code> and <code>age</code> as <code>private</code> and provide public setter and getter methods <code>getName()</code>, <code>setName()</code>, <code>getAge()</code>, and <code>setAge()</code> to modify the values as needed. </p>
<h2 id="heading-what-is-inheritance">What is Inheritance?</h2>
<p>Inheritance establishes a hierarchical relationship between two classes. </p>
<p>In this concept, one class inherits the fields (properties) and methods (behavior) of another class, while having properties and behavior of its own. </p>
<p>The class that inherits from another is called a subclass, derived class, or child class. The class from which the subclass inherits is known as the superclass, base class, or parent class. </p>
<p>In Java, inheritance is achieved using the <code>extends</code> keyword.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span></span>{
        System.out.println(<span class="hljs-string">"Make some animal noise"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Bark"</span>);
    }
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">doSomething</span><span class="hljs-params">()</span></span>{
        System.out.println(<span class="hljs-string">"Play with ball"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Dog myDog = <span class="hljs-keyword">new</span> Dog();
        myDog.makeSomeNoise(); <span class="hljs-comment">// Output - Bark</span>
        myDog.doSomething(); <span class="hljs-comment">// Output - Play with ball</span>
    }
}
</code></pre>
<p>In the above example, the <code>extends</code> keyword indicates that the <code>Dog</code> class is the subclass of the <code>Animal</code> class. </p>
<p>The <code>Dog</code> class inherits the <code>makeSomeNoise()</code> method from the <code>Animal</code> class. This allows the <code>Dog</code> class to reuse the method and provide its own implementation without having to rewrite it completely. </p>
<p>You can also note that the <code>Dog</code> class has its own behavior through the <code>doSomething()</code> method. </p>
<p>Inheritance defines an "IS-A" relationship between the two classes. In our example, Dog IS-A Animal.</p>
<p>Note that Java supports multi-level inheritance. For example, <code>class Labrador</code> inherits from <code>class Dog</code>, which in turn inherits from <code>class Animal</code>. However, it does not support multiple inheritance. That is, a class is not allowed to inherit from two or more parent classes.</p>
<h2 id="heading-what-is-polymorphism">What is Polymorphism?</h2>
<p>Poly (many), morph (forms). </p>
<p>Polymorphism defines the capability of an object to be represented in different forms. </p>
<p>In Java, polymorphism can be categorized into two types: compile-time polymorphism and runtime polymorphism.</p>
<p>Compile-time polymorphism is achieved through method overloading – multiple methods have the same name but different type or number of parameters.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MathOperation</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b)</span> </span>{
        <span class="hljs-keyword">return</span> a + b;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> <span class="hljs-title">add</span><span class="hljs-params">(<span class="hljs-keyword">int</span> a, <span class="hljs-keyword">int</span> b, <span class="hljs-keyword">int</span> c)</span> </span>{
        <span class="hljs-keyword">return</span> a + b + c;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        MathOperation math = <span class="hljs-keyword">new</span> MathOperation();
        System.out.println(math.add(<span class="hljs-number">95</span>, <span class="hljs-number">5</span>));       <span class="hljs-comment">// Output - 100</span>
        System.out.println(math.add(<span class="hljs-number">75</span>, <span class="hljs-number">5</span>, <span class="hljs-number">20</span>));   <span class="hljs-comment">// Output - 100</span>
    }
}
</code></pre>
<p>In the above example, we have overloaded the <code>add()</code> method. There are two methods with the same name <code>add</code> but they have different number of parameters. </p>
<p>During compilation, based on the number of parameters passed to the method, the appropriate call is made.</p>
<p>Runtime polymorphism is achieved through method overriding – a subclass has a method with the same name and same set of parameters as that of its superclass method. However, it provides its own implementation of the method. </p>
<p>Here, the method resolution happens at runtime.</p>
<pre><code class="lang-java"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Make some animal noise"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Dog</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Barks"</span>);
    }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Cat</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Animal</span> </span>{
    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">makeSomeNoise</span><span class="hljs-params">()</span> </span>{
        System.out.println(<span class="hljs-string">"Meows"</span>);
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Main</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Animal myAnimal; 

        myAnimal = <span class="hljs-keyword">new</span> Dog(); 
        myAnimal.makeSomeNoise(); <span class="hljs-comment">// Output - Barks</span>

        myAnimal = <span class="hljs-keyword">new</span> Cat(); 
        myAnimal.makeSomeNoise(); <span class="hljs-comment">// Output - Meows</span>
    }
}
</code></pre>
<p>In the above example, the <code>makeSomeNoise()</code> method of the <code>Animal</code> class is overridden by the <code>Dog</code> and <code>Cat</code> subclasses and they provide their own implementation of this method. </p>
<p>During object creation, the <code>Animal</code> variable holds a <code>Dog</code> or <code>Cat</code> object and when the <code>makeSomeNoise()</code> method is called, the appropriate overridden method is called based on the actual object type.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, we explored the fundamental principles of Object-Oriented Programming (OOP). </p>
<p>Familiarity with these concepts is crucial for building robust, maintainable, and scalable software systems.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Inheritance Works in C# – with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class.  Other pillars of object-oriented programming include encapsulation, polymorphism, and abstrac... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/inheritance-in-c-sharp/</link>
                <guid isPermaLink="false">66c8c86e58265ae76d481676</guid>
                
                    <category>
                        <![CDATA[ C ]]>
                    </category>
                
                    <category>
                        <![CDATA[ inheritance ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Israel Chidera ]]>
                </dc:creator>
                <pubDate>Tue, 29 Nov 2022 20:04:11 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/11/caspar-camille-rubin-fPkvU7RDmCo-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Inheritance is a branch of object-oriented programming that helps you write reusable code. It allows you to extend the content of a class to another class. </p>
<p><a target="_blank" href="https://www.freecodecamp.org/news/four-pillars-of-object-oriented-programming/">Other pillars of object-oriented programming</a> include encapsulation, polymorphism, and abstraction. </p>
<p>In this article, we will learn about inheritance in C# and the various types of inheritance we have in OOP.</p>
<h2 id="heading-what-is-inheritance">What is Inheritance?</h2>
<p>Inheritance is one of the key features of object-oriented programming (OOP). It is simply the process by which one class (the child or derived class) acquires the properties, methods, and fields of another class (the base, parent, or super class).</p>
<p>Inheritance in object-oriented programming means that you're creating classes that can pass down their properties to other classes without having to explicitly define the properties in new classes. </p>
<p>Inheritance does not only ensure the reusability of the codebase, but it also reduces your code’s complexity.</p>
<h2 id="heading-types-of-inheritance-in-c">Types of Inheritance in C</h2>
<p>Inheritance allows you to build families of related classes. The base/parent class defines the common data for the child class to inherit it. You use the colon operator (:) to show inheritance between two classes.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
    }
    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span>:<span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//..</span>
    }
}
</code></pre>
<p>There are different types of inheritance in C#. We'll discuss them now.</p>
<h3 id="heading-single-inheritance-in-c">Single Inheritance in C</h3>
<p>Single inheritance usually occurs between two classes – the base class, and the derived class. It occurs when a class is inherited from a single-parent class. </p>
<p>Below is a code sample that shows single inheritance in C#:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">using</span> System;

<span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//accessing the inherited members from the child class</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass now has access to the fields and properties of the ParentClass through inheritance. We could easily access the inherited members from the ChildClass as seen above.</p>
<h3 id="heading-hierarchical-inheritance-in-c">Hierarchical Inheritance in C</h3>
<p>Hierarchical inheritance occurs when more than one derived class is created from a single-parent class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">displayParentClassDetails</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">$"I am <span class="hljs-subst">{name}</span>"</span>);
            Console.WriteLine(<span class="hljs-string">$"ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>."</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">AnotherChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">getIdFromParentClass</span>(<span class="hljs-params"></span>)</span>
        {
            Console.WriteLine(<span class="hljs-string">"Displaying from my other Child Class"</span>);
            Console.WriteLine(<span class="hljs-string">$"This is my ID : <span class="hljs-subst">{Id}</span>"</span>);
        }
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//accessing the inherited members in the parent class (from the child class)</span>
            ChildClass child = <span class="hljs-keyword">new</span> ChildClass();
            child.getIdFromParentClass();

            <span class="hljs-comment">//accessing the inherited members in the parent class (from the other child class)</span>
            AnotherChildClass anotherChild = <span class="hljs-keyword">new</span> AnotherChildClass();
            anotherChild.getIdFromParentClass();
        }
    }
}
</code></pre>
<p>In the above code, we showed that we can derive more than one child class from a single parent class. </p>
<p>The ChildClass and AnotherChildClass both inherit the fields and methods of the base class, ParentClass. This is called Hierarchical inheritance. The two child classes can therefore access the fields and methods of the parent class.</p>
<h3 id="heading-multi-level-inheritance-in-c">Multi-level Inheritance in C</h3>
<p>Multi-level inheritance occurs when a class is derived from another derived class. It is simply a situation where a derived class is created and used as a base class for another class.</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{
    <span class="hljs-keyword">class</span> <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">string</span> name;
        <span class="hljs-keyword">public</span> <span class="hljs-keyword">int</span> Id = <span class="hljs-number">9</span>;

        <span class="hljs-comment">//...</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ChildClass</span> : <span class="hljs-title">ParentClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The Child class is the derived class in this case</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">ThirdClass</span> : <span class="hljs-title">ChildClass</span>
    {
        <span class="hljs-comment">//...</span>
        <span class="hljs-comment">//The ChildClass is the base class for the ThirdClass</span>
    }

    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
}
</code></pre>
<p>In the above code, we also derived a subclass (ChildClass) from a super class (ParentClass). The ChildClass then acts as a base class for a sub-child class which was named ThirdClass.</p>
<h3 id="heading-multiple-inheritances-interfaces-in-c">Multiple Inheritances – Interfaces in C</h3>
<p>Multiple inheritances are not supported in C#. But you can achieve it by using <em>interfaces</em>. </p>
<p>Multiple inheritances allow a derived class to be inherited from multiple parent classes. You can see an example of how a child class can inherit from multiple interfaces that act like a parent class below:</p>
<pre><code class="lang-cs"><span class="hljs-keyword">namespace</span> <span class="hljs-title">LearningInheritance</span>
{    
    <span class="hljs-keyword">class</span> <span class="hljs-title">Program</span>
    {
        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceA</span>
        {
            <span class="hljs-comment">//...</span>
        }

        <span class="hljs-keyword">interface</span> <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...</span>
        }     

        <span class="hljs-keyword">class</span> <span class="hljs-title">NewClass</span>: <span class="hljs-title">InterfaceA</span>, <span class="hljs-title">InterfaceB</span>
        {
            <span class="hljs-comment">//...            </span>
        }

        <span class="hljs-function"><span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">Main</span>(<span class="hljs-params"><span class="hljs-keyword">string</span>[] args</span>)</span>
        {
            <span class="hljs-comment">//...</span>
        }
    }
}
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>Inheritance is important because it helps keep your code clean. It makes it easier to build families of related classes. The child class can inherit all the fields, properties, and methods that are contained in the parent class except those classes that are declared as a private class. </p>
<p>Through this article, I hope you have gained some insight about inheritance in C#.</p>
<p>Happy Coding.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ OOP Meaning – What is Object-Oriented Programming? ]]>
                </title>
                <description>
                    <![CDATA[ In today's technology driven society, computer programming knowledge is in high demand. And as a developer, you'll need to know various programming languages. Over the past few decades, many programming languages have risen in popularity. You can see... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/what-is-object-oriented-programming/</link>
                <guid isPermaLink="false">66b8dc1df88daef58d10eef4</guid>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Hillary Nyakundi ]]>
                </dc:creator>
                <pubDate>Tue, 06 Sep 2022 17:15:18 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2022/09/OOP--1-.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In today's technology driven society, computer programming knowledge is in high demand. And as a developer, you'll need to know various programming languages.</p>
<p>Over the past few decades, many programming languages have risen in popularity. You can see how popular languages are ranked in this real time ranking chart <a target="_blank" href="https://www.tiobe.com/tiobe-index//">here</a>. </p>
<p>While new languages are being created, existing ones are always being updated to make them better.</p>
<p>Although most programming languages have some similarities, each one has specific rules and methods which makes it unique. </p>
<p>One concept that is common among many programming languages is <strong>Object Oriented Programming</strong>.</p>
<p>When I first came across this term, it was a bit confusing. It took me some time to really understand it's importance in programming. But this also doubled as an opportunity for me to learn its key concepts, and know how important it is for a developer's career and being able to solve challenges.</p>
<p>In this article we will go over Object Oriented Programming (OOP) as a whole, without relying on a particular language. You'll learn what it is, why it's so popular as a programming paradigm, its structure, how it works, its principles, and more. </p>
<p>Let's get started.</p>
<h1 id="heading-what-is-object-oriented-programming">What is Object-Oriented Programming?</h1>
<p>If you were to conduct a fast internet search on what object-oriented programming is, you'll find that OOP is defined as a programming paradigm that relies on the concept of classes and objects.</p>
<p>Now, for a beginner, that might be a little bit confusing – but no need to worry. I will try to explain it in a simplest way possible, just like the famous phrase "Explain it to me like I'm 5".</p>
<p>Here's a brief overview of what you can achieve with OOP: you can use it to structure a software program into simple, reusable code blocks (in this case usually called classes), which you then use to create individual instances of the objects.</p>
<p>So let's find an easier definition of object-oriented programming and learn more about it.</p>
<h2 id="heading-explain-oop-like-im-5">Explain OOP Like I'm 5</h2>
<p>The word object-oriented is a combination of two terms, object and oriented. </p>
<p>The dictionary meaning of an object is "an entity that exists in the real world", and oriented means "interested in a particular kind of thing or entity".</p>
<p>In basic terms, OOP is a programming pattern that is built around objects or entities, so it's called object-oriented programming. </p>
<p>To better understand the concept, let's have a look at commonly used software programs: A good example to explain this would be the use of a printer when you are printing a document.</p>
<p>The first step is initiating the action by clicking on the print command or using keyboard shortcuts. Next you need to select your printer. Afterwards you will wait for a response telling you if the document was printed or not. </p>
<p>Behind what we can't see, the command you clicked interacts with an object (printer) to accomplish the task of printing.</p>
<p>Perhaps you might wonder, how exactly did OOP become so popular?</p>
<h1 id="heading-how-oop-became-popular">How OOP Became Popular</h1>
<p>The concepts of OOP started to surface back in the 60s with a programming language called <a target="_blank" href="https://en.wikipedia.org/wiki/Simula">Simula</a>. Even though back in the day, developers didn't completely embrace the first advances in OOP languages, the methodologies continued to evolve.</p>
<p>Fast forward to the 80s, and an editorial written by David Robinson was one of the first introductions to OOP, as many developers didn't know it existed. </p>
<p>By now languages like C++ and Eiffel had become more popular and mainstream among computer programmers. The recognition continued to grow during the 90s, and with the arrival of Java, OOP attracted a huge following.</p>
<p>In 2002 in conjunction with the release of the .NET Framework, Microsoft introduced a brand new OOP language called C# – which is often described as the most powerful programming language</p>
<p>It's interesting that, generations later, the concept of organizing your code into meaningful objects that model the parts of your problem continues to puzzle programmers. </p>
<p>Many folks who haven't any idea how a computer works find the thought of object-oriented programming quite natural. In contrast, many folks who have experience with computers initially think there's something strange about object oriented systems. </p>
<h1 id="heading-structure-of-oop">Structure of OOP</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2022/09/OOP.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>Imagine that you are running a pet shop, with lots of different breeds and you have to keep track of the names, age, days attended to, and other common upkeep details. How would you design reusable software to handle this? </p>
<p>Keep in mind we have many breeds, so writing code for each would be tiresome. But we can group related information together so that we can produce shorter and more reusable code. </p>
<p>That's where the building blocks come in to help us do this by using <strong>Classes, Objects, Methods</strong> and <strong>Attributes</strong>.</p>
<p>Let's take a deep dive and understand what exactly these building blocks are:</p>
<ul>
<li><p><strong>Classes</strong> - these are user-defined data types that act as the blueprint for objects, attributes, and methods. </p>
</li>
<li><p><strong>Objects</strong> - These are instances of a class with specifically defined data. When a class is defined initially, the description is the only object that is defined. </p>
</li>
<li><p><strong>Methods</strong> - These are functions that are defined inside a class that describe the behavior of an object. They are useful for re-usability or keeping functionality encapsulated inside one object at a time. Code re-usability is a great benefit when debugging.</p>
</li>
<li><p><strong>Attributes</strong> - These are defined in the class template and represent the state of an object. Objects contain data stored in the attribute field.</p>
</li>
</ul>
<h1 id="heading-principles-of-oop">Principles of OOP</h1>
<p><img src="https://www.freecodecamp.org/news/content/images/2021/10/Creative-Business-Template-Presentation--2-.png" alt="OOP" width="600" height="400" loading="lazy"></p>
<p>In order for us to know how to write good OOP code, we need to understand the 4 pillars of OOP we should adhere to: </p>
<ul>
<li>Encapsulation</li>
<li>Abstraction</li>
<li>Inheritance</li>
<li>Polymorphism</li>
</ul>
<p>Let's dive in and better understand what exactly each of these mean.</p>
<h2 id="heading-encapsulation">Encapsulation</h2>
<p>This is the concept that binds data together. Functions manipulate the info and keep it safe. No direct access is granted to the info in case it's hidden. If you wish to gain access to the info, you need to interact with the article in charge of the info.</p>
<p>If you're employed in a company, chances are high that you've had experience with encapsulation. </p>
<p>Think about a human resources department. The human resources staff members encapsulate (hide) the data about employees. They determine how this data will be used and manipulated. Any request for the worker data or request to update the info must be routed through them.</p>
<p>By encapsulating data, you make the information of your system safer and more reliable. You're also able monitor how the information is being accessed and what operations are performed on it. This makes program maintenance easier and simplifies the debugging process. </p>
<h2 id="heading-abstraction">Abstraction</h2>
<p>Abstraction refers to using simple classes to represent complexity. Basically, we use abstraction to handle complexity by allowing the user to only see relevant and useful information. </p>
<p>A good example to explain this is driving an automatic car. When you have an automatic car and want to get from point A to point B, all you need to do is give it the destination and start the car. Then it'll drive you to your destination. </p>
<p>What you don't need to know is how the car is made, how it correctly takes and follows instructions, how the car filters out different options to find the best route, and so on. </p>
<p>The same concept is applied when constructing OOP applications. You do this by hiding details that aren't necessary for the user to see. Abstraction makes it easier and enables you to handle your projects in small, managable parts.</p>
<h2 id="heading-inheritance">Inheritance</h2>
<p>Inheritance allows classes to inherit features of other classes. As an example, you could classify all cats together as having certain common characteristics, like having four legs. Their breeds further classify them into subgroups with common attributes, like size and color.</p>
<p>You use inheritance in OOP to classify the objects in your programs per common characteristics and performance. This makes working with the objects and programming easier, because it enables you to mix general characteristics into a parent object and inherit these characteristics within the child objects.</p>
<p>For example, you'll define an employee object that defines all the overall characteristics of employees in your company. </p>
<p>You'll be able to then define a manager object that inherits the characteristics of the employee object but also adds characteristics unique to managers in your company. The manager object will automatically reflect any changes within the implementation of the employee object.</p>
<h2 id="heading-polymorphism">Polymorphism</h2>
<p>This is the power of two different objects to reply to one form. The program will determine which usage is critical for every execution of the thing from the parent class which reduces code duplication. It also allows different kinds of objects to interact with the same interface.</p>
<h2 id="heading-examples-of-oop-languages">Examples of OOP Languages</h2>
<p>Technology and programming languages are evolving all the time. We have seen the rise of may langs under the OOP category, but <strong>Simula</strong> is credited as the first OOP language. </p>
<p>Programming languages that are considered pure OOP treat everything like objects, while the others are designed primarily with some procedural process. </p>
<p><em>Examples of OOP langs:</em></p>
<ul>
<li>Scala </li>
<li>Emerald</li>
<li>Ruby</li>
<li>JADE </li>
<li>Java</li>
<li>Python</li>
<li>C++</li>
<li>JavaScript</li>
<li>Visual Basic .NET</li>
<li>PHP</li>
</ul>
<p>And many more.</p>
<h2 id="heading-benefits-of-oop">Benefits of OOP</h2>
<p>During the 70s and 80s, procedural-oriented programming languages such as C and Pascal were widely used to develop business-oriented software systems. But as the programs performed more complex business functionality and interacted with other systems, the shortcomings of structural programming methodology began to surface. </p>
<p>Because of this, many software developers turned to object-oriented methodologies and programming languages to solve the encountered problems. The benefits of using this languages included the following: </p>
<ul>
<li><p><strong>Code Re-usability</strong> - through inheritance, you can reuse code. This means a team does not have to write the same code multiple times. </p>
</li>
<li><p>Improved integration with modern operating systems. </p>
</li>
<li><p><strong>Improved Productivity</strong> - developers can construct new programs easily and quickly through the use of multiple libraries.</p>
</li>
<li><p>Polymorphism enables a single function to adapt to the class it is placed in.</p>
</li>
<li><p>Easy to upgrade, and programmers can also implement system functionalities independently.</p>
</li>
<li><p>Through <strong>Encapsulation</strong> objects can be self-contained. It also makes troubleshooting and collaboration on development easier.</p>
</li>
<li><p>By the use of encapsulation and abstraction, complex code is hidden, software maintenance is easier, and internet protocols are protected. </p>
</li>
</ul>
<h2 id="heading-wrapping-up">Wrapping Up</h2>
<p>Today, most languages allow developers to mix programming paradigms. This is often because they will be used for various programming methods. </p>
<p>For instance, take JavaScript – you can use it for both OOP and functional programming. When you're coding object-oriented JS, you have to think carefully about the structure of the program and plan at the start of coding. You might do this by viewing how you'll be able to break the necessities into simple, reusable classes which will be accustomed blueprint instances of objects.</p>
<p>Developers working with OOP typically agree that in general, using it allows for better data structures and re-usability of code. This saves time in the long term.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The Four Pillars of Object-Oriented Programming ]]>
                </title>
                <description>
                    <![CDATA[ JavaScript is a multi-paradigm language and can be written following different programming paradigms. A programming paradigm is essentially a bunch of rules that you follow when writing code, to help you solve a particular problem. That's what the fo... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/four-pillars-of-object-oriented-programming/</link>
                <guid isPermaLink="false">66bc55d4e35f27b353950756</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Kealan Parr ]]>
                </dc:creator>
                <pubDate>Fri, 18 Dec 2020 17:49:25 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/12/The-four-pillars-of-object-orientation.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>JavaScript is a multi-paradigm language and can be written following different programming paradigms. A programming paradigm is essentially a bunch of rules that you follow when writing code, to help you solve a particular problem.</p>
<p>That's what the four pillars are. They're software design principles to help you write clean Object-Orientated code.</p>
<p>The four pillars of object-oriented programming are: </p>
<ul>
<li>Abstraction </li>
<li>Encapsulation</li>
<li>Inheritance</li>
<li>Polymorphism</li>
</ul>
<p>Let's take a closer look at each of them.</p>
<h1 id="heading-abstraction-in-object-oriented-programming">Abstraction in Object-Oriented Programming</h1>
<p>To abstract something away means to hide away the implementation details inside something – sometimes a prototype, sometimes a function. So when you call the function you don't have to understand exactly what it is doing. </p>
<p>If you had to understand every single function in a big codebase you would never code anything. It would take months to finish reading through it all.</p>
<p>You can create a reusable, simple to understand, and easily changeable codebase by abstracting away certain details. Let me give you an example:</p>
<pre><code class="lang-javascript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">hitAPI</span>(<span class="hljs-params">type</span>)</span>{
    <span class="hljs-keyword">if</span> (type <span class="hljs-keyword">instanceof</span> InitialLoad) {
        <span class="hljs-comment">// Implementation example</span>
    } <span class="hljs-keyword">else</span> <span class="hljs-keyword">if</span> (type <span class="hljs-keyword">instanceof</span> NavBar) {
        <span class="hljs-comment">// Implementation example</span>
    } <span class="hljs-keyword">else</span> {
        <span class="hljs-comment">// Implementation example</span>
    }
}
</code></pre>
<p>Can you see in the example how you have to implement exactly what you need for your custom use-case? </p>
<p>Every new API  you need to hit needs a new <code>if</code> block, and it's own custom code. This isn't abstracted away as you need to worry about the implementation for every new type you add. It isn't reusable, and is a maintenance nightmare. </p>
<p>How about something like the below?</p>
<pre><code class="lang-javascript">hitApi(<span class="hljs-string">'www.kealanparr.com'</span>, HTTPMethod.Get)
</code></pre>
<p>You now can just pass a URL to your function and what HTTP method you want to use and you're done.</p>
<p>You don't have to worry about how the function works. It's dealt with. This massively helps code reuse! And makes your code a lot more maintainable, too.</p>
<p>That is what <strong>Abstraction</strong> is all about. Finding things that are similar in your code and providing a generic function or object to serve multiple places/with multiple concerns.</p>
<p>Here's a good final example of <strong>Abstraction</strong>: imagine if you were creating a machine to make coffee for your users. There could be two approaches:</p>
<h2 id="heading-how-to-create-it-with-abstraction">How to Create it With Abstraction</h2>
<ul>
<li>Have a button with the title "Make coffee"</li>
</ul>
<h2 id="heading-how-to-create-it-without-abstraction">How to Create it Without Abstraction</h2>
<ul>
<li>Have a button with the title "Boil the water"</li>
<li>Have a button with the title "Add the cold water to the kettle"</li>
<li>Have a button with the title "Add 1 spoon of ground coffee to a clean cup"</li>
<li>Have a button with the title "Clean any dirty cups"</li>
<li>And all the other buttons</li>
</ul>
<p>It's a very simple example, but the first approach <em>abstracts</em> away the logic into the machine. But the second approach forces the user to understand how to make coffee and essentially make their own.</p>
<p>The next pillar shows us one way we can achieve <strong>Abstraction</strong>, by using <strong>Encapsulation.</strong></p>
<h1 id="heading-encapsulation-in-object-oriented-programming">Encapsulation in Object-Oriented Programming</h1>
<p>The definition of encapsulation is "the action of enclosing something in or as if in a capsule". Removing access to parts of your code and making things private is exactly what <strong>Encapsulation</strong> is all about (often times, people refer to it as data hiding).</p>
<p>Encapsulation means that each object in your code should control its own state. State is the current "snapshot" of your object. The keys, the methods on your object, Boolean properties and so on. If you were to reset a Boolean or delete a key from the object, they're all changes to your state. </p>
<p>Limit what pieces of your code can access. Make more things inaccessible, if they aren't needed.</p>
<p>Private properties are achieved in JavaScript by using closures. Here's an example below:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">var</span> Dog = (<span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{

    <span class="hljs-comment">// Private</span>
    <span class="hljs-keyword">var</span> play = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
        <span class="hljs-comment">// play implementation</span>
    };

    <span class="hljs-comment">// Private</span>
    <span class="hljs-keyword">var</span> breed = <span class="hljs-string">"Dalmatian"</span>

    <span class="hljs-comment">// Public</span>
    <span class="hljs-keyword">var</span> name = <span class="hljs-string">"Rex"</span>;

    <span class="hljs-comment">// Public</span>
    <span class="hljs-keyword">var</span> makeNoise = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
         <span class="hljs-keyword">return</span> <span class="hljs-string">'Bark bark!'</span>;
    };

     <span class="hljs-keyword">return</span> {
        <span class="hljs-attr">makeNoise</span>: makeNoise,
        <span class="hljs-attr">name</span>: name
     };
})();
</code></pre>
<p>The first thing we did was create a function that immediately gets called (called an <strong>Immediately Invoked Function Expression</strong>, or IIFE for short). This created an object that anyone can access but hid away some of the details. You can't call <code>play</code> and you can't access <code>breed</code> as we didn't expose it in the final object with the return. </p>
<p>This particular pattern above is called the <strong>Revealing Module Pattern</strong>, but it's just an example of how you can achieve <strong>Encapsulation.</strong> </p>
<p>I want to focus more on the idea of <strong>Encapsulation</strong> (as it is more important than just learning one pattern and counting <strong>Encapsulation</strong> as totally complete now).</p>
<p>Reflect, and think more about how you can hide away your data and code, and separate it out. Modularising and having clear responsibilities is key to <strong>Object Orientation</strong>.</p>
<p>Why should we prefer privacy? Why not just have everything global?</p>
<ul>
<li>Lots of unrelated bits of code will become dependent/coupled to one another via the global variable.</li>
<li>You will likely override the variables if the name get's reused, which can lead to bugs or unpredictable behaviour.</li>
<li>You will likely end up with <strong>Spaghetti Code</strong> – code that's hard to reason through and follow what is reading and writing to your variables and changing state.</li>
</ul>
<p>Encapsulation can be applied by separating out long lines of code into smaller separate functions. Separate out those functions into modules. We hide away the data in a place nothing else needs access to, and cleanly expose what is needed. </p>
<p>That is <strong>Encapsulation</strong> is a nutshell. Binding your data to something, whether it's a class, object, module or function, and doing your best to keep it as private as you reasonably can.</p>
<h1 id="heading-inheritance-in-object-oriented-programming">Inheritance in Object-Oriented Programming</h1>
<p>Inheritance lets one object acquire the properties and methods of another object. In JavaScript this is done by <strong>Prototypal Inheritance</strong>. </p>
<p>Reusability is the main benefit here. We know sometimes that multiple places need to do the same thing, and they need to do everything the same except for one small part. This is a problem inheritance can solve.</p>
<p>Whenever we use inheritance, we try to make it so that the parent and the child have <strong>high cohesion. Cohesion</strong> is how related your code is. For example, does the  <code>Bird</code> type extend from the <code>DieselEngine</code> type? </p>
<p>Keep your inheritance simple to understand and predictable. Don't inherit from somewhere completely unrelated because there's one method or property you need. Inheritance doesn't fix that particular problem well.</p>
<p>When using inheritance, you should require most of the functionality (you don't always need absolutely everything). </p>
<p>Developers have a principle called the <strong>Liskov Substitution principle</strong>. It states that if you can use a parent class (let's call it <code>ParentType</code>) anywhere you use a child (let's call it <code>ChildType</code>) – and <code>ChildType</code> inherits from the <code>ParentType</code> – then you pass the test. </p>
<p>The main reason you would fail this test, is if the <code>ChildType</code> is removing things from the parent. If <code>ChildType</code> removed methods it inherited from the parent, it'd lead to <code>TypeError</code>'s where things are undefined that you are expecting not to be.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2020/12/image-146.png" alt="Image" width="600" height="400" loading="lazy">
<em>The arrows look like they're going the wrong way. But the Animal is the base - the parent.</em></p>
<p>Inheritance chain is the term used to describe the flow of inheritance from the base object's prototype (the one that everything else inherits from) to the "end" of the inheritance chain (the last type that is inheriting – <strong>Dog</strong> in the above example).</p>
<p>Do your best to keep your inheritance chains clean and sensible. You can easily end up coding an anti-patterns when using <strong>Inheritance (</strong>called the <strong>Fragile base anti-pattern</strong>). This happens where your base prototypes are considered "fragile" because you make a "safe" change to the base object and then start to break all your children. </p>
<h1 id="heading-polymorphism-in-object-oriented-programming">Polymorphism in Object-Oriented Programming</h1>
<p>Polymorphism means "the condition of occurring in several different forms." That's exactly what the fourth and final pillar is concerned with – types in the same inheritance chains being able to do different things. </p>
<p>If you have used inheritance correctly you can now reliably use parents like their children. When two types share an inheritance chain, they can be used interchangeably with no errors or assertions in your code.</p>
<p>From the last diagram, we might have a base prototype that is called <code>Animal</code> which defines <code>makeNoise</code>. Then every type extending from that prototype can override to do their own custom work. Something like this:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Let's set up an Animal and Dog example</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Animal</span>(<span class="hljs-params"></span>)</span>{}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Dog</span>(<span class="hljs-params"></span>)</span>{}

Animal.prototype.makeNoise = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Base noise"</span>);
};

<span class="hljs-comment">// Most animals we code up have 4. This can be overridden if needed</span>
Animal.prototype.legs = <span class="hljs-number">4</span>;

Dog.prototype = <span class="hljs-keyword">new</span> Animal();

Dog.prototype.makeNoise = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Woof woof"</span>);  
};

<span class="hljs-keyword">var</span> animal = <span class="hljs-keyword">new</span> Animal();
<span class="hljs-keyword">var</span> dog = <span class="hljs-keyword">new</span> Dog();

animal.makeNoise(); <span class="hljs-comment">// Base noise</span>
dog.makeNoise();    <span class="hljs-comment">// Woof woof- this was overridden</span>
dog.legs;           <span class="hljs-comment">// 4! This was inherited</span>
</code></pre>
<p><code>Dog</code> extends from <code>Animal</code> and can make use of the default <code>legs</code> property. But it's also able to do its own implementation of making its own noise.</p>
<p>The real power of polymorphism is sharing behaviours, and allowing custom overrides.</p>
<h1 id="heading-conclusion">Conclusion</h1>
<p>I hope this has explained what the four pillars of object-oriented programming are, and how they lead to cleaner and more robust code. </p>
<p>I share my writing on <a target="_blank" href="https://twitter.com/kealanparr">Twitter</a> if you enjoyed this article and want to see more.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Abstract Classes in Java Explained with Examples ]]>
                </title>
                <description>
                    <![CDATA[ Abstract classes are classes declared with abstract. They can be subclassed or extended, but cannot be instantiated. You can think of them as a class version of interfaces, or as an interface with actual code attached to the methods. For example, say... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/abstract-classes-in-java-explained-with-examples/</link>
                <guid isPermaLink="false">66c3437cf9d371e3aae26815</guid>
                
                    <category>
                        <![CDATA[ class ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9d14740569d1a4ca35ca.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Abstract classes are classes declared with <code>abstract</code>. They can be subclassed or extended, but cannot be instantiated. You can think of them as a <strong>class version</strong> of interfaces, or as an interface with actual code attached to the methods.</p>
<p>For example, say you have a class <code>Vehicle</code> which defines the basic functionality (methods) and components (object variables) that vehicles have in common. </p>
<p>You cannot create an object of <code>Vehicle</code> because a vehicle is itself an abstract, general concept. Vehicles have wheels and motors, but the number of wheels and the size of motors can differ greatly.</p>
<p>You can, however, extend the functionality of the vehicle class to create a <code>Car</code> or a <code>Motorcycle</code>:</p>
<pre><code class="lang-java"><span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Vehicle</span>
</span>{
  <span class="hljs-comment">//variable that is used to declare the no. of wheels in a vehicle</span>
  <span class="hljs-keyword">private</span> <span class="hljs-keyword">int</span> wheels;

  <span class="hljs-comment">//Variable to define the type of motor used</span>
  <span class="hljs-keyword">private</span> Motor motor;

  <span class="hljs-comment">//an abstract method that only declares, but does not define the start </span>
  <span class="hljs-comment">//functionality because each vehicle uses a different starting mechanism</span>
  <span class="hljs-function"><span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">start</span><span class="hljs-params">()</span></span>;
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Car</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span>
</span>{
  ...
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Motorcycle</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Vehicle</span>
</span>{
  ...
}
</code></pre>
<p>Remember, you cannot instantiate a <code>Vehicle</code> anywhere in your program – instead, you can use the <code>Car</code> and <code>Motorcycle</code> classes you declared earlier and create instances of those:</p>
<pre><code class="lang-java">Vehicle newVehicle = <span class="hljs-keyword">new</span> Vehicle();    <span class="hljs-comment">// Invalid</span>
Vehicle car = <span class="hljs-keyword">new</span> Car();  <span class="hljs-comment">// valid</span>
Vehicle mBike = <span class="hljs-keyword">new</span> Motorcycle();  <span class="hljs-comment">// valid</span>

Car carObj = <span class="hljs-keyword">new</span> Car();  <span class="hljs-comment">// valid</span>
Motorcycle mBikeObj = <span class="hljs-keyword">new</span> Motorcycle();  <span class="hljs-comment">// valid</span>
</code></pre>
<h2 id="heading-more-information">More information:</h2>
<ul>
<li><a target="_blank" href="https://www.freecodecamp.org/news/functional-programming-in-java-course/">Learn Functional Programming in Java - Full Course</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/java-getters-and-setters/">Getters and Setters in Java Explained</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/inheritance-in-java-explained/">Inheritance in Java Explained</a></li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Object Oriented Programming Concepts: How to go from Zero to One with Objects ]]>
                </title>
                <description>
                    <![CDATA[ Object Oriented Programming is one of the most widely used programming paradigms. The name itself defines how it works. “Object Oriented” - the Object plays an important role. Manipulating objects and getting the results is the ultimate goal of Objec... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/object-oriented-concepts/</link>
                <guid isPermaLink="false">66baefcfff91e9c03fcb30aa</guid>
                
                    <category>
                        <![CDATA[ Blogging ]]>
                    </category>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ freeCodeCamp.org ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Object Oriented Programming ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Parathan Thiyagalingam ]]>
                </dc:creator>
                <pubDate>Wed, 07 Aug 2019 19:09:25 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9ca108740569d1a4ca4c46.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Object Oriented Programming is one of the most widely used programming paradigms. The name itself defines how it works. “Object Oriented” - the Object plays an important role. Manipulating objects and getting the results is the ultimate goal of Object Oriented Programming.</p>
<p>The languages that use Object Oriented Programming paradigms are known as Object Oriented Programming Languages. They are mostly high level languages such as</p>
<ol>
<li>Java</li>
<li>C#</li>
<li>Python - Python is both a Scripted/Structured &amp; Object Oriented Language</li>
</ol>
<p>To program in Object Oriented Programming, concepts called “<strong>Object Oriented Concepts</strong>” are used. These concepts simplify &amp; add more value to Object Oriented Programming.</p>
<p>Those concepts are</p>
<ol>
<li>Encapsulation</li>
<li>Abstraction</li>
<li>Polymorphism</li>
<li>Inheritance</li>
</ol>
<p>Before moving into these concepts, we need to know about Class &amp; Objects.</p>
<p><strong>An Object</strong> is the basic run-time entity in OOP. In our day-today life we see a lot of objects like a television, mobile phone, dog, humans, cars &amp; other living and non-living objects. These can be portrayed as objects in OOP.</p>
<p><strong>A Class</strong> is a blueprint or prototype that defines variables/properties and methods/functions common to all objects of a certain kind. It's a logical component.</p>
<p>Simply said, Class is a <strong>user-defined</strong> data type. Objects are <strong>variables</strong> of a Class. Once the Class has been created we can create as many Objects as we want.</p>
<p>For example, take a class named Tree. State/properties of the Tree class are:</p>
<ul>
<li>Name of the tree</li>
<li>Age of the tree</li>
<li>Type of the tree</li>
<li>Height of the tree</li>
</ul>
<p>State/properties are used to define the attributes of an object.</p>
<p>That is, <strong>State/properties/attributes</strong> all represents the same thing.</p>
<p>Behaviors of the Tree can be:</p>
<ul>
<li>Giving fruit</li>
<li>Falling of leaves</li>
<li>Absorbing water from roots to the upper parts</li>
<li>Creating shadows</li>
</ul>
<p>Then, Mango is a variable of Class Tree. We can store and retrieve all the properties &amp; behaviors we defined for the class Tree by creating an object of Mango.</p>
<p>Syntax for Creating an object of Mango from class Tree:</p>
<p>                                                <strong>Tree</strong> Mango;</p>
<h3 id="heading-encapsulation">Encapsulation</h3>
<p>Have you ever used a tablet/medicine which encapsulated by a colored cover?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/pills_tablets_medicine_capsule_heal_drugs_pharmacy_nutrient_additives-859474.jpg-d.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>Medicines are encapsulated &amp; placed inside the tablet</em></p>
<p>Inside that medicine is kept safely. We can't find anything with our naked eye. To see what's inside we need to open up that cover....</p>
<p>Similarly, all the <strong>data members (variables,attributes/properties)</strong> &amp; <strong>behaviors(functions/methods)</strong> are gathered together and closed. Class is a best example for Encapsulation.</p>
<p>For an instance,</p>
<p>You are going to the pharmacy to buy prescribed medicines for you. You handover the prescription to the pharmacist and then he/she will take the medicine from the store &amp; give you the bill.</p>
<p>In this scenario,</p>
<p>Medicines - act as variables or properties or attributes</p>
<p>Pharmacist - act as member function/method where he/she helps in giving you the        medicine</p>
<p>You - external application or another software code</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot-from-2019-08-20-22-13-54.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>By using Encapsulation, <strong>data can be restricted</strong> from the usage of the outside world. The function defined in the class only can access the properties. This can be defined at the implementation stage. Programmers can define and specify the accessibility of the member variables while under development rather than making all the variables global like in procedural languages. This controlling of accessibility is also known as <strong>Information hiding</strong>.</p>
<p>Encapsulation <strong>allows to expose the necessary things and hiding the important things from the outside world</strong>. So, the hidden parts of a class acts like <strong>Encapsulation</strong> &amp; the exposed parts acts like <strong>Abstraction</strong>.</p>
<h3 id="heading-abstraction">Abstraction</h3>
<p>Exposing necessary features of a class <strong>without explaining much or details</strong> is done by Abstraction.</p>
<p>Today morning I wanted to make a hot tea and I used a water kettle to boil the water. I just turned on the <strong>On</strong> button to start boil water. I don’t want to know the inner workflow of the kettle where it has high resistance and that resistance produces heat and boils the water. Instead, I have to fulfill my work easily. Therefore, having this On button to boil the water is known as Abstraction.</p>
<p>Similarly, we can take a remote controller which helps in manipulating TV operation using simple keys in the remote.</p>
<p><strong>Data abstraction</strong> is a programming technique that depends on the separation of <strong>interface</strong> and <strong>implementation</strong>.</p>
<p>This data abstraction can be archived from using 2 different classes while coding using OOP</p>
<ol>
<li>Abstraction class:  (0-100)% abstraction</li>
<li>Interface class:  100% abstraction</li>
</ol>
<h3 id="heading-inheritance">Inheritance</h3>
<p>The word itself describe what its functionality. Everyone has their inheritance qualities from their birth. You could have your grandparents/ your parents qualities from your birth. This is what Inheritance does in OOP.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/08/Screenshot-from-2019-08-20-22-14-01.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>A class can have properties &amp; methods of its parent class. Additionally the class can have its own properties and methods too. The parent class is called as <strong>base class</strong>. The class that inherits base class is called as <strong>derived class</strong>. Inheritance is the most powerful feature of OOP.</p>
<p>By using Inheritance effectively we could save a lot of time and reduce the errors in our program. This causes us to <strong>increase the quality of work</strong> and <strong>productivity</strong>.</p>
<p>There are different types of Inheritance</p>
<ol>
<li>Single Inheritance</li>
<li>Hierarchical Inheritance</li>
<li>Multiple Inheritance</li>
<li>Multi Level Inheritance</li>
</ol>
<h3 id="heading-polymorphism">Polymorphism</h3>
<p>Polymorphism is a <strong>Greek</strong> term which refers to the ability of taking more than one form / overloading.</p>
<p>Say for example we all know about <strong>functions</strong> in programming. They take different arguments inside parenthesis. Polymorphism is nothing but with the same function name, different arguments passed to get the result.</p>
<p>For e.g :- function called sum can take 2 arguments or 3 arguments.</p>
<p>                                    sum(3,4)  sum(10,23,56)<br>Calling these functions by providing suitable number of parameters will give the result according to how the called function has designed.</p>
<p><strong><em>How the program distinguish which function need to be executed at the above scenario?</em></strong></p>
<p>There is a feature called <strong>Dynamic binding</strong> in OOP. This will call the actual function according to the program execution. When the program runs the function with 2 arguments compiler takes the two argument functions to execute the program similarly for 3 arguments too.</p>
<p>Until the run-time, compiler won’t know exactly which function need to be invoked. It depends on the way the program calls the function name. This is also be known as <strong>Late binding.</strong></p>
<h3 id="heading-uses-of-object-oriented-concepts">Uses of Object Oriented Concepts</h3>
<ul>
<li>Data can be hidden from outside using <strong>Encapsulation</strong> (Information hiding)</li>
<li>Code can be reused by using <strong>Inheritance</strong></li>
<li>Operators/methods.functions can be overloaded by using <strong>Polymorphism</strong>. I.e: same function or operator name can be used for multi-tasking</li>
<li>Data abstraction can be archived from <strong>Abstraction</strong>.</li>
<li>Project migrations are easy (can be converted to larger size from smaller size)</li>
<li>Partitioning the works for same project</li>
<li>Manageable software complexity</li>
</ul>
<h3 id="heading-areas-of-application-of-oop">Areas of application of OOP</h3>
<ol>
<li>AI and expert systems</li>
<li>Enterprise applications</li>
<li>Neural Network and parallel programming</li>
<li>Office automation systems</li>
</ol>
<p>Hope you enjoyed a brief introduction to Object Oriented Concepts by reading. I hope to write how can we program Object Oriented Programming in my upcoming posts too.</p>
<hr>
<p>Please send you feedback about my article to parathan19@gmail.com</p>
<p><a target="_blank" href="https://www.linkedin.com/in/parathantl/">LinkedIn</a> | <a target="_blank" href="http://twitter.com/parathantl">Twitter</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ The 3 Types of Design Patterns All Developers Should Know (with code examples of each) ]]>
                </title>
                <description>
                    <![CDATA[ By Sameeha Rahman What is a Design Pattern? Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌CODE. It is like a description on how to tackle these problems and ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/the-basic-design-patterns-all-developers-need-to-know/</link>
                <guid isPermaLink="false">66d460cfe39d8b5612bc0df1</guid>
                
                    <category>
                        <![CDATA[ command ]]>
                    </category>
                
                    <category>
                        <![CDATA[ decorator ]]>
                    </category>
                
                    <category>
                        <![CDATA[ design patterns ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ singleton ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 24 Jul 2019 06:52:52 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/07/design-patterns-everywhere.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Sameeha Rahman</p>
<h1 id="heading-what-is-a-design-pattern">What is a Design Pattern?</h1>
<p>Design patterns are design level solutions for recurring problems that we software engineers come across often. It’s not code - I repeat, ❌<strong>CODE</strong>. It is like a description on how to tackle these problems and design a solution. </p>
<p>Using these patterns is considered good practice, as the design of the solution is quite tried and tested, resulting in higher readability of the final code. Design patterns are quite often created for and used by OOP Languages, like Java, in which most of the examples from here on will be written.</p>
<h2 id="heading-types-of-design-patterns">Types of design patterns</h2>
<p>There are about 26 Patterns currently discovered (I hardly think I will do them all…).</p>
<p>These 26 can be classified into 3 types:</p>
<ol>
<li><p>Creational: These patterns are designed for class instantiation. They can be either class-creation patterns or object-creational patterns.</p>
</li>
<li><p>Structural: These patterns are designed with regard to a class's structure and composition. The main goal of most of these patterns is to increase the functionality of the class(es) involved, without changing much of its composition.</p>
</li>
<li><p>Behavioral: These patterns are designed depending on how one class communicates with others.</p>
</li>
</ol>
<p>In this post, we will go through one basic design pattern for each classified type.</p>
<h2 id="heading-type-1-creational-the-singleton-design-pattern">Type 1: Creational - The Singleton Design Pattern</h2>
<p>The Singleton Design Pattern is a Creational pattern, whose objective is to create only one instance of a class and to provide only one global access point to that object. One commonly used example of such a class in Java is Calendar, where you cannot make an instance of that class. It also uses its own <code>getInstance()</code>method to get the object to be used.</p>
<p>A class using the singleton design pattern will include,</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/singleton-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Singleton Class Diagram</em></p>
<ol>
<li>A private static variable, holding the only instance of the class.</li>
<li>A private constructor, so it cannot be instantiated anywhere else.</li>
<li>A public static method, to return the single instance of the class.</li>
</ol>
<p>There are many different implementations of singleton design. Today, I’ll be going through the implementations of;</p>
<ol>
<li><p>Eager Instantiation</p>
</li>
<li><p>Lazy Instantiation</p>
</li>
<li><p>Thread-safe Instantiation</p>
</li>
</ol>
<h3 id="heading-eager-beaver">Eager Beaver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">EagerSingleton</span> </span>{
    <span class="hljs-comment">// create an instance of the class.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> EagerSingleton instance = <span class="hljs-keyword">new</span> EagerSingleton();

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">EagerSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// get the only instance of the object created.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> EagerSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This type of instantiation happens during class loading, as the instantiation of the variable instance happens outside any method. This poses a hefty drawback if this class is not being used at all by the client application. The contingency plan, if this class is not being used, is the Lazy Instantiation.</p>
<h3 id="heading-lazy-days">Lazy Days</h3>
<p>There isn’t much difference from the above implementation. The main differences are that the static variable is initially declared null, and is only instantiated within the <code>getInstance()</code> method if - and only if - the instance variable remains null at the time of the check. </p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">LazySingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> LazySingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">LazySingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, and if so, create the object.</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> LazySingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
            instance = <span class="hljs-keyword">new</span> LazySingleton();
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>This fixes one problem, but another one still exists. What if two different clients access the Singleton class at the same time, right to the millisecond? Well, they will check if the instance is null at the same time, and will find it true, and so will create two instances of the class for each request by the two clients. To fix this, Thread Safe instantiation is to be implemented.</p>
<h3 id="heading-thread-safety-is-key">(Thread) Safety is Key</h3>
<p>In Java, the keyword synchronized is used on methods or objects to implement thread safety, so that only one thread will access a particular resource at one time. The class instantiation is put within a synchronized block so that the method can only be accessed by one client at a given time.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">ThreadSafeSingleton</span> </span>{
    <span class="hljs-comment">// initialize the instance as null.</span>
    <span class="hljs-keyword">private</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton instance = <span class="hljs-keyword">null</span>;

    <span class="hljs-comment">// private constructor, so it cannot be instantiated outside this class.</span>
    <span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-title">ThreadSafeSingleton</span><span class="hljs-params">()</span> </span>{  }

    <span class="hljs-comment">// check if the instance is null, within a synchronized block. If so, create the object</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstance</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
        <span class="hljs-keyword">return</span> instance;
    }
}
</code></pre>
<p>The overhead for the synchronized method is high, and reduces the performance of the whole operation. </p>
<p>For example, if the instance variable has already been instantiated, then each time any client accesses the <code>getInstance()</code> method, the <code>synchronized</code> method is run and the performance drops. This just happens in order to check if the <code>instance</code> variables’ value is null. If it finds that it is, it leaves the method. </p>
<p>To reduce this overhead, double locking is used. The check is used before the <code>synchronized</code> method as well, and if the value is null alone, does the <code>synchronized</code> method run.</p>
<pre><code class="lang-java"><span class="hljs-comment">// double locking is used to reduce the overhead of the synchronized method</span>
<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> ThreadSafeSingleton <span class="hljs-title">getInstanceDoubleLocking</span><span class="hljs-params">()</span> </span>{
    <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
        <span class="hljs-keyword">synchronized</span> (ThreadSafeSingleton.class) {
            <span class="hljs-keyword">if</span> (instance == <span class="hljs-keyword">null</span>) {
                instance = <span class="hljs-keyword">new</span> ThreadSafeSingleton();
            }
        }
    }
    <span class="hljs-keyword">return</span> instance;
}
</code></pre>
<p>Now onto the next classification.</p>
<h2 id="heading-type-2-structural-the-decorator-design-pattern">Type 2: Structural - The Decorator Design Pattern</h2>
<p>I’m gonna give you a small scenario to give a better context to why and where you should use the Decorator Pattern.</p>
<p>Say you own a coffee shop, and like any newbie, you start out with just two types of plain coffee, the house blend and dark roast. In your billing system, there was one class for the different coffee blends, which inherits the beverage abstract class. People actually start to come by and have your wonderful (albeit bitter?) coffee. Then there are the coffee newbs that, God forbid, want sugar or milk. Such a travesty for coffee!! ??</p>
<p>Now you need to have those two add-ons as well, both to the menu and unfortunately on the billing system. Originally, your IT person will make a subclass for both coffees, one including sugar, the other milk. Then, since customers are always right, one says these dreaded words:</p>
<p><em>“Can I get a milk coffee, with sugar, please?”</em></p>
<h3 id="heading-pz8">???</h3>
<p>There goes your billing system laughing in your face again. Well, back to the drawing board….</p>
<p>The IT person then adds milk coffee with sugar as another subclass to each parent coffee class. The rest of the month is smooth sailing, people lining up to have your coffee, you actually making money. ??</p>
<p>But wait, there’s more!</p>
<p>The world is against you once again. A competitor opens up across the street, with not just 4 types of coffee, but more than 10 add-ons as well!</p>
<p>You buy all those and more, to sell better coffee yourself, and just then remember that you forgot to update that dratted billing system. You quite possibly cannot make the infinite number of subclasses for any and all combinations of all the add-ons, with the new coffee blends too. Not to mention, the size of the final system.</p>
<p>Time to actually invest in a proper billing system. You find new IT personnel, who actually knows what they are doing and they say,</p>
<p><em>“Why, this will be so much easier and smaller if it used the decorator pattern.”</em></p>
<h3 id="heading-what-on-earth-is-that">What on earth is that?</h3>
<p>The decorator design pattern falls into the structural category, that deals with the actual structure of a class, whether is by inheritance, composition or both. The goal of this design is to modify an objects’ functionality at runtime. This is one of the many other design patterns that utilize abstract classes and interfaces with composition to get its desired result.</p>
<p>Let’s give Math a chance (shudder?) to bring this all into perspective.</p>
<p>Take 4 coffee blends and 10 add-ons. If we stuck to the generation of subclasses for each different combination of all the add-ons for one type of coffee. That’s:</p>
<p>(10–1)² = 9² = 81 subclasses</p>
<p>We subtract 1 from the 10, as you cannot combine one add-on with another of the same type, sugar with sugar sounds stupid. And that’s for just one coffee blend. Multiply that <strong>81 by 4</strong> and you get a whopping <strong>324</strong> different subclasses! Talk about all that coding…</p>
<p>But with the decorator pattern it will require only 16 classes in this scenario. Wanna bet?</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Decorator Design Pattern Class diagram</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-coffee-class-diagram.png" alt="Image" width="600" height="400" loading="lazy">
<em>Class diagram according to coffee shop scenario</em></p>
<p>If we map out our scenario according to the class diagram above, we get 4 classes for the 4 coffee blends, 10 for each add-on and 1 for the abstract component and 1 more for the abstract decorator. See! 16! Now hand over that $100.?? (jk, but it will not be refused if given… just saying)</p>
<p>As you can see from above, just as the concrete coffee blends are subclasses of the beverage abstract class, the AddOn abstract class also inherits its methods from it. The add-ons, that are its subclasses, in turn inherit any new methods to add functionality to the base object when needed.</p>
<p>Let’s get to coding, to see this pattern in use.</p>
<p>First to make the Abstract beverage class, that all the different coffee blends will inherit from:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">private</span> String description;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Beverage</span><span class="hljs-params">(String description)</span> </span>{
        <span class="hljs-keyword">super</span>();
        <span class="hljs-keyword">this</span>.description = description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> description;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>Then to add both the concrete coffee blend classes.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">HouseBlend</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">HouseBlend</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“House blend”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">250</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">DarkRoast</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">DarkRoast</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">super</span>(“Dark roast”);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> <span class="hljs-number">300</span>;
    }
}
</code></pre>
<p>The AddOn abstract class also inherits from the Beverage abstract class (more on this below).</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">AddOn</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Beverage</span> </span>{
    <span class="hljs-keyword">protected</span> Beverage beverage;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">AddOn</span><span class="hljs-params">(String description, Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(description);
        <span class="hljs-keyword">this</span>.beverage = bev;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<p>And now the concrete implementations of this abstract class:</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Sugar</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Sugar</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Sugar”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Mocha”;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">50</span>;
    }
}

<span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Milk</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">AddOn</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Milk</span><span class="hljs-params">(Beverage bev)</span> </span>{
        <span class="hljs-keyword">super</span>(“Milk”, bev);
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> String <span class="hljs-title">getDescription</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.getDescription() + “ with Milk”;
    }

    <span class="hljs-meta">@Override</span>  <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">double</span> <span class="hljs-title">cost</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">return</span> beverage.cost() + <span class="hljs-number">100</span>;
    }
}
</code></pre>
<p>As you can see above, we can pass any subclass of Beverage to any subclass of AddOn, and get the added cost as well as the updated description. And, since the AddOn class is essentially of type Beverage, we can pass an AddOn into another AddOn. This way, we can add any number of add-ons to a specific coffee blend.</p>
<p>Now to write some code to test this out.</p>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">CoffeeShop</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        HouseBlend houseblend = <span class="hljs-keyword">new</span> HouseBlend();
        System.out.println(houseblend.getDescription() + “: “ + houseblend.cost());

        Milk milkAddOn = <span class="hljs-keyword">new</span> Milk(houseblend);
        System.out.println(milkAddOn.getDescription() + “: “ + milkAddOn.cost());

        Sugar sugarAddOn = <span class="hljs-keyword">new</span> Sugar(milkAddOn);
        System.out.println(sugarAddOn.getDescription() + “: “ + sugarAddOn.cost());
    }
}
</code></pre>
<p>The final result is:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/decorator-final.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>P.S. this is in Sri Lankan Rupees</em></p>
<p>It works! We were able to add more than one add-on to a coffee blend and successfully update its final cost and description, without the need to make infinite subclasses for each add-on combination for all coffee blends.</p>
<p>Finally, to the last category.</p>
<h2 id="heading-type-3-behavioral-the-command-design-pattern">Type 3: Behavioral - The Command Design Pattern</h2>
<p>A behavioral design pattern focuses on how classes and objects communicate with each other. The main focus of the command pattern is to inculcate a higher degree of loose coupling between involved parties (read: classes).</p>
<p><em>Uhhhh… What’s that?</em></p>
<p>Coupling is the way that two (or more) classes that interact with each other, well, interact. The ideal scenario when these classes interact is that they do not depend heavily on each other. That’s loose coupling. So, a better definition for loose coupling would be, classes that are interconnected, making the least use of each other.</p>
<p>The need for this pattern arose when requests needed to be sent without consciously knowing what you are asking for or who the receiver is.</p>
<p>In this pattern, the invoking class is decoupled from the class that actually performs an action. The invoker class only has the callable method execute, which runs the necessary command, when the client requests it.</p>
<p>Let’s take a basic real-world example, ordering a meal at a fancy restaurant. As the flow goes, you give your order (command) to the waiter (invoker), who then hands it over to the chef(receiver), so you can get food. Might sound simple… but a bit meh to code.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/chain-of-command-be-like-pop-snoke-im-going-to-27790631.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>The idea is pretty simple, but the coding goes around the nose.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2019/07/command-class-diagram.PNG" alt="Image" width="600" height="400" loading="lazy">
<em>Command Design Pattern Class Diagram</em></p>
<p>The flow of operation on the technical side is, you make a concrete command, which implements the Command interface, asking the receiver to complete an action, and send the command to the invoker. The invoker is the person that knows when to give this command. The chef is the only one who knows what to do when given the specific command/order. So, when the execute method of the invoker is run, it, in turn, causes the command objects’ execute method to run on the receiver, thus completing necessary actions.</p>
<h3 id="heading-what-we-need-to-implement-is">What we need to implement is;</h3>
<ol>
<li>An interface Command</li>
<li>A class Order that implements Command interface</li>
<li>A class Waiter (invoker)</li>
<li>A class Chef (receiver)</li>
</ol>
<p>So, the coding goes like this:</p>
<h3 id="heading-chef-the-receiver">Chef, the receiver</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chef</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cookPasta</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is cooking Chicken Alfredo…”);
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">bakeCake</span><span class="hljs-params">()</span> </span>{
        System.out.println(“Chef is baking Chocolate Fudge Cake…”);
    }
}
</code></pre>
<h3 id="heading-command-the-interface">Command, the interface</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">interface</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">abstract</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span></span>;
}
</code></pre>
<h3 id="heading-order-the-concrete-command">Order, the concrete command</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Order</span> <span class="hljs-keyword">implements</span> <span class="hljs-title">Command</span> </span>{
    <span class="hljs-keyword">private</span> Chef chef;
    <span class="hljs-keyword">private</span> String food;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Order</span><span class="hljs-params">(Chef chef, String food)</span> </span>{
        <span class="hljs-keyword">this</span>.chef = chef;
        <span class="hljs-keyword">this</span>.food = food;
    }

    <span class="hljs-meta">@Override</span>
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">if</span> (<span class="hljs-keyword">this</span>.food.equals(“Pasta”)) {
            <span class="hljs-keyword">this</span>.chef.cookPasta();
        } <span class="hljs-keyword">else</span> {
            <span class="hljs-keyword">this</span>.chef.bakeCake();
        }
    }
}
</code></pre>
<h3 id="heading-waiter-the-invoker">Waiter, the invoker</h3>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Waiter</span> </span>{
    <span class="hljs-keyword">private</span> Order order;

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-title">Waiter</span><span class="hljs-params">(Order ord)</span> </span>{
        <span class="hljs-keyword">this</span>.order = ord;
    }

    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">execute</span><span class="hljs-params">()</span> </span>{
        <span class="hljs-keyword">this</span>.order.execute();
    }
}
</code></pre>
<h2 id="heading-you-the-client">You, the client</h2>
<pre><code class="lang-java"><span class="hljs-keyword">public</span> <span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Client</span> </span>{
    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> <span class="hljs-keyword">void</span> <span class="hljs-title">main</span><span class="hljs-params">(String[] args)</span> </span>{
        Chef chef = <span class="hljs-keyword">new</span> Chef();

        Order order = <span class="hljs-keyword">new</span> Order(chef, “Pasta”);
        Waiter waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();

        order = <span class="hljs-keyword">new</span> Order(chef, “Cake”);
        waiter = <span class="hljs-keyword">new</span> Waiter(order);
        waiter.execute();
    }
}
</code></pre>
<p>As you can see above, the Client makes an Order and sets the Receiver as the Chef. The Order is sent to the Waiter, who will know when to execute the Order (i.e. when to give the chef the order to cook). When the invoker is executed, the Orders’ execute method is run on the receiver (i.e. the chef is given the command to either cook pasta ? or bake cake?).</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*gwsVqEIKFmBj01M7dXsQ_A.png" alt="Image" width="600" height="400" loading="lazy">
<em>Final Client Output</em></p>
<h2 id="heading-quick-recap">Quick recap</h2>
<p>In this post we went through:</p>
<ol>
<li>What a design pattern really is,</li>
<li>The different types of design patterns and why they are different</li>
<li>One basic or common design pattern for each type</li>
</ol>
<p>I hope this was helpful.  </p>
<p>Find the code repo for the post, <a target="_blank" href="https://github.com/samsam-026/Design_Patterns">here</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An introduction to Object-Oriented Programming with Ruby ]]>
                </title>
                <description>
                    <![CDATA[ By Saul Costa Object-oriented programming (OOP) is a programming paradigm organized around objects. At a high level, OOP is all about being able to structure code so that its functionality can be shared throughout the application. If done properly, O... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/introduction-to-object-oriented-programming-with-ruby-d594e1c6eebe/</link>
                <guid isPermaLink="false">66c35866d372f14b49bdcbb6</guid>
                
                    <category>
                        <![CDATA[ learning to code ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Ruby ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 26 Feb 2019 22:49:30 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*yk9cvq3T5pHUsObH3XiA1Q.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Saul Costa</p>
<p><strong>Object-oriented programming</strong> (<strong>OOP</strong>) is a programming paradigm organized around objects. At a high level, OOP is all about being able to structure code so that its functionality can be shared throughout the application. If done properly, OOP can lead to very elegantly written programs that have minimal code duplication.</p>
<p>This is opposed to procedural programming (PP), in which you build programs in sequential order and call methods when you want shared behavior between pages in the application. Common procedural programming languages include <a target="_blank" href="https://en.wikipedia.org/wiki/C_(programming_language)">C</a> and <a target="_blank" href="https://en.wikipedia.org/wiki/Go_(programming_language)">Go</a>.</p>
<p>In this tutorial, you’ll learn the fundamental concepts of OOP for <strong>Ruby</strong>, an object-oriented programming language wherein everything is an object. We will be using Ruby since one of its defining attributes — in addition to its elegant syntax and readability — is how it implements OOP techniques. This makes it a great language to start learning OOP with.</p>
<p>We will cover:</p>
<ul>
<li>Creating classes</li>
<li>Instantiating objects</li>
<li>Initializing arguments</li>
<li>Working with inheritance, and</li>
<li>Private and public methods.</li>
</ul>
<p>In learning these concepts, we will build out our own application: an API connector that communicates dynamically with an application that sends a text message. This will include walking through how to leverage concepts such as inheritance and object instantiation to make our code more scalable and reusable!</p>
<p><em>This brief tutorial is adapted from Next Tech’s <a target="_blank" href="https://c.next.tech/2EyLhYk">Introduction to Ruby course</a>, which includes an in-browser sandboxed environment and auto-checked interactive tasks to complete.</em></p>
<p><em>You can follow along with the code snippets in this tutorial using Next Tech’s sandbox which already has Ruby pre-installed. If you chose to use your own IDE, make sure Ruby is installed by following the instructions on the <a target="_blank" href="https://www.ruby-lang.org/en/documentation/installation/">installation page</a>.</em></p>
<h3 id="heading-creating-classes">Creating Classes</h3>
<p>Before we begin, let’s define what an <strong>object</strong> is. At its core, an object is a self-contained piece of code that contains data (“attributes”) and behavior (“methods”) and can communicate with other objects. Objects of the same type are created from <strong>classes</strong>, which act as blueprints that define properties and behavior.</p>
<p>Creating a class in Ruby is fairly easy. To define a class, simply type the <code>class</code> word followed by the name of the class, and end it with the <code>end</code> word. Anything contained between <code>class</code> and <code>end</code> belongs to this class.</p>
<p>Class names in Ruby have a very specific style requirement. They need to start with a letter and if they represent multiple words, each new word needs also to be an uppercase letter — i.e. “CamelCase”.</p>
<p>We’ll start by creating a class called <code>ApiConnector</code>:</p>
<p>Classes in Ruby can store both data and methods. In many traditional OOP languages such as Java, you need to create two methods for each data element you want to be included in the class. One method, the <strong>setter</strong>, sets the value in the class. The other method, the <strong>getter</strong>, allows you to retrieve the value.</p>
<p>The process of creating setter and getter methods for every data attribute can be tiresome and leads to incredibly long class definitions. Thankfully Ruby has a set of tools called <strong>attribute accessors</strong>.</p>
<p>Let’s implement some setters and getters for some new data elements for our class. Since it’s an API connector, it would make sense to have data elements such as <code>title</code>, <code>description</code>, and <code>url</code>. We can add these elements with the following code:</p>
<p>When you merely create a class, it doesn’t do anything — it is simply a definition. In order to work with the class, we need to create an instance of it…we’ll cover that next!</p>
<h3 id="heading-instantiation">Instantiation</h3>
<p>To understand what <strong>instantiation</strong> is, let’s consider a real-world analogy. Let’s imagine that you’re building a house. The first task is to build a blueprint for the house. This blueprint would contain attributes and features of the house, such as the dimensions for each room, how the plumbing will flow, and so on.</p>
<p>Is the blueprint of the house the actual house? Of course not, it simply lists out the attributes and design elements for how the home will be created. So after the blueprint is completed, the actual home can be built — or, “instantiated”.</p>
<p>As explained in the previous section, in OOP, a class is the blueprint for an object. It simply describes what an object will look like and how it will behave. Therefore, instantiation is the process of taking a class definition and creating an object that you can use in a program.</p>
<p>Let’s create a new instance of our <code>ApiConnector</code> class and store it in a variable called <code>api</code>:</p>
<p>Now that we have an object created, we can use the <code>api</code> variable to work with the class attributes. For example, we can run the code:</p>
<pre><code>[Out:]https:<span class="hljs-comment">//next.tech</span>
</code></pre><p>In addition to creating attributes, you can also create methods within a class:</p>
<p>To access this method, we can use the same syntax that we utilized with the attribute accessors:</p>
<p>Putting this all together, running the full class code below will result in the <code>url</code> and the <code>test_method</code> message to be printed:</p>
<pre><code>[Out:]<span class="hljs-string">"https://next.tech"</span><span class="hljs-string">"testing class call"</span>
</code></pre><h3 id="heading-initializer-method">Initializer Method</h3>
<p>One thing you may find handy in Ruby development is the ability to create an <strong>initializer</strong> method. This is simply a method called <code>initialize</code> that will run every time when you create an instance of your class. In this method, you can give values to your variables, call other methods, and do just about anything that you think should happen when a new instance of that class is created.</p>
<p>Let’s update our <code>ApiConnector</code> to utilize an initializer method:</p>
<p>Within the <code>initialize</code> method, we created an instance variable for each of the parameters so that we can use these variables in other parts of the application as well.</p>
<p>We also removed the <code>attr_accessor</code> method since the new <code>initialize</code> method will take care of this for us. If you need the ability to call the data elements outside of the class, then you would still need to have the <code>attr_accessor</code> call in place.</p>
<p>To test if the <code>initialize</code> method is working, let’s create another method within the class that prints these values out:</p>
<p>Finally, we’ll instantiate the class and test the initialize method:</p>
<pre><code>[Out:]<span class="hljs-string">"My title"</span><span class="hljs-string">"My cool description"</span><span class="hljs-string">"https://next.tech"</span>
</code></pre><h4 id="heading-working-with-optional-values">Working with optional values</h4>
<p>Now, what happens when we want to make one of these values optional? For example, what if we want to give a default value to the URL? To do that, we can update our <code>initialize</code> method with the following syntax:</p>
<p>Now our program will have the same output even if we don’t pass the <code>url</code> value while creating a new instance of the class:</p>
<h4 id="heading-using-named-arguments">Using named arguments</h4>
<p>Though this looks simple, passing arguments can get complex in real-world Ruby applications because some methods may take a large number of arguments. In such cases, it becomes difficult to know the order of arguments and what values to assign to them.</p>
<p>To avoid this confusion, you can utilize named arguments, like this:</p>
<p>You can enter the arguments without having to look at the order in the <code>initialize</code> method, and even change the order of the arguments without causing an error:</p>
<h4 id="heading-overriding-default-values">Overriding default values</h4>
<p>What happens if we want to override a default value? We simply update our instantiation call like this:</p>
<p>This update will override our default value of <code>https://next.tech</code>, and calling <code>api.testing_initializer</code> will now print <code>https://next.xyz</code> as the URL.</p>
<h3 id="heading-inheritance">Inheritance</h3>
<p>Now, we are going to learn about an important object-oriented principle called <strong>inheritance</strong>. Before going into how it is executed in Ruby, let’s see why it’s important for building applications.</p>
<p>To start with, inheritance means your classes can have a hierarchy. It is best used when different classes have some shared responsibilities, since it would be a poor practice to duplicate code in each class for identical or even similar behavior.</p>
<p>Take our <code>ApiConnector</code> class. Let's say we have different API classes for various platforms, but each class shares a number of common data or processes. Instead of duplicating code in each of the API connector classes, we can have one <strong>parent class</strong> with the shared data and methods. From there, we can create <strong>child classes</strong> from this parent class. With the way that inheritance works, each of the child classes will have access to the components provided from the parent class.</p>
<p>For example, say we have three APIs: <code>SmsConnector</code>, <code>PhoneConnector</code>, and <code>MailerConnector</code>. If we wrote code individually for each of these classes, it would look like this:</p>
<p>As you can see, we are simply repeating the same code across different classes. This is considered a poor programming practice that violates the <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY</a> (Don’t Repeat Yourself) principle of development. Instead, we can make an <code>ApiConnector</code> parent class, and each of the other classes can inherit the common functionality from this class:</p>
<p>By leveraging inheritance, we were able to cut all of the duplicate code throughout our classes.</p>
<p>The syntax for using inheritance is to define the child class name, followed by the <code>&amp;</code>lt; symbol, then the parent class name — i.e. o<code>ur SmsConnec</code>to<code>r, MailerConnec</code>tor, a<code>nd PhoneConnec</code>tor classes inherit from t<code>he ApiConnec</code>tor class .</p>
<p>Each of these child classes now has access to the full set of elements provided in the parent <code>ApiConnector</code> class. For example, if we create a new instance of <code>SmsConnector</code> with the following parameters, we can call the <code>send_sms</code> method:</p>
<pre><code>[Out:]Sending SMS message <span class="hljs-keyword">with</span> the title <span class="hljs-string">'Hi there!'</span> and description <span class="hljs-string">'I'</span>m an SMS message<span class="hljs-string">'.</span>
</code></pre><p>A rule of thumb in OOP is to ensure that a class performs a single responsibility. For example, the <code>ApiConnector</code> class should not send SMS messages, make phone calls, or send emails since that would be three core responsibilities.</p>
<h3 id="heading-private-and-public-methods">Private and Public Methods</h3>
<p>Before we dive into private and public methods, let’s first go back to our original <code>ApiConnector</code> class and create a <code>SmsConnector</code> class that inherits from <code>ApiConnector</code>. In this class, we will create a method called <code>send_sms</code> that will run a script that contacts an API:</p>
<p>This method will send a <code>title</code> and <code>url</code> to an API, which will in turn send an SMS message. Now we can instantiate the <code>SmsConnector</code> class and call the <code>send_sms</code> message:</p>
<p>Running this code will contact the SMS API and send the message. You can go to the bottom of <a target="_blank" href="http://edutechional-smsy.herokuapp.com/notifications">this page</a> to see your message!</p>
<p>Now, using this example, let’s discuss the types of methods provided by classes.</p>
<p>The <code>send_sms</code> method is a <strong>public method</strong>. This means that anyone working on our class can communicate with this method. This may not seem like a big deal if you are working on an application that no one else is working on. However, if you build an API or code library that is open sourced for others to use, it's vital that your public methods represent elements of functionality that you actually want other developers to use.</p>
<p>Public methods should rarely, if ever, be altered. This is because other developers may be relying on your public methods to be consistent, and a change to a public method may break components of their programs.</p>
<p>So, if you can’t change public methods, how can you work on a production application? That’s where <strong>private methods</strong> come in. A private method is a method that is only accessed by the class that it is contained in. It should never be called by outside services. This means that you can alter their behavior, assuming that these changes don’t have a domino effect and alter the public methods that they may be called from.</p>
<p>Usually private methods are placed at the end of the file after all the public methods. To designate private methods, we use the <code>private</code> word above the list of methods. Let’s add a private method to our <code>ApiConnector</code> class:</p>
<p>Notice how we’re calling this method from the inside of the <code>initialize</code> method of the <code>ApiConnector</code> class? If we run this code, it will give the following output:</p>
<pre><code>[Out:]A secret message <span class="hljs-keyword">from</span> the parent <span class="hljs-class"><span class="hljs-keyword">class</span></span>
</code></pre><p>Now child classes have access to methods in the parent class, right? Well, not always. Let’s remove the <code>secret_method</code> method from the <code>initialize</code> method in <code>ApiConnector</code> and try to call it from our <code>SmsConnector</code> child class, as shown here:</p>
<pre><code>[Out:]Traceback (most recent call last):main.rb:<span class="hljs-number">29</span>:<span class="hljs-keyword">in</span> <span class="hljs-string">`&lt;main&gt;': private method `</span>secret_method<span class="hljs-string">' called for #SmsConnector:0x000056188cfe19b0&gt; (NoMethodError)</span>
</code></pre><p>This is because the <code>SmsConnector</code> class only has access to the public methods from the parent class. The private methods are, by their nature, private. This means that they can only be accessed by the class that they are defined in.</p>
<p>So a good rule of thumb is to create private methods when they should not be used outside the class and public methods when they have to be available throughout the application or used by outside services.</p>
<h4 id="heading-wrapping-up">Wrapping up</h4>
<p>I hope you enjoyed this quick tutorial on the fundamental concepts of object-oriented programming in Ruby! We covered creating classes, attribute accessors, instantiation, initialization, inheritance, and private and public methods.</p>
<p>Ruby is a powerful object-oriented language used by popular applications, including our own here at Next Tech. With this foundational knowledge of OOP, you’re well on your way to developing your own Ruby apps!</p>
<p><em>If you’re interested in learning more about programming with Ruby, check out our Introduction to Ruby course <a target="_blank" href="https://c.next.tech/2EyLhYk">here</a>! In this course we cover core programming skills, such as variables, strings, loops, and conditionals, more advanced OOP topics, and error handling.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Dynamic class definition in Python ]]>
                </title>
                <description>
                    <![CDATA[ By Peter Gleeson Here’s a neat Python trick you might just find useful one day. Let’s look at how you can dynamically define classes, and create instances of them as required. This trick makes use of Python’s object oriented programming (OOP) capabil... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/dynamic-class-definition-in-python-3e6f7d20a381/</link>
                <guid isPermaLink="false">66d46093246e57ac83a2c7c5</guid>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 11 Dec 2018 17:49:19 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/0*bJlMQkXW7FOfL5CL" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Peter Gleeson</p>
<p>Here’s a neat Python trick you might just find useful one day. Let’s look at how you can dynamically define classes, and create instances of them as required.</p>
<p>This trick makes use of Python’s object oriented programming (OOP) capabilities, so we’ll review those first.</p>
<h3 id="heading-classes-and-objects">Classes and objects</h3>
<p>Python is an object-oriented language, meaning it lets you write code in the <a target="_blank" href="https://guide.freecodecamp.org/design-patterns/object-oriented-programming/">object oriented paradigm</a>.</p>
<p>The key concept in this programming paradigm is classes. In Python, these are used to create objects which can have attributes.</p>
<p>Objects are specific instances of a class. A class is essentially a blueprint of what an object is and how it should behave.</p>
<p>Classes are defined with two types of attribute:</p>
<ul>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/classes.html#instance-objects">Data attributes</a> — variables available to a given instance of that class</li>
<li><a target="_blank" href="https://docs.python.org/3/tutorial/classes.html#method-objects">Methods</a> — functions available to an instance of that class</li>
</ul>
<p>The classic OOP example usually involves different types of animal, or food. Here, I’ve gone more practical with a simple data visualization theme.</p>
<p>First, define the class <code>BarChart</code>.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BarChart</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, title, data</span>):</span>
        self.title = title
        self.data = data
       <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"\n"</span>+self.title)
        <span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> self.data.keys():
            print(<span class="hljs-string">"-"</span>*self.data[k]+<span class="hljs-string">" "</span>+k)
</code></pre>
<p>The <code>__init__</code> method lets you set attributes upon instantiation. That is, when you create a new instance of <code>BarChart</code>, you can pass arguments that provide the chart’s title and data.</p>
<p>This class also has a <code>plot()</code> method. This prints a very basic bar chart to the console when it is called. It could feasibly do more interesting things in a real application.</p>
<p>Next, instantiate an instance of <code>BarChart</code>:</p>
<pre><code class="lang-python">data = {<span class="hljs-string">"a"</span>:<span class="hljs-number">4</span>, <span class="hljs-string">"b"</span>:<span class="hljs-number">7</span>, <span class="hljs-string">"c"</span>:<span class="hljs-number">8</span>}bar = BarChart(<span class="hljs-string">"A Simple Chart"</span>, data)
</code></pre>
<p>Now you can use the <code>bar</code> object in the rest of your code:</p>
<pre><code class="lang-python">bar.data[<span class="hljs-string">'d'</span>] = bar.plot()
</code></pre>
<pre><code>A Simple Chart
---- a
------- b
-------- c
----- d
</code></pre><p>This is great, because it allows you to define a class and create instances dynamically. You can spin up instances of other bar charts in one line of code.</p>
<pre><code class="lang-python">new_data = {<span class="hljs-string">"x"</span>:<span class="hljs-number">1</span>, <span class="hljs-string">"y"</span>:<span class="hljs-number">2</span>, <span class="hljs-string">"z"</span>:<span class="hljs-number">3</span>}
bar2 = BarChart(<span class="hljs-string">"Another Chart"</span>, new_data)
bar2.plot()
</code></pre>
<pre><code>Another Chart
- x
-- y
--- z
</code></pre><p>Say you wanted to define several classes of chart. <a target="_blank" href="https://docs.python.org/3.7/tutorial/classes.html#inheritance">Inheritance</a> lets you define classes which “inherit” properties from base classes.</p>
<p>For example, you could define a base <code>Chart</code> class. Then you can define derived classes which inherit from the base.</p>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Chart</span>:</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">__init__</span>(<span class="hljs-params">self, title, data</span>):</span>
        self.title = title
        self.data = data
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot</span>(<span class="hljs-params">self</span>):</span>
        <span class="hljs-keyword">pass</span>
</code></pre>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">BarChart</span>(<span class="hljs-params">Chart</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot</span>(<span class="hljs-params">self</span>):</span>
        print(<span class="hljs-string">"\n"</span>+self.title)
        <span class="hljs-keyword">for</span> k <span class="hljs-keyword">in</span> self.data.keys():
            print(<span class="hljs-string">"-"</span>*self.data[k]+<span class="hljs-string">" "</span>+k)
</code></pre>
<pre><code class="lang-python"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Scatter</span>(<span class="hljs-params">Chart</span>):</span>
    <span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">plot</span>(<span class="hljs-params">self</span>):</span>
        points = zip(data[<span class="hljs-string">'x'</span>],data[<span class="hljs-string">'y'</span>])
        y = max(self.data[<span class="hljs-string">'y'</span>])+<span class="hljs-number">1</span>
        x = max(self.data[<span class="hljs-string">'x'</span>])+<span class="hljs-number">1</span>
        print(<span class="hljs-string">"\n"</span>+self.title)
        <span class="hljs-keyword">for</span> i <span class="hljs-keyword">in</span> range(y,<span class="hljs-number">-1</span>,<span class="hljs-number">-1</span>):
            line = str(i)+<span class="hljs-string">"|"</span>
            <span class="hljs-keyword">for</span> j <span class="hljs-keyword">in</span> range(x):
                <span class="hljs-keyword">if</span> (j,i) <span class="hljs-keyword">in</span> points:
                    line += <span class="hljs-string">"X"</span>
                <span class="hljs-keyword">else</span>:
                    line += <span class="hljs-string">" "</span>
            print(line)
</code></pre>
<p>Here, the <code>Chart</code> class is a base class. The <code>BarChart</code> and <code>Scatter</code> classes inherit the <code>__init__()</code> method from <code>Chart.</code> But they have their own <code>plot()</code> methods which override the one defined in <code>Chart</code><em>.</em></p>
<p>Now you can create scatter chart objects as well.</p>
<pre><code class="lang-python">data = {<span class="hljs-string">'x'</span>:[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">4</span>,<span class="hljs-number">5</span>], <span class="hljs-string">'y'</span>:[<span class="hljs-number">1</span>,<span class="hljs-number">2</span>,<span class="hljs-number">3</span>,<span class="hljs-number">4</span>]}
scatter = Scatter(<span class="hljs-string">'Scatter Chart'</span>, data)
scatter.plot()
</code></pre>
<pre><code>Scatter Chart
<span class="hljs-number">4</span>|     X
<span class="hljs-number">3</span>|      X 
<span class="hljs-number">2</span>|  X
<span class="hljs-number">1</span>| X
<span class="hljs-number">0</span>|
</code></pre><p>This approach lets you write more abstract code, giving your application greater flexibility. Having blueprints to create countless variations of the same general object will save you unnecessarily repeating lines of code. It can also make your application code easier to understand.</p>
<p>You can also import classes into future projects, if you want to reuse them at a later time.</p>
<h3 id="heading-factory-methods">Factory methods</h3>
<p>Sometimes, you won’t know the specific class you want to implement before runtime. For example, perhaps the objects you create will depend on user input, or the results of another process with a variable outcome.</p>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Factory_method_pattern">Factory methods</a> offer a solution. These are methods that take a dynamic list of arguments and return an object. The arguments supplied determine the class of the object that is returned.</p>
<p>A simple example is illustrated below. This factory can return either a bar chart or a scatter plot object, depending on the <code>style</code> argument it receives. A smarter factory method could even guess the best class to use, by looking at the structure of the <code>data</code> argument.</p>
<pre><code class="lang-python"><span class="hljs-function"><span class="hljs-keyword">def</span> <span class="hljs-title">chart_factory</span>(<span class="hljs-params">title, data, style</span>):</span>
    <span class="hljs-keyword">if</span> style == <span class="hljs-string">"bar"</span>:
        <span class="hljs-keyword">return</span> BarChart(title, data)
    <span class="hljs-keyword">if</span> style == <span class="hljs-string">"scatter"</span>:
        <span class="hljs-keyword">return</span> Scatter(title, data)
    <span class="hljs-keyword">else</span>:
        <span class="hljs-keyword">raise</span> Exception(<span class="hljs-string">"Unrecognized chart style."</span>)
</code></pre>
<pre><code class="lang-python">chart = chart_factory(<span class="hljs-string">"New Chart"</span>, data, <span class="hljs-string">"bar"</span>)
chart.plot()
</code></pre>
<p>Factory methods are great when you know in advance which classes you want to return, and the conditions under which they are returned.</p>
<p>But what if you don’t even know this in advance?</p>
<h3 id="heading-dynamic-definitions">Dynamic definitions</h3>
<p>Python lets you define classes dynamically, and instantiate objects with them as required.</p>
<p>Why might you want to do this? The short answer is yet more abstraction.</p>
<p>Admittedly, needing to write code at this level of abstraction is generally a rare occurrence. As always when programming, you should consider if there is an easier solution.</p>
<p>However, there may be times when it genuinely proves useful to define classes dynamically. We’ll cover a possible use-case below.</p>
<p>You may be familiar with Python’s <code>type()</code> function. With one argument, it simply returns the “type” of the object of the argument.</p>
<pre><code class="lang-python">type(<span class="hljs-number">1</span>) <span class="hljs-comment"># &lt;type 'int'&gt;</span>
type(<span class="hljs-string">'hello'</span>) <span class="hljs-comment"># &lt;type 'str'&gt;</span>
type(<span class="hljs-literal">True</span>) <span class="hljs-comment"># &lt;type 'bool'&gt;</span>
</code></pre>
<p>But, with three arguments, <code>type()</code> returns a whole new <a target="_blank" href="https://docs.python.org/3/library/stdtypes.html#bltin-type-objects">type object</a>. This is <a target="_blank" href="https://docs.python.org/3/library/functions.html#type">equivalent to defining a new class</a>.</p>
<pre><code>NewClass = type(<span class="hljs-string">'NewClass'</span>, (object,), {})
</code></pre><ul>
<li>The first argument is a string that gives the new class a name</li>
<li>The next is a tuple, which contains any base classes the new class should inherit from</li>
<li>The final argument is a dictionary of attributes specific to this class</li>
</ul>
<p>When might you need to use something as abstract as this? Consider the following example.</p>
<p><a target="_blank" href="https://flask-table.readthedocs.io/en/stable/#flask-table">Flask Table</a> is a Python library that generates syntax for HTML tables. It can be installed via the pip package manager.</p>
<p>You can use Flask Table to define classes for each table you want to generate. You define a class that inherits from a base <code>Table</code> class. Its attributes are column objects, which are instances of the <code>Col</code> class.</p>
<pre><code class="lang-python"><span class="hljs-keyword">from</span> flask_table <span class="hljs-keyword">import</span> Table, Col
<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">MonthlyDownloads</span>(<span class="hljs-params">Table</span>):</span>
    month = Col(<span class="hljs-string">'Month'</span>)
    downloads = Col(<span class="hljs-string">'Downloads'</span>)

data = [{<span class="hljs-string">'month'</span>:<span class="hljs-string">'Jun'</span>, <span class="hljs-string">'downloads'</span>:<span class="hljs-number">700</span>},
        {<span class="hljs-string">'month'</span>:<span class="hljs-string">'Jul'</span>, <span class="hljs-string">'downloads'</span>:<span class="hljs-number">900</span>},
        {<span class="hljs-string">'month'</span>:<span class="hljs-string">'Aug'</span>, <span class="hljs-string">'downloads'</span>:<span class="hljs-number">1600</span>},
        {<span class="hljs-string">'month'</span>:<span class="hljs-string">'Sep'</span>, <span class="hljs-string">'downloads'</span>:<span class="hljs-number">1900</span>},
        {<span class="hljs-string">'month'</span>:<span class="hljs-string">'Oct'</span>, <span class="hljs-string">'downloads'</span>:<span class="hljs-number">2200</span>}]

table = MonthlyDownloads(data)print(table.__html__())
</code></pre>
<p>You then create an instance of the class, passing in the data you want to display. The <code>__html__()</code> method generates the required HTML.</p>
<p>Now, say you’re developing a tool that uses Flask Table to generate HTML tables based on a user-provided config file. You don’t know in advance how many columns the user wants to define — it could be one, it could be a hundred! How can your code define the right class for the job?</p>
<p>Dynamic class definition is useful here. For each class you wish to define, you can dynamically build the <code>attributes</code> dictionary.</p>
<p>Say your user config is a CSV file, with the following structure:</p>
<pre><code>Table1, column1, column2, column3
Table2, column1
Table3, column1, column2
</code></pre><p>You could read the CSV file line-by-line, using the first element of each row as the name of each table class. The remaining elements in that row would be used to define <code>Col</code> objects for that table class. These are added to an <code>attributes</code> dictionary, which is built up iteratively.</p>
<pre><code><span class="hljs-keyword">for</span> row <span class="hljs-keyword">in</span> csv_file:
    attributes = {}
    <span class="hljs-keyword">for</span> column <span class="hljs-keyword">in</span> row[<span class="hljs-number">1</span>:]:
        attributes[column] = Col(column)
        globals()[row[<span class="hljs-number">0</span>]] = type(row[<span class="hljs-number">0</span>], (Table,), attributes)
</code></pre><p>The code above defines classes for each of the tables in the CSV config file. Each class is added to the <code>globals</code> dictionary.</p>
<p>Of course, this is a relatively trivial example. FlaskTable is capable of generating much more sophisticated tables. A real life use-case would make better use of this! But, hopefully, you’ve seen how dynamic class definition might prove useful in some contexts.</p>
<h3 id="heading-so-now-you-know">So now you know…</h3>
<p>If you are new to Python, then it is worth getting up to speed with classes and objects early on. Try implementing them in your next learning project. Or, <a target="_blank" href="https://github.com/trending/python">browse open source projects on Github</a> to see how other developers make use of them.</p>
<p>For those with a little more experience, it can be very rewarding to learn how things work “behind-the-scenes”. Browsing <a target="_blank" href="https://docs.python.org/3/">the official docs</a> can be illuminating!</p>
<p>Have you ever found a use-case for dynamic class definition in Python? If so, it’d be great to share it in the responses below.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ An intro to object-oriented programming in JavaScript: objects, prototypes, and classes ]]>
                </title>
                <description>
                    <![CDATA[ By Andrea Koutifaris In many programming languages, classes are a well-defined concept. In JavaScript that is not the case. Or at least that wasn’t the case. If you search for O.O.P. and JavaScript you will run into many articles with a lot of differ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/an-intro-to-object-oriented-programming-in-javascript-objects-prototypes-and-classes-5d135e7361b1/</link>
                <guid isPermaLink="false">66c343fd790a62b5fbf7b871</guid>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ prototype ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 28 Nov 2018 16:31:35 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*zGuG4nFo8O4e0WMoNWVbMA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Andrea Koutifaris</p>
<p>In many programming languages, classes are a well-defined concept. In JavaScript that is not the case. Or at least that wasn’t the case. If you search for O.O.P. and JavaScript you will run into many articles with a lot of different recipes on how you can emulate a <code>class</code> in JavaScript.</p>
<p>Is there a simple, K.I.S.S. way to define a class in JavaScript? And if so, why so many different recipes to define a class?</p>
<p>Before answering to those questions, let’s understand better what a JavaScript <code>Object</code> is.</p>
<h3 id="heading-objects-in-javascript"><strong>Objects in JavaScript</strong></h3>
<p>Let’s begin with a very simple example:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> a = {};
a.foo = <span class="hljs-string">'bar'</span>;
</code></pre>
<p>In the above code snippet an object is created and enhanced with a property <code>foo</code>. The possibility of adding things to an existing object is what makes JavaScript different from classic languages like Java.</p>
<p>More in detail, the fact that an object can be enhanced makes it possible to create an instance of an “implicit” class without the need to actually create the class. Let’s clarify this concept with an example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">distance</span>(<span class="hljs-params">p1, p2</span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">Math</span>.sqrt(
    (p1.x - p2.x) ** <span class="hljs-number">2</span> + 
    (p1.y - p2.y) ** <span class="hljs-number">2</span>
  );
}

distance({<span class="hljs-attr">x</span>:<span class="hljs-number">1</span>,<span class="hljs-attr">y</span>:<span class="hljs-number">1</span>},{<span class="hljs-attr">x</span>:<span class="hljs-number">2</span>,<span class="hljs-attr">y</span>:<span class="hljs-number">2</span>});
</code></pre>
<p>In the example above, I didn’t need a Point class to create a point, I just extended an instance of <code>Object</code> adding <code>x</code> and <code>y</code> properties. The function distance doesn’t care if the arguments are an instance of the class <code>Point</code> or not. Until you call <code>distance</code> function with two objects that have an <code>x</code> and <code>y</code> property of type <code>Number</code>, it will work just fine. This concept is sometimes called <em>duck typing</em>.</p>
<p>Up to now, I’ve only used a data object: an object containing only data and no functions. But in JavaScript it is possible to add functions to an object:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> point1 = {
  <span class="hljs-attr">x</span>: <span class="hljs-number">1</span>,
  <span class="hljs-attr">y</span>: <span class="hljs-number">1</span>,
  toString() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`(<span class="hljs-subst">${<span class="hljs-built_in">this</span>.x}</span>,<span class="hljs-subst">${<span class="hljs-built_in">this</span>.y}</span>)`</span>;
  }
};

<span class="hljs-keyword">const</span> point2 = {
  <span class="hljs-attr">x</span>: <span class="hljs-number">2</span>,
  <span class="hljs-attr">y</span>: <span class="hljs-number">2</span>,
  toString() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`(<span class="hljs-subst">${<span class="hljs-built_in">this</span>.x}</span>,<span class="hljs-subst">${<span class="hljs-built_in">this</span>.y}</span>)`</span>;
  }
};
</code></pre>
<p>This time, the objects representing a 2D point have a <code>toString()</code> method. In the example above, the <code>toString</code> code has been duplicated, and this is not good.</p>
<p>There are many ways to avoid that duplication, and, in fact, in different articles about objects and classes in JS you will find different solutions. Have you ever heard of the “Revealing module pattern”? It contains the words “pattern” and “revealing”, sounds cool, and “module” is a must. So it must be the right way to create objects… except that it isn’t. Revealing module pattern can be the right choice in some cases, but it is definitely not the default way of creating objects with behaviors.</p>
<p>We are now ready to introduce classes.</p>
<h3 id="heading-classes-in-javascript"><strong>Classes in JavaScript</strong></h3>
<p>What is a class? From a dictionary: a class is “a set or category of things having some property or attribute in common and differentiated from others by kind, type, or quality.”</p>
<p>In programming languages we often say “An object is an instance of a class”. This means that, using a class, I can create many objects and they all share methods and properties.</p>
<p>Since objects can be enhanced, as we’ve seen earlier, there are may ways to create objects sharing methods and properties. But we want the simplest one.</p>
<p>Fortunately ECMAScript 6 provides the keyword <code>class</code>, making it very easy to create a class:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
  <span class="hljs-keyword">constructor</span>(x, y) {
    <span class="hljs-built_in">this</span>.x = x;
    <span class="hljs-built_in">this</span>.y = y;
  }

  toString() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`(<span class="hljs-subst">${<span class="hljs-built_in">this</span>.x}</span>,<span class="hljs-subst">${<span class="hljs-built_in">this</span>.y}</span>)`</span>;
  }
}
</code></pre>
<p>So, in my opinion, that is the best way of declaring classes in JavaScript. Classes are often related to inheritance:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">HasXY</span> </span>{
  <span class="hljs-keyword">constructor</span>(x, y) {
    <span class="hljs-built_in">super</span>(x, y);
  }

  toString() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">`(<span class="hljs-subst">${<span class="hljs-built_in">this</span>.x}</span>,<span class="hljs-subst">${<span class="hljs-built_in">this</span>.y}</span>)`</span>;
  }
}
</code></pre>
<p>As you can see in the example above, to extend another class it is enough to use the keyword <code>extends</code> .</p>
<p>You can create an object from a class using the <code>new</code> operator:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> p = <span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>,<span class="hljs-number">1</span>);
<span class="hljs-built_in">console</span>.log(p <span class="hljs-keyword">instanceof</span> Point); <span class="hljs-comment">// prints true</span>
</code></pre>
<p>A good object oriented way of defining classes should provide:</p>
<ul>
<li>a simple syntax to declare a class</li>
<li>a simple way to access to the current instance, a.k.a. <code>this</code></li>
<li>a simple syntax to extend a class</li>
<li>a simple way to access the super class instance, a.k.a. <code>super</code></li>
<li>possibly, a simple way of telling if an object is an instance of a particular class. <code>obj instanceof AClass</code> should return <code>true</code> if that object is an instance of that class.</li>
</ul>
<p>The new <code>class</code> syntax provides all the points above.</p>
<p>Before the introduction of the <code>class</code> keyword, what was the way to define a class in JavaScript?</p>
<p>In addition, what really is a class in JavaScript? Why do we often speak about <em>prototypes</em>?</p>
<h3 id="heading-classes-in-javascript-5"><strong>Classes in JavaScript 5</strong></h3>
<p>From <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes">Mozilla MDN page about classes</a>:</p>
<blockquote>
<p>JavaScript classes, introduced in ECMAScript 2015, are primarily syntactical sugar over JavaScript’s existing <strong>prototype-based inheritance</strong>. The class syntax does not introduce a new object-oriented inheritance model to JavaScript.</p>
</blockquote>
<p>The key concept here is <strong>prototype-based inheritance</strong>. Since there is a lot of misunderstanding on what that kind of inheritance is, I will proceed step by step, moving from <code>class</code> keyword to <code>function</code> keyword.</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> </span>{}
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">typeof</span> Shape);
<span class="hljs-comment">// prints function</span>
</code></pre>
<p>It seems that <code>class</code> and <code>function</code> are related. Is <code>class</code> just an alias for <code>function</code> ? No, it isn’t.</p>
<pre><code class="lang-js">Shape(<span class="hljs-number">2</span>);
<span class="hljs-comment">// Uncaught TypeError: Class constructor Shape cannot be invoked without 'new'</span>
</code></pre>
<p>So, it seems that the people who introduced <code>class</code> keyword wanted to tell us that a class is a function that must be called using the <code>new</code> operator.</p>
<pre><code class="lang-js"><span class="hljs-keyword">var</span> Shape = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Shape</span>(<span class="hljs-params"></span>) </span>{} <span class="hljs-comment">// Or just function Shape(){}</span>
<span class="hljs-keyword">var</span> aShape = <span class="hljs-keyword">new</span> Shape();
<span class="hljs-built_in">console</span>.log(aShape <span class="hljs-keyword">instanceof</span> Shape);
<span class="hljs-comment">// prints true</span>
</code></pre>
<p>The example above shows that we can use <code>function</code> to declare a class. We cannot, however, force the user to call the function using the <code>new</code> operator. It is possible to throw an exception if the <code>new</code> operator wasn’t used to call the function.</p>
<p>Anyway I suggest you don’t put that check in every function that acts as a class. Instead use this convention: any function whose name begins with a capital letter is a class and must be called using the <code>new</code> operator.</p>
<p>Let’s move on, and find out what a <em>prototype</em> is:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Shape</span> </span>{
  getName() {
    <span class="hljs-keyword">return</span> <span class="hljs-string">'Shape'</span>;
  }
}
<span class="hljs-built_in">console</span>.log(Shape.prototype.getName);
<span class="hljs-comment">// prints function getName() ...</span>
</code></pre>
<p>Each time you declare a method inside a class, you actually add that method to the prototype of the corresponding function. The equivalent in JS 5 is:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Shape</span>(<span class="hljs-params"></span>) </span>{}
Shape.prototype.getName = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getName</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'Shape'</span>;
};
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> Shape().getName()); <span class="hljs-comment">// prints Shape</span>
</code></pre>
<p>Sometimes the class-functions are called <em>constructors</em> because they act like constructors in a regular class.</p>
<p>You may wonder what happens if you declare a static method:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
  <span class="hljs-keyword">static</span> distance(p1, p2) {
    <span class="hljs-comment">// ...</span>
  }
}

<span class="hljs-built_in">console</span>.log(Point.distance); <span class="hljs-comment">// prints function distance</span>
<span class="hljs-built_in">console</span>.log(Point.prototype.distance); <span class="hljs-comment">// prints undefined</span>
</code></pre>
<p>Since static methods are in a 1 to 1 relation with classes, the static function is added to the constructor-function, not to the prototype.</p>
<p>Let’s recap all these concepts in a simple example:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Point</span>(<span class="hljs-params">x, y</span>) </span>{
  <span class="hljs-built_in">this</span>.x = x;
  <span class="hljs-built_in">this</span>.y = y;
}

Point.prototype.toString = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toString</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-string">'('</span> + <span class="hljs-built_in">this</span>.x + <span class="hljs-string">','</span> + <span class="hljs-built_in">this</span>.y + <span class="hljs-string">')'</span>;
};
Point.distance = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">distance</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>).toString()); <span class="hljs-comment">// prints (1,2)</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> Point(<span class="hljs-number">1</span>,<span class="hljs-number">2</span>) <span class="hljs-keyword">instanceof</span> Point); <span class="hljs-comment">// prints true</span>
</code></pre>
<p>Up to now, we have found a simple way to:</p>
<ul>
<li>declare a function that acts as a class</li>
<li>access the class instance using the <code>this</code> keyword</li>
<li>create objects that are actually an instance of that class (<code>new Point(1,2) instanceof Point</code> returns <code>true</code> )</li>
</ul>
<p>But what about inheritance? What about accessing the super class?</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Hello</span> </span>{
  <span class="hljs-keyword">constructor</span>(greeting) {
    <span class="hljs-built_in">this</span>._greeting = greeting;
  }

  greeting() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._greeting;
  }
}

<span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">World</span> <span class="hljs-keyword">extends</span> <span class="hljs-title">Hello</span> </span>{
  <span class="hljs-keyword">constructor</span>() {
    <span class="hljs-built_in">super</span>(<span class="hljs-string">'hello'</span>);
  }

  worldGreeting() {
    <span class="hljs-keyword">return</span> <span class="hljs-built_in">super</span>.greeting() + <span class="hljs-string">' world'</span>;
  }
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> World().greeting()); <span class="hljs-comment">// Prints hello</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> World().worldGreeting()); <span class="hljs-comment">// Prints hello world</span>
</code></pre>
<p>Above is a simple example of inheritance using ECMAScript 6, below the same example using the the so called <strong>prototype inheritance</strong>:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Hello</span>(<span class="hljs-params">greeting</span>) </span>{
  <span class="hljs-built_in">this</span>._greeting = greeting;
}

Hello.prototype.greeting = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">return</span> <span class="hljs-built_in">this</span>._greeting;
};

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">World</span>(<span class="hljs-params"></span>) </span>{
  Hello.call(<span class="hljs-built_in">this</span>, <span class="hljs-string">'hello'</span>);
}

<span class="hljs-comment">// Copies the super prototype</span>
World.prototype = <span class="hljs-built_in">Object</span>.create(Hello.prototype);
<span class="hljs-comment">// Makes constructor property reference the sub class</span>
World.prototype.constructor = World;

World.prototype.worldGreeting = <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> hello = Hello.prototype.greeting.call(<span class="hljs-built_in">this</span>);
  <span class="hljs-keyword">return</span> hello + <span class="hljs-string">' world'</span>;
};

<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> World().greeting()); <span class="hljs-comment">// Prints hello</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-keyword">new</span> World().worldGreeting()); <span class="hljs-comment">// Prints hello world</span>
</code></pre>
<p>This way of declaring classes is also suggested in the Mozilla MDN example <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/create#Examples">here</a>.</p>
<p>Using the <code>class</code> syntax, we deduced that creating classes involves altering the prototype of a function. But why is that so? To answer this question we must understand what the <code>new</code> operator actually does.</p>
<h3 id="heading-new-operator-in-javascript">New operator in JavaScript</h3>
<p>The <code>new</code> operator is explained quite well in the Mozilla MDN page <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new">here</a>. But I can provide you with a relatively simple example that emulates what the <code>new</code> operator does:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">customNew</span>(<span class="hljs-params">constructor, ...args</span>) </span>{
  <span class="hljs-keyword">const</span> obj = <span class="hljs-built_in">Object</span>.create(constructor.prototype);
  <span class="hljs-keyword">const</span> result = constructor.call(obj, ...args);

  <span class="hljs-keyword">return</span> result <span class="hljs-keyword">instanceof</span> <span class="hljs-built_in">Object</span> ? result : obj;
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Point</span>(<span class="hljs-params"></span>) </span>{}
<span class="hljs-built_in">console</span>.log(customNew(Point) <span class="hljs-keyword">instanceof</span> Point); <span class="hljs-comment">// prints true</span>
</code></pre>
<p>Note that the real <code>new</code> algorithm is more complex. The purpose of the example above is just to explain what happens when you use the <code>new</code> operator.</p>
<p>When you write <code>new Point(1,2)</code>what happens is:</p>
<ul>
<li>The <code>Point</code> prototype is used to create an object.</li>
<li>The function constructor is called and the just created object is passed as the context (a.k.a. <code>this</code>) along with the other arguments.</li>
<li>If the constructor returns an Object, then this object is the result of the new, otherwise the object created from the prototype is the result.</li>
</ul>
<p>So, what does <strong>prototype inheritance</strong> mean? It means that you can create objects that inherit all the properties defined in the prototype of the function that was called with the <code>new</code> operator.</p>
<p>If you think of it, in a classical language the same process happens: when you create an instance of a class, that instance can use the <code>this</code> keyword to access to all the functions and properties (public) defined in the class (and the ancestors). As opposite to properties, all the instances of a class will likely share the same references to the class methods, because there is no need to duplicate the method’s binary code.</p>
<h3 id="heading-functional-programming">Functional programming</h3>
<p>Sometimes people say that JavaScript is not well suited for Object Oriented programming, and you should use functional programming instead.</p>
<p>While I don’t agree that JS is not suited for O.O.P, I do think that functional programming is a very good way of programming. In JavaScript functions are <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Glossary/First-class_Function">first class citizens</a> (e.g. you can pass a function to another function) and it provides features like <code>bind</code> , <code>call</code> or <code>apply</code> which are base constructs used in functional programming.</p>
<p>In addition RX programming could be seen as an evolution (or a specialization) of functional programming. Have a look to <a target="_blank" href="https://rxjs-dev.firebaseapp.com/">RxJs here</a>.</p>
<h3 id="heading-conclusion">Conclusion</h3>
<p>Use, when possible, ECMAScript 6 <code>class</code> syntax:</p>
<pre><code class="lang-js"><span class="hljs-class"><span class="hljs-keyword">class</span> <span class="hljs-title">Point</span> </span>{
  toString() {
    <span class="hljs-comment">//...</span>
  }
}
</code></pre>
<p>or use function prototypes to define classes in ECMAScript 5:</p>
<pre><code class="lang-js"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">Point</span>(<span class="hljs-params"></span>) </span>{}
Point.prototype.toString = <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">toString</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// ...</span>
}
</code></pre>
<p>Hope you enjoyed the reading!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to explain object-oriented programming concepts to a 6-year-old ]]>
                </title>
                <description>
                    <![CDATA[ By Alexander Petkov Have you noticed how the same cliche questions always get asked at job interviews — over and over again? I’m sure you know what I mean. For example: Where do you see yourself in five years? or, even worse: What do you consider ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/object-oriented-programming-concepts-21bb035f7260/</link>
                <guid isPermaLink="false">66c35c2c258ebfc3dc8f1f63</guid>
                
                    <category>
                        <![CDATA[ interview ]]>
                    </category>
                
                    <category>
                        <![CDATA[ jobs ]]>
                    </category>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 27 Jun 2018 22:16:19 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*EirXoYV7GgRi4frvcW-b0A.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Alexander Petkov</p>
<p>Have you noticed how the same cliche questions always get asked at job interviews — over and over again?</p>
<p>I’m sure you know what I mean.</p>
<p>For example:</p>
<blockquote>
<p>Where do you see yourself in five years?</p>
</blockquote>
<p>or, even worse:</p>
<blockquote>
<p>What do you consider to be your greatest weakness?</p>
</blockquote>
<p>Ugh…give me a break. I consider answering this question a great weakness! Anyway, not my point.</p>
<p>As trivial as questions like these may be, they are important because they give clues about you. Your current state of mind, your attitude, your perspective.</p>
<p>When answering, you should be careful, as you may reveal something you later regret.</p>
<p>Today I want to talk about a similar type of question in the programming world:</p>
<blockquote>
<p>What are the main principles of Object-Oriented Programming?</p>
</blockquote>
<p>I’ve been on both sides of this question. It’s one of those topics that gets asked so often that you can’t allow yourself to not know.</p>
<p>Junior and entry-level developers usually have to answer it. Because it’s an easy way for the interviewer to tell three things:</p>
<ol>
<li><strong>Did the candidate prepare for this interview?</strong><br>Bonus points if you hear an answer immediately — it shows a serious approach.</li>
<li><strong>Is the candidate past the tutorial phase?</strong><br>Understanding the principles of Object-Oriented Programming (OOP) shows you’ve gone beyond copy and pasting from tutorials — you already see things from a higher perspective.</li>
<li><strong>Is the candidate’s understanding deep or shallow?</strong><br>The level of competence on this question often equals the level of competence on <strong>most other subjects</strong>. Trust me.</li>
</ol>
<p><img src="https://cdn-media-1.freecodecamp.org/images/9mzHbZ-kiW9wJnVKRlhZqPotx9diwe0omWXX" alt="Image" width="600" height="400" loading="lazy">
<em>How an entry-level developer looks like after nailing this question!</em></p>
<p>The four principles of object-oriented programming are <strong>encapsulation</strong>, <strong>abstraction</strong>, <strong>inheritance</strong>, and <strong>polymorphism</strong>.</p>
<p>These words may sound scary for a junior developer. And the complex, excessively long explanations in Wikipedia sometimes double the confusion.</p>
<p>That’s why I want to give a simple, short, and clear explanation for each of these concepts. It may sound like something you explain to a child, but I would actually love to hear these answers when I conduct an interview.</p>
<h3 id="heading-encapsulation">Encapsulation</h3>
<p>Say we have a program. It has a few logically different objects which communicate with each other — according to the rules defined in the program.</p>
<p>Encapsulation is achieved when each object keeps its state <strong>private</strong>, inside a class. Other objects don’t have direct access to this state. Instead, they can only call a list of public functions — called methods.</p>
<p>So, the object manages its own state via methods — and no other class can touch it unless explicitly allowed. If you want to communicate with the object, you should use the methods provided. But (by default), you can’t change the state.</p>
<p>Let’s say we’re building a tiny Sims game. There are people and there is a cat. They communicate with each other. We want to apply encapsulation, so we encapsulate all “cat” logic into a <code>Cat</code> class. It may look like this:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/M4t8zW9U71xeKSlzT2o8WO47mdzrWkNa4rWv" alt="Image" width="600" height="400" loading="lazy">
<em>You can feed the cat. But you can’t directly change how hungry the cat is.</em></p>
<p>Here the “state” of the cat is the <strong>private variables</strong> <code>mood</code>, <code>hungry</code> and <code>energy</code>. It also has a private method <code>meow()</code><em>.</em> It can call it whenever it wants, the other classes can’t tell the cat when to meow.</p>
<p>What they can do is defined in the <strong>public methods</strong> <code>sleep()</code>, <code>play()</code> and <code>feed()</code><em>.</em> Each of them modifies the internal state somehow and may invoke <code>meow()</code><em>.</em> Thus, the binding between the private state and public methods is made.</p>
<p>This is encapsulation.</p>
<h3 id="heading-abstraction">Abstraction</h3>
<p>Abstraction can be thought of as a natural extension of encapsulation.</p>
<p>In object-oriented design, programs are often extremely large. And separate objects communicate with each other a lot. So maintaining a large codebase like this for years — with changes along the way — is difficult.</p>
<p>Abstraction is a concept aiming to ease this problem.</p>
<p>Applying abstraction means that each object should <strong>only</strong> expose a high-level mechanism for using it.</p>
<p>This mechanism should hide internal implementation details. It should only reveal operations relevant for the other objects.</p>
<p>Think — a coffee machine. It does a lot of stuff and makes quirky noises under the hood. But all you have to do is put in coffee and press a button.</p>
<p>Preferably, this mechanism should be easy to use and should rarely change over time. Think of it as a small set of public methods which any other class can call without “knowing” how they work.</p>
<p>Another real-life example of abstraction?<br>Think about how you use your phone:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/hiX0NQOcZFShroq-a3FM5pFP2LV4UUI5mLle" alt="Image" width="600" height="400" loading="lazy">
<em>Cell phones are complex. But using them is simple.</em></p>
<p>You interact with your phone by using only a few buttons. What’s going on under the hood? You don’t have to know — implementation details are hidden. You only need to know a short set of actions.</p>
<p>Implementation changes — for example, a software update — rarely affect the abstraction you use.</p>
<h3 id="heading-inheritance">Inheritance</h3>
<p>OK, we saw how encapsulation and abstraction can help us develop and maintain a big codebase.</p>
<p>But do you know what is another common problem in OOP design?</p>
<p>Objects are often very similar. They share common logic. But they’re not <strong>entirely</strong> the same. Ugh…</p>
<p>So how do we reuse the common logic and extract the unique logic into a separate class? One way to achieve this is inheritance.</p>
<p>It means that you create a (child) class by deriving from another (parent) class. This way, we form a hierarchy.</p>
<p>The child class reuses all fields and methods of the parent class (common part) and can implement its own (unique part).</p>
<p>For example:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZIm7lFjlrKeMWxcH8fqBapNkuSJIxW9-t9yf" alt="Image" width="600" height="400" loading="lazy">
<em>A private teacher is a type of teacher. And any teacher is a type of Person.</em></p>
<p>If our program needs to manage public and private teachers, but also other types of people like students, we can implement this class hierarchy.</p>
<p>This way, each class adds only what is necessary for it while reusing common logic with the parent classes.</p>
<h3 id="heading-polymorphism">Polymorphism</h3>
<p>We’re down to the most complex word! Polymorphism means “many shapes” in Greek.</p>
<p>So we already know the power of inheritance and happily use it. But there comes this problem.</p>
<p>Say we have a parent class and a few child classes which inherit from it. Sometimes we want to use a collection — for example a list — which contains a mix of all these classes. Or we have a method implemented for the parent class — but we’d like to use it for the children, too.</p>
<p>This can be solved by using polymorphism.</p>
<p>Simply put, polymorphism gives a way to use a class exactly like its parent so there’s no confusion with mixing types. But each child class keeps its own methods as they are.</p>
<p>This typically happens by defining a (parent) interface to be reused. It outlines a bunch of common methods. Then, each child class implements its own version of these methods.</p>
<p>Any time a collection (such as a list) or a method expects an instance of the parent (where common methods are outlined), the language takes care of evaluating the right implementation of the common method — regardless of which child is passed.</p>
<p>Take a look at a sketch of geometric figures implementation. They reuse a common interface for calculating surface area and perimeter:</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/8GySv1U8Kh9nVVyiTqv5cDuWZC7p0uARVeF0" alt="Image" width="600" height="400" loading="lazy">
<em>Triangle, Circle, and Rectangle now can be used in the same collection</em></p>
<p>Having these three figures inheriting the parent <code>Figure Interface</code> lets you create a list of mixed <code>triangles</code>, <code>circles</code>, and <code>rectangles</code>. And treat them like the same type of object.</p>
<p>Then, if this list attempts to calculate the surface for an element, the correct method is found and executed. If the element is a triangle, triangle’s <code>CalculateSurface()</code> is called. If it’s a circle — then circle’s <code>CalculateSurface()</code> is called. And so on.</p>
<p>If you have a function which operates with a figure by using its parameter, you don’t have to define it three times — once for a triangle, a circle, and a rectangle.</p>
<p>You can define it once and accept a <code>Figure</code> as an argument. Whether you pass a triangle, circle or a rectangle — as long as they implement <code>CalculateParamter()</code>, their type doesn’t matter.</p>
<p>I hope this helped. You can directly use these exact same explanations at job interviews.</p>
<p>If you find something still difficult to understand — don’t hesitate to ask in the comments below.</p>
<h3 id="heading-whats-next">What’s next?</h3>
<p>Being prepared to answer one of the all-time interview question classics is great — but sometimes you never get called for an interview.</p>
<p>Next, I’ll focus on what employers want to see in a junior developer and how to stand out from the crowd when job hunting.</p>
<p>Stay tuned.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/PWiBgy57Ye32At-VBM3qIcWdVJQ01Td-ILKl" alt="Image" width="600" height="400" loading="lazy">
<em>Did you like the read? If you'd like to support me, you can buy me a coffee :)</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ A Short Overview of Object Oriented Software Design ]]>
                </title>
                <description>
                    <![CDATA[ By Stanislav Kozlovski Demonstrated by implementing a Role-Playing Game’s classes _[Zeppelin by Richard Wright](https://www.artstation.com/artwork/rO8e6" rel="noopener" target="blank" title=") Introduction Most modern programming languages support a... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/a-short-overview-of-object-oriented-software-design-c7aa0a622c83/</link>
                <guid isPermaLink="false">66c34333a1d481faeda49af6</guid>
                
                    <category>
                        <![CDATA[ object oriented ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Python ]]>
                    </category>
                
                    <category>
                        <![CDATA[ software development ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Software Engineering ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sun, 15 Apr 2018 01:18:13 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*DuIQNSG6UjcEXpskd4_dEQ.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Stanislav Kozlovski</p>
<h4 id="heading-demonstrated-by-implementing-a-role-playing-games-classes">Demonstrated by implementing a Role-Playing Game’s classes</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*DuIQNSG6UjcEXpskd4_dEQ.jpeg" alt="Image" width="600" height="400" loading="lazy">
_[Zeppelin by Richard Wright](https://www.artstation.com/artwork/rO8e6" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-introduction">Introduction</h3>
<p>Most modern programming languages support and encourage object-oriented programming (OOP). Even though lately we seem to be seeing a slight shift away from this, as people start using languages which are not <strong>heavily</strong> influenced by OOP (such as Go, Rust, Elixir, Elm, Scala), most still have objects. The design principles we are going to outline here apply to non-OOP languages as well.</p>
<p>To succeed in writing clear, high-quality, maintainable and extendable code you will need to know about design principles that have proven themselves effective over decades of experience.</p>
<p><strong>Disclosure:</strong> The example we are going to be going through will be in <strong>Python.</strong> Examples are there to prove a point and may be sloppy in other, obvious ways.</p>
<h3 id="heading-object-types">Object Types</h3>
<p>Since we are going to be modelling our code around objects, it would be useful to differentiate between their different responsibilities and variations.</p>
<p>There are three type of objects:</p>
<h4 id="heading-1-entity-object">1. Entity Object</h4>
<p>This object generally corresponds to some real-world entity in the problem space. Say we’re building a role-playing game (RPG), an entity object would be our simple <code>Hero</code> class:</p>
<p>These objects generally contain properties about themselves (such as <code>health</code> or <code>mana</code>) and are modifiable through certain rules.</p>
<h4 id="heading-2-control-object">2. Control Object</h4>
<p>Control objects (sometimes also called <strong>Manager objects</strong>) are responsible for the coordination of other objects. These are objects that <strong>control</strong> and make use of other objects. A great example in our RPG analogy would be the <code>Fight</code> class, which controls two heroes and makes them fight.</p>
<p>Encapsulating the logic for a fight in such a class provides you with multiple benefits: one of which is the easy extensibility of the action. You can very easily pass in a non-player character (NPC) type for the hero to fight, provided it exposes the same API. You can also very easily inherit the class and override some of the functionality to meet your needs.</p>
<h4 id="heading-3-boundary-object">3. Boundary Object</h4>
<p>These are objects which sit at the boundary of your system. Any object which takes input from or produces output to another system — regardless if that system is a User, the internet or a database — can be classified as a boundary object.</p>
<p>These boundary objects are responsible for translating information into and out of our system. In an example where we take User commands, we would need the boundary object to translate a keyboard input (like a spacebar) into a recognizable domain event (such as a character jump).</p>
<h4 id="heading-bonus-value-object">Bonus: Value Object</h4>
<p><a target="_blank" href="https://en.wikipedia.org/wiki/Value_object">Value objects</a> represent a simple value in your domain. They are immutable and have no identity.</p>
<p>If we were to incorporate them into our game, a <code>Money</code> or <code>Damage</code> class would be a great fit. Said objects let us easily distinguish, find and debug related functionality, while the naive approach of using a primitive type — an array of integers or one integer — does not.</p>
<p>They can be classified as a subcategory of <code>**Entity**</code> objects.</p>
<h3 id="heading-key-design-principles">Key Design Principles</h3>
<p>Design principles are rules in software design that have proven themselves valuable over the years. Following them strictly will help you ensure your software is of top-notch quality.</p>
<h4 id="heading-abstraction">Abstraction</h4>
<p>Abstraction is the idea of simplifying a concept to its bare essentials in some context. It allows you to better understand the concept by stripping it down to a simplified version.</p>
<p>The examples above illustrate abstraction — look at how the <code>Fight</code> class is structured. The way you use it is as simple as possible — you give it two heroes as arguments in instantiation and call the <code>fight()</code> method. Nothing more, nothing less.</p>
<p>Abstraction in your code should follow the <a target="_blank" href="https://en.wikipedia.org/wiki/Principle_of_least_astonishment">rule of least surprise</a>. Your abstraction should not surprise anybody with needless and unrelated behavior/properties. In other words — it should be intuitive.</p>
<p>Note that our <code>Hero#take_damage()</code> function does not do something unexpected, like delete our character upon death. But we can expect it to kill our character if his health goes below zero.</p>
<h4 id="heading-encapsulation">Encapsulation</h4>
<p>Encapsulation can be thought of as putting something inside a capsule — you limit its exposure to the outside world. In software, restricting access to inner objects and properties helps with data integrity.</p>
<p>Encapsulation black-boxes inner logic and makes your classes easier to manage, because you know what part is used by other systems and what isn’t. This means that you can easily rework the inner logic while retaining the public parts and be sure that you have not broken anything. As a side-effect, working with the encapsulated functionality from the outside becomes simpler as you have less things to think about.</p>
<p>In most languages, this is done through the so-called <a target="_blank" href="https://en.wikipedia.org/wiki/Access_modifiers">access modifiers</a> (private, protected, and so on). Python is not the best example of this, as it lacks such explicit modifiers built into the runtime, but we use conventions to work around this. The <code>_</code> prefix to the variables/methods denote them as being private.</p>
<p>For example, imagine we change our <code>Fight#_run_attack</code> method to return a boolean variable that indicates if the fight is over rather than raise an exception. We will know that the only code we might have broken is inside the <code>Fight</code> class, because we made the method private.</p>
<p>Remember, code is more frequently changed than written anew. Being able to change your code with as clear and little repercussions as possible is flexibility you want as a developer.</p>
<h4 id="heading-decomposition">Decomposition</h4>
<p>Decomposition is the action of splitting an object into multiple separate smaller parts. Said parts are easier to understand, maintain and program.</p>
<p>Imagine we wanted to incorporate more RPG features like buffs, inventory, equipment and character attributes on top of our <code>Hero</code>:</p>
<p>I assume you can tell this code is becoming pretty messy. Our <code>Hero</code> object is doing too much stuff at once and this code is becoming pretty brittle as a result of that.</p>
<p>For example, one stamina point is worth 5 health. If we ever want to change this in the future to make it worth 6 health, we’d need to change the implementation in multiple places.</p>
<p>The answer is to decompose the <code>Hero</code> object into multiple smaller objects which each encompass some of the functionality.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*etyn_SN7_v4zqGDbeazJVA.png" alt="Image" width="600" height="400" loading="lazy">
<em>A cleaner architecture</em></p>
<p>Now, after decomposing our Hero object’s functionality into <code>HeroAttributes</code>, <code>HeroInventory</code>, <code>HeroEquipment</code>and <code>HeroBuff</code> objects, adding future functionality will be easier, more encapsulated and better abstracted. You can tell our code is way cleaner and clearer on what it does.</p>
<p>There are three types of decomposition relationships:</p>
<ul>
<li><strong>association</strong> — Defines a loose relationship between two components. Both components do not depend on one another but may work together.</li>
</ul>
<p><strong>Example:</strong> <code>Hero</code> and a <code>Zone</code> object.</p>
<ul>
<li><strong>aggregation</strong> — Defines a weak “has-a” relationship between a whole and its parts. Considered weak, because the parts can exist without the whole.</li>
</ul>
<p><strong>Example:</strong> <code>HeroInventory</code> and <code>Item</code>.<br>A <code>HeroInventory</code> can have many <code>Items</code> and an <code>Item</code> can belong to any <code>HeroInventory</code>(such as trading items).</p>
<ul>
<li><strong>composition</strong> — A strong “has-a” relationship where the whole and the part cannot exist without each other. The parts cannot be shared, as the whole depends on those exact parts.</li>
</ul>
<p><strong>Example:</strong> <code>Hero</code> and <code>HeroAttributes</code>.<br>These are the Hero’s attributes — you cannot change their owner.</p>
<h4 id="heading-generalization">Generalization</h4>
<p>Generalization might be the most important design principle — it is the process of extracting shared characteristics and combining them in one place. All of us know about the concept of functions and class inheritance —both are a kind of generalization.</p>
<p>A comparison might clear things up: while <strong>abstraction</strong> reduces complexity by hiding unnecessary detail, <strong>generalization</strong> reduces complexity by replacing multiple entities which perform similar functions with a single construct.</p>
<p>In the given example, we have generalized our common <code>Hero</code> and <code>NPC</code> classes’ functionality into a common ancestor called <code>Entity</code>. This is always achieved through inheritance.</p>
<p>Here, instead of having our <code>NPC</code> and <code>Hero</code> classes implement all the methods twice and violate the <a target="_blank" href="https://en.wikipedia.org/wiki/Don%27t_repeat_yourself">DRY principle</a>, we reduced the complexity by moving their common functionality into a base class.</p>
<p>As a forewarning — do not overdo <a target="_blank" href="https://softwareengineering.stackexchange.com/questions/260343/why-is-inheritance-generally-viewed-as-a-bad-thing-by-oop-proponents">inheritance</a>. <a target="_blank" href="https://en.wikipedia.org/wiki/Design_Patterns#Introduction,_Chapter_1">Many experienced people</a> recommend you favor <a target="_blank" href="https://stackoverflow.com/a/53354">composition over inheritance</a>.</p>
<p>Inheritance is often abused by amateur programmers, probably because it is one of the first OOP techniques they grasp due to its simplicity.</p>
<h4 id="heading-composition">Composition</h4>
<p>Composition is the principle of combining multiple objects into a more complex one. Practically said — it is creating instances of objects and using their functionality instead of directly inheriting it.</p>
<p>An object that uses composition can be called a <strong>composite object</strong>. It is important that this composite is simpler than the sum of its peers. When combining multiple classes into one we want to raise the level of abstraction higher and make the object simpler.</p>
<p>The composite object’s <a target="_blank" href="https://medium.freecodecamp.org/what-is-an-api-in-english-please-b880a3214a82">API</a> must hide its inner components and the interactions between them. Think of a mechanical clock, it has three hands for showing the time and one knob for setting — but internally contains dozens of moving and inter-dependent parts.</p>
<p>As I said, composition is preferred over inheritance, which means you should strive to move common functionality into a separate object which classes then use — rather than stash it in a base class you’ve inherited.</p>
<p>Let’s illustrate a possible problem with over-inheriting functionality:</p>
<p>We just added movement to our game.</p>
<p>As we learned, instead of duplicating the code we used generalization to put the <code>move_right</code> and <code>move_left</code> functions into the <code>Entity</code> class.</p>
<p>Okay, now what if we wanted to introduce mounts into the game?</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/1*dK8x5H7sJF-3px7cbJ46Jw.jpeg" alt="Image" width="600" height="400" loading="lazy">
<em>a good mount :)</em></p>
<p>Mounts would also need to move left and right but do not have the ability to attack. Come to think of it — they might not even have health!</p>
<p>I know what your solution is:</p>
<p>Simply move the <code>move</code> logic into a separate <code>MoveableEntity</code> or <code>MoveableObject</code> class which only has that functionality. The <code>Mount</code> class can then inherit that.</p>
<p>Then, what do we do if we want mounts that have health but cannot attack? More splitting up into subclasses? I hope you can see how our class hierarchy would begin to become complex even though our business logic is still pretty simple.</p>
<p>A somewhat better approach would be to abstract the movement logic into a <code>Movement</code> class (or some better name) and instantiate it in the classes which might need it. This will nicely package up the functionality and make it reusable across all sorts of objects not limited to <code>Entity</code>.</p>
<p>Hooray, composition!</p>
<h4 id="heading-critical-thinking-disclaimer">Critical Thinking Disclaimer</h4>
<p>Even though these design principles have been formed through decades of experience, it is still extremely important that you are able to think critically before blindly applying a principle to your code.</p>
<p>Like all things, too much can be a bad thing. Sometimes principles can be taken too far, you can get too clever with them and end up with something that is actually harder to work with.</p>
<p>As an engineer, your main trait is to critically evaluate the best approach for your unique situation, not blindly follow and apply arbitrary rules.</p>
<h3 id="heading-cohesion-coupling-amp-separation-of-concerns">Cohesion, Coupling &amp; Separation of Concerns</h3>
<h4 id="heading-cohesion">Cohesion</h4>
<p>Cohesion represents the clarity of responsibilities within a module or in other words — its complexity.</p>
<p>If your class performs one task and nothing else, or has a clear purpose — that class has <strong>high cohesion</strong>. On the other hand, if it is somewhat unclear in what it’s doing or has more than one purpose — it has <strong>low cohesion</strong>.</p>
<p>You want your classes to have high cohesion. They should have only one responsibility and if you catch them having more — it might be time to split it.</p>
<h4 id="heading-coupling">Coupling</h4>
<p>Coupling captures the complexity between connecting different classes. You want your classes to have as little and as simple connections to other classes as possible, so that you can swap them out in future events (like changing web frameworks). The goal is to have <strong>loose coupling</strong>.</p>
<p>In many languages this is achieved by heavy use of interfaces —they abstract away the specific class handling the logic and represent a sort of adapter layer in which any class can plug itself in.</p>
<h4 id="heading-separation-of-concerns">Separation of Concerns</h4>
<p>Separation of Concerns (SoC) is the idea that a software system must be split into parts that do not overlap in functionality. Or as the name says — concern — A general term about anything that provides a solution to a problem <em>—</em> must be separated into different places.</p>
<p>A web page is a good example of this — it has its three layers (Information, Presentation and Behavior) separated into three places (HTML, CSS and <a target="_blank" href="https://shinesolutions.com/2013/10/29/respect-the-javascript/">JavaScript respectively</a>).</p>
<p>If you look again at the RPG <code>Hero</code> example, you will see that it had many concerns at the very beginning (apply buffs, calculate attack damage, handle inventory, equip items, manage attributes). We separated those concerns through <strong>decomposition</strong> into more <strong>cohesive</strong> classes which <strong>abstract</strong> and <strong>encapsulate</strong> their details. Our <code>Hero</code> class now acts as a <a target="_blank" href="https://en.wikipedia.org/wiki/Composite_pattern">composite</a> object and is much simpler than before.</p>
<h3 id="heading-payoff">Payoff</h3>
<p>Applying such principles might look overly complicated for such a small piece of code. The truth is it a <strong>must</strong> for any software project that you plan to develop and maintain in the future. Writing such code has a bit of overhead at the very start but pays off multiple times in the long run.</p>
<p>These principles ensure our system is more:</p>
<ul>
<li><strong>Extendable</strong>: <strong>High cohesion</strong> makes it easier to implement new modules without concern of unrelated functionality. <strong>Low coupling</strong> means that a new module has less stuff to connect to therefore it is easier to implement.</li>
<li><strong>Maintainable</strong>: <strong>Low coupling</strong> ensures a change in one module will generally not affect others. <strong>High cohesion</strong> ensures a change in system requirements will require modifying as little number of classes as possible.</li>
<li><strong>Reusable</strong>: <strong>High cohesion</strong> ensures a module’s functionality is complete and well-defined. <strong>Low coupling</strong> makes the module less dependent on the rest of the system, making it easier to reuse in other software.</li>
</ul>
<h3 id="heading-summary">Summary</h3>
<p>We started off by introducing some basic high-level object types (Entity, Boundary and Control).</p>
<p>We then learned key principles in structuring said objects (Abstraction, Generalization, Composition, Decomposition and Encapsulation).</p>
<p>To follow up we introduced two software quality metrics (Coupling and Cohesion) and learned about the benefits of applying said principles.</p>
<p>I hope this article provided a helpful overview of some design principles. If you wish to further educate yourself in this area, here are some resources I would recommend.</p>
<h4 id="heading-further-readings">Further Readings</h4>
<p><a target="_blank" href="https://www.amazon.com/Design-Patterns-Object-Oriented-Addison-Wesley-Professional-ebook/dp/B000SEIBB8">Design Patterns: Elements of Reusable Object-Oriented Software</a> —Arguably the most influential book in the field. A bit dated in its examples <em>(C++ 98)</em> but the patterns and ideas remain very relevant.</p>
<p><a target="_blank" href="http://www.growing-object-oriented-software.com/">Growing Object-Oriented Software Guided by Tests</a> — A great book which shows how to practically apply principles outlined in this article (and more) by working through a project.</p>
<p><a target="_blank" href="https://effectivesoftwaredesign.com/category/oop/">Effective Software Design</a> — A top notch blog containing much more than design insights.</p>
<p><a target="_blank" href="https://www.coursera.org/specializations/software-design-architecture">Software Design and Architecture Specialization</a> — A great series of 4 video courses which teach you effective design throughout its application on a project that spans all four courses.</p>
<p>If this overview has been informative to you, please consider giving it the amount of claps you think it deserves so that more people can stumble upon it and gain value from it.</p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
