<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Aaquif Zubair on Medium]]></title>
        <description><![CDATA[Stories by Aaquif Zubair on Medium]]></description>
        <link>https://medium.com/@aaquifzubair?source=rss-e94e55184319------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*oMdbNaw8eA5bB4kuSAJslg.jpeg</url>
            <title>Stories by Aaquif Zubair on Medium</title>
            <link>https://medium.com/@aaquifzubair?source=rss-e94e55184319------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 19 Nov 2026 02:37:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aaquifzubair/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Understanding Insertion Sort with Real-Life Examples and Java Code]]></title>
            <link>https://aaquifzubair.medium.com/understanding-insertion-sort-with-real-life-examples-and-java-code-d97e1ed3a13?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/d97e1ed3a13</guid>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[insertion-sort]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <category><![CDATA[dsa-training]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Fri, 04 Aug 2023 10:33:39 GMT</pubDate>
            <atom:updated>2023-08-04T10:47:38.787Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Introduction</strong>: As you are here you know what sorting is? I will try to let you understand insertion sort with real life example.</p><h3>Insertion Sort Explained:</h3><p>Imagine you have an unsorted hand of cards, and you want to arrange them in ascending order. Insertion Sort mimics the way you’d naturally sort these cards. Here’s how it works:</p><h3>Step 1: Begin with the First Card (Element)</h3><p>You start with the first card in your hand, and you consider it as the sorted part. Since you only have one card, it’s technically already sorted.</p><h3>Step 2: Insert Cards into the Sorted Part</h3><ol><li>Pick the next card from the unsorted part of your hand.</li><li>Compare the card with the cards in the sorted part from right to left.</li><li>If the picked card is smaller, move the larger cards one position to the right to make space for the new card.</li><li>Insert the picked card into its correct position in the sorted part.</li></ol><h3>Step 3: Repeat Until All Cards are Sorted</h3><p>Continue picking cards from the unsorted part, inserting them into the correct positions within the sorted part, and expanding the sorted part until no unsorted cards remain.</p><pre>public class InsertionSort {<br>    public static void insertionSort(int[] arr) {<br>        int n = arr.length;<br><br>       for (int i = 0; i &lt;= n - 1; i++) {<br>            int j = i;<br>            while (j &gt; 0 &amp;&amp; arr[j - 1] &gt; arr[j]) {<br>                int temp = arr[j - 1];<br>                arr[j - 1] = arr[j];<br>                arr[j] = temp;<br>                j--;<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {64, 34, 25, 12, 22, 11, 90};<br><br>        System.out.println(&quot;Original Array:&quot;);<br>        printArray(arr);<br><br>        insertionSort(arr);<br><br>        System.out.println(&quot;\nSorted Array:&quot;);<br>        printArray(arr);<br>    }<br><br>    public static void printArray(int[] arr) {<br>        for (int num : arr) {<br>            System.out.print(num + &quot; &quot;);<br>        }<br>        System.out.println();<br>    }<br>}</pre><h3>Conclusion:</h3><p>Insertion Sort is a simple yet effective sorting algorithm that mirrors how we naturally sort objects in real life. By breaking down the algorithm step by step and providing a Java code implementation, we hope this article has helped you understand Insertion Sort and its practical application. As you dive deeper into the world of data structures and algorithms, this knowledge will serve as a solid foundation for exploring more complex sorting techniques.</p><p>You can refer my other articles on sorting algorithm as well.</p><p><a href="https://aaquifzubair.medium.com/title-understanding-bubble-sort-a-simple-sorting-algorithm-in-java-f5591d030c1d">https://aaquifzubair.medium.com/title-understanding-bubble-sort-a-simple-sorting-algorithm-in-java-f5591d030c1d</a><br><a href="https://aaquifzubair.medium.com/selection-sort-a-beginners-guide-to-understanding-sorting-in-java-858be65865cd">https://aaquifzubair.medium.com/selection-sort-a-beginners-guide-to-understanding-sorting-in-java-858be65865cd</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d97e1ed3a13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Title: Understanding Bubble Sort : A Simple Sorting Algorithm in Java]]></title>
            <link>https://aaquifzubair.medium.com/title-understanding-bubble-sort-a-simple-sorting-algorithm-in-java-f5591d030c1d?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/f5591d030c1d</guid>
            <category><![CDATA[bubble-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sorting]]></category>
            <category><![CDATA[java-algorithm]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Wed, 02 Aug 2023 18:52:37 GMT</pubDate>
            <atom:updated>2023-08-02T18:54:30.854Z</atom:updated>
            <content:encoded><![CDATA[<h3>Understanding Bubble Sort : A Simple Sorting Algorithm in Java</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*E8-UPvTELRsEonw1xCVehA.jpeg" /></figure><p><strong>Introduction:</strong><br>Bubble Sort is one of the sorting technique to sort the array / list. It s a basic sorting algorithm that repeatedly steps through a list, compares adjacent elements, and swaps them if they are in the wrong order. This process continues until the entire array / list is sorted.</p><p><strong>Understanding Bubble Sort with real life example.</strong></p><p><em>Imagine you are a teacher and you need to arrange the students in ascending order of there height. From the shortest student in front to the tallest student at the end.</em></p><p><strong>Steps to follow.</strong></p><ol><li><strong>Find the tallest student :</strong> Start from first student and compare it with next one, if next one is shorter then swap them, do it till last student.<br>At the end you will have tallest student in the end.</li><li><strong>Find the second tallest :</strong> Again start from first student and compare it with next one, if next one is shorter then swap them, do it till last second last student. At the end you will have second tallest student at second last position.</li><li><strong>repeat until everyone is placed :</strong> Continue this process for remaining students (excluding the last student), Each time swap the student if next student is shorter.</li><li><strong>Boohoo, Students are sorted!</strong> : In the end the line of students will be sorted from shortest to tallest.</li></ol><p><strong>How Bubble Sort Works:</strong></p><ol><li>Start with the first element (index 0) and compare it with the next element (index 1).</li><li>If the first element is greater than the second element, swap them.</li><li>Move to the next pair (index 1 and index 2) and repeat the comparison and swapping.</li><li>Continue this process until the last pair of elements is compared and swapped if necessary.</li><li>After one pass, the largest element will be in its correct position at the end of the list.</li><li>Repeat the process for the remaining elements (excluding the last element) until the entire list is sorted.</li></ol><p><strong>Example Illustration: <br></strong>Let’s illustrate the bubble sort algorithm with a simple example:</p><p>Consider an unsorted array: [5, 2, 9, 1, 5, 6]</p><p>Step 1: Compare and Swap</p><ul><li>[<strong>5, 2</strong>, 9, 1, 5, 6] (5 &gt; 2, so swap)</li><li>[2, <strong>5, 9</strong>, 1, 5, 6] (5 &lt; 9, no swap)</li><li>[2, 5, <strong>9, 1</strong>, 5, 6] (9 &gt; 1, so swap)</li><li>[2, 5, 1, <strong>9, 5</strong>, 6] (9 &gt; 5, so swap)</li><li>[2, 5, 1, 5, <strong>9, 6</strong>] (9 &gt; 6, so swap)</li></ul><p>Step 2: Continue with the remaining elements (excluding the last element)</p><ul><li>[2, 5, 1, 5, 6, 9] (no swaps in this pass i.e 2nd pass, because 6 is already at right position)</li></ul><p>Step 3: Array will be sorted after 5 pass which is the length of array.<br><strong> [1, 2, 2, 5, 6, 9]</strong></p><p><strong>Code Implementation in Java:</strong></p><pre>public class BubbleSort {<br><br>    public static void bubbleSort(int[] arr) {<br>        int n = arr.length;<br><br>        for (int i = 0; i &lt; n - 1; i++) {<br>            swapped = false;<br><br>            for (int j = 0; j &lt; n - i - 1; j++) {<br>                if (arr[j] &gt; arr[j + 1]) {<br>                    // Swap arr[j] and arr[j+1]<br>                    int temp = arr[j];<br>                    arr[j] = arr[j + 1];<br>                    arr[j + 1] = temp;<br>                }<br>            }<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {5, 2, 9, 1, 5, 6};<br>        bubbleSort(arr);<br><br>        System.out.println(&quot;Sorted Array:&quot;);<br>        for (int num : arr) {<br>            System.out.print(num + &quot; &quot;);<br>        }<br>    }<br>}</pre><p><strong>Conclusion</strong></p><p>Bubble sort is a straightforward sorting algorithm, and although it is not efficient for large datasets, it is essential to understand its principles as it serves as a foundation for other sorting techniques. The algorithm repeatedly compares adjacent elements and swaps them until the entire list is sorted. While not recommended for large-scale sorting tasks, bubble sort is still a valuable learning tool and can be helpful for small arrays or educational purposes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f5591d030c1d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Selection Sort: A Beginner’s Guide to Understanding Sorting in Java]]></title>
            <link>https://aaquifzubair.medium.com/selection-sort-a-beginners-guide-to-understanding-sorting-in-java-858be65865cd?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/858be65865cd</guid>
            <category><![CDATA[data-structures]]></category>
            <category><![CDATA[selection-sort]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[java]]></category>
            <category><![CDATA[sorting-algorithms]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Mon, 31 Jul 2023 11:53:14 GMT</pubDate>
            <atom:updated>2023-07-31T11:53:14.166Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/507/1*gucrT-YQjn1EYnyNtogDVQ.jpeg" /></figure><p><strong>Introduction:</strong> Sorting is a fundamental concept in computer science, and one of the simplest sorting algorithms is the “<strong>Selection Sort.</strong>” As a beginner in Data Structures and Algorithms (DSA), you might find sorting algorithms intimidating, but fear not! In this article, we will discover the Selection Sort algorithm using Java examples, making it easy for you to grasp and remember.</p><p><strong>What is Selection Sort?</strong> Selection Sort is a straightforward sorting algorithm that repeatedly finds the minimum (or maximum) element from an unsorted part of the array and places it at the beginning (or end) of the sorted part. It works by dividing the array into two portions: the sorted portion at the beginning and the unsorted portion at the end.</p><p><strong>Understanding Selection Sort with real life example.</strong></p><p><em>Imagine you are a teacher and you need to arrange the students in ascending order of there height. From the shortest student in front to the tallest student at the end.</em></p><p><strong>Steps to follow.</strong></p><ol><li><strong>Find the shortest student :</strong> Search for the shortest student, Once you find him then place him to at the beginning of the line.</li><li><strong>Find the next shortest student :</strong> Now exclude the first student which you placed at the correct position and look for the next shortest student from the remaining student and put him to 2nd(Behind the first student) place.</li><li><strong>repeat until everyone is placed :</strong> Continue this process, Each time find the shortest student from the remaining students and put him to correct position.</li><li><strong>Boohoo, Students are sorted!</strong> : Continue this process until every student is correctly placed in the line. In the end the line of students will be sorted from shortest to tallest.</li></ol><p><strong>Step-by-Step Explanation using Java code example.</strong></p><ol><li>Let’s consider an array of integers as an example:</li></ol><pre>int[] arr = {64, 25, 12, 22, 11};</pre><p>2. We start by assuming that the first element (index 0) is the minimum element in the unsorted portion. We’ll initialise a variable called minIndex to keep track of the minimum element&#39;s index.</p><p>3. Next, we iterate through the unsorted portion of the array, starting from index i = 0. For each iteration, we find the smallest element in the unsorted portion and swap it with the element at index i. This effectively adds the smallest element to the sorted portion at the beginning of the array.</p><p>4. Let’s walk through the first iteration:</p><ul><li>Initially, minIndex = 0 (the first element is assumed to be the smallest).</li><li>We start the loop with i = 0 and compare arr[i] (i.e., arr[0]) with arr[minIndex] (i.e., arr[0]). Since there&#39;s only one element, it&#39;s the smallest, and no swap is needed.</li><li>The array remains unchanged after the first iteration: {64, 25, 12, 22, 11}.</li></ul><p>5. For the second iteration, we start with i = 1. Now, we find the smallest element in the remaining unsorted portion ({25, 12, 22, 11}), which is 11 at index 4.</p><p>6. We swap the elements at indices i and minIndex, which means we swap arr[1] with arr[4]. The array after the second iteration becomes: {64, 11, 12, 22, 25}.</p><p>7. We continue this process for the remaining iterations until the array is completely sorted.</p><p><strong>Java Implementation:</strong></p><pre>public class SelectionSort {<br>    public static void selectionSort(int[] arr) {<br>        int n = arr.length;<br><br>        for (int i = 0; i &lt; n - 1; i++) {<br>            int minIndex = i;<br>            for (int j = i + 1; j &lt; n; j++) {<br>                // Find the index of the element which is the smallest in remaing array<br>                if (arr[j] &lt; arr[minIndex]) {<br>                    minIndex = j;<br>                }<br>            }<br>            // Swap the minimum element at ith position.<br>            int temp = arr[minIndex];<br>            arr[minIndex] = arr[i];<br>            arr[i] = temp;<br>        }<br>    }<br><br>    public static void main(String[] args) {<br>        int[] arr = {64, 25, 12, 22, 11};<br>        System.out.println(&quot;Original array: &quot; + Arrays.toString(arr));<br>        selectionSort(arr);<br>        System.out.println(&quot;Sorted array: &quot; + Arrays.toString(arr));<br>    }<br>}</pre><p><strong>Conclusion:</strong></p><p>Congratulations! You now understand the Selection Sort algorithm in Java. It is essential to practice implementing and visualizing sorting algorithms to strengthen your DSA skills. Selection Sort, though simple, lays the foundation for more complex sorting algorithms, and mastering it will be valuable in your journey to becoming a proficient programmer. Keep exploring and enjoy your learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=858be65865cd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding the Strategy Design Pattern with Java Examples: A Beginner’s Guide]]></title>
            <link>https://blog.devgenius.io/understanding-the-strategy-design-pattern-with-java-examples-a-beginners-guide-c8cf075603b4?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/c8cf075603b4</guid>
            <category><![CDATA[beginners-guide]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[strategy-design-pattern]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 09:48:56 GMT</pubDate>
            <atom:updated>2023-07-31T12:41:22.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*1vLnOV6BeJS_so0Wjgmmkg.jpeg" /></figure><p><strong>Introduction:</strong> Design patterns are essential tools in a software developer’s toolkit. They provide proven solutions to common programming challenges, making code more flexible, maintainable, and reusable. Among the many design patterns, the Strategy Design Pattern stands out for its simplicity and effectiveness in managing interchangeable algorithms or behaviors. In this article, we will explore the Strategy Design Pattern with easy-to-understand Java examples, perfect for beginners or those with limited knowledge of design patterns.</p><p><strong>What is the Strategy Design Pattern?</strong> The Strategy Design Pattern is a behavioral design pattern that allows us to define a family of algorithms, encapsulate each one as a separate class, and make them interchangeable at runtime. It lets us decouple the algorithms from the main code, promoting flexibility and ease of maintenance.</p><p><strong>Scenario: </strong>Implementing Attack Behaviors for a Video Game Character Let’s imagine we have a video game character that can perform various types of attacks, such as punching, kicking, and shooting. Instead of hard-coding these attack behaviors into the character class, we’ll use the Strategy Design Pattern to manage and switch between different attack strategies.</p><p>Implementation Without Strategy Pattern.</p><pre>// Character class without using strategy<br>public class CharacterWithoutStrategy {<br>    private String attackType;<br><br>    public CharacterWithoutStrategy() {<br>        this.attackType = &quot;punch&quot;; // Default attack type<br>    }<br><br>    public void setAttackType(String attackType) {<br>        this.attackType = attackType;<br>    }<br><br>    public void performAttack() {<br>        if (attackType.equals(&quot;punch&quot;)) {<br>            System.out.println(&quot;Character performs a punch attack!&quot;);<br>        } else if (attackType.equals(&quot;kick&quot;)) {<br>            System.out.println(&quot;Character performs a kick attack!&quot;);<br>        } else if (attackType.equals(&quot;shoot&quot;)) {<br>            System.out.println(&quot;Character performs a shoot attack!&quot;);<br>        } else {<br>            System.out.println(&quot;Invalid attack type!&quot;);<br>        }<br>    }<br>}<br><br>// Usage of CharacterWithoutStrategy<br>public class MainWithoutStrategy {<br>    public static void main(String[] args) {<br>        CharacterWithoutStrategy character = new CharacterWithoutStrategy();<br>        character.performAttack(); // Output: Character performs a punch attack!<br><br>        character.setAttackType(&quot;kick&quot;);<br>        character.performAttack(); // Output: Character performs a kick attack!<br><br>        character.setAttackType(&quot;shoot&quot;);<br>        character.performAttack(); // Output: Character performs a shoot attack!<br><br>        character.setAttackType(&quot;fire&quot;); // Invalid attack type!<br>        character.performAttack(); // Output: Invalid attack type!<br>    }<br>}</pre><p><strong>Explanation:</strong> In this implementation, we’ve discarded the use of the Strategy Design Pattern, and the attack behaviors are directly incorporated into the CharacterWithoutStrategy class. As a result, the character class itself has the responsibility of handling different attack behaviors based on the value of the attackType variable.</p><p>While this approach might seem simpler initially, it can quickly become cumbersome and less maintainable as more attack types or variations are added to the game. Each time a new attack behavior is introduced, the performAttack() method needs to be updated with additional conditional checks, leading to code duplication and decreased readability.</p><p>Moreover, with this approach, any changes to the character’s attack logic would require modifications directly to the CharacterWithoutStrategy class, potentially introducing bugs or unexpected side effects. This tight coupling can hinder code maintenance and make the system less flexible when accommodating future changes or new attack strategies.</p><p>By avoiding the Strategy Design Pattern, we miss out on the opportunity to separate concerns and maintain a clear separation of attack behaviors, which is where the Strategy pattern shines.</p><p>Implementation with Strategy Design Pattern.</p><ol><li>Define the AttackStrategy Interface:</li></ol><pre>// AttackStrategy interface<br>public interface AttackStrategy {<br>    void attack();<br>}</pre><p>2. Implement Concrete Strategy Classes:</p><pre>// Concrete strategy classes<br>public class PunchAttack implements AttackStrategy {<br>    @Override<br>    public void attack() {<br>        System.out.println(&quot;Character performs a punch attack!&quot;);<br>    }<br>}<br><br>public class KickAttack implements AttackStrategy {<br>    @Override<br>    public void attack() {<br>        System.out.println(&quot;Character performs a kick attack!&quot;);<br>    }<br>}<br><br>public class ShootAttack implements AttackStrategy {<br>    @Override<br>    public void attack() {<br>        System.out.println(&quot;Character performs a shoot attack!&quot;);<br>    }<br>}</pre><p>3. Create the Character Class using the Strategy:</p><pre>// Character class using strategy<br>public class Character {<br>    private AttackStrategy attackStrategy;<br><br>    public Character(AttackStrategy attackStrategy) {<br>        this.attackStrategy = attackStrategy;<br>    }<br><br>    public void setAttackStrategy(AttackStrategy attackStrategy) {<br>        this.attackStrategy = attackStrategy;<br>    }<br><br>    public void performAttack() {<br>        attackStrategy.attack();<br>    }<br>}</pre><p>4. Usage</p><pre>public class Main {<br>    public static void main(String[] args) {<br>        Character character = new Character(new PunchAttack());<br>        character.performAttack(); // Output: Character performs a punch attack!<br><br>        character.setAttackStrategy(new KickAttack());<br>        character.performAttack(); // Output: Character performs a kick attack!<br><br>        character.setAttackStrategy(new ShootAttack());<br>        character.performAttack(); // Output: Character performs a shoot attack!<br>    }<br>}</pre><p><strong>Conclusion:</strong> The Strategy Design Pattern allows us to design more maintainable and flexible code by separating different algorithms or behaviors into interchangeable classes. In our video game character example, we successfully encapsulated the attack strategies and switched between them at runtime without modifying the character class. By leveraging the Strategy Design Pattern, developers can improve code quality, promote code reuse, and make future modifications easier, ultimately leading to more robust and efficient software.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c8cf075603b4" width="1" height="1" alt=""><hr><p><a href="https://blog.devgenius.io/understanding-the-strategy-design-pattern-with-java-examples-a-beginners-guide-c8cf075603b4">Understanding the Strategy Design Pattern with Java Examples: A Beginner’s Guide</a> was originally published in <a href="https://blog.devgenius.io/">Dev Genius</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What the heck is SOLID Principle.]]></title>
            <link>https://aaquifzubair.medium.com/what-the-heck-is-solid-principle-2d029a35ed14?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/2d029a35ed14</guid>
            <category><![CDATA[single-responsibility]]></category>
            <category><![CDATA[solid]]></category>
            <category><![CDATA[interface-design]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[java]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Thu, 27 Jul 2023 09:12:12 GMT</pubDate>
            <atom:updated>2023-07-27T09:12:12.196Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Definition:-</strong><br>The SOLID principles are a set of five design principles that were introduced by <strong>Robert C. Martin</strong> to help developers create more maintainable and scalable software. Each letter in the word <strong>“SOLID”</strong> represents one of these principles Which are described below:</p><p>1. Single Responsibility Principle (SRP)<br>2. Open/Closed Principle (OCP)<br>3. Liskov Substitution Principle (LSP)<br>4. Interface Segregation Principle (ISP)<br>5. Dependency Inversion Principle (DIP)</p><ol><li><strong>Single Responsibility Principle (SRP)</strong> : The Single Responsibility Principle states that a class should have only one reason to change. It should have a single responsibility or purpose, meaning it should do one thing and do it well. It might look little confusing, We will try to understand with below example:</li></ol><p>The ReportGeneratorAndSaver class combines the responsibilities of both report generation and saving to a file into a single class. The generateReport method generates the report content and then directly calls the saveToFile method to save it to a file.</p><p>Code Without SRP.</p><pre>public class ReportGeneratorAndSaver {<br>    private Data data;<br><br>    public ReportGeneratorAndSaver(Data data) {<br>        this.data = data;<br>    }<br><br>    public String generateReport() {<br>        // Generate the report from data<br>        String reportContent = &quot;Report Content...&quot;;<br>        saveToFile(reportContent); // Issue: Mixing responsibilities of report generation and saving<br>        return reportContent;<br>    }<br><br>    public void saveToFile(String content) {<br>        // Save the report content to a file<br>        try (FileWriter fileWriter = new FileWriter(&quot;report.txt&quot;)) {<br>            fileWriter.write(content);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p><strong>Issues:-</strong> The issue with this approach is that the class now violates the Single Responsibility Principle. It has two distinct responsibilities: generating a report and saving it to a file. If there are any changes needed in the report generation logic or the way reports are saved, you would need to modify this single class, which increases the risk of introducing bugs and makes the code harder to maintain.</p><p>Refactored code with SRP.</p><pre><br>// Report generation class<br>public class ReportGenerator {<br>    private Data data;<br><br>    public ReportGenerator(Data data) {<br>        this.data = data;<br>    }<br><br>    public String generateReport() {<br>        // Generate the report from data<br>        String reportContent = &quot;Report Content...&quot;;<br>        return reportContent;<br>    }<br>}<br><br>// Report saving class<br>public class ReportSaver {<br>    public void saveToFile(String content) {<br>        // Save the report content to a file<br>        try (FileWriter fileWriter = new FileWriter(&quot;report.txt&quot;)) {<br>            fileWriter.write(content);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p><strong>Explaination:-</strong> In the Above example, the ReportGenerator class has the responsibility of generating the report content, and the ReportSaver class has the responsibility of saving the report content to a file. Each class focuses on its own specific task, following the SRP. By separating these responsibilities into two separate classes (ReportGenerator and ReportSaver as shown in the Above Example), each class has a single responsibility, and changes in one aspect of the system won&#39;t affect the other. This promotes better code organization, maintainability, and reusability, which aligns with the principles of SOLID.</p><p>2. <strong>Open/Closed Principle (OCP):</strong> Software entities (classes, modules, functions, etc.) should be open for extension but closed for modification. In other words, the behavior of a component can be extended without modifying its source code. This principle encourages the use of abstractions and interfaces, allowing new functionality to be added through new classes rather than altering existing ones. Let’s understand it with an example:</p><p>In this example, we’ve added a new Triangle class representing a triangle shape. Without adhering to the OCP(Open/Closed Principle), we had to modify the existing AreaCalculator class to handle the new Triangle shape. We&#39;ve added an additional conditional check for the Triangle type inside the calculateArea method.</p><pre>public class AreaCalculator {<br>    public double calculateArea(Shape shape) {<br>        if (shape instanceof Circle) {<br>            Circle circle = (Circle) shape;<br>            return Math.PI * circle.getRadius() * circle.getRadius();<br>        } else if (shape instanceof Rectangle) {<br>            Rectangle rectangle = (Rectangle) shape;<br>            return rectangle.getWidth() * rectangle.getHeight();<br>        } else if (shape instanceof Triangle) {<br>            Triangle triangle = (Triangle) shape;<br>            return (triangle.getBase() * triangle.getHeight()) / 2;<br>        } else {<br>            throw new IllegalArgumentException(&quot;Unsupported shape type&quot;);<br>        }<br>    }<br>}<br><br>public class Triangle extends Shape {<br>    private double base;<br>    private double height;<br><br>    public Triangle(double base, double height) {<br>        this.base = base;<br>        this.height = height;<br>    }<br><br>    // Other methods specific to the Triangle shape<br>}</pre><p>Issue: The problem with this approach is that every time we add a new shape, we have to modify the existing AreaCalculator class. This violates the Open/Closed Principle, as we are constantly modifying the class when new shapes are introduced. This can lead to several issues:</p><ol><li>Code Modification: Frequent modifications to the AreaCalculator class increase the chances of introducing bugs and make the codebase more complex and harder to maintain.</li><li>Code Duplication: If we have other classes that also need to calculate the area of shapes, we might end up duplicating the same conditional checks for shape types in multiple places, leading to code duplication.</li><li>Tight Coupling: The AreaCalculator class becomes tightly coupled to specific shape classes, which reduces its flexibility and reusability.</li></ol><p>To follow the Open/Closed Principle, we can use abstraction and polymorphism to design the classes more effectively:</p><pre>public abstract class Shape {<br>    public abstract double calculateArea();<br>}<br><br>public class Circle extends Shape {<br>    private double radius;<br><br>    public Circle(double radius) {<br>        this.radius = radius;<br>    }<br><br>    public double calculateArea() {<br>        return Math.PI * radius * radius;<br>    }<br>}<br><br>public class Rectangle extends Shape {<br>    private double width;<br>    private double height;<br><br>    public Rectangle(double width, double height) {<br>        this.width = width;<br>        this.height = height;<br>    }<br><br>    public double calculateArea() {<br>        return width * height;<br>    }<br>}<br><br>// Add other shape classes extending Shape and providing their own calculateArea method.<br><br>public class AreaCalculator {<br>    public double calculateArea(Shape shape) {<br>        return shape.calculateArea(); // No conditional checks needed; open for extension, closed for modification.<br>    }<br>}</pre><p>Now, the AreaCalculator class is open for extension because we can add new shape classes without modifying the AreaCalculator class. The AreaCalculator depends on the abstraction provided by the Shape class, and new shapes can be added by creating new classes extending Shape and implementing their own calculateArea method. This approach adheres to the Open/Closed Principle, promoting a more flexible and maintainable design.</p><p>3. <strong>Liskov Substitution Principle (LSP)</strong>: Objects of a superclass should be replaceable with objects of a subclass without affecting the correctness of the program. In essence, any subclass should be able to replace its parent class without causing unexpected behavior. Adhering to this principle ensures that the behavior of the base class is preserved in all derived classes. Lets understand with an example.</p><p>In below example, we have overridden the withdraw method in the SavingsAccount class to prevent withdrawals for savings accounts. This approach does not adhere to the Liskov Substitution Principle.</p><pre>public class BankAccount {<br>    protected double balance;<br><br>    public BankAccount(double balance) {<br>        this.balance = balance;<br>    }<br><br>    public void deposit(double amount) {<br>        balance += amount;<br>    }<br><br>    public void withdraw(double amount) {<br>        if (amount &lt;= balance) {<br>            balance -= amount;<br>        } else {<br>            System.out.println(&quot;Insufficient funds&quot;);<br>        }<br>    }<br><br>    public double getBalance() {<br>        return balance;<br>    }<br>}<br><br>public class SavingsAccount extends BankAccount {<br>    private double interestRate;<br><br>    public SavingsAccount(double balance, double interestRate) {<br>        super(balance);<br>        this.interestRate = interestRate;<br>    }<br><br>    // Not following LSP: Overriding a behavior that is not applicable to SavingsAccount<br>    @Override<br>    public void withdraw(double amount) {<br>        System.out.println(&quot;Withdrawal not allowed for Savings Account&quot;);<br>    }<br><br>    public void applyInterest() {<br>        balance += balance * interestRate;<br>    }<br>}<br><br>public class CheckingAccount extends BankAccount {<br>    private double overdraftLimit;<br><br>    public CheckingAccount(double balance, double overdraftLimit) {<br>        super(balance);<br>        this.overdraftLimit = overdraftLimit;<br>    }<br><br>    public void withdraw(double amount) {<br>        if (amount &lt;= balance + overdraftLimit) {<br>            balance -= amount;<br>        } else {<br>            System.out.println(&quot;Exceeded overdraft limit&quot;);<br>        }<br>    }<br>}</pre><p><strong>Issues: <br>1. Unexpected Behavior:</strong> When a subclass (e.g., SavingsAccount) violates LSP by modifying or overriding the behavior of the parent class (e.g., BankAccount), it can lead to unexpected behavior. In this case, calling the withdraw method on a SavingsAccount object will not withdraw money as expected, and it will only print a message stating that withdrawal is not allowed.</p><p><strong>2. Breaks Substitution: </strong>The Liskov Substitution Principle guarantees that any instance of a subclass can replace its superclass instance without changing the program’s correctness. However, since the behavior of SavingsAccount differs from that of BankAccount, we can no longer substitute a SavingsAccount object for a BankAccount object without affecting the correctness of the program.</p><p><strong>3. Harder to Reason:</strong> Violating LSP makes it harder to reason about the behavior of subclasses. Users of the BankAccount class might assume that any subclass can be used in the same way, but that assumption would be incorrect when dealing with SavingsAccount.</p><p><strong>Solution: </strong>The Liskov Substitution Principle ensures that a subclass can replace its parent class without affecting the correctness of the program. Let’s consider a banking example:</p><pre>public class BankAccount {<br>    protected double balance;<br><br>    public BankAccount(double balance) {<br>        this.balance = balance;<br>    }<br><br>    public void deposit(double amount) {<br>        balance += amount;<br>    }<br><br>    public void withdraw(double amount) {<br>        if (amount &lt;= balance) {<br>            balance -= amount;<br>        } else {<br>            System.out.println(&quot;Insufficient funds&quot;);<br>        }<br>    }<br><br>    public double getBalance() {<br>        return balance;<br>    }<br>}<br><br>public class SavingsAccount extends BankAccount {<br>    private double interestRate;<br><br>    public SavingsAccount(double balance, double interestRate) {<br>        super(balance);<br>        this.interestRate = interestRate;<br>    }<br><br>    public void applyInterest() {<br>        balance += balance * interestRate;<br>    }<br>}<br><br>public class CheckingAccount extends BankAccount {<br>    private double overdraftLimit;<br><br>    public CheckingAccount(double balance, double overdraftLimit) {<br>        super(balance);<br>        this.overdraftLimit = overdraftLimit;<br>    }<br><br>    public void withdraw(double amount) {<br>        if (amount &lt;= balance + overdraftLimit) {<br>            balance -= amount;<br>        } else {<br>            System.out.println(&quot;Exceeded overdraft limit&quot;);<br>        }<br>    }<br>}<br><br>public class Main {<br>    public static void main(String[] args) {<br>        BankAccount account1 = new SavingsAccount(1000, 0.05);<br>        BankAccount account2 = new CheckingAccount(500, 200);<br><br>        account1.deposit(200);<br>        account2.withdraw(300);<br>       /* Both SavingsAccount and CheckingAccount can replace BankAccount in <br>       this example, and the behavior of the program remains consistent. */<br><br>        System.out.println(&quot;Account 1 balance: &quot; + account1.getBalance()); // Output: Account 1 balance: 1300.0<br>        System.out.println(&quot;Account 2 balance: &quot; + account2.getBalance()); // Output: Account 2 balance: 200.0<br>    }<br>}</pre><p>The Liskov Substitution Principle states that you should be able to replace a BankAccount object with a SavingsAccount or CheckingAccount object without altering the behavior of the program. This means you can treat both sub classes as if they were the base class.</p><p><strong>4. Interface Segregation Principle (ISP):</strong> In the LEGO world, interfaces are like connectors that allow you to attach different blocks together. The Interface Segregation Principle tells you to create small and specific interfaces, so you don’t force LEGO blocks to connect to interfaces they don’t need. For instance, if a block is only meant to be attached to the back of the car, it shouldn’t have connectors for the front or sides. This way, you can choose which blocks to connect based on their specific needs, making the construction simpler and less dependent on other blocks.</p><p>In this example below, we have an Printer interface with three methods: print, scan, and fax. We have two classes, MultifunctionPrinter and BasicPrinter, that implement this interface. However, not all printers support scanning and faxing. In the current design, even a basic printer, which doesn&#39;t support scanning or faxing, is forced to implement these methods.</p><pre>public interface Printer {<br>    void print();<br>    void scan();<br>    void fax();<br>}<br><br>public class MultifunctionPrinter implements Printer {<br>    public void print() {<br>        // Implementation for printing<br>    }<br><br>    public void scan() {<br>        // Implementation for scanning<br>    }<br><br>    public void fax() {<br>        // Implementation for faxing<br>    }<br>}<br><br>public class BasicPrinter implements Printer {<br>    public void print() {<br>        // Implementation for printing<br>    }<br><br>    public void scan() {<br>        // Not supported for a basic printer<br>    }<br><br>    public void fax() {<br>        // Not supported for a basic printer<br>    }<br>}</pre><p>Issues with Violating ISP:</p><ol><li><strong>Interface Pollution:</strong> The Printer interface is large and includes methods that are not relevant to all printer types. Forcing all printer classes to implement methods they don&#39;t need leads to interface pollution, making it harder to understand and maintain the code.</li><li><strong>Unnecessary Implementations:</strong> The BasicPrinter class implements scan and fax methods even though it doesn&#39;t support these functionalities. This may lead to empty method bodies or methods that throw exceptions, which is not ideal and can cause confusion.</li><li><strong>Tight Coupling:</strong> Clients that use the Printer interface are forced to depend on methods they might not use. This tight coupling can make the code harder to maintain and evolve.</li></ol><p>To follow the Interface Segregation Principle, we can refactor the code as follows:<br>After implementing ISP:</p><pre>// Separate interfaces for specific functionalities<br><br>public interface Printer {<br>    void print();<br>}<br><br>public interface Scanner {<br>    void scan();<br>}<br><br>public interface FaxMachine {<br>    void fax();<br>}<br><br>// Implement specific interfaces based on functionalities<br><br>public class MultifunctionPrinter implements Printer, Scanner, FaxMachine {<br>    public void print() {<br>        // Implementation for printing<br>    }<br><br>    public void scan() {<br>        // Implementation for scanning<br>    }<br><br>    public void fax() {<br>        // Implementation for faxing<br>    }<br>}<br><br>public class BasicPrinter implements Printer {<br>    public void print() {<br>        // Implementation for printing<br>    }<br>}</pre><p>In this refactored code, we have separated the large Printer interface into smaller interfaces (Printer, Scanner, and FaxMachine) each representing specific functionalities. Now, classes can choose to implement only the interfaces they need, reducing unnecessary dependencies and adhering to the Interface Segregation Principle.</p><p>Benefits of Following ISP:</p><ol><li><strong>Smaller, Focused Interfaces:</strong> The interfaces are now smaller and focused on specific functionalities, making them more manageable and easier to understand.</li><li><strong>Reduced Dependencies: </strong>Classes can implement only the interfaces they need, reducing unnecessary dependencies and making the code more flexible and maintainable.</li><li><strong>Better Composability:</strong> Composing behavior by implementing specific interfaces allows for greater flexibility and extensibility in the system.</li></ol><p>By following the Interface Segregation Principle, we can create more modular and loosely coupled code, where clients only depend on the functionality they require, leading to better code organization and maintainability.</p><p><strong>5. Dependency Inversion Principle (DIP):</strong> The Dependency Inversion Principle (DIP) states that high-level modules should not depend on low-level modules. Both should depend on abstractions. Abstractions should not depend on details; details should depend on abstractions. In simpler terms, it promotes the use of interfaces or abstract classes to decouple high-level modules from low-level modules, allowing for more flexibility and easier maintenance. Lets understand with an example.</p><p>Let’s consider an example with a ReportGenerator class and a ReportSaver class:</p><p>Before implementing DIP:</p><pre>public class ReportGenerator {<br>    private DataProvider dataProvider;<br><br>    public ReportGenerator() {<br>        this.dataProvider = new DatabaseDataProvider(); // Issue: High-level module directly depends on low-level module.<br>    }<br><br>    public String generateReport() {<br>        // Use dataProvider to fetch data and generate report<br>        Data data = dataProvider.getData();<br>        // Report generation logic...<br>        String reportContent = &quot;Report Content...&quot;;<br>        return reportContent;<br>    }<br>}<br><br>public class DatabaseDataProvider {<br>    public Data getData() {<br>        // Retrieve data from the database<br>        return new Data();<br>    }<br>}<br><br>public class ReportSaver {<br>    public void saveToFile(String content) {<br>        // Save the report content to a file<br>        try (FileWriter fileWriter = new FileWriter(&quot;report.txt&quot;)) {<br>            fileWriter.write(content);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>In this example, the ReportGenerator class directly creates an instance of DatabaseDataProvider, a low-level module responsible for retrieving data from the database. This tight coupling between high-level and low-level modules violates the Dependency Inversion Principle.</p><p>Issues with Violating DIP:</p><ol><li><strong>High Coupling:</strong> The high-level module (ReportGenerator) is tightly coupled with the low-level module (DatabaseDataProvider). If you later decide to change the data source or use a different data retrieval mechanism, you would need to modify the ReportGenerator class.</li><li><strong>Difficult to Test:</strong> Unit testing the ReportGenerator class becomes challenging because it is directly dependent on the concrete implementation of DatabaseDataProvider. To test the report generation logic, you would need to deal with database connections and data retrieval, making tests more complex and slower.</li></ol><p>After implementing DIP:</p><p>To follow DIP, we introduce an abstraction (interface) to decouple the ReportGenerator from the specific data provider:</p><pre>public interface DataProvider {<br>    Data getData();<br>}<br><br>public class DatabaseDataProvider implements DataProvider {<br>    public Data getData() {<br>        // Retrieve data from the database<br>        return new Data();<br>    }<br>}<br><br>public class ReportGenerator {<br>    private DataProvider dataProvider;<br><br>    public ReportGenerator(DataProvider dataProvider) {<br>        this.dataProvider = dataProvider; // High-level module now depends on abstraction (DataProvider interface).<br>    }<br><br>    public String generateReport() {<br>        // Use dataProvider to fetch data and generate report<br>        Data data = dataProvider.getData();<br>        // Report generation logic...<br>        String reportContent = &quot;Report Content...&quot;;<br>        return reportContent;<br>    }<br>}<br><br>public class ReportSaver {<br>    public void saveToFile(String content) {<br>        // Save the report content to a file<br>        try (FileWriter fileWriter = new FileWriter(&quot;report.txt&quot;)) {<br>            fileWriter.write(content);<br>        } catch (IOException e) {<br>            e.printStackTrace();<br>        }<br>    }<br>}</pre><p>In above refactored code, the ReportGenerator class depends on the DataProvider interface rather than the concrete DatabaseDataProvider class. Now, the high-level module is decoupled from the low-level module, adhering to the Dependency Inversion Principle.</p><p>Benefits of Following DIP:</p><ol><li><strong>Reduced Coupling:</strong> The high-level module is no longer directly dependent on the low-level module, resulting in reduced coupling between different components.</li><li><strong>Easy Testing:</strong> By depending on abstractions, unit testing becomes easier. You can now easily create mock implementations of DataProvider for testing the ReportGenerator class without dealing with database connections.</li><li><strong>Flexibility: </strong>The code becomes more flexible and extensible. You can easily switch to a different data provider implementation without affecting the ReportGenerator class.</li></ol><p>By following the Dependency Inversion Principle, you create a more modular and maintainable codebase, making it easier to change individual components and adapt to future requirements.</p><p><em>Thanks for reading, Feel free to give your inputs.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2d029a35ed14" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Access control allow origin]]></title>
            <link>https://aaquifzubair.medium.com/access-control-allow-origin-5e3abbdf0250?source=rss-e94e55184319------2</link>
            <guid isPermaLink="false">https://medium.com/p/5e3abbdf0250</guid>
            <category><![CDATA[blocked-access-control]]></category>
            <category><![CDATA[cross-origin]]></category>
            <category><![CDATA[no-access-control]]></category>
            <category><![CDATA[cross-origin-resource]]></category>
            <category><![CDATA[cors]]></category>
            <dc:creator><![CDATA[Aaquif Zubair]]></dc:creator>
            <pubDate>Sat, 24 Apr 2021 16:31:07 GMT</pubDate>
            <atom:updated>2021-04-24T16:41:19.927Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/615/1*kwX5qCkBqrL7d5fVv4M7bg.png" /></figure><p>For understanding the concept of <strong>access control allow origin</strong>, we will have to learn that from where it is coming, where are we using this. For that, We will have to learn <strong>Cross-Origin Resource Sharing(CORS).</strong></p><h3>What is CORS?</h3><p>CORS stands for Cross-Origin Resource Sharing, It is a mechanism that the browser uses to handle cases when an application running at a particular origin wants to access resources from another application running at another origin. You may wonder what exactly the origin is?</p><p><strong>Origin is defined by the protocol, domain, and port of the URL used to access it. Two objects are said to be of the same origin when the protocol, host, and port all match.</strong></p><p><strong>Let’s understand it by example.</strong></p><p><a href="http://google.com/index.html"><em>http://google.com/index.html</em></a></p><p><a href="http://google.com/index.html"><em>http://google.com/index.html</em></a></p><blockquote>Same origin because the same protocol(HTTP) and host(google.com)</blockquote><p><a href="http://google.com/"><em>http://google.com:80</em></a></p><p><a href="http://google.com/"><em>http://google.com</em></a></p><blockquote>Same-origin because same protocol(HTTP), host(google.com) and port(80). you may notice that in the second URL there is no port number mentioned, if there is no port no mentioned then HTTP serves it on port 80 by default.</blockquote><p><a href="https://google.com/"><em>https://google.com</em></a></p><p><a href="http://google.com/"><em>http://google.com</em></a></p><blockquote>Different origin because the protocol and ports are different. because the default port no of HTTP is 80 and for HTTPS is 443.</blockquote><p><a href="https://google.com/">h<em>ttps://google.com:443</em></a></p><p><a href="https://facebook.com/"><em>https://facebook.com:443</em></a></p><blockquote>Different origins because the hostname is different.</blockquote><p><a href="http://google.com/"><em>http://google.com:80</em></a></p><p><a href="http://google.com:1234/"><em>http://google.com:1234</em></a></p><blockquote>Different origins because the port is different.</blockquote><p>But Why browsers need this mechanism? The reason is that most browsers implement a security policy known as ‘Same Origin Policy. Due to this policy, we can’t access resources from another origin. This is the main reason browsers need CORS to get resources from a different origin.</p><p><strong>How does it work?</strong></p><p>When a client application at an origin A tries to access resources from the server application running at an origin B, It can’t access the resource unless some specific CORS HTTP headers are present in the request and response, and it will throw a cors error in the console. If the request header is the same as the response header client will fetch the resources. You may wonder which type of header are we discussing here. I am explaining it below.</p><p>For some types of access requests that can possibly cause side effects to the server e.g a DELETE request. In this case, a <strong>preflight request </strong>would be automatically sent by the browser to tell the server about the actual request. After that server will approve or reject the request y analyzing the request headers.</p><p><strong>CORS HTTP Headers.</strong></p><p>It can be grouped into two request headers i.e headers in the request from the client and the and Response headers i.e headers in the response from the server.</p><p><strong>Request Headers</strong></p><p>There are three types of request headers.</p><p>1. Origin: It let the server know the Origin of the client application.</p><p>2. Access-Control-Request-Method: This header lets the server know, what HTTP method the client intends to send. It is set by the browser during preflight requests.</p><p>3. Access-Control-Request-Headers: This method lets the server know what HTTP headers the client intends to send. This is also set by the browser during preflight requests.</p><p><strong>Response Headers</strong></p><p>1.<strong> Acces-Control-Allow-Origin</strong>: This specifies the origin that the server wants to allow to access the resource. Confusing? let me explain if we will put the value of this header like this(“access-control-allow-origin”: “*”). * is defining here that all origin can access the resource of this server. If we want to give access to this server to only a particular client we will put the URL of that request client.</p><p>e.g { ‘allow-access-control-origin’ : ‘http://google.com&#39;}</p><p>In the previous example server wants to give access to his resources only ‘google.com’.</p><p>2. <strong>Access-Control-Allow-Headers:</strong> This specifies the set of headers that can be in client requests. If this doesn’t match then the browser will throw a cors error.</p><p>3. <strong>Access-Control-Allow-Methods:</strong> This specifies the set of methods that can be used for client requests. If the server wants to give access to different methods, it may be specified as comma-separated.</p><p>e.g { access-control-allow-methods’: GET, POST, DELETE }</p><p>There are whole other types of response headers, You can see on this <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN Link.</a></p><h3>How to handle CORS?</h3><p>It is very simple to handle cors. This is something that has to be done at the server application.</p><p>If you want to specify that which origin should access the resource of your server, you can use access-contro-allow origin, If you want to specify which HTTP method can any client use from your server you can use access-control-allow-methods. Like this, you can use different types of response header properties according to your use.</p><h3>Summary</h3><blockquote>I tried my best to convey my knowledge to you. I hope I was able to provide you at least a basic understanding of cors and how does it work? If You want to go deep more into it, follow the <a href="https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS">MDN Documentation</a>. This is a very good place to start.</blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5e3abbdf0250" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>